@@ -181,31 +181,41 @@ Module functions and constants
181
181
182
182
.. data :: PARSE_DECLTYPES
183
183
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:
186
191
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.
193
203
194
204
195
205
.. data :: PARSE_COLNAMES
196
206
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
199
214
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.
209
219
210
220
211
221
.. function :: connect(database[, timeout, detect_types, isolation_level, check_same_thread, factory, cached_statements, uri])
@@ -229,14 +239,17 @@ Module functions and constants
229
239
230
240
SQLite natively supports only the types TEXT, INTEGER, REAL, BLOB and NULL. If
231
241
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
233
243
module-level :func: `register_converter ` function allow you to easily do that.
234
244
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 `.
240
253
241
254
By default, *check_same_thread * is :const: `True ` and only the creating thread may
242
255
use the connection. If set :const: `False `, the returned connection may be shared
@@ -291,21 +304,27 @@ Module functions and constants
291
304
Added the ``sqlite3.connect/handle `` auditing event.
292
305
293
306
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.
295
316
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.
301
319
302
320
303
- .. function :: register_adapter(type, callable )
321
+ .. function :: register_adapter(type, adapter )
304
322
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> `.
309
328
310
329
311
330
.. function :: complete_statement(statement)
@@ -1004,60 +1023,53 @@ you can let the :mod:`sqlite3` module convert SQLite types to different Python
1004
1023
types via converters.
1005
1024
1006
1025
1007
- Using adapters to store additional Python types in SQLite databases
1008
- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1026
+ Using adapters to store custom Python types in SQLite databases
1027
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1009
1028
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> `.
1014
1032
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.
1017
1040
1018
1041
1019
1042
Letting your object adapt itself
1020
1043
""""""""""""""""""""""""""""""""
1021
1044
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 `.
1034
1052
1035
1053
.. literalinclude :: ../includes/sqlite3/adapter_point_1.py
1036
1054
1037
1055
1038
1056
Registering an adapter callable
1039
1057
"""""""""""""""""""""""""""""""
1040
1058
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 `.
1043
1062
1044
1063
.. literalinclude :: ../includes/sqlite3/adapter_point_2.py
1045
1064
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
-
1053
1065
1054
1066
Converting SQLite values to custom Python types
1055
1067
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1056
1068
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 * .
1061
1073
1062
1074
Let's go back to the :class: `Point ` class. We stored the x and y coordinates
1063
1075
separated via semicolons as strings in SQLite.
@@ -1067,26 +1079,26 @@ and constructs a :class:`Point` object from it.
1067
1079
1068
1080
.. note ::
1069
1081
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.
1072
1084
1073
1085
::
1074
1086
1075
1087
def convert_point(s):
1076
1088
x, y = map(float, s.split(b";"))
1077
1089
return Point(x, y)
1078
1090
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:
1083
1094
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.
1085
1100
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:
1090
1102
1091
1103
.. literalinclude :: ../includes/sqlite3/converter_point.py
1092
1104
@@ -1120,6 +1132,52 @@ timestamp converter.
1120
1132
offsets in timestamps, either leave converters disabled, or register an
1121
1133
offset-aware converter with :func: `register_converter `.
1122
1134
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
+
1123
1181
.. _sqlite3-controlling-transactions :
1124
1182
1125
1183
Controlling Transactions
0 commit comments