@@ -209,31 +209,41 @@ Module functions and constants
209
209
210
210
.. data :: PARSE_DECLTYPES
211
211
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:
214
219
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.
221
231
222
232
223
233
.. data :: PARSE_COLNAMES
224
234
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
227
242
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.
237
247
238
248
239
249
.. function :: connect(database[, timeout, detect_types, isolation_level, check_same_thread, factory, cached_statements, uri])
@@ -257,14 +267,17 @@ Module functions and constants
257
267
258
268
SQLite natively supports only the types TEXT, INTEGER, REAL, BLOB and NULL. If
259
269
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
261
271
module-level :func: `register_converter ` function allow you to easily do that.
262
272
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 `.
268
281
269
282
By default, *check_same_thread * is :const: `True ` and only the creating thread may
270
283
use the connection. If set :const: `False `, the returned connection may be shared
@@ -319,21 +332,27 @@ Module functions and constants
319
332
Added the ``sqlite3.connect/handle `` auditing event.
320
333
321
334
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.
323
344
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.
329
347
330
348
331
- .. function :: register_adapter(type, callable )
349
+ .. function :: register_adapter(type, adapter )
332
350
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> `.
337
356
338
357
339
358
.. function :: complete_statement(statement)
@@ -1246,60 +1265,53 @@ you can let the :mod:`sqlite3` module convert SQLite types to different Python
1246
1265
types via converters.
1247
1266
1248
1267
1249
- Using adapters to store additional Python types in SQLite databases
1250
- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1268
+ Using adapters to store custom Python types in SQLite databases
1269
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1251
1270
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> `.
1256
1274
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.
1259
1282
1260
1283
1261
1284
Letting your object adapt itself
1262
1285
""""""""""""""""""""""""""""""""
1263
1286
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 `.
1276
1294
1277
1295
.. literalinclude :: ../includes/sqlite3/adapter_point_1.py
1278
1296
1279
1297
1280
1298
Registering an adapter callable
1281
1299
"""""""""""""""""""""""""""""""
1282
1300
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 `.
1285
1304
1286
1305
.. literalinclude :: ../includes/sqlite3/adapter_point_2.py
1287
1306
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
-
1295
1307
1296
1308
Converting SQLite values to custom Python types
1297
1309
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1298
1310
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 * .
1303
1315
1304
1316
Let's go back to the :class: `Point ` class. We stored the x and y coordinates
1305
1317
separated via semicolons as strings in SQLite.
@@ -1309,26 +1321,26 @@ and constructs a :class:`Point` object from it.
1309
1321
1310
1322
.. note ::
1311
1323
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.
1314
1326
1315
1327
::
1316
1328
1317
1329
def convert_point(s):
1318
1330
x, y = map(float, s.split(b";"))
1319
1331
return Point(x, y)
1320
1332
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:
1325
1336
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.
1327
1342
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:
1332
1344
1333
1345
.. literalinclude :: ../includes/sqlite3/converter_point.py
1334
1346
@@ -1362,6 +1374,52 @@ timestamp converter.
1362
1374
offsets in timestamps, either leave converters disabled, or register an
1363
1375
offset-aware converter with :func: `register_converter `.
1364
1376
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
+
1365
1423
.. _sqlite3-controlling-transactions :
1366
1424
1367
1425
Controlling Transactions
0 commit comments