Skip to content

Commit c4e8ec9

Browse files
[3.10] pythongh-90016: Reword sqlite3 adapter/converter docs (pythonGH-93095)
Also add adapters and converter recipes. Co-authored-by: CAM Gerlach <[email protected]> Co-authored-by: Alex Waygood <[email protected]. (cherry picked from commit bd3c1c1) Co-authored-by: Erlend Egeberg Aasland <[email protected]>
1 parent 75dda3b commit c4e8ec9

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
@@ -181,31 +181,41 @@ Module functions and constants
181181

182182
.. data:: PARSE_DECLTYPES
183183

184-
This constant is meant to be used with the *detect_types* parameter of the
185-
:func:`connect` function.
184+
Pass this flag value to the *detect_types* parameter of
185+
:func:`connect` to look up a converter function using
186+
the declared types for each column.
187+
The types are declared when the database table is created.
188+
``sqlite3`` will look up a converter function using the first word of the
189+
declared type as the converter dictionary key.
190+
For example:
186191

187-
Setting it makes the :mod:`sqlite3` module parse the declared type for each
188-
column it returns. It will parse out the first word of the declared type,
189-
i. e. for "integer primary key", it will parse out "integer", or for
190-
"number(10)" it will parse out "number". Then for that column, it will look
191-
into the converters dictionary and use the converter function registered for
192-
that type there.
192+
193+
.. code-block:: sql
194+
195+
CREATE TABLE test(
196+
i integer primary key, ! will look up a converter named "integer"
197+
p point, ! will look up a converter named "point"
198+
n number(10) ! will look up a converter named "number"
199+
)
200+
201+
This flag may be combined with :const:`PARSE_COLNAMES` using the ``|``
202+
(bitwise or) operator.
193203

194204

195205
.. data:: PARSE_COLNAMES
196206

197-
This constant is meant to be used with the *detect_types* parameter of the
198-
:func:`connect` function.
207+
Pass this flag value to the *detect_types* parameter of
208+
:func:`connect` to look up a converter function by
209+
using the type name, parsed from the query column name,
210+
as the converter dictionary key.
211+
The type name must be wrapped in square brackets (``[]``).
212+
213+
.. code-block:: sql
199214
200-
Setting this makes the SQLite interface parse the column name for each column it
201-
returns. It will look for a string formed [mytype] in there, and then decide
202-
that 'mytype' is the type of the column. It will try to find an entry of
203-
'mytype' in the converters dictionary and then use the converter function found
204-
there to return the value. The column name found in :attr:`Cursor.description`
205-
does not include the type, i. e. if you use something like
206-
``'as "Expiration date [datetime]"'`` in your SQL, then we will parse out
207-
everything until the first ``'['`` for the column name and strip
208-
the preceding space: the column name would simply be "Expiration date".
215+
SELECT p as "p [point]" FROM test; ! will look up converter "point"
216+
217+
This flag may be combined with :const:`PARSE_DECLTYPES` using the ``|``
218+
(bitwise or) operator.
209219

210220

211221
.. function:: connect(database[, timeout, detect_types, isolation_level, check_same_thread, factory, cached_statements, uri])
@@ -229,14 +239,17 @@ Module functions and constants
229239

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

235-
*detect_types* defaults to 0 (i. e. off, no type detection), you can set it to
236-
any combination of :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES` to turn
237-
type detection on. Due to SQLite behaviour, types can't be detected for generated
238-
fields (for example ``max(data)``), even when *detect_types* parameter is set. In
239-
such case, the returned type is :class:`str`.
245+
*detect_types* defaults to 0 (type detection disabled).
246+
Set it to any combination (using ``|``, bitwise or) of
247+
:const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES`
248+
to enable type detection.
249+
Column names takes precedence over declared types if both flags are set.
250+
Types cannot be detected for generated fields (for example ``max(data)``),
251+
even when the *detect_types* parameter is set.
252+
In such cases, the returned type is :class:`str`.
240253

241254
By default, *check_same_thread* is :const:`True` and only the creating thread may
242255
use the connection. If set :const:`False`, the returned connection may be shared
@@ -291,21 +304,27 @@ Module functions and constants
291304
Added the ``sqlite3.connect/handle`` auditing event.
292305

293306

294-
.. function:: register_converter(typename, callable)
307+
.. function:: register_converter(typename, converter)
308+
309+
Register the *converter* callable to convert SQLite objects of type
310+
*typename* into a Python object of a specific type.
311+
The converter is invoked for all SQLite values of type *typename*;
312+
it is passed a :class:`bytes` object and should return an object of the
313+
desired Python type.
314+
Consult the parameter *detect_types* of
315+
:func:`connect` for information regarding how type detection works.
295316

296-
Registers a callable to convert a bytestring from the database into a custom
297-
Python type. The callable will be invoked for all database values that are of
298-
the type *typename*. Confer the parameter *detect_types* of the :func:`connect`
299-
function for how the type detection works. Note that *typename* and the name of
300-
the type in your query are matched in case-insensitive manner.
317+
Note: *typename* and the name of the type in your query are matched
318+
case-insensitively.
301319

302320

303-
.. function:: register_adapter(type, callable)
321+
.. function:: register_adapter(type, adapter)
304322

305-
Registers a callable to convert the custom Python type *type* into one of
306-
SQLite's supported types. The callable *callable* accepts as single parameter
307-
the Python value, and must return a value of the following types: int,
308-
float, str or bytes.
323+
Register an *adapter* callable to adapt the Python type *type* into an
324+
SQLite type.
325+
The adapter is called with a Python object of type *type* as its sole
326+
argument, and must return a value of a
327+
:ref:`type that SQLite natively understands<sqlite3-types>`.
309328

310329

311330
.. function:: complete_statement(statement)
@@ -1004,60 +1023,53 @@ you can let the :mod:`sqlite3` module convert SQLite types to different Python
10041023
types via converters.
10051024

10061025

1007-
Using adapters to store additional Python types in SQLite databases
1008-
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1026+
Using adapters to store custom Python types in SQLite databases
1027+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
10091028

1010-
As described before, SQLite supports only a limited set of types natively. To
1011-
use other Python types with SQLite, you must **adapt** them to one of the
1012-
sqlite3 module's supported types for SQLite: one of NoneType, int, float,
1013-
str, bytes.
1029+
SQLite supports only a limited set of data types natively.
1030+
To store custom Python types in SQLite databases, *adapt* them to one of the
1031+
:ref:`Python types SQLite natively understands<sqlite3-types>`.
10141032

1015-
There are two ways to enable the :mod:`sqlite3` module to adapt a custom Python
1016-
type to one of the supported ones.
1033+
There are two ways to adapt Python objects to SQLite types:
1034+
letting your object adapt itself, or using an *adapter callable*.
1035+
The latter will take precedence above the former.
1036+
For a library that exports a custom type,
1037+
it may make sense to enable that type to adapt itself.
1038+
As an application developer, it may make more sense to take direct control by
1039+
registering custom adapter functions.
10171040

10181041

10191042
Letting your object adapt itself
10201043
""""""""""""""""""""""""""""""""
10211044

1022-
This is a good approach if you write the class yourself. Let's suppose you have
1023-
a class like this::
1024-
1025-
class Point:
1026-
def __init__(self, x, y):
1027-
self.x, self.y = x, y
1028-
1029-
Now you want to store the point in a single SQLite column. First you'll have to
1030-
choose one of the supported types to be used for representing the point.
1031-
Let's just use str and separate the coordinates using a semicolon. Then you need
1032-
to give your class a method ``__conform__(self, protocol)`` which must return
1033-
the converted value. The parameter *protocol* will be :class:`PrepareProtocol`.
1045+
Suppose we have a ``Point`` class that represents a pair of coordinates,
1046+
``x`` and ``y``, in a Cartesian coordinate system.
1047+
The coordinate pair will be stored as a text string in the database,
1048+
using a semicolon to separate the coordinates.
1049+
This can be implemented by adding a ``__conform__(self, protocol)``
1050+
method which returns the adapted value.
1051+
The object passed to *protocol* will be of type :class:`PrepareProtocol`.
10341052

10351053
.. literalinclude:: ../includes/sqlite3/adapter_point_1.py
10361054

10371055

10381056
Registering an adapter callable
10391057
"""""""""""""""""""""""""""""""
10401058

1041-
The other possibility is to create a function that converts the type to the
1042-
string representation and register the function with :meth:`register_adapter`.
1059+
The other possibility is to create a function that converts the Python object
1060+
to an SQLite-compatible type.
1061+
This function can then be registered using :func:`register_adapter`.
10431062

10441063
.. literalinclude:: ../includes/sqlite3/adapter_point_2.py
10451064

1046-
The :mod:`sqlite3` module has two default adapters for Python's built-in
1047-
:class:`datetime.date` and :class:`datetime.datetime` types. Now let's suppose
1048-
we want to store :class:`datetime.datetime` objects not in ISO representation,
1049-
but as a Unix timestamp.
1050-
1051-
.. literalinclude:: ../includes/sqlite3/adapter_datetime.py
1052-
10531065

10541066
Converting SQLite values to custom Python types
10551067
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
10561068

1057-
Writing an adapter lets you send custom Python types to SQLite. But to make it
1058-
really useful we need to make the Python to SQLite to Python roundtrip work.
1059-
1060-
Enter converters.
1069+
Writing an adapter lets you convert *from* custom Python types *to* SQLite
1070+
values.
1071+
To be able to convert *from* SQLite values *to* custom Python types,
1072+
we use *converters*.
10611073

10621074
Let's go back to the :class:`Point` class. We stored the x and y coordinates
10631075
separated via semicolons as strings in SQLite.
@@ -1067,26 +1079,26 @@ and constructs a :class:`Point` object from it.
10671079

10681080
.. note::
10691081

1070-
Converter functions **always** get called with a :class:`bytes` object, no
1071-
matter under which data type you sent the value to SQLite.
1082+
Converter functions are **always** passed a :class:`bytes` object,
1083+
no matter the underlying SQLite data type.
10721084

10731085
::
10741086

10751087
def convert_point(s):
10761088
x, y = map(float, s.split(b";"))
10771089
return Point(x, y)
10781090

1079-
Now you need to make the :mod:`sqlite3` module know that what you select from
1080-
the database is actually a point. There are two ways of doing this:
1081-
1082-
* Implicitly via the declared type
1091+
We now need to tell ``sqlite3`` when it should convert a given SQLite value.
1092+
This is done when connecting to a database, using the *detect_types* parameter
1093+
of :func:`connect`. There are three options:
10831094

1084-
* Explicitly via the column name
1095+
* Implicit: set *detect_types* to :const:`PARSE_DECLTYPES`
1096+
* Explicit: set *detect_types* to :const:`PARSE_COLNAMES`
1097+
* Both: set *detect_types* to
1098+
``sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES``.
1099+
Colum names take precedence over declared types.
10851100

1086-
Both ways are described in section :ref:`sqlite3-module-contents`, in the entries
1087-
for the constants :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES`.
1088-
1089-
The following example illustrates both approaches.
1101+
The following example illustrates the implicit and explicit approaches:
10901102

10911103
.. literalinclude:: ../includes/sqlite3/converter_point.py
10921104

@@ -1120,6 +1132,52 @@ timestamp converter.
11201132
offsets in timestamps, either leave converters disabled, or register an
11211133
offset-aware converter with :func:`register_converter`.
11221134

1135+
1136+
.. _sqlite3-adapter-converter-recipes:
1137+
1138+
Adapter and Converter Recipes
1139+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1140+
1141+
This section shows recipes for common adapters and converters.
1142+
1143+
.. code-block::
1144+
1145+
import datetime
1146+
import sqlite3
1147+
1148+
def adapt_date_iso(val):
1149+
"""Adapt datetime.date to ISO 8601 date."""
1150+
return val.isoformat()
1151+
1152+
def adapt_datetime_iso(val):
1153+
"""Adapt datetime.datetime to timezone-naive ISO 8601 date."""
1154+
return val.isoformat()
1155+
1156+
def adapt_datetime_epoch(val)
1157+
"""Adapt datetime.datetime to Unix timestamp."""
1158+
return int(val.timestamp())
1159+
1160+
sqlite3.register_adapter(datetime.date, adapt_date_iso)
1161+
sqlite3.register_adapter(datetime.datetime, adapt_datetime_iso)
1162+
sqlite3.register_adapter(datetime.datetime, adapt_datetime_epoch)
1163+
1164+
def convert_date(val):
1165+
"""Convert ISO 8601 date to datetime.date object."""
1166+
return datetime.date.fromisoformat(val)
1167+
1168+
def convert_datetime(val):
1169+
"""Convert ISO 8601 datetime to datetime.datetime object."""
1170+
return datetime.datetime.fromisoformat(val)
1171+
1172+
def convert_timestamp(val):
1173+
"""Convert Unix epoch timestamp to datetime.datetime object."""
1174+
return datetime.datetime.fromtimestamp(val)
1175+
1176+
sqlite3.register_converter("date", convert_date)
1177+
sqlite3.register_converter("datetime", convert_datetime)
1178+
sqlite3.register_converter("timestamp", convert_timestamp)
1179+
1180+
11231181
.. _sqlite3-controlling-transactions:
11241182

11251183
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)