Skip to content

Commit bd3c1c1

Browse files
gh-90016: Reword sqlite3 adapter/converter docs (#93095)
Also add adapters and converter recipes. Co-authored-by: CAM Gerlach <CAM.Gerlach@Gerlach.CAM> Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com
1 parent bec802d commit bd3c1c1

File tree

5 files changed

+156
-122
lines changed

5 files changed

+156
-122
lines changed

Doc/includes/sqlite3/adapter_datetime.py

-17
This file was deleted.

Doc/includes/sqlite3/converter_point.py

+7-14
Original file line numberDiff line numberDiff line change
@@ -5,40 +5,33 @@ def __init__(self, x, y):
55
self.x, self.y = x, y
66

77
def __repr__(self):
8-
return "(%f;%f)" % (self.x, self.y)
8+
return f"Point({self.x}, {self.y})"
99

1010
def adapt_point(point):
11-
return ("%f;%f" % (point.x, point.y)).encode('ascii')
11+
return f"{point.x};{point.y}".encode("utf-8")
1212

1313
def convert_point(s):
1414
x, y = list(map(float, s.split(b";")))
1515
return Point(x, y)
1616

17-
# Register the adapter
17+
# Register the adapter and converter
1818
sqlite3.register_adapter(Point, adapt_point)
19-
20-
# Register the converter
2119
sqlite3.register_converter("point", convert_point)
2220

21+
# 1) Parse using declared types
2322
p = Point(4.0, -3.2)
24-
25-
#########################
26-
# 1) Using declared types
2723
con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES)
28-
cur = con.cursor()
29-
cur.execute("create table test(p point)")
24+
cur = con.execute("create table test(p point)")
3025

3126
cur.execute("insert into test(p) values (?)", (p,))
3227
cur.execute("select p from test")
3328
print("with declared types:", cur.fetchone()[0])
3429
cur.close()
3530
con.close()
3631

37-
#######################
38-
# 1) Using column names
32+
# 2) Parse using column names
3933
con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_COLNAMES)
40-
cur = con.cursor()
41-
cur.execute("create table test(p)")
34+
cur = con.execute("create table test(p)")
4235

4336
cur.execute("insert into test(p) values (?)", (p,))
4437
cur.execute('select p as "p [point]" from test')

Doc/library/sqlite3.rst

+138-80
Original file line numberDiff line numberDiff line change
@@ -209,31 +209,41 @@ Module functions and constants
209209

210210
.. data:: PARSE_DECLTYPES
211211

212-
This constant is meant to be used with the *detect_types* parameter of the
213-
:func:`connect` function.
212+
Pass this flag value to the *detect_types* parameter of
213+
:func:`connect` to look up a converter function using
214+
the declared types for each column.
215+
The types are declared when the database table is created.
216+
``sqlite3`` will look up a converter function using the first word of the
217+
declared type as the converter dictionary key.
218+
For example:
214219

215-
Setting it makes the :mod:`sqlite3` module parse the declared type for each
216-
column it returns. It will parse out the first word of the declared type,
217-
i. e. for "integer primary key", it will parse out "integer", or for
218-
"number(10)" it will parse out "number". Then for that column, it will look
219-
into the converters dictionary and use the converter function registered for
220-
that type there.
220+
221+
.. code-block:: sql
222+
223+
CREATE TABLE test(
224+
i integer primary key, ! will look up a converter named "integer"
225+
p point, ! will look up a converter named "point"
226+
n number(10) ! will look up a converter named "number"
227+
)
228+
229+
This flag may be combined with :const:`PARSE_COLNAMES` using the ``|``
230+
(bitwise or) operator.
221231

222232

223233
.. data:: PARSE_COLNAMES
224234

225-
This constant is meant to be used with the *detect_types* parameter of the
226-
:func:`connect` function.
235+
Pass this flag value to the *detect_types* parameter of
236+
:func:`connect` to look up a converter function by
237+
using the type name, parsed from the query column name,
238+
as the converter dictionary key.
239+
The type name must be wrapped in square brackets (``[]``).
240+
241+
.. code-block:: sql
227242
228-
Setting this makes the SQLite interface parse the column name for each column it
229-
returns. It will look for a string formed [mytype] in there, and then decide
230-
that 'mytype' is the type of the column. It will try to find an entry of
231-
'mytype' in the converters dictionary and then use the converter function found
232-
there to return the value. The column name found in :attr:`Cursor.description`
233-
does not include the type, i. e. if you use something like
234-
``'as "Expiration date [datetime]"'`` in your SQL, then we will parse out
235-
everything until the first ``'['`` for the column name and strip
236-
the preceding space: the column name would simply be "Expiration date".
243+
SELECT p as "p [point]" FROM test; ! will look up converter "point"
244+
245+
This flag may be combined with :const:`PARSE_DECLTYPES` using the ``|``
246+
(bitwise or) operator.
237247

238248

239249
.. function:: connect(database[, timeout, detect_types, isolation_level, check_same_thread, factory, cached_statements, uri])
@@ -257,14 +267,17 @@ Module functions and constants
257267

258268
SQLite natively supports only the types TEXT, INTEGER, REAL, BLOB and NULL. If
259269
you want to use other types you must add support for them yourself. The
260-
*detect_types* parameter and the using custom **converters** registered with the
270+
*detect_types* parameter and using custom **converters** registered with the
261271
module-level :func:`register_converter` function allow you to easily do that.
262272

263-
*detect_types* defaults to 0 (i. e. off, no type detection), you can set it to
264-
any combination of :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES` to turn
265-
type detection on. Due to SQLite behaviour, types can't be detected for generated
266-
fields (for example ``max(data)``), even when *detect_types* parameter is set. In
267-
such case, the returned type is :class:`str`.
273+
*detect_types* defaults to 0 (type detection disabled).
274+
Set it to any combination (using ``|``, bitwise or) of
275+
:const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES`
276+
to enable type detection.
277+
Column names takes precedence over declared types if both flags are set.
278+
Types cannot be detected for generated fields (for example ``max(data)``),
279+
even when the *detect_types* parameter is set.
280+
In such cases, the returned type is :class:`str`.
268281

269282
By default, *check_same_thread* is :const:`True` and only the creating thread may
270283
use the connection. If set :const:`False`, the returned connection may be shared
@@ -319,21 +332,27 @@ Module functions and constants
319332
Added the ``sqlite3.connect/handle`` auditing event.
320333

321334

322-
.. function:: register_converter(typename, callable)
335+
.. function:: register_converter(typename, converter)
336+
337+
Register the *converter* callable to convert SQLite objects of type
338+
*typename* into a Python object of a specific type.
339+
The converter is invoked for all SQLite values of type *typename*;
340+
it is passed a :class:`bytes` object and should return an object of the
341+
desired Python type.
342+
Consult the parameter *detect_types* of
343+
:func:`connect` for information regarding how type detection works.
323344

324-
Registers a callable to convert a bytestring from the database into a custom
325-
Python type. The callable will be invoked for all database values that are of
326-
the type *typename*. Confer the parameter *detect_types* of the :func:`connect`
327-
function for how the type detection works. Note that *typename* and the name of
328-
the type in your query are matched in case-insensitive manner.
345+
Note: *typename* and the name of the type in your query are matched
346+
case-insensitively.
329347

330348

331-
.. function:: register_adapter(type, callable)
349+
.. function:: register_adapter(type, adapter)
332350

333-
Registers a callable to convert the custom Python type *type* into one of
334-
SQLite's supported types. The callable *callable* accepts as single parameter
335-
the Python value, and must return a value of the following types: int,
336-
float, str or bytes.
351+
Register an *adapter* callable to adapt the Python type *type* into an
352+
SQLite type.
353+
The adapter is called with a Python object of type *type* as its sole
354+
argument, and must return a value of a
355+
:ref:`type that SQLite natively understands<sqlite3-types>`.
337356

338357

339358
.. function:: complete_statement(statement)
@@ -1246,60 +1265,53 @@ you can let the :mod:`sqlite3` module convert SQLite types to different Python
12461265
types via converters.
12471266

12481267

1249-
Using adapters to store additional Python types in SQLite databases
1250-
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1268+
Using adapters to store custom Python types in SQLite databases
1269+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
12511270

1252-
As described before, SQLite supports only a limited set of types natively. To
1253-
use other Python types with SQLite, you must **adapt** them to one of the
1254-
sqlite3 module's supported types for SQLite: one of NoneType, int, float,
1255-
str, bytes.
1271+
SQLite supports only a limited set of data types natively.
1272+
To store custom Python types in SQLite databases, *adapt* them to one of the
1273+
:ref:`Python types SQLite natively understands<sqlite3-types>`.
12561274

1257-
There are two ways to enable the :mod:`sqlite3` module to adapt a custom Python
1258-
type to one of the supported ones.
1275+
There are two ways to adapt Python objects to SQLite types:
1276+
letting your object adapt itself, or using an *adapter callable*.
1277+
The latter will take precedence above the former.
1278+
For a library that exports a custom type,
1279+
it may make sense to enable that type to adapt itself.
1280+
As an application developer, it may make more sense to take direct control by
1281+
registering custom adapter functions.
12591282

12601283

12611284
Letting your object adapt itself
12621285
""""""""""""""""""""""""""""""""
12631286

1264-
This is a good approach if you write the class yourself. Let's suppose you have
1265-
a class like this::
1266-
1267-
class Point:
1268-
def __init__(self, x, y):
1269-
self.x, self.y = x, y
1270-
1271-
Now you want to store the point in a single SQLite column. First you'll have to
1272-
choose one of the supported types to be used for representing the point.
1273-
Let's just use str and separate the coordinates using a semicolon. Then you need
1274-
to give your class a method ``__conform__(self, protocol)`` which must return
1275-
the converted value. The parameter *protocol* will be :class:`PrepareProtocol`.
1287+
Suppose we have a ``Point`` class that represents a pair of coordinates,
1288+
``x`` and ``y``, in a Cartesian coordinate system.
1289+
The coordinate pair will be stored as a text string in the database,
1290+
using a semicolon to separate the coordinates.
1291+
This can be implemented by adding a ``__conform__(self, protocol)``
1292+
method which returns the adapted value.
1293+
The object passed to *protocol* will be of type :class:`PrepareProtocol`.
12761294

12771295
.. literalinclude:: ../includes/sqlite3/adapter_point_1.py
12781296

12791297

12801298
Registering an adapter callable
12811299
"""""""""""""""""""""""""""""""
12821300

1283-
The other possibility is to create a function that converts the type to the
1284-
string representation and register the function with :meth:`register_adapter`.
1301+
The other possibility is to create a function that converts the Python object
1302+
to an SQLite-compatible type.
1303+
This function can then be registered using :func:`register_adapter`.
12851304

12861305
.. literalinclude:: ../includes/sqlite3/adapter_point_2.py
12871306

1288-
The :mod:`sqlite3` module has two default adapters for Python's built-in
1289-
:class:`datetime.date` and :class:`datetime.datetime` types. Now let's suppose
1290-
we want to store :class:`datetime.datetime` objects not in ISO representation,
1291-
but as a Unix timestamp.
1292-
1293-
.. literalinclude:: ../includes/sqlite3/adapter_datetime.py
1294-
12951307

12961308
Converting SQLite values to custom Python types
12971309
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
12981310

1299-
Writing an adapter lets you send custom Python types to SQLite. But to make it
1300-
really useful we need to make the Python to SQLite to Python roundtrip work.
1301-
1302-
Enter converters.
1311+
Writing an adapter lets you convert *from* custom Python types *to* SQLite
1312+
values.
1313+
To be able to convert *from* SQLite values *to* custom Python types,
1314+
we use *converters*.
13031315

13041316
Let's go back to the :class:`Point` class. We stored the x and y coordinates
13051317
separated via semicolons as strings in SQLite.
@@ -1309,26 +1321,26 @@ and constructs a :class:`Point` object from it.
13091321

13101322
.. note::
13111323

1312-
Converter functions **always** get called with a :class:`bytes` object, no
1313-
matter under which data type you sent the value to SQLite.
1324+
Converter functions are **always** passed a :class:`bytes` object,
1325+
no matter the underlying SQLite data type.
13141326

13151327
::
13161328

13171329
def convert_point(s):
13181330
x, y = map(float, s.split(b";"))
13191331
return Point(x, y)
13201332

1321-
Now you need to make the :mod:`sqlite3` module know that what you select from
1322-
the database is actually a point. There are two ways of doing this:
1323-
1324-
* Implicitly via the declared type
1333+
We now need to tell ``sqlite3`` when it should convert a given SQLite value.
1334+
This is done when connecting to a database, using the *detect_types* parameter
1335+
of :func:`connect`. There are three options:
13251336

1326-
* Explicitly via the column name
1337+
* Implicit: set *detect_types* to :const:`PARSE_DECLTYPES`
1338+
* Explicit: set *detect_types* to :const:`PARSE_COLNAMES`
1339+
* Both: set *detect_types* to
1340+
``sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES``.
1341+
Colum names take precedence over declared types.
13271342

1328-
Both ways are described in section :ref:`sqlite3-module-contents`, in the entries
1329-
for the constants :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES`.
1330-
1331-
The following example illustrates both approaches.
1343+
The following example illustrates the implicit and explicit approaches:
13321344

13331345
.. literalinclude:: ../includes/sqlite3/converter_point.py
13341346

@@ -1362,6 +1374,52 @@ timestamp converter.
13621374
offsets in timestamps, either leave converters disabled, or register an
13631375
offset-aware converter with :func:`register_converter`.
13641376

1377+
1378+
.. _sqlite3-adapter-converter-recipes:
1379+
1380+
Adapter and Converter Recipes
1381+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1382+
1383+
This section shows recipes for common adapters and converters.
1384+
1385+
.. code-block::
1386+
1387+
import datetime
1388+
import sqlite3
1389+
1390+
def adapt_date_iso(val):
1391+
"""Adapt datetime.date to ISO 8601 date."""
1392+
return val.isoformat()
1393+
1394+
def adapt_datetime_iso(val):
1395+
"""Adapt datetime.datetime to timezone-naive ISO 8601 date."""
1396+
return val.isoformat()
1397+
1398+
def adapt_datetime_epoch(val)
1399+
"""Adapt datetime.datetime to Unix timestamp."""
1400+
return int(val.timestamp())
1401+
1402+
sqlite3.register_adapter(datetime.date, adapt_date_iso)
1403+
sqlite3.register_adapter(datetime.datetime, adapt_datetime_iso)
1404+
sqlite3.register_adapter(datetime.datetime, adapt_datetime_epoch)
1405+
1406+
def convert_date(val):
1407+
"""Convert ISO 8601 date to datetime.date object."""
1408+
return datetime.date.fromisoformat(val)
1409+
1410+
def convert_datetime(val):
1411+
"""Convert ISO 8601 datetime to datetime.datetime object."""
1412+
return datetime.datetime.fromisoformat(val)
1413+
1414+
def convert_timestamp(val):
1415+
"""Convert Unix epoch timestamp to datetime.datetime object."""
1416+
return datetime.datetime.fromtimestamp(val)
1417+
1418+
sqlite3.register_converter("date", convert_date)
1419+
sqlite3.register_converter("datetime", convert_datetime)
1420+
sqlite3.register_converter("timestamp", convert_timestamp)
1421+
1422+
13651423
.. _sqlite3-controlling-transactions:
13661424

13671425
Controlling Transactions

Modules/_sqlite/clinic/module.c.h

+5-5
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)