blob: 8c80eb66642ea474ae051c54883fbfb3d79b46a5 [file] [log] [blame]
Thomas Wouters477c8d52006-05-27 19:21:47 +00001\section{\module{sqlite3} ---
2 DB-API 2.0 interface for SQLite databases}
3
4\declaremodule{builtin}{sqlite3}
5\modulesynopsis{A DB-API 2.0 implementation using SQLite 3.x.}
6\sectionauthor{Gerhard Häring}{gh@ghaering.de}
7\versionadded{2.5}
8
9\subsection{Module functions and constants\label{sqlite3-Module-Contents}}
10
11\begin{datadesc}{PARSE_DECLTYPES}
12This constant is meant to be used with the \var{detect_types} parameter of the
13\function{connect} function.
14
15Setting it makes the \module{sqlite3} module parse the declared type for each column it
16returns. It will parse out the first word of the declared type, i. e. for
17"integer primary key", it will parse out "integer". Then for that column, it
18will look into the converters dictionary and use the converter function
19registered for that type there. Converter names are case-sensitive!
20\end{datadesc}
21
22
23\begin{datadesc}{PARSE_COLNAMES}
24This constant is meant to be used with the \var{detect_types} parameter of the
25\function{connect} function.
26
27Setting this makes the SQLite interface parse the column name for each column
28it returns. It will look for a string formed [mytype] in there, and then
29decide that 'mytype' is the type of the column. It will try to find an entry of
30'mytype' in the converters dictionary and then use the converter function found
31there to return the value. The column name found in \member{cursor.description} is only
32the first word of the column name, i. e. if you use something like
33\code{'as "x [datetime]"'} in your SQL, then we will parse out everything until the
34first blank for the column name: the column name would simply be "x".
35\end{datadesc}
36
37\begin{funcdesc}{connect}{database\optional{, timeout, isolation_level, detect_types, factory}}
38Opens a connection to the SQLite database file \var{database}. You can use
39\code{":memory:"} to open a database connection to a database that resides in
40RAM instead of on disk.
41
42When a database is accessed by multiple connections, and one of the processes
43modifies the database, the SQLite database is locked until that transaction is
44committed. The \var{timeout} parameter specifies how long the connection should
45wait for the lock to go away until raising an exception. The default for the
46timeout parameter is 5.0 (five seconds).
47
48For the \var{isolation_level} parameter, please see \member{isolation_level}
49\ref{sqlite3-Connection-IsolationLevel} property of \class{Connection} objects.
50
51SQLite natively supports only the types TEXT, INTEGER, FLOAT, BLOB and NULL. If
52you want to use other types, like you have to add support for them yourself.
53The \var{detect_types} parameter and the using custom \strong{converters} registered with
54the module-level \function{register_converter} function allow you to easily do that.
55
56\var{detect_types} defaults to 0 (i. e. off, no type detection), you can set it
57to any combination of \constant{PARSE_DECLTYPES} and \constant{PARSE_COLNAMES} to turn type
58detection on.
59
60By default, the \module{sqlite3} module uses its \class{Connection} class for the
61connect call. You can, however, subclass the \class{Connection} class and make
62\function{connect} use your class instead by providing your class for the
63\var{factory} parameter.
64
65Consult the section \ref{sqlite3-Types} of this manual for details.
66
67The \module{sqlite3} module internally uses a statement cache to avoid SQL parsing
68overhead. If you want to explicitly set the number of statements that are
69cached for the connection, you can set the \var{cached_statements} parameter.
70The currently implemented default is to cache 100 statements.
71\end{funcdesc}
72
73\begin{funcdesc}{register_converter}{typename, callable}
74Registers a callable to convert a bytestring from the database into a custom
75Python type. The callable will be invoked for all database values that are of
76the type \var{typename}. Confer the parameter \var{detect_types} of the
77\function{connect} function for how the type detection works. Note that the case of
78\var{typename} and the name of the type in your query must match!
79\end{funcdesc}
80
81\begin{funcdesc}{register_adapter}{type, callable}
82Registers a callable to convert the custom Python type \var{type} into one of
83SQLite's supported types. The callable \var{callable} accepts as single
84parameter the Python value, and must return a value of the following types:
85int, long, float, str (UTF-8 encoded), unicode or buffer.
86\end{funcdesc}
87
88\begin{funcdesc}{complete_statement}{sql}
89Returns \constant{True} if the string \var{sql} one or more complete SQL
90statements terminated by semicolons. It does not verify if the SQL is
91syntactically correct, only if there are no unclosed string literals and if the
92statement is terminated by a semicolon.
93
94This can be used to build a shell for SQLite, like in the following example:
95
96 \verbatiminput{sqlite3/complete_statement.py}
97\end{funcdesc}
98
99\subsection{Connection Objects \label{sqlite3-Connection-Objects}}
100
101A \class{Connection} instance has the following attributes and methods:
102
103\label{sqlite3-Connection-IsolationLevel}
104\begin{memberdesc}{isolation_level}
105 Get or set the current isolation level. None for autocommit mode or one of
106 "DEFERRED", "IMMEDIATE" or "EXLUSIVE". See Controlling Transactions
107 \ref{sqlite3-Controlling-Transactions} for a more detailed explanation.
108\end{memberdesc}
109
110\begin{methoddesc}{cursor}{\optional{cursorClass}}
111 The cursor method accepts a single optional parameter \var{cursorClass}.
112 This is a custom cursor class which must extend \class{sqlite3.Cursor}.
113\end{methoddesc}
114
115\begin{methoddesc}{execute}{sql, \optional{parameters}}
116This is a nonstandard shortcut that creates an intermediate cursor object by
117calling the cursor method, then calls the cursor's \method{execute} method with the
118parameters given.
119\end{methoddesc}
120
121\begin{methoddesc}{executemany}{sql, \optional{parameters}}
122This is a nonstandard shortcut that creates an intermediate cursor object by
123calling the cursor method, then calls the cursor's \method{executemany} method with the
124parameters given.
125\end{methoddesc}
126
127\begin{methoddesc}{executescript}{sql_script}
128This is a nonstandard shortcut that creates an intermediate cursor object by
129calling the cursor method, then calls the cursor's \method{executescript} method with the
130parameters given.
131\end{methoddesc}
132
133\begin{methoddesc}{create_function}{name, num_params, func}
134
135Creates a user-defined function that you can later use from within SQL
136statements under the function name \var{name}. \var{num_params} is the number
137of parameters the function accepts, and \var{func} is a Python callable that is
138called as SQL function.
139
140The function can return any of the types supported by SQLite: unicode, str,
141int, long, float, buffer and None. Exceptions in the function are ignored and
142they are handled as if the function returned None.
143
144Example:
145
146 \verbatiminput{sqlite3/md5func.py}
147\end{methoddesc}
148
149\begin{methoddesc}{create_aggregate}{name, num_params, aggregate_class}
150
151Creates a user-defined aggregate function.
152
153The aggregate class must implement a \code{step} method, which accepts the
154number of parameters \var{num_params}, and a \code{finalize} method which
155will return the final result of the aggregate.
156
157The \code{finalize} method can return any of the types supported by SQLite:
158unicode, str, int, long, float, buffer and None. Any exceptions are ignored.
159
160Example:
161
162 \verbatiminput{sqlite3/mysumaggr.py}
163\end{methoddesc}
164
165\begin{methoddesc}{create_collation}{name, callable}
166
167Creates a collation with the specified \var{name} and \var{callable}. The
168callable will be passed two string arguments. It should return -1 if the first
169is ordered lower than the second, 0 if they are ordered equal and 1 and if the
170first is ordered higher than the second. Note that this controls sorting
171(ORDER BY in SQL) so your comparisons don't affect other SQL operations.
172
173Note that the callable will get its parameters as Python bytestrings, which
174will normally be encoded in UTF-8.
175
176The following example shows a custom collation that sorts "the wrong way":
177
178 \verbatiminput{sqlite3/collation_reverse.py}
179
180To remove a collation, call \code{create_collation} with None as callable:
181
182\begin{verbatim}
183 con.create_collation("reverse", None)
184\end{verbatim}
185\end{methoddesc}
186
187
188\begin{memberdesc}{row_factory}
189 You can change this attribute to a callable that accepts the cursor and
190 the original row as tuple and will return the real result row. This
191 way, you can implement more advanced ways of returning results, like
192 ones that can also access columns by name.
193
194 Example:
195
196 \verbatiminput{sqlite3/row_factory.py}
197
198 If the standard tuple types don't suffice for you, and you want name-based
199 access to columns, you should consider setting \member{row_factory} to the
200 highly-optimized sqlite3.Row type. It provides both
201 index-based and case-insensitive name-based access to columns with almost
202 no memory overhead. Much better than your own custom dictionary-based
203 approach or even a db_row based solution.
204\end{memberdesc}
205
206\begin{memberdesc}{text_factory}
207 Using this attribute you can control what objects are returned for the
208 TEXT data type. By default, this attribute is set to \class{unicode} and
209 the \module{sqlite3} module will return Unicode objects for TEXT. If you want to return
210 bytestrings instead, you can set it to \class{str}.
211
212 For efficiency reasons, there's also a way to return Unicode objects only
213 for non-ASCII data, and bytestrings otherwise. To activate it, set this
214 attribute to \constant{sqlite3.OptimizedUnicode}.
215
216 You can also set it to any other callable that accepts a single bytestring
217 parameter and returns the result object.
218
219 See the following example code for illustration:
220
221 \verbatiminput{sqlite3/text_factory.py}
222\end{memberdesc}
223
224\begin{memberdesc}{total_changes}
225 Returns the total number of database rows that have be modified, inserted,
226 or deleted since the database connection was opened.
227\end{memberdesc}
228
229
230
231
232
233\subsection{Cursor Objects \label{sqlite3-Cursor-Objects}}
234
235A \class{Cursor} instance has the following attributes and methods:
236
237\begin{methoddesc}{execute}{sql, \optional{parameters}}
238
239Executes a SQL statement. The SQL statement may be parametrized (i. e.
240placeholders instead of SQL literals). The \module{sqlite3} module supports two kinds of
241placeholders: question marks (qmark style) and named placeholders (named
242style).
243
244This example shows how to use parameters with qmark style:
245
246 \verbatiminput{sqlite3/execute_1.py}
247
248This example shows how to use the named style:
249
250 \verbatiminput{sqlite3/execute_2.py}
251
252 \method{execute} will only execute a single SQL statement. If you try to
253 execute more than one statement with it, it will raise a Warning. Use
254 \method{executescript} if want to execute multiple SQL statements with one
255 call.
256\end{methoddesc}
257
258
259\begin{methoddesc}{executemany}{sql, seq_of_parameters}
260Executes a SQL command against all parameter sequences or mappings found in the
261sequence \var{sql}. The \module{sqlite3} module also allows
262to use an iterator yielding parameters instead of a sequence.
263
264\verbatiminput{sqlite3/executemany_1.py}
265
266Here's a shorter example using a generator:
267
268\verbatiminput{sqlite3/executemany_2.py}
269\end{methoddesc}
270
271\begin{methoddesc}{executescript}{sql_script}
272
273This is a nonstandard convenience method for executing multiple SQL statements
274at once. It issues a COMMIT statement before, then executes the SQL script it
275gets as a parameter.
276
277\var{sql_script} can be a bytestring or a Unicode string.
278
279Example:
280
281\verbatiminput{sqlite3/executescript.py}
282\end{methoddesc}
283
284\begin{memberdesc}{rowcount}
285 Although the \class{Cursor} class of the \module{sqlite3} module implements this
286 attribute, the database engine's own support for the determination of "rows
287 affected"/"rows selected" is quirky.
288
289 For \code{SELECT} statements, \member{rowcount} is always None because we cannot
290 determine the number of rows a query produced until all rows were fetched.
291
292 For \code{DELETE} statements, SQLite reports \member{rowcount} as 0 if you make a
293 \code{DELETE FROM table} without any condition.
294
295 For \method{executemany} statements, the number of modifications are summed
296 up into \member{rowcount}.
297
298 As required by the Python DB API Spec, the \member{rowcount} attribute "is -1
299 in case no executeXX() has been performed on the cursor or the rowcount
300 of the last operation is not determinable by the interface".
301\end{memberdesc}
302
303\subsection{SQLite and Python types\label{sqlite3-Types}}
304
305\subsubsection{Introduction}
306
307SQLite natively supports the following types: NULL, INTEGER, REAL, TEXT, BLOB.
308
309The following Python types can thus be sent to SQLite without any problem:
310
311\begin{tableii} {c|l}{code}{Python type}{SQLite type}
312\lineii{None}{NULL}
313\lineii{int}{INTEGER}
314\lineii{long}{INTEGER}
315\lineii{float}{REAL}
316\lineii{str (UTF8-encoded)}{TEXT}
317\lineii{unicode}{TEXT}
318\lineii{buffer}{BLOB}
319\end{tableii}
320
321This is how SQLite types are converted to Python types by default:
322
323\begin{tableii} {c|l}{code}{SQLite type}{Python type}
324\lineii{NULL}{None}
325\lineii{INTEGER}{int or long, depending on size}
326\lineii{REAL}{float}
327\lineii{TEXT}{depends on text_factory, unicode by default}
328\lineii{BLOB}{buffer}
329\end{tableii}
330
331The type system of the \module{sqlite3} module is extensible in both ways: you can store
332additional Python types in a SQLite database via object adaptation, and you can
333let the \module{sqlite3} module convert SQLite types to different Python types via
334converters.
335
336\subsubsection{Using adapters to store additional Python types in SQLite databases}
337
338Like described before, SQLite supports only a limited set of types natively. To
339use other Python types with SQLite, you must \strong{adapt} them to one of the sqlite3
340module's supported types for SQLite. So, one of NoneType, int, long, float,
341str, unicode, buffer.
342
343The \module{sqlite3} module uses the Python object adaptation, like described in PEP 246
344for this. The protocol to use is \class{PrepareProtocol}.
345
346There are two ways to enable the \module{sqlite3} module to adapt a custom Python type
347to one of the supported ones.
348
349\paragraph{Letting your object adapt itself}
350
351This is a good approach if you write the class yourself. Let's suppose you have
352a class like this:
353
354\begin{verbatim}
355class Point(object):
356 def __init__(self, x, y):
357 self.x, self.y = x, y
358\end{verbatim}
359
360Now you want to store the point in a single SQLite column. You'll have to
361choose one of the supported types first that you use to represent the point in.
362Let's just use str and separate the coordinates using a semicolon. Then you
363need to give your class a method \code{__conform__(self, protocol)} which must
364return the converted value. The parameter \var{protocol} will be
365\class{PrepareProtocol}.
366
367\verbatiminput{sqlite3/adapter_point_1.py}
368
369\paragraph{Registering an adapter callable}
370
371The other possibility is to create a function that converts the type to the
372string representation and register the function with \method{register_adapter}.
373
374 \verbatiminput{sqlite3/adapter_point_2.py}
375
376\begin{notice}
377The type/class to adapt must be a new-style class, i. e. it must have
378\class{object} as one of its bases.
379\end{notice}
380
381The \module{sqlite3} module has two default adapters for Python's builtin
382\class{datetime.date} and \class{datetime.datetime} types. Now let's suppose we
383want to store \class{datetime.datetime} objects not in ISO representation, but
384as Unix timestamp.
385
386 \verbatiminput{sqlite3/adapter_datetime.py}
387
388\subsubsection{Converting SQLite values to custom Python types}
389
390Now that's all nice and dandy that you can send custom Python types to SQLite.
391But to make it really useful we need to make the Python to SQLite to Python
392roundtrip work.
393
394Enter converters.
395
396Let's go back to the Point class. We stored the x and y coordinates separated
397via semicolons as strings in SQLite.
398
399Let's first define a converter function that accepts the string as a parameter and constructs a Point object from it.
400
401\begin{notice}
402Converter functions \strong{always} get called with a string, no matter
403under which data type you sent the value to SQLite.
404\end{notice}
405
406\begin{notice}
407Converter names are looked up in a case-sensitive manner.
408\end{notice}
409
410
411\begin{verbatim}
412 def convert_point(s):
413 x, y = map(float, s.split(";"))
414 return Point(x, y)
415\end{verbatim}
416
417Now you need to make the \module{sqlite3} module know that what you select from the
418database is actually a point. There are two ways of doing this:
419
420\begin{itemize}
421 \item Implicitly via the declared type
422 \item Explicitly via the column name
423\end{itemize}
424
425Both ways are described at \ref{sqlite3-Module-Contents} in the text explaining
426the constants \constant{PARSE_DECLTYPES} and \constant{PARSE_COlNAMES}.
427
428
429The following example illustrates both ways.
430
431 \verbatiminput{sqlite3/converter_point.py}
432
433\subsubsection{Default adapters and converters}
434
435There are default adapters for the date and datetime types in the datetime
436module. They will be sent as ISO dates/ISO timestamps to SQLite.
437
438The default converters are registered under the name "date" for datetime.date
439and under the name "timestamp" for datetime.datetime.
440
441This way, you can use date/timestamps from Python without any additional
442fiddling in most cases. The format of the adapters is also compatible with the
443experimental SQLite date/time functions.
444
445The following example demonstrates this.
446
447 \verbatiminput{sqlite3/pysqlite_datetime.py}
448
449\subsection{Controlling Transactions \label{sqlite3-Controlling-Transactions}}
450
451By default, the \module{sqlite3} module opens transactions implicitly before a DML
452statement (INSERT/UPDATE/DELETE/REPLACE), and commits transactions implicitly
453before a non-DML, non-DQL statement (i. e. anything other than
454SELECT/INSERT/UPDATE/DELETE/REPLACE).
455
456So if you are within a transaction, and issue a command like \code{CREATE TABLE
457...}, \code{VACUUM}, \code{PRAGMA}, the \module{sqlite3} module will commit implicitly
458before executing that command. There are two reasons for doing that. The first
459is that some of these commands don't work within transactions. The other reason
460is that pysqlite needs to keep track of the transaction state (if a transaction
461is active or not).
462
463You can control which kind of "BEGIN" statements pysqlite implicitly executes
464(or none at all) via the \var{isolation_level} parameter to the
465\function{connect} call, or via the \member{isolation_level} property of
466connections.
467
468If you want \strong{autocommit mode}, then set \member{isolation_level} to None.
469
470Otherwise leave it at it's default, which will result in a plain "BEGIN"
471statement, or set it to one of SQLite's supported isolation levels: DEFERRED,
472IMMEDIATE or EXCLUSIVE.
473
474As the \module{sqlite3} module needs to keep track of the transaction state, you should
475not use \code{OR ROLLBACK} or \code{ON CONFLICT ROLLBACK} in your SQL. Instead,
476catch the \exception{IntegrityError} and call the \method{rollback} method of
477the connection yourself.
478
479\subsection{Using pysqlite efficiently}
480
481\subsubsection{Using shortcut methods}
482
483Using the nonstandard \method{execute}, \method{executemany} and
484\method{executescript} methods of the \class{Connection} object, your code can
485be written more concisely, because you don't have to create the - often
486superfluous \class{Cursor} objects explicitly. Instead, the \class{Cursor}
487objects are created implicitly and these shortcut methods return the cursor
488objects. This way, you can for example execute a SELECT statement and iterate
489over it directly using only a single call on the \class{Connection} object.
490
491 \verbatiminput{sqlite3/shortcut_methods.py}
492
493\subsubsection{Accessing columns by name instead of by index}
494
495One cool feature of the \module{sqlite3} module is the builtin \class{sqlite3.Row} class
496designed to be used as a row factory.
497
498Rows wrapped with this class can be accessed both by index (like tuples) and
499case-insensitively by name:
500
501 \verbatiminput{sqlite3/rowclass.py}
502
503