~ubuntu-branches/ubuntu/lucid/python-apsw/lucid

« back to all changes in this revision

Viewing changes to apsw.html

  • Committer: Bazaar Package Importer
  • Author(s): Joel Rosdahl
  • Date: 2008-07-07 20:24:11 UTC
  • mfrom: (1.1.5 upstream) (3.1.1 lenny)
  • Revision ID: james.westby@ubuntu.com-20080707202411-612ylo5p89y9ilvi
Tags: 3.5.9-r2-1
* New upstream release.
* Build dependency on libsqlite3-dev 3.5.9.
* Updated Standards-Version to 3.8.0.

Show diffs side-by-side

added added

removed removed

Lines of Context:
3
3
 
4
4
<html xmlns="http://www.w3.org/1999/xhtml">
5
5
<head>
6
 
  <meta name="generator" content=
7
 
  "HTML Tidy for Linux (vers 1 September 2005), see www.w3.org" />
 
6
  <meta name="generator" content="HTML Tidy for Linux (vers 6 November 2007), see www.w3.org" />
8
7
 
9
8
  <title>APSW - Another Python SQLite Wrapper</title>
10
 
<style type="text/css">
 
9
  <style type="text/css">
11
10
/*<![CDATA[*/
12
 
body { 
 
11
  body { 
13
12
  font-family: verdana, arial, helvetica, sans-serif;
14
13
  margin: 20px;
15
14
  background-color: #ffcc99;
16
15
  padding: 7px;
17
 
 }
18
 
/*]]>*/
19
 
</style>
 
16
  }
 
17
  .pynumber    { color: #0080C0;}
 
18
  .pyoperator  { color: #0000C0;}
 
19
  .pystring    { color: #004080;}
 
20
  .pycomment   { color: #008000;}
 
21
  .pyname      { color: #000000;}
 
22
  .pyerror     { color: #FF8080;}
 
23
  .pykeyword   { color: #C00000;}
 
24
  .pytext      { color: #000000;}
 
25
  .pyoutput    { color: #0000FF;}
 
26
  /*]]>*/
 
27
  </style>
20
28
</head>
21
29
 
22
30
<body>
23
31
  <h1 class="notoc">APSW - Another Python SQLite Wrapper</h1>
24
32
 
25
 
  <p><font size="-1">apsw-3.3.13-r1 18th February 2007</font></p>
26
 
 
27
 
  <p>APSW provides an SQLite 3 wrapper that provides the thinnest layer over
28
 
  <a href="http://www.sqlite.org">SQLite 3</a> possible. Everything you can do
29
 
  from the <a href="http://www.sqlite.org/capi3ref.html">C API</a> to SQLite 3,
30
 
  you can do from Python. Although APSW looks vaguely similar to the <a href=
31
 
  "http://www.python.org/peps/pep-0249.html">DBAPI</a>, it is <a href=
32
 
  "#dbapinotes">not compliant</a> with that API and instead works the way
33
 
  SQLite 3 does. (<a href="http://www.pysqlite.org">pysqlite</a> is DBAPI
34
 
  compliant - <a href="#pysqlitediffs">differences between apsw and pysqlite
35
 
  2</a>).</p>
36
 
 
37
 
  <blockquote>
38
 
    <p><b>Important changes in 3.3.10 release</b> You must explicitly call
39
 
    <a href="#Connection_class">close()</a> on Connection objects. If you do
40
 
    not call close then a detailed error message will be printed when
41
 
    Connection's destructor runs and cleanup will not happen of that
42
 
    connection. This is because it is not possible to raise Exceptions in
43
 
    destructors (actually it is, but Python just calls the destructor again
44
 
    which can result in an infinite loop). I did try to work around this, but
45
 
    with things like no control over which thread destructors run in, virtual
46
 
    tables, triggers, incomplete statements and SQLite's transaction control,
47
 
    it becomes impossible to cleanly close a connection if bits of code are
48
 
    returning errors. Using the close() method allows errors to be returned and
49
 
    it can be called again once they are fixed.</p>
50
 
 
51
 
    <p>All strings returned by APSW are now in Unicode. Previously strings that
52
 
    consisted only of ASCII characters where returned as the string type and
53
 
    other strings were returned as the unicode type. This did allow easy usage
54
 
    with other components that knew nothing of Unicode. However it could make
55
 
    Unicode aware software do more work.</p>
56
 
  </blockquote>
 
33
  <p><font size="-1">apsw-3.5.9-r2 6th July 2008</font> (Use with SQLite 3.5.9 or later, Python 2.3 or later including
 
34
  Python 3)</p>
 
35
 
 
36
  <p>APSW provides an SQLite 3 wrapper that provides the thinnest layer over <a href="http://www.sqlite.org">SQLite
 
37
  3</a> possible. Everything you can do from the <a href="http://www.sqlite.org/c3ref/intro.html">C API</a> to SQLite
 
38
  3, you can do from Python. Although APSW looks vaguely similar to the <a href=
 
39
  "http://www.python.org/peps/pep-0249.html">DBAPI</a>, it is <a href="#dbapinotes">not compliant</a> with that API and
 
40
  instead works the way SQLite 3 does. (<a href="http://www.pysqlite.org">pysqlite</a> is DBAPI compliant - <a href=
 
41
  "#pysqlitediffs">differences between apsw and pysqlite 2</a>).</p>
57
42
 
58
43
  <h1 class="notoc">Table of contents</h1>
59
44
 
60
 
  <table cellspacing="5" cellpadding="5">
 
45
  <table cellspacing="5" cellpadding="5" summary="Table of contents">
61
46
    <tr>
62
47
      <td valign="top">
63
48
        <!--toc-->
73
58
            </ul>
74
59
          </li>
75
60
 
76
 
          <li><a href="#SQLiteVersionCompatibilityAndBenchmarking">SQLite
77
 
          version compatibility and benchmarking</a></li>
 
61
          <li><a href="#SQLiteVersionCompatibilityAndBenchmarking">SQLite version compatibility and
 
62
          benchmarking</a></li>
78
63
 
79
64
          <li><a href="#Example">Example</a></li>
80
65
 
81
 
          <li><a href="#Building">Building</a></li>
 
66
          <li>
 
67
            <a href="#Building">Building</a>
 
68
 
 
69
            <ul>
 
70
              <li><a href="#Finding">Finding SQLite 3</a></li>
 
71
 
 
72
              <li><a href="#Recommended">Recommended</a></li>
 
73
            </ul>
 
74
          </li>
82
75
 
83
76
          <li>
84
77
            <a href="#APIReference">API Reference</a>
92
85
 
93
86
              <li><a href="#Connection_class">Connection class</a></li>
94
87
 
 
88
              <li><a href="#blobio">Blob I/O</a></li>
 
89
 
95
90
              <li><a href="#Cursor">Cursor class</a></li>
96
91
 
97
92
              <li><a href="#VirtualTables">Virtual Tables</a></li>
102
97
            <a href="#Exceptions">Exceptions</a>
103
98
 
104
99
            <ul>
105
 
              <li><a href="#augmentedstacktraces">Augmented stack
106
 
              traces</a></li>
 
100
              <li><a href="#augmentedstacktraces">Augmented stack traces</a></li>
107
101
            </ul>
108
102
          </li>
109
103
 
143
137
 
144
138
              <li><a href="#dpapitypes">Type objects</a></li>
145
139
 
146
 
              <li><a href="#dbapiextensions">Optional DB API
147
 
              Extensions</a></li>
 
140
              <li><a href="#dbapiextensions">Optional DB API Extensions</a></li>
148
141
            </ul>
149
142
          </li>
150
143
 
156
149
            <a href="#verhistory">Version History</a>
157
150
 
158
151
            <ul>
 
152
              <li><a href="#359r2">3.5.9-r2</a></li>
 
153
 
 
154
              <li><a href="#359r1">3.5.9-r1</a></li>
 
155
 
159
156
              <li><a href="#3313r1">3.3.13-r1</a></li>
160
157
 
161
158
              <li><a href="#3310r1">3.3.10-r1</a></li>
195
192
  <p>You can download this release in source or binary form.</p>
196
193
 
197
194
  <ul>
198
 
    <li><a href=
199
 
    "http://initd.org/pub/software/pysqlite/apsw/3.3.13-r1/apsw-3.3.13-r1.zip">apsw-3.3.13-r1.zip</a>
200
 
    (source)</li>
201
 
 
202
 
    <li><a href=
203
 
    "http://initd.org/pub/software/pysqlite/apsw/3.3.13-r1/apsw-3.3.13-r1.win32-py2.3">
204
 
    apsw-3.3.13-r1.win32-py2.3.exe</a> (Windows Python 2.3)</li>
205
 
 
206
 
    <li><a href=
207
 
    "http://initd.org/pub/software/pysqlite/apsw/3.3.13-r1/apsw-3.3.13-r1.win32-py2.4">
208
 
    apsw-3.3.13-r1.win32-py2.4.exe</a> (Windows Python 2.4)</li>
209
 
 
210
 
    <li><a href=
211
 
    "http://initd.org/pub/software/pysqlite/apsw/3.3.13-r1/apsw-3.3.13-r1.win32-py2.5">
212
 
    apsw-3.3.13-r1.win32-py2.5.exe</a> (Windows Python 2.5)</li>
 
195
 
 
196
    <li><a href="http://apsw.googlecode.com/files/apsw-3.5.9-r2.zip">apsw-3.5.9-r2.zip</a> (source)</li>
 
197
 
 
198
    <li><a href="http://apsw.googlecode.com/files/apsw-3.5.9-r2.win32-py2.3.exe">apsw-3.5.9-r2.win32-py2.3.exe</a>
 
199
    (Windows Python 2.3)</li>
 
200
 
 
201
    <li><a href="http://apsw.googlecode.com/files/apsw-3.5.9-r2.win32-py2.4.exe">apsw-3.5.9-r2.win32-py2.4.exe</a>
 
202
    (Windows Python 2.4)</li>
 
203
 
 
204
    <li><a href="http://apsw.googlecode.com/files/apsw-3.5.9-r2.win32-py2.5.exe">apsw-3.5.9-r2.win32-py2.5.exe</a>
 
205
    (Windows Python 2.5)</li>
213
206
  </ul>
214
207
 
215
 
  <p>Some Linux distributions also have packages. Debian users can grab the
216
 
  package <a href="http://packages.debian.org/python-apsw">python-apsw</a>.
217
 
  Gentoo users can grab the package <a href=
 
208
  <p>Some Linux distributions also have packages. Debian/Ubuntu users can grab the package <a href=
 
209
  "http://packages.debian.org/python-apsw">python-apsw</a>. Gentoo users can grab the package <a href=
218
210
  "http://www.gentoo-portage.com/dev-python/apsw">dev-python/apsw</a>.</p>
219
211
 
220
212
  <h2><a name="Sourcecode" id="Sourcecode">Source code control</a></h2>
221
213
 
222
 
  <p>The source is controlled by Subversion accessible as <a href=
223
 
  "http://initd.org/svn/pysqlite/apsw/trunk">http://initd.org/svn/pysqlite/apsw/trunk</a></p>
224
 
 
225
 
  <h1><a name="SQLiteVersionCompatibilityAndBenchmarking" id=
226
 
  "SQLiteVersionCompatibilityAndBenchmarking">SQLite version compatibility and
227
 
  benchmarking</a></h1>
228
 
 
229
 
  <p>APSW binds to the C interface of SQLite. That interface is stable for each
230
 
  major version of SQLite (ie the C interface for any SQLite 3.x is stable, but
231
 
  SQLite 4.x would be an incompatible change). Consequently you can use APSW
232
 
  against any revision of SQLite with the same major version number. There are
233
 
  small enhancements to the C api over time, and APSW adds support for them as
234
 
  appropriate. The version number of APSW covers the version these enhancements
235
 
  were added. The vast majority of changes to SQLite are in the SQL syntax and
236
 
  engine. Those will be picked up with any version of APSW. The one exception
237
 
  to this is experimental features in SQLite which may change API between
238
 
  revisions. Consequently you will need to turn them off if you want to work
239
 
  against a variety of versions of SQLite (see EXPERIMENTAL in
240
 
  <code>setup.py</code>). I strongly recommend you embed the SQLite library
241
 
  into APSW which will put you in control of versions.</p>
242
 
 
243
 
  <p>Before you do any benchmarking with APSW or other ways of accessing
244
 
  SQLite, you must understand how and when SQLite does transactions. See
245
 
  section 7.0, <i>Transaction Control At The SQL Level</i> of <a href=
246
 
  "http://sqlite.org/lockingv3.html">sqlite.org/lockingv3.html</a>. <b>APSW
247
 
  does not alter SQLite's behaviour with transactions.</b> Some access layers
248
 
  try to interpret your SQL and manage transactions behind your back, which may
249
 
  or may not work well with SQLite also do its own transactions. You should
250
 
  always manage your transactions yourself. For example to insert 1,000 rows
251
 
  wrap it in a single transaction else you will have 1,000 transactions. The
252
 
  best clue that you have one transaction per statement is having a maximum of
253
 
  60 statements per second. You need two drive rotations to do a transaction -
254
 
  the data has to be committed to the main file and the journal - and 7200 RPM
255
 
  drives do 120 rotations a second. On the other hand if you don't put in the
256
 
  transaction boundaries yourself and get more than 60 statements a second,
257
 
  then your access mechanism is silently starting transactions for you. This
258
 
  topic also comes up fairly frequently in the SQLite mailing list
259
 
  archives.</p>
 
214
  <p>The source is controlled by Subversion documented at <a href=
 
215
  "http://code.google.com/p/apsw/source/checkout">http://code.google.com/p/apsw/source/checkout</a></p>
 
216
 
 
217
  <h1><a name="SQLiteVersionCompatibilityAndBenchmarking" id="SQLiteVersionCompatibilityAndBenchmarking">SQLite version
 
218
  compatibility and benchmarking</a></h1>
 
219
 
 
220
  <p>APSW binds to the C interface of SQLite. That interface is stable for each major version of SQLite (ie the C
 
221
  interface for any SQLite 3.x is stable, but SQLite 4.x would be an incompatible change). Consequently you can use
 
222
  APSW against any revision of SQLite with the same major version number. There are small enhancements to the C api
 
223
  over time, and APSW adds support for them as appropriate. The version number of APSW covers the version these
 
224
  enhancements were added. The vast majority of changes to SQLite are in the SQL syntax and engine. Those will be
 
225
  picked up with any version of APSW. The one exception to this is experimental features in SQLite which may change API
 
226
  between revisions. Consequently you will need to turn them off if you want to work against a variety of versions of
 
227
  SQLite (see EXPERIMENTAL in <code>setup.py</code>). I strongly recommend you embed the SQLite library into APSW which
 
228
  will put you in control of versions.</p>
 
229
 
 
230
  <p>Before you do any benchmarking with APSW or other ways of accessing SQLite, you must understand how and when
 
231
  SQLite does transactions. See section 7.0, <i>Transaction Control At The SQL Level</i> of <a href=
 
232
  "http://sqlite.org/lockingv3.html">sqlite.org/lockingv3.html</a>. <b>APSW does not alter SQLite's behaviour with
 
233
  transactions.</b> Some access layers try to interpret your SQL and manage transactions behind your back, which may or
 
234
  may not work well with SQLite also do its own transactions. You should always manage your transactions yourself. For
 
235
  example to insert 1,000 rows wrap it in a single transaction else you will have 1,000 transactions. The best clue
 
236
  that you have one transaction per statement is having a maximum of 60 statements per second. You need two drive
 
237
  rotations to do a transaction - the data has to be committed to the main file and the journal - and 7200 RPM drives
 
238
  do 120 rotations a second. On the other hand if you don't put in the transaction boundaries yourself and get more
 
239
  than 60 statements a second, then your access mechanism is silently starting transactions for you. This topic also
 
240
  comes up fairly frequently in the SQLite mailing list archives.</p>
260
241
 
261
242
  <h1><a name="Example" id="Example">Example</a></h1>
262
243
 
263
 
  <p>This is an example of how to use apsw, and also demonstrates all the
264
 
  features.</p>
 
244
  <p>This is an example of how to use apsw, and also demonstrates all the features.</p>
265
245
 
266
246
  <blockquote>
267
247
    <pre>
268
248
<!--sourcestart-->
269
 
<font face="Lucida,Courier New"><font color=
270
 
"#C00000">import </font>os<font color="#0000C0">, </font>sys<font color=
271
 
"#0000C0">, </font>time
272
 
<font color="#C00000">import </font>apsw
 
249
<font face="Lucida,Courier New,monospace"><span class="pykeyword">import </span><span class=
 
250
"pyname">os</span><span class="pyoperator">, </span><span class="pyname">sys</span><span class=
 
251
"pyoperator">, </span><span class="pyname">time
 
252
</span><span class="pykeyword">import </span><span class="pyname">apsw
273
253
 
274
 
<font color="#008000">###
 
254
</span><span class="pycomment">###
275
255
### Check we have the expected version of apsw and sqlite
276
256
###
277
257
 
278
 
</font><font color="#C00000">print </font><font color=
279
 
"#004080">"Using APSW file"</font><font color=
280
 
"#0000C0">,</font>apsw<font color="#0000C0">.</font>__file__                <font color="#008000"># from the extension module
281
 
</font><font color="#C00000">print </font><font color=
282
 
"#004080">"   APSW version"</font><font color=
283
 
"#0000C0">,</font>apsw<font color="#0000C0">.</font>apswversion<font color=
284
 
"#0000C0">()           </font><font color="#008000"># from the extension module
285
 
</font><font color="#C00000">print </font><font color=
286
 
"#004080">" SQLite version"</font><font color=
287
 
"#0000C0">,</font>apsw<font color="#0000C0">.</font>sqlitelibversion<font color="#0000C0">()      </font><font color="#008000"># from the sqlite library code
288
 
</font><font color="#C00000">print </font><font color=
289
 
"#004080">" SQLite version"</font><font color=
290
 
"#0000C0">,</font>apsw<font color="#0000C0">.</font>SQLITE_VERSION_NUMBER   <font color="#008000"># from the sqlite header file at compile time
 
258
</span><span class="pykeyword">print </span><span class="pystring">"      Using APSW file"</span><span class=
 
259
"pyoperator">,</span><span class="pyname">apsw</span><span class="pyoperator">.</span><span class=
 
260
"pyname">__file__                </span><span class="pycomment"># from the extension module
 
261
</span><span class="pykeyword">print </span><span class="pystring">"         APSW version"</span><span class=
 
262
"pyoperator">,</span><span class="pyname">apsw</span><span class="pyoperator">.</span><span class=
 
263
"pyname">apswversion</span><span class="pyoperator">()           </span><span class=
 
264
"pycomment"># from the extension module
 
265
</span><span class="pykeyword">print </span><span class="pystring">"   SQLite lib version"</span><span class=
 
266
"pyoperator">,</span><span class="pyname">apsw</span><span class="pyoperator">.</span><span class=
 
267
"pyname">sqlitelibversion</span><span class="pyoperator">()      </span><span class=
 
268
"pycomment"># from the sqlite library code
 
269
</span><span class="pykeyword">print </span><span class="pystring">"SQLite header version"</span><span class=
 
270
"pyoperator">,</span><span class="pyname">apsw</span><span class="pyoperator">.</span><span class=
 
271
"pyname">SQLITE_VERSION_NUMBER   </span><span class="pycomment"># from the sqlite header file at compile time
291
272
 
292
 
</font><font color="blue">   Using APSW file /space/apsw/apsw.so
293
 
      APSW version 3.3.13-r1
294
 
    SQLite version 3.3.13
295
 
    SQLite version 3003013
296
 
</font>
297
 
<font color="#008000">###
 
273
</span><span class="pyoutput">         Using APSW file /space/apsw/apsw.so
 
274
            APSW version 3.5.9-r2
 
275
      SQLite lib version 3.5.9
 
276
   SQLite header version 3005009
 
277
</span>
 
278
<span class="pycomment">###
298
279
### Opening/creating database
299
280
###
300
281
 
301
 
</font><font color="#C00000">if </font>os<font color=
302
 
"#0000C0">.</font>path<font color="#0000C0">.</font>exists<font color=
303
 
"#0000C0">(</font><font color="#004080">"dbfile"</font><font color=
304
 
"#0000C0">): </font>os<font color="#0000C0">.</font>remove<font color=
305
 
"#0000C0">(</font><font color="#004080">"dbfile"</font><font color="#0000C0">)
306
 
</font>connection<font color="#0000C0">=</font>apsw<font color=
307
 
"#0000C0">.</font>Connection<font color="#0000C0">(</font><font color=
308
 
"#004080">"dbfile"</font><font color="#0000C0">)
309
 
</font>cursor<font color="#0000C0">=</font>connection<font color=
310
 
"#0000C0">.</font>cursor<font color="#0000C0">()
 
282
</span><span class="pykeyword">if </span><span class="pyname">os</span><span class="pyoperator">.</span><span class=
 
283
"pyname">path</span><span class="pyoperator">.</span><span class="pyname">exists</span><span class=
 
284
"pyoperator">(</span><span class="pystring">"dbfile"</span><span class="pyoperator">): </span><span class=
 
285
"pyname">os</span><span class="pyoperator">.</span><span class="pyname">remove</span><span class=
 
286
"pyoperator">(</span><span class="pystring">"dbfile"</span><span class="pyoperator">)
 
287
</span><span class="pyname">connection</span><span class="pyoperator">=</span><span class=
 
288
"pyname">apsw</span><span class="pyoperator">.</span><span class="pyname">Connection</span><span class=
 
289
"pyoperator">(</span><span class="pystring">"dbfile"</span><span class="pyoperator">)
 
290
</span><span class="pyname">cursor</span><span class="pyoperator">=</span><span class=
 
291
"pyname">connection</span><span class="pyoperator">.</span><span class="pyname">cursor</span><span class=
 
292
"pyoperator">()
311
293
 
312
 
</font><font color="#008000">###
 
294
</span><span class="pycomment">###
313
295
### simple statement
314
296
###
315
297
 
316
 
</font>cursor<font color="#0000C0">.</font>execute<font color=
317
 
"#0000C0">(</font><font color=
318
 
"#004080">"create table foo(x,y,z)"</font><font color="#0000C0">)
 
298
</span><span class="pyname">cursor</span><span class="pyoperator">.</span><span class=
 
299
"pyname">execute</span><span class="pyoperator">(</span><span class=
 
300
"pystring">"create table foo(x,y,z)"</span><span class="pyoperator">)
319
301
 
320
 
</font><font color="#008000">###
 
302
</span><span class="pycomment">###
321
303
### multiple statements
322
304
###
323
305
 
324
 
</font>cursor<font color="#0000C0">.</font>execute<font color=
325
 
"#0000C0">(</font><font color=
326
 
"#004080">"insert into foo values(1,2,3); create table bar(a,b,c) ; insert into foo values(4, 'five', 6.0)"</font><font color="#0000C0">)
 
306
</span><span class="pyname">cursor</span><span class="pyoperator">.</span><span class=
 
307
"pyname">execute</span><span class="pyoperator">(</span><span class=
 
308
"pystring">"insert into foo values(1,2,3); create table bar(a,b,c) ; insert into foo values(4, 'five', 6.0)"</span><span class="pyoperator">)
327
309
 
328
 
</font><font color="#008000">###
 
310
</span><span class="pycomment">###
329
311
### iterator
330
312
###
331
313
 
332
 
</font><font color="#C00000">for </font>x<font color=
333
 
"#0000C0">,</font>y<font color="#0000C0">,</font>z <font color=
334
 
"#C00000">in </font>cursor<font color="#0000C0">.</font>execute<font color=
335
 
"#0000C0">(</font><font color=
336
 
"#004080">"select x,y,z from foo"</font><font color="#0000C0">):
337
 
    </font><font color="#C00000">print </font>cursor<font color=
338
 
"#0000C0">.</font>getdescription<font color="#0000C0">()  </font><font color=
339
 
"#008000"># shows column names and declared types
340
 
    </font><font color="#C00000">print </font>x<font color=
341
 
"#0000C0">,</font>y<font color="#0000C0">,</font>z
 
314
</span><span class="pykeyword">for </span><span class="pyname">x</span><span class="pyoperator">,</span><span class=
 
315
"pyname">y</span><span class="pyoperator">,</span><span class="pyname">z </span><span class=
 
316
"pykeyword">in </span><span class="pyname">cursor</span><span class="pyoperator">.</span><span class=
 
317
"pyname">execute</span><span class="pyoperator">(</span><span class=
 
318
"pystring">"select x,y,z from foo"</span><span class="pyoperator">):
 
319
    </span><span class="pykeyword">print </span><span class="pyname">cursor</span><span class=
 
320
"pyoperator">.</span><span class="pyname">getdescription</span><span class="pyoperator">()  </span><span class=
 
321
"pycomment"># shows column names and declared types
 
322
    </span><span class="pykeyword">print </span><span class="pyname">x</span><span class=
 
323
"pyoperator">,</span><span class="pyname">y</span><span class="pyoperator">,</span><span class="pyname">z
342
324
 
343
 
<font color="#008000">###        
 
325
</span><span class="pycomment">###        
344
326
### iterator - multiple statements
345
327
###
346
328
 
347
 
</font><font color="#C00000">for </font>m<font color=
348
 
"#0000C0">,</font>n<font color="#0000C0">,</font>o <font color=
349
 
"#C00000">in </font>cursor<font color="#0000C0">.</font>execute<font color=
350
 
"#0000C0">(</font><font color=
351
 
"#004080">"select x,y,z from foo ; select a,b,c from bar"</font><font color=
352
 
"#0000C0">):
353
 
    </font><font color="#C00000">print </font>m<font color=
354
 
"#0000C0">,</font>n<font color="#0000C0">,</font>o
 
329
</span><span class="pykeyword">for </span><span class="pyname">m</span><span class="pyoperator">,</span><span class=
 
330
"pyname">n</span><span class="pyoperator">,</span><span class="pyname">o </span><span class=
 
331
"pykeyword">in </span><span class="pyname">cursor</span><span class="pyoperator">.</span><span class=
 
332
"pyname">execute</span><span class="pyoperator">(</span><span class=
 
333
"pystring">"select x,y,z from foo ; select a,b,c from bar"</span><span class="pyoperator">):
 
334
    </span><span class="pykeyword">print </span><span class="pyname">m</span><span class=
 
335
"pyoperator">,</span><span class="pyname">n</span><span class="pyoperator">,</span><span class="pyname">o
355
336
 
356
 
<font color="#008000">###
 
337
</span><span class="pycomment">###
357
338
### bindings - sequence
358
339
###
359
340
 
360
 
</font>cursor<font color="#0000C0">.</font>execute<font color=
361
 
"#0000C0">(</font><font color=
362
 
"#004080">"insert into foo values(?,?,?)"</font><font color=
363
 
"#0000C0">, (</font><font color="#0080C0">7</font><font color=
364
 
"#0000C0">, </font><font color="#004080">'eight'</font><font color=
365
 
"#0000C0">, </font>False<font color="#0000C0">))
366
 
</font>cursor<font color="#0000C0">.</font>execute<font color=
367
 
"#0000C0">(</font><font color=
368
 
"#004080">"insert into foo values(?,?,?1)"</font><font color=
369
 
"#0000C0">, (</font><font color="#004080">'one'</font><font color=
370
 
"#0000C0">, </font><font color="#004080">'two'</font><font color=
371
 
"#0000C0">))  </font><font color="#008000"># nb sqlite does the numbers from 1
 
341
</span><span class="pyname">cursor</span><span class="pyoperator">.</span><span class=
 
342
"pyname">execute</span><span class="pyoperator">(</span><span class=
 
343
"pystring">"insert into foo values(?,?,?)"</span><span class="pyoperator">, (</span><span class=
 
344
"pynumber">7</span><span class="pyoperator">, </span><span class="pystring">'eight'</span><span class=
 
345
"pyoperator">, </span><span class="pyname">False</span><span class="pyoperator">))
 
346
</span><span class="pyname">cursor</span><span class="pyoperator">.</span><span class=
 
347
"pyname">execute</span><span class="pyoperator">(</span><span class=
 
348
"pystring">"insert into foo values(?,?,?1)"</span><span class="pyoperator">, (</span><span class=
 
349
"pystring">'one'</span><span class="pyoperator">, </span><span class="pystring">'two'</span><span class=
 
350
"pyoperator">))  </span><span class="pycomment"># nb sqlite does the numbers from 1
372
351
 
373
352
###
374
353
### bindings - dictionary
375
354
###
376
355
 
377
 
</font>cursor<font color="#0000C0">.</font>execute<font color=
378
 
"#0000C0">(</font><font color=
379
 
"#004080">"insert into foo values(:alpha, :beta, :gamma)"</font><font color=
380
 
"#0000C0">, {</font><font color="#004080">'alpha'</font><font color=
381
 
"#0000C0">: </font><font color="#0080C0">1</font><font color=
382
 
"#0000C0">, </font><font color="#004080">'beta'</font><font color=
383
 
"#0000C0">: </font><font color="#0080C0">2</font><font color=
384
 
"#0000C0">, </font><font color="#004080">'gamma'</font><font color=
385
 
"#0000C0">: </font><font color="#004080">'three'</font><font color="#0000C0">})
 
356
</span><span class="pyname">cursor</span><span class="pyoperator">.</span><span class=
 
357
"pyname">execute</span><span class="pyoperator">(</span><span class=
 
358
"pystring">"insert into foo values(:alpha, :beta, :gamma)"</span><span class="pyoperator">, {</span><span class=
 
359
"pystring">'alpha'</span><span class="pyoperator">: </span><span class="pynumber">1</span><span class=
 
360
"pyoperator">, </span><span class="pystring">'beta'</span><span class="pyoperator">: </span><span class=
 
361
"pynumber">2</span><span class="pyoperator">, </span><span class="pystring">'gamma'</span><span class=
 
362
"pyoperator">: </span><span class="pystring">'three'</span><span class="pyoperator">})
386
363
 
387
 
</font><font color="#008000">###
 
364
</span><span class="pycomment">###
388
365
### <a name="example-exectrace" id="example-exectrace">tracing execution</a> 
389
366
###
390
367
 
391
 
</font><font color="#C00000">def </font>mytrace<font color=
392
 
"#0000C0">(</font>statement<font color="#0000C0">, </font>bindings<font color=
393
 
"#0000C0">):
394
 
    </font><font color="#004080">"Called just before executing each statement"
395
 
    </font><font color="#C00000">print </font><font color=
396
 
"#004080">"SQL:"</font><font color="#0000C0">,</font>statement
397
 
    <font color="#C00000">if </font>bindings<font color="#0000C0">:
398
 
        </font><font color="#C00000">print </font><font color=
399
 
"#004080">"Bindings:"</font><font color="#0000C0">,</font>bindings
400
 
    <font color="#C00000">return </font>True  <font color=
401
 
"#008000"># if you return False then execution is aborted
402
 
 
403
 
</font>cursor<font color="#0000C0">.</font>setexectrace<font color=
404
 
"#0000C0">(</font>mytrace<font color="#0000C0">)
405
 
</font>cursor<font color="#0000C0">.</font>execute<font color=
406
 
"#0000C0">(</font><font color=
407
 
"#004080">"drop table bar ; create table bar(x,y,z); select * from foo where x=?"</font><font color="#0000C0">, (</font><font color="#0080C0">3</font><font color="#0000C0">,))
408
 
 
409
 
</font><font color="blue">   SQL: drop table bar ;
 
368
</span><span class="pykeyword">def </span><span class="pyname">mytrace</span><span class=
 
369
"pyoperator">(</span><span class="pyname">statement</span><span class="pyoperator">, </span><span class=
 
370
"pyname">bindings</span><span class="pyoperator">):
 
371
    </span><span class="pystring">"Called just before executing each statement"
 
372
    </span><span class="pykeyword">print </span><span class="pystring">"SQL:"</span><span class=
 
373
"pyoperator">,</span><span class="pyname">statement
 
374
    </span><span class="pykeyword">if </span><span class="pyname">bindings</span><span class="pyoperator">:
 
375
        </span><span class="pykeyword">print </span><span class="pystring">"Bindings:"</span><span class=
 
376
"pyoperator">,</span><span class="pyname">bindings
 
377
    </span><span class="pykeyword">return </span><span class="pyname">True  </span><span class=
 
378
"pycomment"># if you return False then execution is aborted
 
379
 
 
380
</span><span class="pyname">cursor</span><span class="pyoperator">.</span><span class=
 
381
"pyname">setexectrace</span><span class="pyoperator">(</span><span class="pyname">mytrace</span><span class=
 
382
"pyoperator">)
 
383
</span><span class="pyname">cursor</span><span class="pyoperator">.</span><span class=
 
384
"pyname">execute</span><span class="pyoperator">(</span><span class=
 
385
"pystring">"drop table bar ; create table bar(x,y,z); select * from foo where x=?"</span><span class=
 
386
"pyoperator">, (</span><span class="pynumber">3</span><span class="pyoperator">,))
 
387
 
 
388
</span><span class="pyoutput">   SQL: drop table bar ;
410
389
   SQL:  create table bar(x,y,z);
411
390
   SQL:  select * from foo where x=?
412
391
   Bindings: (3,)
413
 
</font>
414
 
<font color="#008000">###
 
392
</span>
 
393
<span class="pycomment">###
415
394
### <a name="example-rowtrace" id="example-rowtrace">tracing results</a> 
416
395
###
417
396
 
418
 
</font><font color="#C00000">def </font>rowtrace<font color=
419
 
"#0000C0">(*</font>results<font color="#0000C0">):
420
 
    </font><font color=
421
 
"#004080">"""Called with each row of results before they are handed off.  You can return None to
 
397
</span><span class="pykeyword">def </span><span class="pyname">rowtrace</span><span class=
 
398
"pyoperator">(*</span><span class="pyname">results</span><span class="pyoperator">):
 
399
    </span><span class=
 
400
"pystring">"""Called with each row of results before they are handed off.  You can return None to
422
401
    cause the row to be skipped or a different set of values to return"""
423
 
    </font><font color="#C00000">print </font><font color=
424
 
"#004080">"Row:"</font><font color="#0000C0">,</font>results
425
 
    <font color="#C00000">return </font>results
426
 
 
427
 
cursor<font color="#0000C0">.</font>setrowtrace<font color=
428
 
"#0000C0">(</font>rowtrace<font color="#0000C0">)
429
 
</font><font color="#C00000">for </font>row <font color=
430
 
"#C00000">in </font>cursor<font color="#0000C0">.</font>execute<font color=
431
 
"#0000C0">(</font><font color=
432
 
"#004080">"select x,y from foo where x&gt;3"</font><font color="#0000C0">):
433
 
     </font><font color="#C00000">pass
434
 
 
435
 
</font><font color="blue">   SQL: select x,y from foo where x&gt;3
436
 
   Row: (4, u'five')
437
 
   Row: (7, u'eight')
 
402
    </span><span class="pykeyword">print </span><span class="pystring">"Row:"</span><span class=
 
403
"pyoperator">,</span><span class="pyname">results
 
404
    </span><span class="pykeyword">return </span><span class="pyname">results
 
405
 
 
406
cursor</span><span class="pyoperator">.</span><span class="pyname">setrowtrace</span><span class=
 
407
"pyoperator">(</span><span class="pyname">rowtrace</span><span class="pyoperator">)
 
408
</span><span class="pykeyword">for </span><span class="pyname">row </span><span class=
 
409
"pykeyword">in </span><span class="pyname">cursor</span><span class="pyoperator">.</span><span class=
 
410
"pyname">execute</span><span class="pyoperator">(</span><span class=
 
411
"pystring">"select x,y from foo where x&gt;3"</span><span class="pyoperator">):
 
412
     </span><span class="pykeyword">pass
 
413
 
 
414
</span><span class="pyoutput">   SQL: select x,y from foo where x&gt;3
 
415
   Row: (4L, u'five')
 
416
   Row: (7L, u'eight')
438
417
   Row: (u'one', u'two')
439
 
</font>
440
 
<font color="#008000"># Clear tracers
441
 
</font>cursor<font color="#0000C0">.</font>setrowtrace<font color=
442
 
"#0000C0">(</font>None<font color="#0000C0">)
443
 
</font>cursor<font color="#0000C0">.</font>setexectrace<font color=
444
 
"#0000C0">(</font>None<font color="#0000C0">)
 
418
</span>
 
419
<span class="pycomment"># Clear tracers
 
420
</span><span class="pyname">cursor</span><span class="pyoperator">.</span><span class=
 
421
"pyname">setrowtrace</span><span class="pyoperator">(</span><span class="pyname">None</span><span class="pyoperator">)
 
422
</span><span class="pyname">cursor</span><span class="pyoperator">.</span><span class=
 
423
"pyname">setexectrace</span><span class="pyoperator">(</span><span class="pyname">None</span><span class="pyoperator">)
445
424
 
446
 
</font><font color="#008000">###
 
425
</span><span class="pycomment">###
447
426
### executemany
448
427
###
449
428
 
450
429
# (This will work correctly with multiple statements, as well as statements that
451
430
# return data.  The second argument can be anything that is iterable.)
452
 
</font>cursor<font color="#0000C0">.</font>executemany<font color=
453
 
"#0000C0">(</font><font color=
454
 
"#004080">"insert into foo (x) values(?)"</font><font color=
455
 
"#0000C0">, ( [</font><font color="#0080C0">1</font><font color=
456
 
"#0000C0">], [</font><font color="#0080C0">2</font><font color=
457
 
"#0000C0">], [</font><font color="#0080C0">3</font><font color="#0000C0">] ) )
458
 
 
459
 
</font><font color=
460
 
"#008000"># You can also use it for statements that return data
461
 
</font><font color="#C00000">for </font>row <font color=
462
 
"#C00000">in </font>cursor<font color="#0000C0">.</font>executemany<font color=
463
 
"#0000C0">(</font><font color=
464
 
"#004080">"select * from foo where x=?"</font><font color=
465
 
"#0000C0">, ( [</font><font color="#0080C0">1</font><font color=
466
 
"#0000C0">], [</font><font color="#0080C0">2</font><font color=
467
 
"#0000C0">], [</font><font color="#0080C0">3</font><font color="#0000C0">] ) ):
468
 
    </font><font color="#C00000">print </font>row
469
 
 
470
 
<font color="#008000">###
 
431
</span><span class="pyname">cursor</span><span class="pyoperator">.</span><span class=
 
432
"pyname">executemany</span><span class="pyoperator">(</span><span class=
 
433
"pystring">"insert into foo (x) values(?)"</span><span class="pyoperator">, ( [</span><span class=
 
434
"pynumber">1</span><span class="pyoperator">], [</span><span class="pynumber">2</span><span class=
 
435
"pyoperator">], [</span><span class="pynumber">3</span><span class="pyoperator">] ) )
 
436
 
 
437
</span><span class="pycomment"># You can also use it for statements that return data
 
438
</span><span class="pykeyword">for </span><span class="pyname">row </span><span class=
 
439
"pykeyword">in </span><span class="pyname">cursor</span><span class="pyoperator">.</span><span class=
 
440
"pyname">executemany</span><span class="pyoperator">(</span><span class=
 
441
"pystring">"select * from foo where x=?"</span><span class="pyoperator">, ( [</span><span class=
 
442
"pynumber">1</span><span class="pyoperator">], [</span><span class="pynumber">2</span><span class=
 
443
"pyoperator">], [</span><span class="pynumber">3</span><span class="pyoperator">] ) ):
 
444
    </span><span class="pykeyword">print </span><span class="pyname">row
 
445
 
 
446
</span><span class="pycomment">###
471
447
### defining your own functions
472
448
###
473
449
 
474
 
</font><font color="#C00000">def </font>ilove7<font color=
475
 
"#0000C0">(*</font>args<font color="#0000C0">):
476
 
    </font><font color="#004080">"a scalar function"
477
 
    </font><font color="#C00000">print </font><font color=
478
 
"#004080">"ilove7 got"</font><font color="#0000C0">,</font>args<font color=
479
 
"#0000C0">,</font><font color="#004080">"but I love 7"
480
 
    </font><font color="#C00000">return </font><font color="#0080C0">7
481
 
 
482
 
</font>connection<font color="#0000C0">.</font>createscalarfunction<font color=
483
 
"#0000C0">(</font><font color="#004080">"seven"</font><font color=
484
 
"#0000C0">, </font>ilove7<font color="#0000C0">)
485
 
 
486
 
</font><font color="#C00000">for </font>row <font color=
487
 
"#C00000">in </font>cursor<font color="#0000C0">.</font>execute<font color=
488
 
"#0000C0">(</font><font color=
489
 
"#004080">"select seven(x,y) from foo"</font><font color="#0000C0">):
490
 
    </font><font color="#C00000">print </font>row
491
 
 
492
 
<font color="#008000">###
 
450
</span><span class="pykeyword">def </span><span class="pyname">ilove7</span><span class=
 
451
"pyoperator">(*</span><span class="pyname">args</span><span class="pyoperator">):
 
452
    </span><span class="pystring">"a scalar function"
 
453
    </span><span class="pykeyword">print </span><span class="pystring">"ilove7 got"</span><span class=
 
454
"pyoperator">,</span><span class="pyname">args</span><span class="pyoperator">,</span><span class=
 
455
"pystring">"but I love 7"
 
456
    </span><span class="pykeyword">return </span><span class="pynumber">7
 
457
 
 
458
</span><span class="pyname">connection</span><span class="pyoperator">.</span><span class=
 
459
"pyname">createscalarfunction</span><span class="pyoperator">(</span><span class="pystring">"seven"</span><span class=
 
460
"pyoperator">, </span><span class="pyname">ilove7</span><span class="pyoperator">)
 
461
 
 
462
</span><span class="pykeyword">for </span><span class="pyname">row </span><span class=
 
463
"pykeyword">in </span><span class="pyname">cursor</span><span class="pyoperator">.</span><span class=
 
464
"pyname">execute</span><span class="pyoperator">(</span><span class=
 
465
"pystring">"select seven(x,y) from foo"</span><span class="pyoperator">):
 
466
    </span><span class="pykeyword">print </span><span class="pyname">row
 
467
 
 
468
</span><span class="pycomment">###
493
469
### aggregate functions are more complex
494
470
###
495
471
 
496
472
# here we return the longest item when represented as a string
497
473
 
498
 
</font><font color="#C00000">def </font>longeststep<font color=
499
 
"#0000C0">(</font>context<font color="#0000C0">, *</font>args<font color=
500
 
"#0000C0">):
501
 
    </font><font color=
502
 
"#004080">"are any of the arguments longer than our current candidate"
503
 
    </font><font color="#C00000">for </font>arg <font color=
504
 
"#C00000">in </font>args<font color="#0000C0">:
505
 
        </font><font color="#C00000">if </font>len<font color=
506
 
"#0000C0">( </font>str<font color="#0000C0">(</font>arg<font color=
507
 
"#0000C0">) ) &gt; </font>len<font color="#0000C0">( </font>context<font color=
508
 
"#0000C0">[</font><font color="#004080">'longest'</font><font color=
509
 
"#0000C0">] ):
510
 
            </font>context<font color="#0000C0">[</font><font color=
511
 
"#004080">'longest'</font><font color="#0000C0">]=</font>str<font color=
512
 
"#0000C0">(</font>arg<font color="#0000C0">)
513
 
 
514
 
</font><font color="#C00000">def </font>longestfinal<font color=
515
 
"#0000C0">(</font>context<font color="#0000C0">):
516
 
    </font><font color="#004080">"return the winner"
517
 
    </font><font color="#C00000">return </font>context<font color=
518
 
"#0000C0">[</font><font color="#004080">'longest'</font><font color="#0000C0">]
519
 
 
520
 
</font><font color="#C00000">def </font>longestfactory<font color="#0000C0">():
521
 
    </font><font color=
522
 
"#004080">"""called for a new query.  The first item returned can be
 
474
</span><span class="pykeyword">def </span><span class="pyname">longeststep</span><span class=
 
475
"pyoperator">(</span><span class="pyname">context</span><span class="pyoperator">, *</span><span class=
 
476
"pyname">args</span><span class="pyoperator">):
 
477
    </span><span class="pystring">"are any of the arguments longer than our current candidate"
 
478
    </span><span class="pykeyword">for </span><span class="pyname">arg </span><span class=
 
479
"pykeyword">in </span><span class="pyname">args</span><span class="pyoperator">:
 
480
        </span><span class="pykeyword">if </span><span class="pyname">len</span><span class=
 
481
"pyoperator">( </span><span class="pyname">str</span><span class="pyoperator">(</span><span class=
 
482
"pyname">arg</span><span class="pyoperator">) ) &gt; </span><span class="pyname">len</span><span class=
 
483
"pyoperator">( </span><span class="pyname">context</span><span class="pyoperator">[</span><span class=
 
484
"pystring">'longest'</span><span class="pyoperator">] ):
 
485
            </span><span class="pyname">context</span><span class="pyoperator">[</span><span class=
 
486
"pystring">'longest'</span><span class="pyoperator">]=</span><span class="pyname">str</span><span class=
 
487
"pyoperator">(</span><span class="pyname">arg</span><span class="pyoperator">)
 
488
 
 
489
</span><span class="pykeyword">def </span><span class="pyname">longestfinal</span><span class=
 
490
"pyoperator">(</span><span class="pyname">context</span><span class="pyoperator">):
 
491
    </span><span class="pystring">"return the winner"
 
492
    </span><span class="pykeyword">return </span><span class="pyname">context</span><span class=
 
493
"pyoperator">[</span><span class="pystring">'longest'</span><span class="pyoperator">]
 
494
 
 
495
</span><span class="pykeyword">def </span><span class="pyname">longestfactory</span><span class="pyoperator">():
 
496
    </span><span class="pystring">"""called for a new query.  The first item returned can be
523
497
    anything and is passed as the context to the step
524
498
    and final methods.  We use a dict."""
525
 
    </font><font color="#C00000">return </font><font color=
526
 
"#0000C0">( { </font><font color="#004080">'longest'</font><font color=
527
 
"#0000C0">: </font><font color="#004080">'' </font><font color=
528
 
"#0000C0">}, </font>longeststep<font color=
529
 
"#0000C0">, </font>longestfinal<font color="#0000C0">)
530
 
 
531
 
</font>connection<font color=
532
 
"#0000C0">.</font>createaggregatefunction<font color=
533
 
"#0000C0">(</font><font color="#004080">"longest"</font><font color=
534
 
"#0000C0">, </font>longestfactory<font color="#0000C0">)
535
 
 
536
 
</font><font color="#C00000">for </font>row <font color=
537
 
"#C00000">in </font>cursor<font color="#0000C0">.</font>execute<font color=
538
 
"#0000C0">(</font><font color=
539
 
"#004080">"select longest(x) from foo"</font><font color="#0000C0">):
540
 
    </font><font color="#C00000">print </font>row
541
 
 
542
 
<font color="#008000">###
 
499
    </span><span class="pykeyword">return </span><span class="pyoperator">( { </span><span class=
 
500
"pystring">'longest'</span><span class="pyoperator">: </span><span class="pystring">'' </span><span class=
 
501
"pyoperator">}, </span><span class="pyname">longeststep</span><span class="pyoperator">, </span><span class=
 
502
"pyname">longestfinal</span><span class="pyoperator">)
 
503
 
 
504
</span><span class="pyname">connection</span><span class="pyoperator">.</span><span class=
 
505
"pyname">createaggregatefunction</span><span class="pyoperator">(</span><span class=
 
506
"pystring">"longest"</span><span class="pyoperator">, </span><span class="pyname">longestfactory</span><span class=
 
507
"pyoperator">)
 
508
 
 
509
</span><span class="pykeyword">for </span><span class="pyname">row </span><span class=
 
510
"pykeyword">in </span><span class="pyname">cursor</span><span class="pyoperator">.</span><span class=
 
511
"pyname">execute</span><span class="pyoperator">(</span><span class=
 
512
"pystring">"select longest(x) from foo"</span><span class="pyoperator">):
 
513
    </span><span class="pykeyword">print </span><span class="pyname">row
 
514
 
 
515
</span><span class="pycomment">###
543
516
### Defining collations.  
544
517
###
545
518
 
546
519
# The default sorting mechanisms don't understand numbers at the end of strings
547
520
# so here we define a collation that does
548
521
 
549
 
</font>cursor<font color="#0000C0">.</font>execute<font color=
550
 
"#0000C0">(</font><font color=
551
 
"#004080">"create table s(str)"</font><font color="#0000C0">)
552
 
</font>cursor<font color="#0000C0">.</font>executemany<font color=
553
 
"#0000C0">(</font><font color=
554
 
"#004080">"insert into s values(?)"</font><font color="#0000C0">,
555
 
                  ( [</font><font color="#004080">"file1"</font><font color=
556
 
"#0000C0">], [</font><font color="#004080">"file7"</font><font color=
557
 
"#0000C0">], [</font><font color="#004080">"file17"</font><font color=
558
 
"#0000C0">], [</font><font color="#004080">"file20"</font><font color=
559
 
"#0000C0">], [</font><font color="#004080">"file3"</font><font color=
560
 
"#0000C0">] ) )
561
 
 
562
 
</font><font color="#C00000">for </font>row <font color=
563
 
"#C00000">in </font>cursor<font color="#0000C0">.</font>execute<font color=
564
 
"#0000C0">(</font><font color=
565
 
"#004080">"select * from s order by str"</font><font color="#0000C0">):
566
 
    </font><font color="#C00000">print </font>row
567
 
 
568
 
</font><font color="blue">   (u'file1',)
 
522
</span><span class="pyname">cursor</span><span class="pyoperator">.</span><span class=
 
523
"pyname">execute</span><span class="pyoperator">(</span><span class="pystring">"create table s(str)"</span><span class=
 
524
"pyoperator">)
 
525
</span><span class="pyname">cursor</span><span class="pyoperator">.</span><span class=
 
526
"pyname">executemany</span><span class="pyoperator">(</span><span class=
 
527
"pystring">"insert into s values(?)"</span><span class="pyoperator">,
 
528
                  ( [</span><span class="pystring">"file1"</span><span class="pyoperator">], [</span><span class=
 
529
"pystring">"file7"</span><span class="pyoperator">], [</span><span class="pystring">"file17"</span><span class=
 
530
"pyoperator">], [</span><span class="pystring">"file20"</span><span class="pyoperator">], [</span><span class=
 
531
"pystring">"file3"</span><span class="pyoperator">] ) )
 
532
 
 
533
</span><span class="pykeyword">for </span><span class="pyname">row </span><span class=
 
534
"pykeyword">in </span><span class="pyname">cursor</span><span class="pyoperator">.</span><span class=
 
535
"pyname">execute</span><span class="pyoperator">(</span><span class=
 
536
"pystring">"select * from s order by str"</span><span class="pyoperator">):
 
537
    </span><span class="pykeyword">print </span><span class="pyname">row
 
538
 
 
539
</span><span class="pyoutput">   (u'file1',)
569
540
   (u'file17',)
570
541
   (u'file20',)
571
542
   (u'file3',)
572
543
   (u'file7',)
573
 
</font>
574
 
<font color="#C00000">def </font>strnumcollate<font color=
575
 
"#0000C0">(</font>s1<font color="#0000C0">, </font>s2<font color="#0000C0">):
576
 
    </font><font color="#008000"># return -1 if s1&lt;s2, +1 if s1&gt;s2 else 0
 
544
</span>
 
545
<span class="pykeyword">def </span><span class="pyname">strnumcollate</span><span class=
 
546
"pyoperator">(</span><span class="pyname">s1</span><span class="pyoperator">, </span><span class=
 
547
"pyname">s2</span><span class="pyoperator">):
 
548
    </span><span class="pycomment"># return -1 if s1&lt;s2, +1 if s1&gt;s2 else 0
577
549
 
578
550
    # split values into two parts - the head and the numeric tail
579
 
    </font>values<font color="#0000C0">=[</font>s1<font color=
580
 
"#0000C0">, </font>s2<font color="#0000C0">]
581
 
    </font><font color="#C00000">for </font>vn<font color=
582
 
"#0000C0">,</font>v <font color="#C00000">in </font>enumerate<font color=
583
 
"#0000C0">(</font>values<font color="#0000C0">):
584
 
        </font><font color="#C00000">for </font>i <font color=
585
 
"#C00000">in </font>range<font color="#0000C0">(</font>len<font color=
586
 
"#0000C0">(</font>v<font color="#0000C0">), </font><font color=
587
 
"#0080C0">0</font><font color="#0000C0">, -</font><font color=
588
 
"#0080C0">1</font><font color="#0000C0">):
589
 
            </font><font color="#C00000">if </font>v<font color=
590
 
"#0000C0">[</font>i<font color="#0000C0">-</font><font color=
591
 
"#0080C0">1</font><font color="#0000C0">] </font><font color=
592
 
"#C00000">not in </font><font color="#004080">"01234567890"</font><font color=
593
 
"#0000C0">:
594
 
                </font><font color="#C00000">break
595
 
        try</font><font color="#0000C0">:
596
 
            </font>v<font color="#0000C0">=( </font>v<font color=
597
 
"#0000C0">[:</font>i<font color="#0000C0">], </font>int<font color=
598
 
"#0000C0">(</font>v<font color="#0000C0">[</font>i<font color="#0000C0">:]) )
599
 
        </font><font color="#C00000">except </font>ValueError<font color=
600
 
"#0000C0">:
601
 
            </font>v<font color="#0000C0">=( </font>v<font color=
602
 
"#0000C0">[:</font>i<font color="#0000C0">], </font>None <font color=
603
 
"#0000C0">)
604
 
        </font>values<font color="#0000C0">[</font>vn<font color=
605
 
"#0000C0">]=</font>v
606
 
    <font color="#008000"># compare
607
 
    </font><font color="#C00000">if </font>values<font color=
608
 
"#0000C0">[</font><font color="#0080C0">0</font><font color=
609
 
"#0000C0">]&lt;</font>values<font color="#0000C0">[</font><font color=
610
 
"#0080C0">1</font><font color="#0000C0">]:
611
 
        </font><font color="#C00000">return </font><font color=
612
 
"#0000C0">-</font><font color="#0080C0">1
613
 
    </font><font color="#C00000">if </font>values<font color=
614
 
"#0000C0">[</font><font color="#0080C0">0</font><font color=
615
 
"#0000C0">]&gt;</font>values<font color="#0000C0">[</font><font color=
616
 
"#0080C0">1</font><font color="#0000C0">]:
617
 
        </font><font color="#C00000">return </font><font color="#0080C0">1
618
 
    </font><font color="#C00000">return </font><font color="#0080C0">0
619
 
 
620
 
</font>connection<font color="#0000C0">.</font>createcollation<font color=
621
 
"#0000C0">(</font><font color="#004080">"strnum"</font><font color=
622
 
"#0000C0">, </font>strnumcollate<font color="#0000C0">)
623
 
 
624
 
</font><font color="#C00000">for </font>row <font color=
625
 
"#C00000">in </font>cursor<font color="#0000C0">.</font>execute<font color=
626
 
"#0000C0">(</font><font color=
627
 
"#004080">"select * from s order by str collate strnum"</font><font color=
628
 
"#0000C0">):
629
 
    </font><font color="#C00000">print </font>row
630
 
 
631
 
<font color="blue">   (u'file1',)
 
551
    </span><span class="pyname">values</span><span class="pyoperator">=[</span><span class=
 
552
"pyname">s1</span><span class="pyoperator">, </span><span class="pyname">s2</span><span class="pyoperator">]
 
553
    </span><span class="pykeyword">for </span><span class="pyname">vn</span><span class=
 
554
"pyoperator">,</span><span class="pyname">v </span><span class="pykeyword">in </span><span class=
 
555
"pyname">enumerate</span><span class="pyoperator">(</span><span class="pyname">values</span><span class="pyoperator">):
 
556
        </span><span class="pykeyword">for </span><span class="pyname">i </span><span class=
 
557
"pykeyword">in </span><span class="pyname">range</span><span class="pyoperator">(</span><span class=
 
558
"pyname">len</span><span class="pyoperator">(</span><span class="pyname">v</span><span class=
 
559
"pyoperator">), </span><span class="pynumber">0</span><span class="pyoperator">, -</span><span class=
 
560
"pynumber">1</span><span class="pyoperator">):
 
561
            </span><span class="pykeyword">if </span><span class="pyname">v</span><span class=
 
562
"pyoperator">[</span><span class="pyname">i</span><span class="pyoperator">-</span><span class=
 
563
"pynumber">1</span><span class="pyoperator">] </span><span class="pykeyword">not in </span><span class=
 
564
"pystring">"01234567890"</span><span class="pyoperator">:
 
565
                </span><span class="pykeyword">break
 
566
        try</span><span class="pyoperator">:
 
567
            </span><span class="pyname">v</span><span class="pyoperator">=( </span><span class=
 
568
"pyname">v</span><span class="pyoperator">[:</span><span class="pyname">i</span><span class=
 
569
"pyoperator">], </span><span class="pyname">int</span><span class="pyoperator">(</span><span class=
 
570
"pyname">v</span><span class="pyoperator">[</span><span class="pyname">i</span><span class="pyoperator">:]) )
 
571
        </span><span class="pykeyword">except </span><span class="pyname">ValueError</span><span class="pyoperator">:
 
572
            </span><span class="pyname">v</span><span class="pyoperator">=( </span><span class=
 
573
"pyname">v</span><span class="pyoperator">[:</span><span class="pyname">i</span><span class=
 
574
"pyoperator">], </span><span class="pyname">None </span><span class="pyoperator">)
 
575
        </span><span class="pyname">values</span><span class="pyoperator">[</span><span class=
 
576
"pyname">vn</span><span class="pyoperator">]=</span><span class="pyname">v
 
577
    </span><span class="pycomment"># compare
 
578
    </span><span class="pykeyword">if </span><span class="pyname">values</span><span class=
 
579
"pyoperator">[</span><span class="pynumber">0</span><span class="pyoperator">]&lt;</span><span class=
 
580
"pyname">values</span><span class="pyoperator">[</span><span class="pynumber">1</span><span class="pyoperator">]:
 
581
        </span><span class="pykeyword">return </span><span class="pyoperator">-</span><span class="pynumber">1
 
582
    </span><span class="pykeyword">if </span><span class="pyname">values</span><span class=
 
583
"pyoperator">[</span><span class="pynumber">0</span><span class="pyoperator">]&gt;</span><span class=
 
584
"pyname">values</span><span class="pyoperator">[</span><span class="pynumber">1</span><span class="pyoperator">]:
 
585
        </span><span class="pykeyword">return </span><span class="pynumber">1
 
586
    </span><span class="pykeyword">return </span><span class="pynumber">0
 
587
 
 
588
</span><span class="pyname">connection</span><span class="pyoperator">.</span><span class=
 
589
"pyname">createcollation</span><span class="pyoperator">(</span><span class="pystring">"strnum"</span><span class=
 
590
"pyoperator">, </span><span class="pyname">strnumcollate</span><span class="pyoperator">)
 
591
 
 
592
</span><span class="pykeyword">for </span><span class="pyname">row </span><span class=
 
593
"pykeyword">in </span><span class="pyname">cursor</span><span class="pyoperator">.</span><span class=
 
594
"pyname">execute</span><span class="pyoperator">(</span><span class=
 
595
"pystring">"select * from s order by str collate strnum"</span><span class="pyoperator">):
 
596
    </span><span class="pykeyword">print </span><span class="pyname">row
 
597
 
 
598
</span><span class="pyoutput">   (u'file1',)
632
599
   (u'file3',)
633
600
   (u'file7',)
634
601
   (u'file17',)
635
602
   (u'file20',)
636
 
</font>
637
 
<font color="#008000">###
 
603
</span>
 
604
<span class="pycomment">###
638
605
### Authorizer (eg if you want to control what user supplied SQL can do)
639
606
###
640
607
 
641
 
</font><font color="#C00000">def </font>authorizer<font color=
642
 
"#0000C0">(</font>operation<font color="#0000C0">, </font>paramone<font color=
643
 
"#0000C0">, </font>paramtwo<font color=
644
 
"#0000C0">, </font>databasename<font color=
645
 
"#0000C0">, </font>triggerorview<font color="#0000C0">):
646
 
    </font><font color=
647
 
"#004080">"""Called when each operation is prepared.  We can return SQLITE_OK, SQLITE_DENY or
 
608
</span><span class="pykeyword">def </span><span class="pyname">authorizer</span><span class=
 
609
"pyoperator">(</span><span class="pyname">operation</span><span class="pyoperator">, </span><span class=
 
610
"pyname">paramone</span><span class="pyoperator">, </span><span class="pyname">paramtwo</span><span class=
 
611
"pyoperator">, </span><span class="pyname">databasename</span><span class="pyoperator">, </span><span class=
 
612
"pyname">triggerorview</span><span class="pyoperator">):
 
613
    </span><span class="pystring">"""Called when each operation is prepared.  We can return SQLITE_OK, SQLITE_DENY or
648
614
    SQLITE_IGNORE"""
649
 
    </font><font color="#008000"># find the operation name
650
 
    </font><font color="#C00000">print </font>apsw<font color=
651
 
"#0000C0">.</font>mapping_authorizer_function<font color=
652
 
"#0000C0">[</font>operation<font color="#0000C0">],
653
 
    </font><font color="#C00000">print </font>paramone<font color=
654
 
"#0000C0">, </font>paramtwo<font color=
655
 
"#0000C0">, </font>databasename<font color="#0000C0">, </font>triggerorview
656
 
    <font color="#C00000">if </font>operation<font color=
657
 
"#0000C0">==</font>apsw<font color=
658
 
"#0000C0">.</font>SQLITE_CREATE_TABLE <font color=
659
 
"#C00000">and </font>paramone<font color=
660
 
"#0000C0">.</font>startswith<font color="#0000C0">(</font><font color=
661
 
"#004080">"private"</font><font color="#0000C0">):
662
 
        </font><font color="#C00000">return </font>apsw<font color=
663
 
"#0000C0">.</font>SQLITE_DENY  <font color=
664
 
"#008000"># not allowed to create tables whose names start with private
665
 
 
666
 
    </font><font color="#C00000">return </font>apsw<font color=
667
 
"#0000C0">.</font>SQLITE_OK  <font color="#008000"># always allow
668
 
 
669
 
</font>connection<font color="#0000C0">.</font>setauthorizer<font color=
670
 
"#0000C0">(</font>authorizer<font color="#0000C0">)
671
 
</font>cursor<font color="#0000C0">.</font>execute<font color=
672
 
"#0000C0">(</font><font color=
673
 
"#004080">"insert into s values('foo')"</font><font color="#0000C0">)
674
 
</font>cursor<font color="#0000C0">.</font>execute<font color=
675
 
"#0000C0">(</font><font color=
676
 
"#004080">"select str from s limit 1"</font><font color="#0000C0">)
677
 
 
678
 
</font><font color="blue">   SQLITE_INSERT s None main None
 
615
    </span><span class="pycomment"># find the operation name
 
616
    </span><span class="pykeyword">print </span><span class="pyname">apsw</span><span class=
 
617
"pyoperator">.</span><span class="pyname">mapping_authorizer_function</span><span class=
 
618
"pyoperator">[</span><span class="pyname">operation</span><span class="pyoperator">],
 
619
    </span><span class="pykeyword">print </span><span class="pyname">paramone</span><span class=
 
620
"pyoperator">, </span><span class="pyname">paramtwo</span><span class="pyoperator">, </span><span class=
 
621
"pyname">databasename</span><span class="pyoperator">, </span><span class="pyname">triggerorview
 
622
    </span><span class="pykeyword">if </span><span class="pyname">operation</span><span class=
 
623
"pyoperator">==</span><span class="pyname">apsw</span><span class="pyoperator">.</span><span class=
 
624
"pyname">SQLITE_CREATE_TABLE </span><span class="pykeyword">and </span><span class="pyname">paramone</span><span class=
 
625
"pyoperator">.</span><span class="pyname">startswith</span><span class="pyoperator">(</span><span class=
 
626
"pystring">"private"</span><span class="pyoperator">):
 
627
        </span><span class="pykeyword">return </span><span class="pyname">apsw</span><span class=
 
628
"pyoperator">.</span><span class="pyname">SQLITE_DENY  </span><span class=
 
629
"pycomment"># not allowed to create tables whose names start with private
 
630
 
 
631
    </span><span class="pykeyword">return </span><span class="pyname">apsw</span><span class=
 
632
"pyoperator">.</span><span class="pyname">SQLITE_OK  </span><span class="pycomment"># always allow
 
633
 
 
634
</span><span class="pyname">connection</span><span class="pyoperator">.</span><span class=
 
635
"pyname">setauthorizer</span><span class="pyoperator">(</span><span class="pyname">authorizer</span><span class=
 
636
"pyoperator">)
 
637
</span><span class="pyname">cursor</span><span class="pyoperator">.</span><span class=
 
638
"pyname">execute</span><span class="pyoperator">(</span><span class=
 
639
"pystring">"insert into s values('foo')"</span><span class="pyoperator">)
 
640
</span><span class="pyname">cursor</span><span class="pyoperator">.</span><span class=
 
641
"pyname">execute</span><span class="pyoperator">(</span><span class=
 
642
"pystring">"select str from s limit 1"</span><span class="pyoperator">)
 
643
 
 
644
</span><span class="pyoutput">   SQLITE_INSERT s None main None
679
645
   SQLITE_SELECT None None None None
680
646
   SQLITE_READ s str main None
681
 
</font>
682
 
<font color="#008000"># Cancel authorizer
683
 
</font>connection<font color="#0000C0">.</font>setauthorizer<font color=
684
 
"#0000C0">(</font>None<font color="#0000C0">)
 
647
</span>
 
648
<span class="pycomment"># Cancel authorizer
 
649
</span><span class="pyname">connection</span><span class="pyoperator">.</span><span class=
 
650
"pyname">setauthorizer</span><span class="pyoperator">(</span><span class="pyname">None</span><span class=
 
651
"pyoperator">)
685
652
 
686
 
</font><font color="#008000">###
 
653
</span><span class="pycomment">###
687
654
### progress handler (SQLite 3 experimental feature)
688
655
###
689
656
 
690
657
# something to give us large numbers of random numbers
691
 
</font><font color="#C00000">import </font>random
692
 
<font color="#C00000">def </font>randomintegers<font color=
693
 
"#0000C0">(</font>howmany<font color="#0000C0">):
694
 
    </font><font color="#C00000">for </font>i <font color=
695
 
"#C00000">in </font>xrange<font color="#0000C0">(</font>howmany<font color=
696
 
"#0000C0">):
697
 
        </font><font color="#C00000">yield </font><font color=
698
 
"#0000C0">(</font>random<font color="#0000C0">.</font>randint<font color=
699
 
"#0000C0">(</font><font color="#0080C0">0</font><font color=
700
 
"#0000C0">,</font><font color="#0080C0">9999999999</font><font color=
701
 
"#0000C0">),)
702
 
 
703
 
</font><font color="#008000"># create a table with 500 random numbers
704
 
</font>cursor<font color="#0000C0">.</font>execute<font color=
705
 
"#0000C0">(</font><font color=
706
 
"#004080">"begin ; create table bigone(x)"</font><font color="#0000C0">)
707
 
</font>cursor<font color="#0000C0">.</font>executemany<font color=
708
 
"#0000C0">(</font><font color=
709
 
"#004080">"insert into bigone values(?)"</font><font color=
710
 
"#0000C0">, </font>randomintegers<font color="#0000C0">(</font><font color=
711
 
"#0080C0">500</font><font color="#0000C0">))
712
 
</font>cursor<font color="#0000C0">.</font>execute<font color=
713
 
"#0000C0">(</font><font color="#004080">"commit"</font><font color="#0000C0">)
714
 
 
715
 
</font><font color="#008000"># display an ascii spinner
716
 
</font>_phcount<font color="#0000C0">=</font><font color="#0080C0">0
717
 
</font>_phspinner<font color="#0000C0">=</font><font color="#004080">"|/-\\"
718
 
</font><font color="#C00000">def </font>progresshandler<font color=
719
 
"#0000C0">():
720
 
    </font><font color="#C00000">global </font>_phcount
721
 
    sys<font color="#0000C0">.</font>stdout<font color=
722
 
"#0000C0">.</font>write<font color="#0000C0">(</font>_phspinner<font color=
723
 
"#0000C0">[</font>_phcount<font color="#0000C0">%</font>len<font color=
724
 
"#0000C0">(</font>_phspinner<font color="#0000C0">)]+</font>chr<font color=
725
 
"#0000C0">(</font><font color="#0080C0">8</font><font color=
726
 
"#0000C0">)) </font><font color="#008000"># chr(8) is backspace
727
 
    </font>sys<font color="#0000C0">.</font>stdout<font color=
728
 
"#0000C0">.</font>flush<font color="#0000C0">()
729
 
    </font>_phcount<font color="#0000C0">+=</font><font color="#0080C0">1
730
 
    </font>time<font color="#0000C0">.</font>sleep<font color=
731
 
"#0000C0">(</font><font color="#0080C0">0.1</font><font color=
732
 
"#0000C0">) </font><font color=
733
 
"#008000"># deliberate delay so we can see the spinner (SQLite is too fast otherwise!)
734
 
    </font><font color="#C00000">return </font><font color=
735
 
"#0080C0">0  </font><font color="#008000"># returning non-zero aborts
 
658
</span><span class="pykeyword">import </span><span class="pyname">random
 
659
</span><span class="pykeyword">def </span><span class="pyname">randomintegers</span><span class=
 
660
"pyoperator">(</span><span class="pyname">howmany</span><span class="pyoperator">):
 
661
    </span><span class="pykeyword">for </span><span class="pyname">i </span><span class=
 
662
"pykeyword">in </span><span class="pyname">xrange</span><span class="pyoperator">(</span><span class=
 
663
"pyname">howmany</span><span class="pyoperator">):
 
664
        </span><span class="pykeyword">yield </span><span class="pyoperator">(</span><span class=
 
665
"pyname">random</span><span class="pyoperator">.</span><span class="pyname">randint</span><span class=
 
666
"pyoperator">(</span><span class="pynumber">0</span><span class="pyoperator">,</span><span class=
 
667
"pynumber">9999999999</span><span class="pyoperator">),)
 
668
 
 
669
</span><span class="pycomment"># create a table with 100 random numbers
 
670
</span><span class="pyname">cursor</span><span class="pyoperator">.</span><span class=
 
671
"pyname">execute</span><span class="pyoperator">(</span><span class=
 
672
"pystring">"begin ; create table bigone(x)"</span><span class="pyoperator">)
 
673
</span><span class="pyname">cursor</span><span class="pyoperator">.</span><span class=
 
674
"pyname">executemany</span><span class="pyoperator">(</span><span class=
 
675
"pystring">"insert into bigone values(?)"</span><span class="pyoperator">, </span><span class=
 
676
"pyname">randomintegers</span><span class="pyoperator">(</span><span class="pynumber">100</span><span class=
 
677
"pyoperator">))
 
678
</span><span class="pyname">cursor</span><span class="pyoperator">.</span><span class=
 
679
"pyname">execute</span><span class="pyoperator">(</span><span class="pystring">"commit"</span><span class=
 
680
"pyoperator">)
 
681
 
 
682
</span><span class="pycomment"># display an ascii spinner
 
683
</span><span class="pyname">_phcount</span><span class="pyoperator">=</span><span class="pynumber">0
 
684
</span><span class="pyname">_phspinner</span><span class="pyoperator">=</span><span class="pystring">"|/-\\"
 
685
</span><span class="pykeyword">def </span><span class="pyname">progresshandler</span><span class="pyoperator">():
 
686
    </span><span class="pykeyword">global </span><span class="pyname">_phcount
 
687
    sys</span><span class="pyoperator">.</span><span class="pyname">stdout</span><span class=
 
688
"pyoperator">.</span><span class="pyname">write</span><span class="pyoperator">(</span><span class=
 
689
"pyname">_phspinner</span><span class="pyoperator">[</span><span class="pyname">_phcount</span><span class=
 
690
"pyoperator">%</span><span class="pyname">len</span><span class="pyoperator">(</span><span class=
 
691
"pyname">_phspinner</span><span class="pyoperator">)]+</span><span class="pyname">chr</span><span class=
 
692
"pyoperator">(</span><span class="pynumber">8</span><span class="pyoperator">)) </span><span class=
 
693
"pycomment"># chr(8) is backspace
 
694
    </span><span class="pyname">sys</span><span class="pyoperator">.</span><span class=
 
695
"pyname">stdout</span><span class="pyoperator">.</span><span class="pyname">flush</span><span class="pyoperator">()
 
696
    </span><span class="pyname">_phcount</span><span class="pyoperator">+=</span><span class="pynumber">1
 
697
    </span><span class="pyname">time</span><span class="pyoperator">.</span><span class=
 
698
"pyname">sleep</span><span class="pyoperator">(</span><span class="pynumber">0.1</span><span class=
 
699
"pyoperator">) </span><span class=
 
700
"pycomment"># deliberate delay so we can see the spinner (SQLite is too fast otherwise!)
 
701
    </span><span class="pykeyword">return </span><span class="pynumber">0  </span><span class=
 
702
"pycomment"># returning non-zero aborts
736
703
 
737
704
# register progresshandler every 20 instructions
738
 
</font>connection<font color="#0000C0">.</font>setprogresshandler<font color=
739
 
"#0000C0">(</font>progresshandler<font color="#0000C0">, </font><font color=
740
 
"#0080C0">20</font><font color="#0000C0">)
741
 
 
742
 
</font><font color=
743
 
"#008000"># see it in action - sorting 500 numbers to find the biggest takes a while
744
 
</font><font color="#C00000">print </font><font color=
745
 
"#004080">"spinny thing -&gt; "</font><font color="#0000C0">,
746
 
</font><font color="#C00000">for </font>i <font color=
747
 
"#C00000">in </font>cursor<font color="#0000C0">.</font>execute<font color=
748
 
"#0000C0">(</font><font color=
749
 
"#004080">"select max(x) from bigone"</font><font color="#0000C0">):
750
 
    </font><font color="#C00000">print </font><font color="#008000"># newline
751
 
    </font><font color="#C00000">print </font>i <font color=
752
 
"#008000"># and the maximum number
753
 
 
754
 
</font>connection<font color="#0000C0">.</font>setprogresshandler<font color=
755
 
"#0000C0">(</font>None<font color="#0000C0">)
756
 
 
757
 
</font><font color="#008000">###
 
705
</span><span class="pyname">connection</span><span class="pyoperator">.</span><span class=
 
706
"pyname">setprogresshandler</span><span class="pyoperator">(</span><span class=
 
707
"pyname">progresshandler</span><span class="pyoperator">, </span><span class="pynumber">20</span><span class=
 
708
"pyoperator">)
 
709
 
 
710
</span><span class="pycomment"># see it in action - sorting 100 numbers to find the biggest takes a while
 
711
</span><span class="pykeyword">print </span><span class="pystring">"spinny thing -&gt; "</span><span class=
 
712
"pyoperator">,
 
713
</span><span class="pykeyword">for </span><span class="pyname">i </span><span class="pykeyword">in </span><span class=
 
714
"pyname">cursor</span><span class="pyoperator">.</span><span class="pyname">execute</span><span class=
 
715
"pyoperator">(</span><span class="pystring">"select max(x) from bigone"</span><span class="pyoperator">):
 
716
    </span><span class="pykeyword">print </span><span class="pycomment"># newline
 
717
    </span><span class="pykeyword">print </span><span class="pyname">i </span><span class=
 
718
"pycomment"># and the maximum number
 
719
 
 
720
</span><span class="pyname">connection</span><span class="pyoperator">.</span><span class=
 
721
"pyname">setprogresshandler</span><span class="pyoperator">(</span><span class="pyname">None</span><span class=
 
722
"pyoperator">)
 
723
 
 
724
</span><span class="pycomment">###
758
725
### commit hook (SQLite3 experimental feature)
759
726
###
760
727
 
761
 
</font><font color="#C00000">def </font>mycommithook<font color="#0000C0">():
762
 
    </font><font color="#C00000">print </font><font color=
763
 
"#004080">"in commit hook"
764
 
    </font>hour<font color="#0000C0">=</font>time<font color=
765
 
"#0000C0">.</font>localtime<font color="#0000C0">()[</font><font color=
766
 
"#0080C0">3</font><font color="#0000C0">]
767
 
    </font><font color="#C00000">if </font>hour<font color=
768
 
"#0000C0">&lt;</font><font color="#0080C0">8 </font><font color=
769
 
"#C00000">or </font>hour<font color="#0000C0">&gt;</font><font color=
770
 
"#0080C0">17</font><font color="#0000C0">:
771
 
        </font><font color="#C00000">print </font><font color=
772
 
"#004080">"no commits out of hours"
773
 
        </font><font color="#C00000">return </font><font color=
774
 
"#0080C0">1  </font><font color=
775
 
"#008000"># abort commits outside of 8am through 6pm
776
 
    </font><font color="#C00000">print </font><font color=
777
 
"#004080">"commits okay at this time"
778
 
    </font><font color="#C00000">return </font><font color=
779
 
"#0080C0">0  </font><font color="#008000"># let commit go ahead
780
 
 
781
 
</font>connection<font color="#0000C0">.</font>setcommithook<font color=
782
 
"#0000C0">(</font>mycommithook<font color="#0000C0">)
783
 
</font><font color="#C00000">try</font><font color="#0000C0">:
784
 
    </font>cursor<font color="#0000C0">.</font>execute<font color=
785
 
"#0000C0">(</font><font color=
786
 
"#004080">"begin; create table example(x,y,z); insert into example values (3,4,5) ; commit"</font><font color="#0000C0">)
787
 
</font><font color="#C00000">except </font>apsw<font color=
788
 
"#0000C0">.</font>ConstraintError<font color="#0000C0">:
789
 
    </font><font color="#C00000">print </font><font color=
790
 
"#004080">"commit was not allowed"
791
 
 
792
 
</font>connection<font color="#0000C0">.</font>setcommithook<font color=
793
 
"#0000C0">(</font>None<font color="#0000C0">)
794
 
 
795
 
</font><font color="#008000">###
 
728
</span><span class="pykeyword">def </span><span class="pyname">mycommithook</span><span class="pyoperator">():
 
729
    </span><span class="pykeyword">print </span><span class="pystring">"in commit hook"
 
730
    </span><span class="pyname">hour</span><span class="pyoperator">=</span><span class=
 
731
"pyname">time</span><span class="pyoperator">.</span><span class="pyname">localtime</span><span class=
 
732
"pyoperator">()[</span><span class="pynumber">3</span><span class="pyoperator">]
 
733
    </span><span class="pykeyword">if </span><span class="pyname">hour</span><span class=
 
734
"pyoperator">&lt;</span><span class="pynumber">8 </span><span class="pykeyword">or </span><span class=
 
735
"pyname">hour</span><span class="pyoperator">&gt;</span><span class="pynumber">17</span><span class="pyoperator">:
 
736
        </span><span class="pykeyword">print </span><span class="pystring">"no commits out of hours"
 
737
        </span><span class="pykeyword">return </span><span class="pynumber">1  </span><span class=
 
738
"pycomment"># abort commits outside of 8am through 6pm
 
739
    </span><span class="pykeyword">print </span><span class="pystring">"commits okay at this time"
 
740
    </span><span class="pykeyword">return </span><span class="pynumber">0  </span><span class=
 
741
"pycomment"># let commit go ahead
 
742
 
 
743
</span><span class="pyname">connection</span><span class="pyoperator">.</span><span class=
 
744
"pyname">setcommithook</span><span class="pyoperator">(</span><span class="pyname">mycommithook</span><span class=
 
745
"pyoperator">)
 
746
</span><span class="pykeyword">try</span><span class="pyoperator">:
 
747
    </span><span class="pyname">cursor</span><span class="pyoperator">.</span><span class=
 
748
"pyname">execute</span><span class="pyoperator">(</span><span class=
 
749
"pystring">"begin; create table example(x,y,z); insert into example values (3,4,5) ; commit"</span><span class=
 
750
"pyoperator">)
 
751
</span><span class="pykeyword">except </span><span class="pyname">apsw</span><span class=
 
752
"pyoperator">.</span><span class="pyname">ConstraintError</span><span class="pyoperator">:
 
753
    </span><span class="pykeyword">print </span><span class="pystring">"commit was not allowed"
 
754
 
 
755
</span><span class="pyname">connection</span><span class="pyoperator">.</span><span class=
 
756
"pyname">setcommithook</span><span class="pyoperator">(</span><span class="pyname">None</span><span class=
 
757
"pyoperator">)
 
758
 
 
759
</span><span class="pycomment">###
 
760
### <a name="example-blobio" id="example-blobio">Blob I/O</a> 
 
761
###
 
762
 
 
763
</span><span class="pyname">cursor</span><span class="pyoperator">.</span><span class=
 
764
"pyname">execute</span><span class="pyoperator">(</span><span class=
 
765
"pystring">"create table blobby(x,y)"</span><span class="pyoperator">)
 
766
</span><span class="pycomment"># Add a blob we will fill in later
 
767
</span><span class="pyname">cursor</span><span class="pyoperator">.</span><span class=
 
768
"pyname">execute</span><span class="pyoperator">(</span><span class=
 
769
"pystring">"insert into blobby values(1,zeroblob(10000))"</span><span class="pyoperator">)
 
770
</span><span class="pycomment"># Or as a binding
 
771
</span><span class="pyname">cursor</span><span class="pyoperator">.</span><span class=
 
772
"pyname">execute</span><span class="pyoperator">(</span><span class=
 
773
"pystring">"insert into blobby values(2,?)"</span><span class="pyoperator">, (</span><span class=
 
774
"pyname">apsw</span><span class="pyoperator">.</span><span class="pyname">zeroblob</span><span class=
 
775
"pyoperator">(</span><span class="pynumber">20000</span><span class="pyoperator">),))
 
776
</span><span class="pycomment"># Open a blob for writing.  We need to know the rowid
 
777
</span><span class="pyname">rowid</span><span class="pyoperator">=</span><span class="pyname">cursor</span><span class=
 
778
"pyoperator">.</span><span class="pyname">execute</span><span class="pyoperator">(</span><span class=
 
779
"pystring">"select ROWID from blobby where x=1"</span><span class="pyoperator">).</span><span class=
 
780
"pyname">next</span><span class="pyoperator">()[</span><span class="pynumber">0</span><span class="pyoperator">]
 
781
</span><span class="pyname">blob</span><span class="pyoperator">=</span><span class=
 
782
"pyname">connection</span><span class="pyoperator">.</span><span class="pyname">blobopen</span><span class=
 
783
"pyoperator">(</span><span class="pystring">"main"</span><span class="pyoperator">, </span><span class=
 
784
"pystring">"blobby"</span><span class="pyoperator">, </span><span class="pystring">"y"</span><span class=
 
785
"pyoperator">, </span><span class="pyname">rowid</span><span class="pyoperator">, </span><span class=
 
786
"pynumber">1</span><span class="pyoperator">) </span><span class="pycomment"># 1 is for read/write
 
787
</span><span class="pyname">blob</span><span class="pyoperator">.</span><span class="pyname">write</span><span class=
 
788
"pyoperator">(</span><span class="pystring">"hello world"</span><span class="pyoperator">)
 
789
</span><span class="pyname">blob</span><span class="pyoperator">.</span><span class="pyname">seek</span><span class=
 
790
"pyoperator">(</span><span class="pynumber">2000</span><span class="pyoperator">)
 
791
</span><span class="pyname">blob</span><span class="pyoperator">.</span><span class="pyname">write</span><span class=
 
792
"pyoperator">(</span><span class="pystring">"hello world, again"</span><span class="pyoperator">)
 
793
</span><span class="pyname">blob</span><span class="pyoperator">.</span><span class="pyname">close</span><span class=
 
794
"pyoperator">()
 
795
 
 
796
</span><span class="pycomment">###
796
797
### Virtual tables
797
798
###
798
799
 
799
800
# This virtual table stores information about files in a set of
800
801
# directories so you can execute SQL queries
801
802
 
802
 
</font><font color="#C00000">def </font>getfiledata<font color=
803
 
"#0000C0">(</font>directories<font color="#0000C0">):
804
 
    </font>columns<font color="#0000C0">=</font>None
805
 
    data<font color="#0000C0">=[]
806
 
    </font>counter<font color="#0000C0">=</font><font color="#0080C0">1
807
 
    </font><font color="#C00000">for </font>directory <font color=
808
 
"#C00000">in </font>directories<font color="#0000C0">:
809
 
        </font><font color="#C00000">for </font>f <font color=
810
 
"#C00000">in </font>os<font color="#0000C0">.</font>listdir<font color=
811
 
"#0000C0">(</font>directory<font color="#0000C0">):
812
 
            </font><font color="#C00000">if not </font>os<font color=
813
 
"#0000C0">.</font>path<font color="#0000C0">.</font>isfile<font color=
814
 
"#0000C0">(</font>os<font color="#0000C0">.</font>path<font color=
815
 
"#0000C0">.</font>join<font color="#0000C0">(</font>directory<font color=
816
 
"#0000C0">,</font>f<font color="#0000C0">)):
817
 
                </font><font color="#C00000">continue
818
 
            </font>counter<font color="#0000C0">+=</font><font color=
819
 
"#0080C0">1
820
 
            </font>st<font color="#0000C0">=</font>os<font color=
821
 
"#0000C0">.</font>stat<font color="#0000C0">(</font>os<font color=
822
 
"#0000C0">.</font>path<font color="#0000C0">.</font>join<font color=
823
 
"#0000C0">(</font>directory<font color="#0000C0">,</font>f<font color=
824
 
"#0000C0">))
825
 
            </font><font color="#C00000">if </font>columns <font color=
826
 
"#C00000">is </font>None<font color="#0000C0">:
827
 
                </font>columns<font color="#0000C0">=[</font><font color=
828
 
"#004080">"rowid"</font><font color="#0000C0">, </font><font color=
829
 
"#004080">"name"</font><font color="#0000C0">, </font><font color=
830
 
"#004080">"directory"</font><font color="#0000C0">]+[</font>x <font color=
831
 
"#C00000">for </font>x <font color="#C00000">in </font>dir<font color=
832
 
"#0000C0">(</font>st<font color="#0000C0">) </font><font color=
833
 
"#C00000">if </font>x<font color="#0000C0">.</font>startswith<font color=
834
 
"#0000C0">(</font><font color="#004080">"st_"</font><font color="#0000C0">)]
835
 
            </font>data<font color="#0000C0">.</font>append<font color=
836
 
"#0000C0">( [</font>counter<font color="#0000C0">, </font>f<font color=
837
 
"#0000C0">, </font>directory<font color=
838
 
"#0000C0">] + [</font>getattr<font color="#0000C0">(</font>st<font color=
839
 
"#0000C0">,</font>x<font color="#0000C0">) </font><font color=
840
 
"#C00000">for </font>x <font color="#C00000">in </font>columns<font color=
841
 
"#0000C0">[</font><font color="#0080C0">3</font><font color="#0000C0">:]] )
842
 
    </font><font color="#C00000">return </font>columns<font color=
843
 
"#0000C0">, </font>data
844
 
 
845
 
<font color="#008000"># This gets registered with the Connection
846
 
</font><font color="#C00000">class </font>Source<font color="#0000C0">:
847
 
    </font><font color="#C00000">def </font>Create<font color=
848
 
"#0000C0">(</font>self<font color="#0000C0">, </font>db<font color=
849
 
"#0000C0">, </font>modulename<font color="#0000C0">, </font>dbname<font color=
850
 
"#0000C0">, </font>tablename<font color="#0000C0">, *</font>args<font color=
851
 
"#0000C0">):
852
 
        </font>columns<font color="#0000C0">,</font>data<font color=
853
 
"#0000C0">=</font>getfiledata<font color="#0000C0">([</font>eval<font color=
854
 
"#0000C0">(</font>a<font color="#0000C0">) </font><font color=
855
 
"#C00000">for </font>a <font color="#C00000">in </font>args<font color=
856
 
"#0000C0">]) </font><font color="#008000"># eval strips off layer of quotes
857
 
        </font>schema<font color="#0000C0">=</font><font color=
858
 
"#004080">"create table foo("</font><font color="#0000C0">+</font><font color=
859
 
"#004080">','</font><font color="#0000C0">.</font>join<font color=
860
 
"#0000C0">([</font><font color="#004080">"'%s'" </font><font color=
861
 
"#0000C0">% (</font>x<font color="#0000C0">,) </font><font color=
862
 
"#C00000">for </font>x <font color="#C00000">in </font>columns<font color=
863
 
"#0000C0">[</font><font color="#0080C0">1</font><font color=
864
 
"#0000C0">:]])+</font><font color="#004080">")"
865
 
        </font><font color="#C00000">return </font>schema<font color=
866
 
"#0000C0">,</font>Table<font color="#0000C0">(</font>columns<font color=
867
 
"#0000C0">,</font>data<font color="#0000C0">)
868
 
    </font>Connect<font color="#0000C0">=</font>Create
869
 
 
870
 
<font color="#008000"># Represents a table
871
 
</font><font color="#C00000">class </font>Table<font color="#0000C0">:
872
 
    </font><font color="#C00000">def </font>__init__<font color=
873
 
"#0000C0">(</font>self<font color="#0000C0">, </font>columns<font color=
874
 
"#0000C0">, </font>data<font color="#0000C0">):
875
 
        </font>self<font color="#0000C0">.</font>columns<font color=
876
 
"#0000C0">=</font>columns
877
 
        self<font color="#0000C0">.</font>data<font color=
878
 
"#0000C0">=</font>data
879
 
 
880
 
    <font color="#C00000">def </font>BestIndex<font color=
881
 
"#0000C0">(</font>self<font color="#0000C0">, *</font>args<font color=
882
 
"#0000C0">):
883
 
        </font><font color="#C00000">return </font>None
884
 
 
885
 
    <font color="#C00000">def </font>Open<font color=
886
 
"#0000C0">(</font>self<font color="#0000C0">):
887
 
        </font><font color="#C00000">return </font>Cursor<font color=
888
 
"#0000C0">(</font>self<font color="#0000C0">)
889
 
 
890
 
    </font><font color="#C00000">def </font>Disconnect<font color=
891
 
"#0000C0">(</font>self<font color="#0000C0">):
892
 
        </font><font color="#C00000">pass
893
 
 
894
 
    </font>Destroy<font color="#0000C0">=</font>Disconnect
895
 
 
896
 
<font color="#008000"># Represents a cursor
897
 
</font><font color="#C00000">class </font>Cursor<font color="#0000C0">:
898
 
    </font><font color="#C00000">def </font>__init__<font color=
899
 
"#0000C0">(</font>self<font color="#0000C0">, </font>table<font color=
900
 
"#0000C0">):
901
 
        </font>self<font color="#0000C0">.</font>table<font color=
902
 
"#0000C0">=</font>table
903
 
 
904
 
    <font color="#C00000">def </font>Filter<font color=
905
 
"#0000C0">(</font>self<font color="#0000C0">, *</font>args<font color=
906
 
"#0000C0">):
907
 
        </font>self<font color="#0000C0">.</font>pos<font color=
908
 
"#0000C0">=</font><font color="#0080C0">0
909
 
 
910
 
    </font><font color="#C00000">def </font>Eof<font color=
911
 
"#0000C0">(</font>self<font color="#0000C0">):
912
 
        </font><font color="#C00000">return </font>self<font color=
913
 
"#0000C0">.</font>pos<font color="#0000C0">&gt;=</font>len<font color=
914
 
"#0000C0">(</font>self<font color="#0000C0">.</font>table<font color=
915
 
"#0000C0">.</font>data<font color="#0000C0">)
916
 
 
917
 
    </font><font color="#C00000">def </font>Rowid<font color=
918
 
"#0000C0">(</font>self<font color="#0000C0">):
919
 
        </font><font color="#C00000">return </font>self<font color=
920
 
"#0000C0">.</font>table<font color="#0000C0">.</font>data<font color=
921
 
"#0000C0">[</font>self<font color="#0000C0">.</font>pos<font color=
922
 
"#0000C0">][</font><font color="#0080C0">0</font><font color="#0000C0">]
923
 
 
924
 
    </font><font color="#C00000">def </font>Column<font color=
925
 
"#0000C0">(</font>self<font color="#0000C0">, </font>col<font color=
926
 
"#0000C0">):
927
 
        </font><font color="#C00000">return </font>self<font color=
928
 
"#0000C0">.</font>table<font color="#0000C0">.</font>data<font color=
929
 
"#0000C0">[</font>self<font color="#0000C0">.</font>pos<font color=
930
 
"#0000C0">][</font><font color="#0080C0">1</font><font color=
931
 
"#0000C0">+</font>col<font color="#0000C0">]
932
 
 
933
 
    </font><font color="#C00000">def </font>Next<font color=
934
 
"#0000C0">(</font>self<font color="#0000C0">):
935
 
        </font>self<font color="#0000C0">.</font>pos<font color=
936
 
"#0000C0">+=</font><font color="#0080C0">1
937
 
 
938
 
    </font><font color="#C00000">def </font>Close<font color=
939
 
"#0000C0">(</font>self<font color="#0000C0">):
940
 
        </font><font color="#C00000">pass
941
 
 
942
 
</font><font color="#008000"># Register the module as filesource
943
 
</font>connection<font color="#0000C0">.</font>createmodule<font color=
944
 
"#0000C0">(</font><font color="#004080">"filesource"</font><font color=
945
 
"#0000C0">, </font>Source<font color="#0000C0">())
946
 
 
947
 
</font><font color=
948
 
"#008000"># Arguments to module - all directories in sys.path
949
 
</font>sysdirs<font color="#0000C0">=</font><font color=
950
 
"#004080">","</font><font color="#0000C0">.</font>join<font color=
951
 
"#0000C0">([</font><font color="#004080">"'%s'" </font><font color=
952
 
"#0000C0">% (</font>x<font color="#0000C0">,) </font><font color=
953
 
"#C00000">for </font>x <font color="#C00000">in </font>sys<font color=
954
 
"#0000C0">.</font>path<font color="#0000C0">[</font><font color=
955
 
"#0080C0">1</font><font color="#0000C0">:] </font><font color=
956
 
"#C00000">if </font>len<font color="#0000C0">(</font>x<font color=
957
 
"#0000C0">) </font><font color="#C00000">and </font>os<font color=
958
 
"#0000C0">.</font>path<font color="#0000C0">.</font>isdir<font color=
959
 
"#0000C0">(</font>x<font color="#0000C0">)])
960
 
</font>cursor<font color="#0000C0">.</font>execute<font color=
961
 
"#0000C0">(</font><font color=
962
 
"#004080">"create virtual table sysfiles using filesource("</font><font color=
963
 
"#0000C0">+</font>sysdirs<font color="#0000C0">+</font><font color=
964
 
"#004080">")"</font><font color="#0000C0">)
965
 
 
966
 
</font><font color="#008000"># Which 3 files are the biggest?
967
 
</font><font color="#C00000">for </font>size<font color=
968
 
"#0000C0">,</font>directory<font color="#0000C0">,</font>file <font color=
969
 
"#C00000">in </font>cursor<font color="#0000C0">.</font>execute<font color=
970
 
"#0000C0">(</font><font color=
971
 
"#004080">"select st_size,directory,name from sysfiles order by st_size desc limit 3"</font><font color="#0000C0">):
972
 
    </font><font color="#C00000">print </font>size<font color=
973
 
"#0000C0">,</font>file<font color="#0000C0">,</font>directory
974
 
 
975
 
<font color="blue">   1610924 apsw.so /usr/lib64/python2.4/site-packages
976
 
   1527536 _lcms.so /usr/lib64/python2.4/site-packages
977
 
   736616 lapack_lite.so /usr/lib64/python2.4/site-packages/Numeric
978
 
</font>
979
 
<font color="#008000"># Which 3 files are the oldest?
980
 
</font><font color="#C00000">for </font>ctime<font color=
981
 
"#0000C0">,</font>directory<font color="#0000C0">,</font>file <font color=
982
 
"#C00000">in </font>cursor<font color="#0000C0">.</font>execute<font color=
983
 
"#0000C0">(</font><font color=
984
 
"#004080">"select st_ctime,directory,name from sysfiles order by st_ctime limit 3"</font><font color="#0000C0">):
985
 
    </font><font color="#C00000">print </font>ctime<font color=
986
 
"#0000C0">,</font>file<font color="#0000C0">,</font>directory
987
 
 
988
 
<font color="blue">   1157247798 libcdemu.py /usr/lib64/python2.4/site-packages
989
 
   1157247798 libcdemu.pyo /usr/lib64/python2.4/site-packages
990
 
   1157247798 libcdemu.pyc /usr/lib64/python2.4/site-packages
991
 
</font>
992
 
<font color="#008000">###
 
803
</span><span class="pykeyword">def </span><span class="pyname">getfiledata</span><span class=
 
804
"pyoperator">(</span><span class="pyname">directories</span><span class="pyoperator">):
 
805
    </span><span class="pyname">columns</span><span class="pyoperator">=</span><span class="pyname">None
 
806
    data</span><span class="pyoperator">=[]
 
807
    </span><span class="pyname">counter</span><span class="pyoperator">=</span><span class="pynumber">1
 
808
    </span><span class="pykeyword">for </span><span class="pyname">directory </span><span class=
 
809
"pykeyword">in </span><span class="pyname">directories</span><span class="pyoperator">:
 
810
        </span><span class="pykeyword">for </span><span class="pyname">f </span><span class=
 
811
"pykeyword">in </span><span class="pyname">os</span><span class="pyoperator">.</span><span class=
 
812
"pyname">listdir</span><span class="pyoperator">(</span><span class="pyname">directory</span><span class=
 
813
"pyoperator">):
 
814
            </span><span class="pykeyword">if not </span><span class="pyname">os</span><span class=
 
815
"pyoperator">.</span><span class="pyname">path</span><span class="pyoperator">.</span><span class=
 
816
"pyname">isfile</span><span class="pyoperator">(</span><span class="pyname">os</span><span class=
 
817
"pyoperator">.</span><span class="pyname">path</span><span class="pyoperator">.</span><span class=
 
818
"pyname">join</span><span class="pyoperator">(</span><span class="pyname">directory</span><span class=
 
819
"pyoperator">,</span><span class="pyname">f</span><span class="pyoperator">)):
 
820
                </span><span class="pykeyword">continue
 
821
            </span><span class="pyname">counter</span><span class="pyoperator">+=</span><span class="pynumber">1
 
822
            </span><span class="pyname">st</span><span class="pyoperator">=</span><span class=
 
823
"pyname">os</span><span class="pyoperator">.</span><span class="pyname">stat</span><span class=
 
824
"pyoperator">(</span><span class="pyname">os</span><span class="pyoperator">.</span><span class=
 
825
"pyname">path</span><span class="pyoperator">.</span><span class="pyname">join</span><span class=
 
826
"pyoperator">(</span><span class="pyname">directory</span><span class="pyoperator">,</span><span class=
 
827
"pyname">f</span><span class="pyoperator">))
 
828
            </span><span class="pykeyword">if </span><span class="pyname">columns </span><span class=
 
829
"pykeyword">is </span><span class="pyname">None</span><span class="pyoperator">:
 
830
                </span><span class="pyname">columns</span><span class="pyoperator">=[</span><span class=
 
831
"pystring">"rowid"</span><span class="pyoperator">, </span><span class="pystring">"name"</span><span class=
 
832
"pyoperator">, </span><span class="pystring">"directory"</span><span class="pyoperator">]+[</span><span class=
 
833
"pyname">x </span><span class="pykeyword">for </span><span class="pyname">x </span><span class=
 
834
"pykeyword">in </span><span class="pyname">dir</span><span class="pyoperator">(</span><span class=
 
835
"pyname">st</span><span class="pyoperator">) </span><span class="pykeyword">if </span><span class=
 
836
"pyname">x</span><span class="pyoperator">.</span><span class="pyname">startswith</span><span class=
 
837
"pyoperator">(</span><span class="pystring">"st_"</span><span class="pyoperator">)]
 
838
            </span><span class="pyname">data</span><span class="pyoperator">.</span><span class=
 
839
"pyname">append</span><span class="pyoperator">( [</span><span class="pyname">counter</span><span class=
 
840
"pyoperator">, </span><span class="pyname">f</span><span class="pyoperator">, </span><span class=
 
841
"pyname">directory</span><span class="pyoperator">] + [</span><span class="pyname">getattr</span><span class=
 
842
"pyoperator">(</span><span class="pyname">st</span><span class="pyoperator">,</span><span class=
 
843
"pyname">x</span><span class="pyoperator">) </span><span class="pykeyword">for </span><span class=
 
844
"pyname">x </span><span class="pykeyword">in </span><span class="pyname">columns</span><span class=
 
845
"pyoperator">[</span><span class="pynumber">3</span><span class="pyoperator">:]] )
 
846
    </span><span class="pykeyword">return </span><span class="pyname">columns</span><span class=
 
847
"pyoperator">, </span><span class="pyname">data
 
848
 
 
849
</span><span class="pycomment"># This gets registered with the Connection
 
850
</span><span class="pykeyword">class </span><span class="pyname">Source</span><span class="pyoperator">:
 
851
    </span><span class="pykeyword">def </span><span class="pyname">Create</span><span class=
 
852
"pyoperator">(</span><span class="pyname">self</span><span class="pyoperator">, </span><span class=
 
853
"pyname">db</span><span class="pyoperator">, </span><span class="pyname">modulename</span><span class=
 
854
"pyoperator">, </span><span class="pyname">dbname</span><span class="pyoperator">, </span><span class=
 
855
"pyname">tablename</span><span class="pyoperator">, *</span><span class="pyname">args</span><span class="pyoperator">):
 
856
        </span><span class="pyname">columns</span><span class="pyoperator">,</span><span class=
 
857
"pyname">data</span><span class="pyoperator">=</span><span class="pyname">getfiledata</span><span class=
 
858
"pyoperator">([</span><span class="pyname">eval</span><span class="pyoperator">(</span><span class=
 
859
"pyname">a</span><span class="pyoperator">.</span><span class="pyname">replace</span><span class=
 
860
"pyoperator">(</span><span class="pystring">"\\"</span><span class="pyoperator">, </span><span class=
 
861
"pystring">"\\\\"</span><span class="pyoperator">)) </span><span class="pykeyword">for </span><span class=
 
862
"pyname">a </span><span class="pykeyword">in </span><span class="pyname">args</span><span class=
 
863
"pyoperator">]) </span><span class="pycomment"># eval strips off layer of quotes
 
864
        </span><span class="pyname">schema</span><span class="pyoperator">=</span><span class=
 
865
"pystring">"create table foo("</span><span class="pyoperator">+</span><span class="pystring">','</span><span class=
 
866
"pyoperator">.</span><span class="pyname">join</span><span class="pyoperator">([</span><span class=
 
867
"pystring">"'%s'" </span><span class="pyoperator">% (</span><span class="pyname">x</span><span class=
 
868
"pyoperator">,) </span><span class="pykeyword">for </span><span class="pyname">x </span><span class=
 
869
"pykeyword">in </span><span class="pyname">columns</span><span class="pyoperator">[</span><span class=
 
870
"pynumber">1</span><span class="pyoperator">:]])+</span><span class="pystring">")"
 
871
        </span><span class="pykeyword">return </span><span class="pyname">schema</span><span class=
 
872
"pyoperator">,</span><span class="pyname">Table</span><span class="pyoperator">(</span><span class=
 
873
"pyname">columns</span><span class="pyoperator">,</span><span class="pyname">data</span><span class="pyoperator">)
 
874
    </span><span class="pyname">Connect</span><span class="pyoperator">=</span><span class="pyname">Create
 
875
 
 
876
</span><span class="pycomment"># Represents a table
 
877
</span><span class="pykeyword">class </span><span class="pyname">Table</span><span class="pyoperator">:
 
878
    </span><span class="pykeyword">def </span><span class="pyname">__init__</span><span class=
 
879
"pyoperator">(</span><span class="pyname">self</span><span class="pyoperator">, </span><span class=
 
880
"pyname">columns</span><span class="pyoperator">, </span><span class="pyname">data</span><span class="pyoperator">):
 
881
        </span><span class="pyname">self</span><span class="pyoperator">.</span><span class=
 
882
"pyname">columns</span><span class="pyoperator">=</span><span class="pyname">columns
 
883
        self</span><span class="pyoperator">.</span><span class="pyname">data</span><span class=
 
884
"pyoperator">=</span><span class="pyname">data
 
885
 
 
886
    </span><span class="pykeyword">def </span><span class="pyname">BestIndex</span><span class=
 
887
"pyoperator">(</span><span class="pyname">self</span><span class="pyoperator">, *</span><span class=
 
888
"pyname">args</span><span class="pyoperator">):
 
889
        </span><span class="pykeyword">return </span><span class="pyname">None
 
890
 
 
891
    </span><span class="pykeyword">def </span><span class="pyname">Open</span><span class=
 
892
"pyoperator">(</span><span class="pyname">self</span><span class="pyoperator">):
 
893
        </span><span class="pykeyword">return </span><span class="pyname">Cursor</span><span class=
 
894
"pyoperator">(</span><span class="pyname">self</span><span class="pyoperator">)
 
895
 
 
896
    </span><span class="pykeyword">def </span><span class="pyname">Disconnect</span><span class=
 
897
"pyoperator">(</span><span class="pyname">self</span><span class="pyoperator">):
 
898
        </span><span class="pykeyword">pass
 
899
 
 
900
    </span><span class="pyname">Destroy</span><span class="pyoperator">=</span><span class="pyname">Disconnect
 
901
 
 
902
</span><span class="pycomment"># Represents a cursor
 
903
</span><span class="pykeyword">class </span><span class="pyname">Cursor</span><span class="pyoperator">:
 
904
    </span><span class="pykeyword">def </span><span class="pyname">__init__</span><span class=
 
905
"pyoperator">(</span><span class="pyname">self</span><span class="pyoperator">, </span><span class=
 
906
"pyname">table</span><span class="pyoperator">):
 
907
        </span><span class="pyname">self</span><span class="pyoperator">.</span><span class=
 
908
"pyname">table</span><span class="pyoperator">=</span><span class="pyname">table
 
909
 
 
910
    </span><span class="pykeyword">def </span><span class="pyname">Filter</span><span class=
 
911
"pyoperator">(</span><span class="pyname">self</span><span class="pyoperator">, *</span><span class=
 
912
"pyname">args</span><span class="pyoperator">):
 
913
        </span><span class="pyname">self</span><span class="pyoperator">.</span><span class=
 
914
"pyname">pos</span><span class="pyoperator">=</span><span class="pynumber">0
 
915
 
 
916
    </span><span class="pykeyword">def </span><span class="pyname">Eof</span><span class=
 
917
"pyoperator">(</span><span class="pyname">self</span><span class="pyoperator">):
 
918
        </span><span class="pykeyword">return </span><span class="pyname">self</span><span class=
 
919
"pyoperator">.</span><span class="pyname">pos</span><span class="pyoperator">&gt;=</span><span class=
 
920
"pyname">len</span><span class="pyoperator">(</span><span class="pyname">self</span><span class=
 
921
"pyoperator">.</span><span class="pyname">table</span><span class="pyoperator">.</span><span class=
 
922
"pyname">data</span><span class="pyoperator">)
 
923
 
 
924
    </span><span class="pykeyword">def </span><span class="pyname">Rowid</span><span class=
 
925
"pyoperator">(</span><span class="pyname">self</span><span class="pyoperator">):
 
926
        </span><span class="pykeyword">return </span><span class="pyname">self</span><span class=
 
927
"pyoperator">.</span><span class="pyname">table</span><span class="pyoperator">.</span><span class=
 
928
"pyname">data</span><span class="pyoperator">[</span><span class="pyname">self</span><span class=
 
929
"pyoperator">.</span><span class="pyname">pos</span><span class="pyoperator">][</span><span class=
 
930
"pynumber">0</span><span class="pyoperator">]
 
931
 
 
932
    </span><span class="pykeyword">def </span><span class="pyname">Column</span><span class=
 
933
"pyoperator">(</span><span class="pyname">self</span><span class="pyoperator">, </span><span class=
 
934
"pyname">col</span><span class="pyoperator">):
 
935
        </span><span class="pykeyword">return </span><span class="pyname">self</span><span class=
 
936
"pyoperator">.</span><span class="pyname">table</span><span class="pyoperator">.</span><span class=
 
937
"pyname">data</span><span class="pyoperator">[</span><span class="pyname">self</span><span class=
 
938
"pyoperator">.</span><span class="pyname">pos</span><span class="pyoperator">][</span><span class=
 
939
"pynumber">1</span><span class="pyoperator">+</span><span class="pyname">col</span><span class="pyoperator">]
 
940
 
 
941
    </span><span class="pykeyword">def </span><span class="pyname">Next</span><span class=
 
942
"pyoperator">(</span><span class="pyname">self</span><span class="pyoperator">):
 
943
        </span><span class="pyname">self</span><span class="pyoperator">.</span><span class=
 
944
"pyname">pos</span><span class="pyoperator">+=</span><span class="pynumber">1
 
945
 
 
946
    </span><span class="pykeyword">def </span><span class="pyname">Close</span><span class=
 
947
"pyoperator">(</span><span class="pyname">self</span><span class="pyoperator">):
 
948
        </span><span class="pykeyword">pass
 
949
 
 
950
</span><span class="pycomment"># Register the module as filesource
 
951
</span><span class="pyname">connection</span><span class="pyoperator">.</span><span class=
 
952
"pyname">createmodule</span><span class="pyoperator">(</span><span class="pystring">"filesource"</span><span class=
 
953
"pyoperator">, </span><span class="pyname">Source</span><span class="pyoperator">())
 
954
 
 
955
</span><span class="pycomment"># Arguments to module - all directories in sys.path
 
956
</span><span class="pyname">sysdirs</span><span class="pyoperator">=</span><span class=
 
957
"pystring">","</span><span class="pyoperator">.</span><span class="pyname">join</span><span class=
 
958
"pyoperator">([</span><span class="pystring">"'%s'" </span><span class="pyoperator">% (</span><span class=
 
959
"pyname">x</span><span class="pyoperator">,) </span><span class="pykeyword">for </span><span class=
 
960
"pyname">x </span><span class="pykeyword">in </span><span class="pyname">sys</span><span class=
 
961
"pyoperator">.</span><span class="pyname">path</span><span class="pyoperator">[</span><span class=
 
962
"pynumber">1</span><span class="pyoperator">:] </span><span class="pykeyword">if </span><span class=
 
963
"pyname">len</span><span class="pyoperator">(</span><span class="pyname">x</span><span class=
 
964
"pyoperator">) </span><span class="pykeyword">and </span><span class="pyname">os</span><span class=
 
965
"pyoperator">.</span><span class="pyname">path</span><span class="pyoperator">.</span><span class=
 
966
"pyname">isdir</span><span class="pyoperator">(</span><span class="pyname">x</span><span class="pyoperator">)])
 
967
</span><span class="pyname">cursor</span><span class="pyoperator">.</span><span class=
 
968
"pyname">execute</span><span class="pyoperator">(</span><span class=
 
969
"pystring">"create virtual table sysfiles using filesource("</span><span class="pyoperator">+</span><span class=
 
970
"pyname">sysdirs</span><span class="pyoperator">+</span><span class="pystring">")"</span><span class="pyoperator">)
 
971
 
 
972
</span><span class="pycomment"># Which 3 files are the biggest?
 
973
</span><span class="pykeyword">for </span><span class="pyname">size</span><span class="pyoperator">,</span><span class=
 
974
"pyname">directory</span><span class="pyoperator">,</span><span class="pyname">file </span><span class=
 
975
"pykeyword">in </span><span class="pyname">cursor</span><span class="pyoperator">.</span><span class=
 
976
"pyname">execute</span><span class="pyoperator">(</span><span class=
 
977
"pystring">"select st_size,directory,name from sysfiles order by st_size desc limit 3"</span><span class=
 
978
"pyoperator">):
 
979
    </span><span class="pykeyword">print </span><span class="pyname">size</span><span class=
 
980
"pyoperator">,</span><span class="pyname">file</span><span class="pyoperator">,</span><span class="pyname">directory
 
981
 
 
982
</span><span class="pyoutput">   8625144 qt.so /usr/lib/python2.5/site-packages
 
983
   786208 qtsql.so /usr/lib/python2.5/site-packages
 
984
   481008 unicodedata.so /usr/lib/python2.5/lib-dynload
 
985
</span>
 
986
<span class="pycomment"># Which 3 files are the oldest?
 
987
</span><span class="pykeyword">for </span><span class="pyname">ctime</span><span class=
 
988
"pyoperator">,</span><span class="pyname">directory</span><span class="pyoperator">,</span><span class=
 
989
"pyname">file </span><span class="pykeyword">in </span><span class="pyname">cursor</span><span class=
 
990
"pyoperator">.</span><span class="pyname">execute</span><span class="pyoperator">(</span><span class=
 
991
"pystring">"select st_ctime,directory,name from sysfiles order by st_ctime limit 3"</span><span class="pyoperator">):
 
992
    </span><span class="pykeyword">print </span><span class="pyname">ctime</span><span class=
 
993
"pyoperator">,</span><span class="pyname">file</span><span class="pyoperator">,</span><span class="pyname">directory
 
994
 
 
995
</span><span class="pyoutput">   1194713443.0 GnuPGInterface-0.3.2.egg-info /var/lib/python-support/python2.5
 
996
   1194713443.0 GnuPGInterface.py /var/lib/python-support/python2.5
 
997
   1194713447.0 sexy.so /usr/lib/python2.5/site-packages/gtk-2.0
 
998
</span>
 
999
<span class="pycomment">###
 
1000
### Limits
 
1001
###
 
1002
 
 
1003
# Print some limits
 
1004
</span><span class="pykeyword">for </span><span class="pyname">limit </span><span class=
 
1005
"pykeyword">in </span><span class="pyoperator">(</span><span class="pystring">"LENGTH"</span><span class=
 
1006
"pyoperator">, </span><span class="pystring">"COLUMN"</span><span class="pyoperator">, </span><span class=
 
1007
"pystring">"ATTACHED"</span><span class="pyoperator">):
 
1008
    </span><span class="pyname">name</span><span class="pyoperator">=</span><span class=
 
1009
"pystring">"SQLITE_LIMIT_"</span><span class="pyoperator">+</span><span class="pyname">limit
 
1010
    maxname</span><span class="pyoperator">=</span><span class="pystring">"SQLITE_MAX_"</span><span class=
 
1011
"pyoperator">+</span><span class="pyname">limit  </span><span class="pycomment"># compile time
 
1012
    </span><span class="pyname">orig</span><span class="pyoperator">=</span><span class=
 
1013
"pyname">connection</span><span class="pyoperator">.</span><span class="pyname">limit</span><span class=
 
1014
"pyoperator">(</span><span class="pyname">getattr</span><span class="pyoperator">(</span><span class=
 
1015
"pyname">apsw</span><span class="pyoperator">, </span><span class="pyname">name</span><span class="pyoperator">))
 
1016
    </span><span class="pykeyword">print </span><span class="pyname">name</span><span class=
 
1017
"pyoperator">, </span><span class="pyname">orig
 
1018
    </span><span class="pycomment"># To get the maximum, set to 0x7fffffff and then read value back
 
1019
    </span><span class="pyname">connection</span><span class="pyoperator">.</span><span class=
 
1020
"pyname">limit</span><span class="pyoperator">(</span><span class="pyname">getattr</span><span class=
 
1021
"pyoperator">(</span><span class="pyname">apsw</span><span class="pyoperator">, </span><span class=
 
1022
"pyname">name</span><span class="pyoperator">), </span><span class="pynumber">0x7fffffff</span><span class=
 
1023
"pyoperator">)
 
1024
    </span><span class="pyname">max</span><span class="pyoperator">=</span><span class=
 
1025
"pyname">connection</span><span class="pyoperator">.</span><span class="pyname">limit</span><span class=
 
1026
"pyoperator">(</span><span class="pyname">getattr</span><span class="pyoperator">(</span><span class=
 
1027
"pyname">apsw</span><span class="pyoperator">, </span><span class="pyname">name</span><span class="pyoperator">))
 
1028
    </span><span class="pykeyword">print </span><span class="pyname">maxname</span><span class=
 
1029
"pyoperator">, </span><span class="pyname">max
 
1030
 
 
1031
</span><span class="pycomment"># Set limit for size of a string
 
1032
</span><span class="pyname">cursor</span><span class="pyoperator">.</span><span class=
 
1033
"pyname">execute</span><span class="pyoperator">(</span><span class=
 
1034
"pystring">"create table testlimit(s)"</span><span class="pyoperator">)
 
1035
</span><span class="pyname">cursor</span><span class="pyoperator">.</span><span class=
 
1036
"pyname">execute</span><span class="pyoperator">(</span><span class=
 
1037
"pystring">"insert into testlimit values(?)"</span><span class="pyoperator">, ( </span><span class=
 
1038
"pystring">"x"</span><span class="pyoperator">*</span><span class="pynumber">1024</span><span class=
 
1039
"pyoperator">, )) </span><span class="pycomment"># 1024 char string
 
1040
</span><span class="pyname">connection</span><span class="pyoperator">.</span><span class=
 
1041
"pyname">limit</span><span class="pyoperator">(</span><span class="pyname">apsw</span><span class=
 
1042
"pyoperator">.</span><span class="pyname">SQLITE_LIMIT_LENGTH</span><span class="pyoperator">, </span><span class=
 
1043
"pynumber">1023</span><span class="pyoperator">) </span><span class="pycomment"># limit is now 1023
 
1044
</span><span class="pykeyword">try</span><span class="pyoperator">:
 
1045
    </span><span class="pyname">cursor</span><span class="pyoperator">.</span><span class=
 
1046
"pyname">execute</span><span class="pyoperator">(</span><span class=
 
1047
"pystring">"insert into testlimit values(?)"</span><span class="pyoperator">, ( </span><span class=
 
1048
"pystring">"y"</span><span class="pyoperator">*</span><span class="pynumber">1024</span><span class="pyoperator">, ))
 
1049
    </span><span class="pykeyword">print </span><span class="pystring">"string exceeding limit was inserted"
 
1050
</span><span class="pykeyword">except </span><span class="pyname">apsw</span><span class=
 
1051
"pyoperator">.</span><span class="pyname">TooBigError</span><span class="pyoperator">:
 
1052
    </span><span class="pykeyword">print </span><span class="pystring">"Caught toobig exception"
 
1053
 
 
1054
 
 
1055
</span><span class="pyoutput">   SQLITE_LIMIT_LENGTH 1000000000
 
1056
   SQLITE_MAX_LENGTH 1000000000
 
1057
   SQLITE_LIMIT_COLUMN 2000
 
1058
   SQLITE_MAX_COLUMN 2000
 
1059
   SQLITE_LIMIT_ATTACHED 10
 
1060
   SQLITE_MAX_ATTACHED 10
 
1061
   Caught toobig exception
 
1062
</span>
 
1063
<span class="pycomment">###
993
1064
### Cleanup
994
1065
###
995
1066
 
996
 
# We must close connections
997
 
</font>connection<font color="#0000C0">.</font>close<font color=
998
 
"#0000C0">(</font>True<font color="#0000C0">)  </font><font color=
999
 
"#008000"># force it since we want to exit</font>
 
1067
# We can close connections manually (useful if you want to catch exceptions)
 
1068
# but you don't have to
 
1069
</span><span class="pyname">connection</span><span class="pyoperator">.</span><span class=
 
1070
"pyname">close</span><span class="pyoperator">(</span><span class="pyname">True</span><span class=
 
1071
"pyoperator">)  </span><span class="pycomment"># force it since we want to exit</span></font>
1000
1072
<!--sourceend-->
1001
1073
</pre>
1002
1074
  </blockquote>
1008
1080
  <blockquote>
1009
1081
    <pre>
1010
1082
python setup.py install
 
1083
 
1011
1084
</pre>
1012
1085
  </blockquote>
1013
1086
 
1014
 
  <p>On Windows the above command uses Visual C++. You can use MinGW with the
1015
 
  command below. (If MinGW complains about missing Python functions starting
1016
 
  with <code>_imp__Py_</code> then run <code>mingwsetup.bat</code> which will
1017
 
  ensure your Python distribution is initialized for MinGW compilation).</p>
 
1087
  <p>On Windows the above command uses Visual C++. You can use MinGW with the command below. (If MinGW complains about
 
1088
  missing Python functions starting with <code>_imp__Py_</code> then run <code>mingwsetup.bat</code> which will ensure
 
1089
  your Python distribution is initialized for MinGW compilation).</p>
1018
1090
 
1019
1091
  <blockquote>
1020
1092
    <pre>
1021
1093
python setup.py build --compile=mingw32 install
 
1094
 
1022
1095
</pre>
1023
1096
  </blockquote>
1024
1097
 
1025
 
  <p>By default whatever SQLite 3 you already have on your system is used. If
1026
 
  you place a copy of the headers and library in a <code>sqlite3</code>
1027
 
  subdirectory then that will be used instead. It is highly recommended that
1028
 
  you build SQLite into APSW. Here is a quick and easy way of doing everything
1029
 
  on Linux/Mac or Windows with MinGW, including the SQLite library statically
1030
 
  into the extension (ie no external DLLs/shared libraries will be needed at
1031
 
  runtime). You should follow these instructions with your current directory
1032
 
  being where you extracted the APSW source to.</p>
1033
 
 
1034
 
  <blockquote>
1035
 
    <p>Download the <a href="http://www.sqlite.org/download.html">SQLite 3
1036
 
    code</a>.</p>
1037
 
 
1038
 
    <dl>
1039
 
      <dt><b>Windows</b><br />
1040
 
      Get the processed .zip</dt>
1041
 
 
1042
 
      <dd>
1043
 
        <pre>
1044
 
&gt; mkdir sqlite3
1045
 
&gt; cd sqlite3
1046
 
&gt; unzip sqlite-source-3_3_10.zip
1047
 
&gt; del tclsqlite.c
1048
 
&gt; gcc -DTHREADSAFE -DNDEBUG -O3 -c *.c
1049
 
&gt; ar r libsqlite3.a *.o
1050
 
&gt; ranlib libsqlite3.a
1051
 
&gt; cd ..
1052
 
&gt; python setup.py build --compile=mingw32 install
 
1098
  <h2><a name="Finding" id="Finding">Finding SQLite 3</a></h2>
 
1099
 
 
1100
  <p>SQLite 3 is needed during the build process. These methods are tried in order:</p>
 
1101
 
 
1102
  <dl>
 
1103
    <dt><a href="http://www.sqlite.org/cvstrac/wiki?p=TheAmalgamation">Amalgamation</a></dt>
 
1104
 
 
1105
    <dd>The file <tt>sqlite3.c</tt> and then <tt>sqlite3/sqlite3.c</tt> is looked for.</dd>
 
1106
 
 
1107
    <dt>Local build</dt>
 
1108
 
 
1109
    <dd>The header <tt>sqlite3/sqlite3.h</tt> and library <tt>sqlite3/libsqlite3.{a,so,dll}</tt> is looked for.</dd>
 
1110
 
 
1111
    <dt>System</dt>
 
1112
 
 
1113
    <dd>The default compiler include path (eg <tt>/usr/include</tt>) and library path (eg <tt>/usr/lib</tt>) are
 
1114
    used.</dd>
 
1115
  </dl>
 
1116
 
 
1117
  <p>Note that if you compiled SQLite with any OMIT flags (eg <tt>SQLITE_OMIT_LOAD_EXTENSION</tt>) then you should edit
 
1118
  <tt>setup.py</tt> to add the same flags.</p>
 
1119
 
 
1120
  <h2><a name="Recommended" id="Recommended">Recommended</a></h2>
 
1121
 
 
1122
  <p>These instructions show how to build using the amalgamation. Any existing SQLite on your system is ignored at
 
1123
  build time and runtime. (Note that you can even use APSW in the same process as a different SQLite is used by other
 
1124
  libraries - this happens a lot on Mac.) You should follow these instructions with your current directory being where
 
1125
  you extracted the APSW source to. You can use 3.5.9 or later versions of SQLite.</p>
 
1126
 
 
1127
  <dl>
 
1128
    <dt><b>Windows</b></dt>
 
1129
  </dl>
 
1130
  <pre>
 
1131
 <font color="blue"> Manually download and extract <a href=
 
1132
"http://sqlite.org/sqlite-amalgamation-3_5_9.zip">http://sqlite.org/sqlite-amalgamation-3_5_9.zip</a></font>
 
1133
&gt; python setup.py build --compile=mingw32 install         <font color=
 
1134
"blue">Leave out --compile=... flag if using Microsoft compiler</font>
1053
1135
&gt; python -c "import apsw ; print  apsw.sqlitelibversion(), apsw.apswversion()"
1054
 
</pre>
1055
 
      </dd>
1056
 
 
1057
 
      <dt><b>Mac/Linux/etc</b><br />
1058
 
      Get the normal source.</dt>
1059
 
 
1060
 
      <dd>
1061
 
        <pre>
1062
 
$ wget http://www.sqlite.org/sqlite-3.3.13.tar.gz
1063
 
$ tar xvfz sqlite-3.3.13.tar.gz
1064
 
$ mv sqlite-3.3.13 sqlite3
1065
 
$ cd sqlite3
1066
 
<font color=
1067
 
"blue"># The static library is not built for inclusion into a seperate shared library
1068
 
# by default.  If using gcc, then do this</font>
1069
 
$ env CC="gcc -fPIC" CFLAGS="-DHAVE_DLOPEN" ./configure --enable-threadsafe --disable-tcl
1070
 
<font color="blue"># otherwise do this</font>
1071
 
$ env CFLAGS="-DHAVE_DLOPEN" ./configure --enable-threadsafe --disable-tcl
1072
 
<font color=
1073
 
"blue"># The <tt>CFLAGS="-DHAVE_DLOPEN</tt> bit is needed for loading dynamic
1074
 
# extensions.  See SQLite bug <a href=
1075
 
"http://www.sqlite.org/cvstrac/tktview?tn=2082">2082</a></font>
1076
 
$ make
1077
 
$ cp .libs/*.a .
1078
 
$ cd ..
 
1136
&gt; python test.py       <font color="blue"># optional - checks everything works correctly</font>
 
1137
 
 
1138
</pre>Note that there will be many warnings during the compilation step about sqlite3.c, <a href=
 
1139
"http://sqlite.org/faq.html#q17">but they are harmless</a>.
 
1140
 
 
1141
  <dl>
 
1142
    <dt><b>Mac/Linux/etc</b></dt>
 
1143
  </dl>
 
1144
  <pre>
 
1145
$ wget <a href="http://sqlite.org/sqlite-amalgamation-3_5_9.zip">http://sqlite.org/sqlite-amalgamation-3_5_9.zip</a>
 
1146
$ unzip sqlite-amalgamation-3_5_9.zip
1079
1147
$ python setup.py install
1080
 
$ python -c "import apsw ; print  apsw.sqlitelibversion(), apsw.apswversion()"      
1081
 
</pre>
1082
 
      </dd>
1083
 
    </dl>
1084
 
  </blockquote>
1085
 
 
1086
 
  <p>The extension just turns into a single file apsw.so (Linux/Mac) or
1087
 
  apsw.pyd (Windows). You don't need to install it and can drop it into any
1088
 
  directory that is more convenient for you and that your code can reach. To
1089
 
  just do the build and not install, leave out <code>install</code> from the
1090
 
  lines above and add <code>build</code> if it isn't already there.</p>
1091
 
 
1092
 
  <p>If you want to check that your build is correct then you can run the unit
1093
 
  tests. Run <tt>tests.py</tt>. It will print the APSW file used, APSW and
1094
 
  SQLite versions and then run lots of tests all of which should pass.</p>
 
1148
$ python -c "import apsw ; print  apsw.sqlitelibversion(), apsw.apswversion()"     
 
1149
$ python test.py       <font color="blue"># optional - checks everything works correctly</font>
 
1150
 
 
1151
</pre>Note that there will be many warnings during the compilation step about sqlite3.c, <a href=
 
1152
"http://sqlite.org/faq.html#q17">but they are harmless</a>.
 
1153
 
 
1154
  <p>The extension just turns into a single file apsw.so (Linux/Mac) or apsw.pyd (Windows). You don't need to install
 
1155
  it and can drop it into any directory that is more convenient for you and that your code can reach. To just do the
 
1156
  build and not install, leave out <code>install</code> from the lines above and add <code>build</code> if it isn't
 
1157
  already there.</p>
 
1158
 
 
1159
  <p>If you want to check that your build is correct then you can run the unit tests. Run <tt>tests.py</tt>. It will
 
1160
  print the APSW file used, APSW and SQLite versions and then run lots of tests all of which should pass.</p>
1095
1161
 
1096
1162
  <h1><a name="APIReference" id="APIReference">API Reference</a></h1>
1097
1163
 
1098
 
  <p>Everything you can do from the <a href=
1099
 
  "http://www.sqlite.org/capi3ref.html">SQLite 3 C API</a> you can do from
1100
 
  Python. The documentation below notes which C API functions are called where
1101
 
  you can get further details on what happens. The only C function not
1102
 
  implemented is <a href=
1103
 
  "http://www.sqlite.org/capi3ref.html#sqlite3_collation_needed">sqlite3_collation_needed</a>.
1104
 
  (You can still add collations, you just can't use this function to find out
1105
 
  about them on-demand.) Additionally <a href=
1106
 
  "http://www.sqlite.org/capi3ref.html#sqlite3_trace">sqlite3_trace</a> is not
1107
 
  wrapped but instead <a href="#tracers">tracers</a> are provided that have
1108
 
  more functionality.</p>
1109
 
 
1110
 
  <p>Some functions are marked experimental in the SQLite API. These have also
1111
 
  been made available, but as the SQLite documentation notes these functions
1112
 
  may change form or disappear in future versions of SQLite. You can exclude
1113
 
  these functions by commenting out the relevant line in the
1114
 
  <code>setup.py</code> when building aspw.</p>
1115
 
 
1116
 
  <p>Various methods create functions, collations and set various hooks and
1117
 
  handlers. To remove the relevant function/collation/hook/handler, pass in
1118
 
  None as the callable method.</p>
 
1164
  <p>Everything you can do from the <a href="http://www.sqlite.org/c3ref/intro.html">SQLite 3 C API</a> you can do from
 
1165
  Python. The documentation below notes which C API functions are called where you can get further details on what
 
1166
  happens. The only functionality not implemented is <a href="http://www.sqlite.org/c3ref/vfs.html">VFS</a> because it
 
1167
  is being changed for SQLite 3.6. Additionally <a href="http://sqlite.org/c3ref/profile.html">sqlite3_trace</a> is not
 
1168
  wrapped but instead <a href="#tracers">tracers</a> are provided that have more functionality.</p>
 
1169
 
 
1170
  <p>Some functions are marked experimental in the SQLite API. These have also been made available, but as the SQLite
 
1171
  documentation notes these functions may change form or disappear in future versions of SQLite. You can exclude these
 
1172
  functions by commenting out the relevant line in the <code>setup.py</code> when building aspw.</p>
 
1173
 
 
1174
  <p>Various methods create functions, collations and set various hooks and handlers. To remove the relevant
 
1175
  function/collation/hook/handler, pass in None as the callable method.</p>
1119
1176
 
1120
1177
  <h2><a name="module-methods" id="module-methods">Module methods</a></h2>
1121
1178
 
1123
1180
    <dt><strong>sqlitelibversion()</strong></dt>
1124
1181
 
1125
1182
    <dd>
1126
 
      <p>Returns the version of the SQLite library as a string. This function
1127
 
      calls <a href=
1128
 
      "http://www.sqlite.org/capi3ref.html#sqlite3_libversion">sqlite3_libversion</a>.</p>
 
1183
      <p>Returns the version of the SQLite library as a string. This function calls <a href=
 
1184
      "http://sqlite.org/c3ref/libversion.html">sqlite3_libversion</a>.</p>
1129
1185
    </dd>
1130
1186
 
1131
1187
    <dt><strong>apswversion()</strong></dt>
1137
1193
    <dt><strong>enablesharedcache(boolean)</strong></dt>
1138
1194
 
1139
1195
    <dd>
1140
 
      <p>Calls <a href=
1141
 
      "http://www.sqlite.org/capi3ref.html#sqlite3_enable_shared_cache">sqlite3_enable_shared_cache</a>.
1142
 
      This sets the <a href="http://www.sqlite.org/sharedcache.html">shared
1143
 
      cache mode</a> which was introduced in SQLite 3.3. Note that it only
1144
 
      affects the current thread and should be called before any databases are
1145
 
      opened. If called after that then you'll get MisuseError. APSW already
1146
 
      enforces the other conditions required to use this functionality, namely
1147
 
      that all operations on a Connection must happen in the same thread.
1148
 
      Consequently you can safely use this functionality. You do not need to
1149
 
      worry about <a href=
1150
 
      "http://www.sqlite.org/capi3ref.html#sqlite3_thread_cleanup">sqlite3_thread_cleanup</a>
1151
 
      as that is only needed when abnormally terminating a thread (something
1152
 
      you can't do in Python). Python's normal reference counting ensures all
1153
 
      objects are cleaned up, and SQLite automatically cleans up the shared
1154
 
      cache when the last Connection in a thread is closed.</p>
 
1196
      <p>Calls <a href="http://sqlite.org/c3ref/enable_shared_cache.html">sqlite3_enable_shared_cache</a>. This sets
 
1197
      the <a href="http://www.sqlite.org/sharedcache.html">shared cache mode</a> which was introduced in SQLite
 
1198
      3.3.</p>
1155
1199
    </dd>
1156
1200
 
1157
1201
    <dt><strong>createmodule("modulename", module_object)</strong></dt>
1158
1202
 
1159
1203
    <dd>
1160
 
      <p>Registers a virtual table. See <a href="#VirtualTables">virtual
1161
 
      tables</a> for more details.</p>
 
1204
      <p>Registers a virtual table. See <a href="#VirtualTables">virtual tables</a> for more details.</p>
1162
1205
    </dd>
1163
1206
  </dl>
1164
1207
 
1165
 
  <h2><a name="Module_variables" id="Module_variables">Module
1166
 
  variables</a></h2>
 
1208
  <h2><a name="Module_variables" id="Module_variables">Module variables</a></h2>
1167
1209
 
1168
1210
  <dl>
1169
1211
    <dt><strong>connection_hooks</strong></dt>
1170
1212
 
1171
1213
    <dd>
1172
 
      <p>The purpose of the hooks is to allow the easy registration of
1173
 
      functions, virtual tables or similar items with each Connection as it is
1174
 
      created. The default value is an empty list. Whenever a Connection is
1175
 
      created, each item in <code>apsw.connection_hooks</code> is invoked with
1176
 
      a single parameter being the new Connection object. If the hook raises an
1177
 
      exception then the creation of the Connection fails.</p>
 
1214
      <p>The purpose of the hooks is to allow the easy registration of functions, virtual tables or similar items with
 
1215
      each Connection as it is created. The default value is an empty list. Whenever a Connection is created, each item
 
1216
      in <code>apsw.connection_hooks</code> is invoked with a single parameter being the new Connection object. If the
 
1217
      hook raises an exception then the creation of the Connection fails.</p>
1178
1218
    </dd>
1179
1219
  </dl>
1180
1220
 
1181
 
  <h2><a name="Module_constants" id="Module_constants">Module
1182
 
  constants</a></h2>
 
1221
  <h2><a name="Module_constants" id="Module_constants">Module constants</a></h2>
1183
1222
 
1184
 
  <p>Note that the same values can be used in different contexts. For example
1185
 
  SQLITE_OK and SQLITE_CREATE_INDEX both have a value of zero. For each group
1186
 
  of constants there is also a mapping (dict) available that you can supply a
1187
 
  string to and get the corresponding numeric value, or supply a numeric value
1188
 
  and get the corresponding string. These can help improve diagnostics/logging,
1189
 
  calling other modules etc. For example</p>
 
1223
  <p>Note that the same values can be used in different contexts. For example SQLITE_OK and SQLITE_CREATE_INDEX both
 
1224
  have a value of zero. For each group of constants there is also a mapping (dict) available that you can supply a
 
1225
  string to and get the corresponding numeric value, or supply a numeric value and get the corresponding string. These
 
1226
  can help improve diagnostics/logging, calling other modules etc. For example</p>
1190
1227
 
1191
1228
  <blockquote>
1192
1229
    <pre>
1193
1230
apsw.mapping_authorizer_function["SQLITE_READ"]=20
1194
1231
apsw.mapping_authorizer_function[20]="SQLITE_READ"
 
1232
 
1195
1233
</pre>
1196
1234
  </blockquote>
1197
1235
 
1199
1237
    <dt><strong>SQLITE_VERSION_NUMBER</strong></dt>
1200
1238
 
1201
1239
    <dd>
1202
 
      <p>This is the version of the SQLite library from the header file
1203
 
      <tt>sqlite3.h</tt> at apsw compile time. It is expressed as an integer
1204
 
      (eg 3003010 for SQLite 3.3.10).</p>
 
1240
      <p>This is the version of the SQLite library from the header file <tt>sqlite3.h</tt> at apsw compile time. It is
 
1241
      expressed as an integer (eg 3003010 for SQLite 3.3.10).</p>
1205
1242
    </dd>
1206
1243
 
1207
 
    <dt><strong>SQLITE_OK, SQLITE_DENY, SQLITE_IGNORE</strong></dt>
 
1244
    <dt><strong><a href="http://sqlite.org/c3ref/c_deny.html">SQLITE_OK, SQLITE_DENY, SQLITE_IGNORE</a></strong></dt>
1208
1245
 
1209
1246
    <dd>
1210
1247
      <p>These values are returned from authorizer functions. Mapping is
1211
1248
      <code>apsw.mapping_authorizer_return</code></p>
1212
1249
    </dd>
1213
1250
 
1214
 
    <dt><strong>SQLITE_CREATE_INDEX, SQLITE_CREATE_TABLE</strong> and 30
1215
 
    others</dt>
 
1251
    <dt><a href="http://sqlite.org/c3ref/c_alter_table.html"><strong>SQLITE_CREATE_INDEX, SQLITE_CREATE_TABLE</strong>
 
1252
    and 30 others</a></dt>
1216
1253
 
1217
1254
    <dd>
1218
 
      <p>The values are passed to authorizer functions. You can see a complete
1219
 
      list in the <a href=
1220
 
      "http://sqlite.org/capi3ref.html#sqlite3_set_authorizer">sqlite3_set_authorizer
1221
 
      documentation</a>. Mapping is
 
1255
      <p>The values are passed to authorizer functions. You can see a complete list in the <a href=
 
1256
      "http://sqlite.org/c3ref/set_authorizer.html">sqlite3_set_authorizer documentation</a>. Mapping is
1222
1257
      <code>apsw.mapping_authorizer_function</code></p>
1223
1258
    </dd>
1224
1259
 
1225
 
    <dt><strong>SQLITE_INDEX_CONSTRAINT_EQ, SQLITE_INDEX_CONSTRAINT_GT</strong>
1226
 
    and 4 others</dt>
 
1260
    <dt><strong>SQLITE_INDEX_CONSTRAINT_EQ, SQLITE_INDEX_CONSTRAINT_GT</strong> and 4 others</dt>
1227
1261
 
1228
1262
    <dd>
1229
 
      <p>These values are passed to the BestIndex method of <a href=
1230
 
      "#VirtualTables">virtual tables</a>. Mapping is
 
1263
      <p>These values are passed to the BestIndex method of <a href="#VirtualTables">virtual tables</a>. Mapping is
1231
1264
      <code>apsw.mapping_bestindex_constraints</code></p>
1232
1265
    </dd>
1233
1266
 
1234
 
    <dt><strong>SQLITE_IOERR_READ, SQLITE_IOERR_FSYNC</strong> and 7
1235
 
    others</dt>
1236
 
 
1237
 
    <dd>
1238
 
      <p>These are <a href=
1239
 
      "http://www.sqlite.org/cvstrac/wiki?p=ExtendedResultCodes">extended
1240
 
      result codes</a> which are provided in <a href=
1241
 
      "#Exceptions">exceptions</a>. Mapping is
1242
 
      <code>apsw.mapping_extended_result_codes</code></p>
1243
 
    </dd>
1244
 
 
1245
 
    <dt><strong>SQLITE_OK, SQLITE_ERROR, SQLITE_PERM</strong> and 22
1246
 
    others</dt>
1247
 
 
1248
 
    <dd>
1249
 
      <p>These are <a href=
1250
 
      "http://sqlite.org/capi3ref.html#result-codes">SQLite result codes</a>
1251
 
      which are provided in <a href="#Exceptions">exceptions</a>. Mapping is
1252
 
      <code>apsw.mapping_result_codes</code></p>
 
1267
    <dt><a href="http://sqlite.org/c3ref/c_ioerr_blocked.html"><strong>SQLITE_IOERR_READ, SQLITE_IOERR_FSYNC</strong>
 
1268
    and 7 others</a></dt>
 
1269
 
 
1270
    <dd>
 
1271
      <p>These are <a href="http://sqlite.org/c3ref/c_ioerr_blocked.html">extended result codes</a> which are provided
 
1272
      in <a href="#Exceptions">exceptions</a>. Mapping is <code>apsw.mapping_extended_result_codes</code></p>
 
1273
    </dd>
 
1274
 
 
1275
    <dt><a href="http://sqlite.org/c3ref/c_abort.html"><strong>SQLITE_OK, SQLITE_ERROR, SQLITE_PERM</strong> and 22
 
1276
    others</a></dt>
 
1277
 
 
1278
    <dd>
 
1279
      <p>These are <a href="http://sqlite.org/c3ref/c_abort.html">SQLite result codes</a> which are provided in
 
1280
      <a href="#Exceptions">exceptions</a>. Mapping is <code>apsw.mapping_result_codes</code></p>
 
1281
    </dd>
 
1282
 
 
1283
    <dt><a href="http://sqlite.org/c3ref/c_open_create.html"><strong>SQLITE_OPEN_READONLY, SQLITE_OPEN_CREATE</strong>
 
1284
    and 10 others</a></dt>
 
1285
 
 
1286
    <dd>
 
1287
      <p>These are used for <a href="http://sqlite.org/c3ref/open.html">opening the database</a> as well as the VFS.
 
1288
      Mapping is <code>apsw.mapping_open_flags</code></p>
 
1289
    </dd>
 
1290
 
 
1291
    <dt><a href="http://www.sqlite.org/c3ref/c_limit_attached.html"><strong>SQLITE_LIMIT_LENGTH,
 
1292
    SQLITE_LIMIT_SQL_LENGTH</strong> and 8 others</a></dt>
 
1293
 
 
1294
    <dd>
 
1295
      <p>These are used for getting or setting <a href="http://www.sqlite.org/c3ref/limit.html">run-time limits</a></p>
1253
1296
    </dd>
1254
1297
  </dl>
1255
1298
 
1256
 
  <h2><a name="Connection_class" id="Connection_class">Connection
1257
 
  class</a></h2>
 
1299
  <h2><a name="Connection_class" id="Connection_class">Connection class</a></h2>
1258
1300
 
1259
1301
  <p>The connection class wraps a <code>sqlite3 pointer</code>.</p>
1260
1302
 
1261
1303
  <dl>
1262
 
    <dt><strong>Connection(filename)</strong></dt>
 
1304
    <dt><strong>Connection(filename, flags=SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, vfs=None,
 
1305
    statementcachesize=100)</strong></dt>
1263
1306
 
1264
1307
    <dd>
1265
 
      <p>Opens an SQLite database named <code>filename</code>. (This calls
1266
 
      <a href=
1267
 
      "http://www.sqlite.org/capi3ref.html#sqlite3_open">sqlite3_open</a>
1268
 
      behind the scenes. You must call close when finished with a Connection.
1269
 
      If you do not call close then the destructor will invoke
1270
 
      <code>sys.excepthook</code> which by default will print a traceback.</p>
 
1308
      <p>Opens an SQLite database named <code>filename</code>. (This calls <a href=
 
1309
      "http://sqlite.org/c3ref/open.html">sqlite3_open_v2</a> behind the scenes.) If you don't supply a vfs then the
 
1310
      default will be used. You can also set how many entries there are in the statement cache. You will generally want
 
1311
      this to be the total number of distinct SQL statements you execute frequently.</p>
1271
1312
    </dd>
1272
1313
 
1273
1314
    <dt><strong>close(force=False)</strong></dt>
1274
1315
 
1275
1316
    <dd>
1276
 
      <p>You must call this method when you are done with a Connection. Behind
1277
 
      the scenes it calls <a href=
1278
 
      "http://www.sqlite.org/capi3ref.html#sqlite3_close">sqlite3_close</a>. It
1279
 
      is ok to call this method multiple times. Note that this method can raise
1280
 
      an exception. Some examples of when exceptions are raised:</p>
 
1317
      <p>You must call this method when you are done with a Connection. Behind the scenes it calls <a href=
 
1318
      "http://sqlite.org/c3ref/close.html">sqlite3_close</a>. It is ok to call this method multiple times. Note that
 
1319
      this method can raise an exception. Some examples of when exceptions are raised:</p>
1281
1320
 
1282
1321
      <ul>
1283
 
        <li>You have statements still executing (ie currently positioned at a
1284
 
        row). Statements that have consumed all results will not hold up
1285
 
        closing a Connection.</li>
1286
 
 
1287
 
        <li>You were in the middle of a transaction. SQLite will attempt to do
1288
 
        a rollback and errors in your rollback hook will be passed back.</li>
1289
 
 
1290
 
        <li>Any virtual tables will be dropped/disconnected. Errors in your
1291
 
        Disconnect/Destroy methods will be passed back.</li>
 
1322
        <li>You have statements still executing (ie currently positioned at a row, with more statements to execute).
 
1323
        Statements that have consumed all results will not hold up closing a Connection.</li>
 
1324
 
 
1325
        <li>You were in the middle of a transaction. SQLite will attempt to do a rollback and errors in your rollback
 
1326
        hook will be passed back.</li>
 
1327
 
 
1328
        <li>Any virtual tables will be dropped/disconnected. Errors in your Disconnect/Destroy methods will be passed
 
1329
        back.</li>
1292
1330
      </ul>
1293
1331
 
1294
 
      <p>If <tt>force</tt> is True, then any executing cursors are forcibly
1295
 
      closed.</p>
 
1332
      <p>If <tt>force</tt> is True, then any executing cursors are forcibly closed.</p>
1296
1333
    </dd>
1297
1334
 
1298
1335
    <dt><strong>cursor()</strong></dt>
1299
1336
 
1300
1337
    <dd>
1301
 
      <p>Creates a new <a href="#Cursor">cursor</a> object on this
1302
 
      database.</p>
 
1338
      <p>Creates a new <a href="#Cursor">cursor</a> object on this database.</p>
1303
1339
    </dd>
1304
1340
 
1305
1341
    <dt><strong>changes()</strong></dt>
1306
1342
 
1307
1343
    <dd>
1308
 
      <p>This function returns the number of database rows that were changed
1309
 
      (or inserted or deleted) by the most recently completed INSERT, UPDATE,
1310
 
      or DELETE statement. (This calls <a href=
1311
 
      "http://www.sqlite.org/capi3ref.html#sqlite3_changes">sqlite3_changes</a>.
1312
 
      Read that link for some additional notes.)</p>
 
1344
      <p>This function returns the number of database rows that were changed (or inserted or deleted) by the most
 
1345
      recently completed INSERT, UPDATE, or DELETE statement. (This calls <a href=
 
1346
      "http://sqlite.org/c3ref/changes.html">sqlite3_changes</a>. Read that link for some additional notes.)</p>
1313
1347
    </dd>
1314
1348
 
1315
1349
    <dt><strong>totalchanges()</strong></dt>
1316
1350
 
1317
1351
    <dd>
1318
 
      <p>This function returns the total number of database rows that have be
1319
 
      modified, inserted, or deleted since the database connection was opened.
1320
 
      (This calls <a href=
1321
 
      "http://www.sqlite.org/capi3ref.html#sqlite3_total_changes">sqlite3_total_changes</a>.
1322
 
      Read that link for some additional notes.)</p>
 
1352
      <p>This function returns the total number of database rows that have be modified, inserted, or deleted since the
 
1353
      database connection was opened. (This calls <a href=
 
1354
      "http://sqlite.org/c3ref/total_changes.html">sqlite3_total_changes</a>. Read that link for some additional
 
1355
      notes.)</p>
1323
1356
    </dd>
1324
1357
 
1325
1358
    <dt><strong>last_insert_rowid()</strong></dt>
1326
1359
 
1327
1360
    <dd>
1328
 
      <p>Returns the integer key of the most recent insert in the database.
1329
 
      (This calls <a href=
1330
 
      "http://www.sqlite.org/capi3ref.html#sqlite3_last_insert_rowid">sqlite3_last_insert_rowid</a>.)</p>
 
1361
      <p>Returns the integer key of the most recent insert in the database. (This calls <a href=
 
1362
      "http://sqlite.org/c3ref/last_insert_rowid.html">sqlite3_last_insert_rowid</a>.)</p>
1331
1363
    </dd>
1332
1364
 
1333
1365
    <dt><strong>complete(statement)</strong></dt>
1334
1366
 
1335
1367
    <dd>
1336
 
      <p>Calls <a href=
1337
 
      "http://www.sqlite.org/capi3ref.html#sqlite3_complete">sqlite3_complete</a>
1338
 
      which tells you if the input string comprises one or more complete SQL
1339
 
      statements.</p>
 
1368
      <p>Calls <a href="http://sqlite.org/c3ref/complete.html">sqlite3_complete</a> which tells you if the input string
 
1369
      comprises one or more complete SQL statements.</p>
1340
1370
    </dd>
1341
1371
 
1342
1372
    <dt><strong>setbusytimeout(milliseconds)</strong></dt>
1343
1373
 
1344
1374
    <dd>
1345
1375
      <p>Sets the busy timeout. (This calls <a href=
1346
 
      "http://www.sqlite.org/capi3ref.html#sqlite3_busy_timeout">sqlite3_busy_timeout</a>).</p>
 
1376
      "http://sqlite.org/c3ref/busy_timeout.html">sqlite3_busy_timeout</a>).</p>
1347
1377
    </dd>
1348
1378
 
1349
1379
    <dt><strong>setbusyhandler(callable)</strong></dt>
1350
1380
 
1351
1381
    <dd>
1352
 
      <p>Sets the busy handler to callable. callable will be called with one
1353
 
      integer argument which is the number of prior calls to the busy callback
1354
 
      for the same lock. If the busy callback returns something that evaluates
1355
 
      to False, then SQLite returns SQLITE_BUSY to the calling code.. If the
1356
 
      callback returns something that evaluates to True, then SQLite tries to
1357
 
      open the table again and the cycle repeats. (This calls <a href=
1358
 
      "http://www.sqlite.org/capi3ref.html#sqlite3_busy_handler">sqlite3_busy_handler</a>).</p>
 
1382
      <p>Sets the busy handler to callable. callable will be called with one integer argument which is the number of
 
1383
      prior calls to the busy callback for the same lock. If the busy callback returns something that evaluates to
 
1384
      False, then SQLite returns SQLITE_BUSY to the calling code.. If the callback returns something that evaluates to
 
1385
      True, then SQLite tries to open the table again and the cycle repeats. (This calls <a href=
 
1386
      "http://sqlite.org/c3ref/busy_handler.html">sqlite3_busy_handler</a>).</p>
1359
1387
    </dd>
1360
1388
 
1361
1389
    <dt><strong>interrupt()</strong></dt>
1362
1390
 
1363
1391
    <dd>
1364
 
      <p>Causes any pending operations on the database to abort at the earliest
1365
 
      opportunity. You can call this from any thread. (This calls <a href=
1366
 
      "http://www.sqlite.org/capi3ref.html#sqlite3_interrupt">sqlite3_interrupt</a>).</p>
 
1392
      <p>Causes any pending operations on the database to abort at the earliest opportunity. You can call this from any
 
1393
      thread. (This calls <a href="http://sqlite.org/c3ref/interrupt.html">sqlite3_interrupt</a>).</p>
 
1394
    </dd>
 
1395
 
 
1396
    <dt><a name="Connection_limit" id="Connection_limit"><strong>limit(id [, newval])</strong></a></dt>
 
1397
 
 
1398
    <dd>
 
1399
      <p>If called with one parameter then the relevant limit is returned. If called with two then the limit is
 
1400
      changed. Returns the old value of the limit. This calls <a href=
 
1401
      "http://www.sqlite.org/c3ref/limit.html">sqlite3_limit</a>. For example
 
1402
      <code>connection.limit(apsw.SQLITE_LIMIT_LENGTH, 1024)</code> would set the limit for blobs and strings to 1
 
1403
      kilobyte. To find the maximum value, set the limit to 0x7fffffff and then call <tt>connection.limit</tt> again to
 
1404
      see what value it was set to.</p>
1367
1405
    </dd>
1368
1406
 
1369
1407
    <dt><strong>createscalarfunction(name, callable, numargs=-1)</strong></dt>
1370
1408
 
1371
1409
    <dd>
1372
 
      <p>Registers a scalar function. The callable will be called. You can
1373
 
      specify how many arguments your function takes as the numargs parameter
1374
 
      or supply -1 to take any amount. (This calls <a href=
1375
 
      "http://www.sqlite.org/capi3ref.html#sqlite3_create_function">sqlite3_create_function</a>).</p>
 
1410
      <p>Registers a scalar function. The callable will be called. You can specify how many arguments your function
 
1411
      takes as the numargs parameter or supply -1 to take any amount. (This calls <a href=
 
1412
      "http://sqlite.org/c3ref/create_function.html">sqlite3_create_function</a>).</p>
1376
1413
    </dd>
1377
1414
 
1378
 
    <dt><strong>createaggregatefunction(name, factorycallback,
1379
 
    numargs=-1)</strong></dt>
 
1415
    <dt><strong>createaggregatefunction(name, factorycallback, numargs=-1)</strong></dt>
1380
1416
 
1381
1417
    <dd>
1382
1418
      <p>Registers an aggregate function. (This calls <a href=
1383
 
      "http://www.sqlite.org/capi3ref.html#sqlite3_create_function">sqlite3_create_function</a>.)
1384
 
      You can specify how many arguments your function takes as the numargs
1385
 
      parameter or supply -1 to take any amount. When the function is called by
1386
 
      an SQL query, the factorycallback is called without any arguments. The
1387
 
      factorycallback needs to return a tuple consisting of three 3 items.</p>
 
1419
      "http://sqlite.org/c3ref/create_function.html">sqlite3_create_function</a>.) You can specify how many arguments
 
1420
      your function takes as the numargs parameter or supply -1 to take any amount. When the function is called by an
 
1421
      SQL query, the factorycallback is called without any arguments. The factorycallback needs to return a tuple
 
1422
      consisting of three 3 items.</p>
1388
1423
 
1389
1424
      <ul>
1390
1425
        <li>
1392
1427
        </li>
1393
1428
 
1394
1429
        <li>
1395
 
          <p>a step function which is called for each row. The context object
1396
 
          will be the first parameter, and the remaining parameters will be
1397
 
          from the SQL statement. The return value is ignored - you supply it
1398
 
          in final.</p>
 
1430
          <p>a step function which is called for each row. The context object will be the first parameter, and the
 
1431
          remaining parameters will be from the SQL statement. The return value is ignored - you supply it in
 
1432
          final.</p>
1399
1433
        </li>
1400
1434
 
1401
1435
        <li>
1402
 
          <p>a final function which is called at the end. The only parameter
1403
 
          will be the context object. The value returned is set as the return
1404
 
          for the function. It must be a valid SQLite type. Note that the final
1405
 
          function is always called even if an exception was raised by the step
1406
 
          function. This allows you to ensure any resources are cleaned up.</p>
 
1436
          <p>a final function which is called at the end. The only parameter will be the context object. The value
 
1437
          returned is set as the return for the function. It must be a valid SQLite type. Note that the final function
 
1438
          is always called even if an exception was raised by the step function. This allows you to ensure any
 
1439
          resources are cleaned up.</p>
1407
1440
        </li>
1408
1441
      </ul>
1409
1442
    </dd>
1411
1444
    <dt><strong>createcollation(name, callable)</strong></dt>
1412
1445
 
1413
1446
    <dd>
1414
 
      <p>Creates a collation with the specified name and callable. The callable
1415
 
      will be passed two string arguments. It should return -1 if the first is
1416
 
      less than the second, 0 if they are equal and 1 and if the first is
1417
 
      greater than the second. Note that this controls sorting (ORDER BY in
1418
 
      SQL) so your comparisons don't affect other SQL operations. Read more
1419
 
      about <a href="http://www.sqlite.org/datatype3.html#collation">SQLite's
1420
 
      handling of collations.</a> (This calls <a href=
1421
 
      "http://www.sqlite.org/capi3ref.html#sqlite3_create_collation">sqlite3_create_collation</a>.)
1422
 
      If there is an error in your Python code then 0 (ie items are equal) is
1423
 
      returned.</p>
 
1447
      <p>Creates a collation with the specified name and callable. The callable will be passed two string arguments. It
 
1448
      should return -1 if the first is less than the second, 0 if they are equal and 1 and if the first is greater than
 
1449
      the second. Note that this controls sorting (ORDER BY in SQL) so your comparisons don't affect other SQL
 
1450
      operations. Read more about <a href="http://www.sqlite.org/datatype3.html#collation">SQLite's handling of
 
1451
      collations.</a> (This calls <a href=
 
1452
      "http://sqlite.org/c3ref/create_collation.html">sqlite3_create_collation</a>.) If there is an error in your
 
1453
      Python code then 0 (ie items are equal) is returned.</p>
 
1454
    </dd>
 
1455
 
 
1456
    <dt><strong>collationneeded(callable)</strong></dt>
 
1457
 
 
1458
    <dd>
 
1459
      <p><tt>callable</tt> will be called if a statement requires a collation that hasn't been registered. Your
 
1460
      callable will be passed two parameters. The first is the connection object. The second is the name of the
 
1461
      collation. If you have the collation code available then call createcollation, else just return.</p>
1424
1462
    </dd>
1425
1463
 
1426
1464
    <dt><strong>setauthorizer(callable)</strong></dt>
1427
1465
 
1428
1466
    <dd>
1429
 
      <p>The callable is invoked while SQL statements are being prepared. The
1430
 
      intent is to allow applications to safely execute user entered SQL. The
1431
 
      callable is called with 5 parameters:</p>
 
1467
      <p>The callable is invoked while SQL statements are being prepared. The intent is to allow applications to safely
 
1468
      execute user entered SQL. The callable is called with 5 parameters:</p>
1432
1469
 
1433
1470
      <ul>
1434
1471
        <li>
1435
 
          <p>an integer representing the operation (the constants are available
1436
 
          on the apsw module - eg <code>apsw.SQLITE_CREATE_TABLE</code>.</p>
 
1472
          <p>an integer representing the operation (the constants are available on the apsw module - eg
 
1473
          <code>apsw.SQLITE_CREATE_TABLE</code>.</p>
1437
1474
        </li>
1438
1475
 
1439
1476
        <li>
1449
1486
        </li>
1450
1487
 
1451
1488
        <li>
1452
 
          <p>Name of the innermost trigger or view doing the access (or
1453
 
          None)</p>
 
1489
          <p>Name of the innermost trigger or view doing the access (or None)</p>
1454
1490
        </li>
1455
1491
      </ul>
1456
1492
 
1457
 
      <p>You should return <code>apsw.SQLITE_OK</code> to allow the operation
1458
 
      or <code>apsw.SQLITE_DENY</code> or <code>apsw.SQLITE_IGNORE</code> as
1459
 
      applicable. (SQLITE_DENY is returned if there is an error in your Python
 
1493
      <p>You should return <code>apsw.SQLITE_OK</code> to allow the operation or <code>apsw.SQLITE_DENY</code> or
 
1494
      <code>apsw.SQLITE_IGNORE</code> as applicable. (SQLITE_DENY is returned if there is an error in your Python
1460
1495
      code).</p>
1461
1496
 
1462
 
      <p>This calls <a href=
1463
 
      "http://www.sqlite.org/capi3ref.html#sqlite3_set_authorizer">sqlite3_set_authorizer</a>
1464
 
      which contains more detailed documentation.</p>
 
1497
      <p>This calls <a href="http://sqlite.org/c3ref/set_authorizer.html">sqlite3_set_authorizer</a> which contains
 
1498
      more detailed documentation.</p>
1465
1499
    </dd>
1466
1500
 
1467
1501
    <dt><strong>setupdatehook(callable)</strong></dt>
1468
1502
 
1469
1503
    <dd>
1470
 
      <p>Sets a callable which is invoked during data changing. The callable
1471
 
      takes four parameters:</p>
 
1504
      <p>Sets a callable which is invoked during data changing. The callable takes four parameters:</p>
1472
1505
 
1473
1506
      <ul>
1474
 
        <li>An integer whose value is one of apsw.SQLITE_INSERT,
1475
 
        apsw.SQLITE_DELETE or apsw.SQLITE_UPDATE</li>
 
1507
        <li>An integer whose value is one of apsw.SQLITE_INSERT, apsw.SQLITE_DELETE or apsw.SQLITE_UPDATE</li>
1476
1508
 
1477
 
        <li>A string naming the database on which the operation is happening.
1478
 
        (This will typically be <tt>main</tt> unless you used <a href=
1479
 
        "http://sqlite.org/lang_attach.html"><tt>ATTACH</tt></a></li>
 
1509
        <li>A string naming the database on which the operation is happening. (This will typically be <tt>main</tt>
 
1510
        unless you used <a href="http://sqlite.org/lang_attach.html"><tt>ATTACH</tt></a></li>
1480
1511
 
1481
1512
        <li>A string naming the table on which the operation is happening.</li>
1482
1513
 
1483
1514
        <li>An integer with the rowid of the row that is changing.</li>
1484
1515
      </ul>
1485
1516
 
1486
 
      <p>(This calls <a href=
1487
 
      "http://www.sqlite.org/capi3ref.html#sqlite3_update_hook">sqlite3_update_hook</a>.)</p>
 
1517
      <p>(This calls <a href="http://sqlite.org/c3ref/update_hook.html">sqlite3_update_hook</a>.)</p>
1488
1518
    </dd>
1489
1519
 
1490
1520
    <dt><strong>setrollbackhook(callable)</strong></dt>
1491
1521
 
1492
1522
    <dd>
1493
 
      <p>Sets a callable which is invoked during a rollback. The callable takes
1494
 
      no parameters and the return value is ignored. (This calls <a href=
1495
 
      "http://www.sqlite.org/capi3ref.html#sqlite3_rollback_hook">sqlite3_rollback_hook</a>.)</p>
1496
 
    </dd>
1497
 
 
1498
 
    <dt><strong>setcommithook(callable)</strong> (SQLite 3 experimental
1499
 
    feature)</dt>
1500
 
 
1501
 
    <dd>
1502
 
      <p>Sets a callable which is invoked just before a commit. It should
1503
 
      return zero for the commit to go ahead and non-zero for it to be turned
1504
 
      into a rollback. In the case of an exception in your callable, a non-zero
1505
 
      (ie rollback) value is returned. (This calls <a href=
1506
 
      "http://www.sqlite.org/capi3ref.html#sqlite3_commit_hook">sqlite3_commit_hook</a>.)</p>
1507
 
    </dd>
1508
 
 
1509
 
    <dt><strong>setprofile(callable)</strong> (SQLite 3 experimental
1510
 
    feature)</dt>
1511
 
 
1512
 
    <dd>
1513
 
      <p>Sets a callable which is invoked at the end of execution of each
1514
 
      statement and passed the statement string and how long it took to
1515
 
      execute. (The execution time appears to be in nanoseconds.) Note that it
1516
 
      is called only on completion. If for example you do a <tt>SELECT</tt> and
1517
 
      only read the first result, then you won't reach the end of the
1518
 
      statement.</p>
1519
 
 
1520
 
      <p>(This calls <tt>sqlite3_profile</tt> which is not documented on the
1521
 
      SQLite web site. See the <tt>sqlite3.h</tt> header file for
1522
 
      documentation.).</p>
1523
 
    </dd>
1524
 
 
1525
 
    <dt><strong>setprogresshandler(callable, nsteps=20)</strong> (SQLite 3
1526
 
    experimental feature)</dt>
1527
 
 
1528
 
    <dd>
1529
 
      <p>Sets a callable which is invoked every <i>nsteps</i> SQLite
1530
 
      inststructions. The callable should return a non-zero value to abort or
1531
 
      zero to continue. (If there is an error in your Python callable then
1532
 
      non-zero will be returned). (This calls <a href=
1533
 
      "http://www.sqlite.org/capi3ref.html#sqlite3_progress_handler">sqlite3_progress_handler</a>
1534
 
      which has more detailed documentation).</p>
1535
 
    </dd>
1536
 
 
1537
 
    <dt><strong>enableloadextension(bool)</strong> (SQLite 3 experimental
1538
 
    feature)</dt>
1539
 
 
1540
 
    <dd>
1541
 
      <p>Enables <a href=
1542
 
      "http://www.sqlite.org/cvstrac/wiki/wiki?p=LoadableExtensions">extension</a>
1543
 
      loading which is disabled by default. Calls
1544
 
      sqlite3_enable_load_extension. See note below about enabling extension
1545
 
      loading.</p>
1546
 
    </dd>
1547
 
 
1548
 
    <dt><strong>loadextension(filename, entrypoint=None)</strong> (SQLite 3
1549
 
    experimental feature)</dt>
1550
 
 
1551
 
    <dd>
1552
 
      <p>Loads an <a href=
1553
 
      "http://www.sqlite.org/cvstrac/wiki/wiki?p=LoadableExtensions">extension</a>
1554
 
      by calling sqlite3_load_extension. If you don't specify the entrypoint
1555
 
      then SQLite uses a default of sqlite3_extension_init.</p>
1556
 
 
1557
 
      <p>Note that if you build SQLite on Unix then extension loading won't be
1558
 
      built into SQLite by default. The details are in SQLite ticket <a href=
1559
 
      "http://www.sqlite.org/cvstrac/tktview?tn=2082">2082</a>. You need to
1560
 
      edit <tt>setup.py</tt> if you enable extension loading.</p>
1561
 
    </dd>
 
1523
      <p>Sets a callable which is invoked during a rollback. The callable takes no parameters and the return value is
 
1524
      ignored. (This calls <a href="http://sqlite.org/c3ref/commit_hook.html">sqlite3_rollback_hook</a>.)</p>
 
1525
    </dd>
 
1526
 
 
1527
    <dt><strong>setcommithook(callable)</strong> (SQLite 3 experimental feature)</dt>
 
1528
 
 
1529
    <dd>
 
1530
      <p>Sets a callable which is invoked just before a commit. It should return zero for the commit to go ahead and
 
1531
      non-zero for it to be turned into a rollback. In the case of an exception in your callable, a non-zero (ie
 
1532
      rollback) value is returned. (This calls <a href=
 
1533
      "http://sqlite.org/c3ref/commit_hook.html">sqlite3_commit_hook</a>.)</p>
 
1534
    </dd>
 
1535
 
 
1536
    <dt><strong>setprofile(callable)</strong> (SQLite 3 experimental feature)</dt>
 
1537
 
 
1538
    <dd>
 
1539
      <p>Sets a callable which is invoked at the end of execution of each statement and passed the statement string and
 
1540
      how long it took to execute. (The execution time appears to be in nanoseconds.) Note that it is called only on
 
1541
      completion. If for example you do a <tt>SELECT</tt> and only read the first result, then you won't reach the end
 
1542
      of the statement.</p>
 
1543
 
 
1544
      <p>(This calls <tt>sqlite3_profile</tt> which is not documented on the SQLite web site. See the
 
1545
      <tt>sqlite3.h</tt> header file for documentation.).</p>
 
1546
    </dd>
 
1547
 
 
1548
    <dt><strong>setprogresshandler(callable, nsteps=20)</strong> (SQLite 3 experimental feature)</dt>
 
1549
 
 
1550
    <dd>
 
1551
      <p>Sets a callable which is invoked every <i>nsteps</i> SQLite inststructions. The callable should return a
 
1552
      non-zero value to abort or zero to continue. (If there is an error in your Python callable then non-zero will be
 
1553
      returned). (This calls <a href="http://sqlite.org/c3ref/progress_handler.html">sqlite3_progress_handler</a> which
 
1554
      has more detailed documentation).</p>
 
1555
    </dd>
 
1556
 
 
1557
    <dt><strong>enableloadextension(bool)</strong> (SQLite 3 experimental feature)</dt>
 
1558
 
 
1559
    <dd>
 
1560
      <p>Enables <a href="http://www.sqlite.org/cvstrac/wiki/wiki?p=LoadableExtensions">extension</a> loading which is
 
1561
      disabled by default. Calls sqlite3_enable_load_extension. See note below about enabling extension loading.</p>
 
1562
    </dd>
 
1563
 
 
1564
    <dt><strong>loadextension(filename, entrypoint=None)</strong> (SQLite 3 experimental feature)</dt>
 
1565
 
 
1566
    <dd>
 
1567
      <p>Loads an <a href="http://www.sqlite.org/cvstrac/wiki/wiki?p=LoadableExtensions">extension</a> by calling
 
1568
      sqlite3_load_extension. If you don't specify the entrypoint then SQLite uses a default of
 
1569
      sqlite3_extension_init.</p>
 
1570
 
 
1571
      <p>Note that if you build SQLite on Unix then extension loading won't be built into SQLite by default. The
 
1572
      details are in SQLite ticket <a href="http://www.sqlite.org/cvstrac/tktview?tn=2082">2082</a>. You need to edit
 
1573
      <tt>setup.py</tt> if you enable extension loading.</p>
 
1574
    </dd>
 
1575
 
 
1576
    <dt><strong>blobopen(databasename, tablename, columnname, rowid, flags)</strong></dt>
 
1577
 
 
1578
    <dd>Returns a new <a href="#blobio">blob</a>. The database name will be <tt>main</tt>, unless you want to refer to
 
1579
    a database you <a href="http://www.sqlite.org/lang_attach.html">ATTACH</a>ed.</dd>
 
1580
  </dl>
 
1581
 
 
1582
  <h2><a name="blobio" id="blobio">Blob I/O</a></h2>
 
1583
 
 
1584
  <p>Historically SQLite only let you access and create blobs in their entirity. For example to reading or writing a
 
1585
  single byte from a blob required reading or writing the whole blob.</p>
 
1586
 
 
1587
  <p>SQLite now provides incremental blob access, with APSW exposing it as a file like object. Call Connection.blobopen
 
1588
  to open a blob. <b>Note</b> that the underlying <a href="http://www.sqlite.org/c3ref/blob.html">SQLite blob apis</a>
 
1589
  require offsets to be provided to each call, but the APSW blob object tracks that for you.</p>
 
1590
 
 
1591
  <dl>
 
1592
    <dt><strong>close(force=False)</strong></dt>
 
1593
 
 
1594
    <dd>
 
1595
      <p>Stops any further access to the blob. You should proactively call close as it will return errors that may
 
1596
      correspond to earlier blob i/o. See <a href="http://www.sqlite.org/c3ref/blob_close.html">blob_close()</a> for
 
1597
      more details. If you call any of the other methods on a closed blob then you will get a ValueError exception
 
1598
      (this is the same as calling methods on a closed Python file object).</p>
 
1599
 
 
1600
      <p><i>force</i> currently has no effect and is present for compatibility with cursor objects.</p>
 
1601
    </dd>
 
1602
 
 
1603
    <dt><strong>read([amount])</strong></dt>
 
1604
 
 
1605
    <dd>Reads amount of data requested, or till end of file, whichever is earlier. Attempting to read beyond the end of
 
1606
    the blob returns the empty string, in the same manner as end of file on normal file objects.</dd>
 
1607
 
 
1608
    <dt><strong>write(data)</strong></dt>
 
1609
 
 
1610
    <dd>Writes the requested data. Note that you cannot make the blob larger or smaller. Normally you would create a
 
1611
    zeroblob and then come back and fill it in with this method, as shown in the <a href=
 
1612
    "#example-blobio">example</a>.</dd>
 
1613
 
 
1614
    <dt><strong>tell()</strong></dt>
 
1615
 
 
1616
    <dd>Returns the current position.</dd>
 
1617
 
 
1618
    <dt><strong>seek(offset, [whence])</strong></dt>
 
1619
 
 
1620
    <dd>Change the current position. If whence is omitted or zero, then the position is set to offset. If whence is 1
 
1621
    then offset is added to the current position. If whence is 2 then offset is relative to the end of the blob.</dd>
1562
1622
  </dl>
1563
1623
 
1564
1624
  <h2><a name="Cursor" id="Cursor">Cursor class</a></h2>
1569
1629
    <dt><strong>Cursor()</strong></dt>
1570
1630
 
1571
1631
    <dd>
1572
 
      <p>You cannot create cursors directly. The are created by calling
1573
 
      Connection.cursor().</p>
 
1632
      <p>You cannot create cursors directly. The are created by calling Connection.cursor().</p>
1574
1633
    </dd>
1575
1634
 
1576
1635
    <dt><strong>close(force=False)</strong></dt>
1577
1636
 
1578
1637
    <dd>
1579
 
      <p>In general cursors are in a closed state, and you won't need to call
1580
 
      this method. Calling while the cursor is already closed or if the
1581
 
      Connection is closed will not result in errors. An open Cursor prevents
1582
 
      closing of Connections. The circumstances in which they are not closed
1583
 
      include:</p>
 
1638
      <p>In general cursors are in a closed state, and you won't need to call this method. Calling while the cursor is
 
1639
      already closed or if the Connection is closed will not result in errors. An open Cursor prevents closing of
 
1640
      Connections. The circumstances in which they are not closed include:</p>
1584
1641
 
1585
1642
      <ul>
1586
 
        <li>You haven't requested all the rows of available data (calling
1587
 
        next() or using the cursor as an iterator will return more data)</li>
 
1643
        <li>You haven't requested all the rows of available data (calling next() or using the cursor as an iterator
 
1644
        will return more data)</li>
1588
1645
 
1589
1646
        <li>You got a recoverable error and can try again (eg SQLITE_BUDY)</li>
1590
1647
 
1591
 
        <li style="list-style: none">
1592
 
          <p>If force is False then you will get exceptions if there is
1593
 
          remaining work to do be in the Cursor such as more statements to
1594
 
          execute, more data from the executemany binding sequence etc. If
1595
 
          force is True then all remaining work and state information will be
1596
 
          discarded.</p>
1597
 
        </li>
 
1648
        <li>If force is False then you will get exceptions if there is remaining work to do be in the Cursor such as
 
1649
        more statements to execute, more data from the executemany binding sequence etc. If force is True then all
 
1650
        remaining work and state information will be discarded.</li>
1598
1651
      </ul>
1599
1652
    </dd>
1600
1653
 
1601
1654
    <dt><strong>getconnection()</strong></dt>
1602
1655
 
1603
1656
    <dd>
1604
 
      <p>Returns the <a href="#Connection">Connection</a> object to which this
1605
 
      cursor belongs.</p>
 
1657
      <p>Returns the <a href="#Connection">Connection</a> object to which this cursor belongs.</p>
1606
1658
    </dd>
1607
1659
 
1608
1660
    <dt><strong>execute(statements, bindings=())</strong></dt>
1609
1661
 
1610
1662
    <dd>
1611
 
      <p>Executes the statements using the supplied bindings. The bindings can
1612
 
      be supplied as a tuple or as a dict. Execution returns when the first row
1613
 
      is available or all statements have completed. The cursor object is
1614
 
      returned which you can use as an iterator. (See <a href=
1615
 
      "#executionmodel">execution model</a> for more details. This function
1616
 
      wraps <a href=
1617
 
      "http://www.sqlite.org/capi3ref.html#sqlite3_prepare">sqlite3_prepare</a>
1618
 
      and <a href=
1619
 
      "http://www.sqlite.org/capi3ref.html#sqlite3_step">sqlite3_step</a>.)</p>
 
1663
      <p>Executes the statements using the supplied bindings. The bindings can be supplied as a tuple or as a dict.
 
1664
      Execution returns when the first row is available or all statements have completed. The cursor object is returned
 
1665
      which you can use as an iterator. (See <a href="#executionmodel">execution model</a> for more details. This
 
1666
      function wraps <a href="http://sqlite.org/c3ref/prepare.html">sqlite3_prepare_v2</a> and <a href=
 
1667
      "http://sqlite.org/c3ref/step.html">sqlite3_step</a>.)</p>
1620
1668
    </dd>
1621
1669
 
1622
1670
    <dt><strong>executemany(statements, sequenceofbindings=())</strong></dt>
1623
1671
 
1624
1672
    <dd>
1625
 
      <p>Repeatedly executes statements using each element of
1626
 
      sequenceofbindings for the bindings each time. Execution returns when the
1627
 
      first row is available or all statements have completed. The cursor
1628
 
      object is returned which you can use as an iterator. (See <a href=
1629
 
      "#executionmodel">execution model</a> for more details. This function
1630
 
      runs in a loop on each member of sequenceofbindings and wraps <a href=
1631
 
      "http://www.sqlite.org/capi3ref.html#sqlite3_prepare">sqlite3_prepare</a>
1632
 
      and <a href=
1633
 
      "http://www.sqlite.org/capi3ref.html#sqlite3_step">sqlite3_step</a>
1634
 
      .)</p>
 
1673
      <p>Repeatedly executes statements using each element of sequenceofbindings for the bindings each time. Execution
 
1674
      returns when the first row is available or all statements have completed. The cursor object is returned which you
 
1675
      can use as an iterator. (See <a href="#executionmodel">execution model</a> for more details. This function runs
 
1676
      in a loop on each member of sequenceofbindings and wraps <a href=
 
1677
      "http://sqlite.org/c3ref/prepare.html">sqlite3_prepare_v2</a> and <a href=
 
1678
      "http://sqlite.org/c3ref/step.html">sqlite3_step</a>.)</p>
1635
1679
    </dd>
1636
1680
 
1637
1681
    <dt><strong>next()</strong></dt>
1638
1682
 
1639
1683
    <dd>
1640
 
      <p>The Cursor object is an iterator, and so you can use it in a for loop
1641
 
      or similar situations. You can also explicitly call the
1642
 
      <code>next()</code> method. This method returns a tuple of the contents
1643
 
      of a returned row or raises StopIteration after all returned rows have
1644
 
      been seen.</p>
 
1684
      <p>The Cursor object is an iterator, and so you can use it in a for loop or similar situations. You can also
 
1685
      explicitly call the <code>next()</code> method. This method returns a tuple of the contents of a returned row or
 
1686
      raises StopIteration after all returned rows have been seen.</p>
1645
1687
    </dd>
1646
1688
 
1647
1689
    <dt><strong>getdescription()</strong></dt>
1648
1690
 
1649
1691
    <dd>
1650
 
      <p>Returns a list describing each column in the current result set. Each
1651
 
      item is a tuple of (column name, declared column type). You should only
1652
 
      call this function while data is being returned such as when
 
1692
      <p>Returns a list describing each column in the current result set. Each item is a tuple of (column name,
 
1693
      declared column type). You should only call this function while data is being returned such as when
1653
1694
      <code>next()</code> returns a row. This function calls <a href=
1654
 
      "http://www.sqlite.org/capi3ref.html#sqlite3_column_name">sqlite3_column_name</a>
1655
 
      and <a href=
1656
 
      "http://www.sqlite.org/capi3ref.html#sqlite3_column_decltype">sqlite3_column_decltype</a>.</p>
 
1695
      "http://sqlite.org/c3ref/column_name.html">sqlite3_column_name</a> and <a href=
 
1696
      "http://sqlite.org/c3ref/column_decltype.html">sqlite3_column_decltype</a>.</p>
1657
1697
    </dd>
1658
1698
 
1659
1699
    <dt><strong>setexectrace(callable)</strong><br />
1668
1708
 
1669
1709
  <h2><a name="VirtualTables" id="VirtualTables">Virtual Tables</a></h2>
1670
1710
 
1671
 
  <p><a href="http://www.sqlite.org/cvstrac/wiki?p=VirtualTables">Virtual
1672
 
  Tables</a> are a new experimental feature introduced in SQLite 3.3.7 and
1673
 
  updated in 3.3.8. They let a developer provide underlying table
1674
 
  implementations, while still presenting a normal SQL interface to the user.
1675
 
  The person writing SQL doesn't need to know or care that some of the tables
1676
 
  come from elsewhere.</p>
 
1711
  <p><a href="http://www.sqlite.org/cvstrac/wiki?p=VirtualTables">Virtual Tables</a> are an experimental feature
 
1712
  introduced in SQLite 3.3.7. They let a developer provide underlying table implementations, while still presenting a
 
1713
  normal SQL interface to the user. The person writing SQL doesn't need to know or care that some of the tables come
 
1714
  from elsewhere.</p>
1677
1715
 
1678
1716
  <p>Some examples of how you might use this:</p>
1679
1717
 
1680
1718
  <ul>
1681
 
    <li>Translating to/from information stored in other formats (eg a csv/ini
1682
 
    format file)</li>
1683
 
 
1684
 
    <li>Accessing the data remotely (eg you could make a table that backends
1685
 
    into <a href="http://www.josephson.org/projects/pyamazon/">Amazon's
1686
 
    API</a></li>
1687
 
 
1688
 
    <li>Dynamic information (eg currently running processes, files and
1689
 
    directories, objects in your program)</li>
1690
 
 
1691
 
    <li>Information that needs reformatting (eg if you have complex rules about
1692
 
    how to convert strings to/from Unicode in the dataset)</li>
1693
 
 
1694
 
    <li>Information that isn't relationally correct (eg if you have data that
1695
 
    has ended up with duplicate "unique" keys with code that dynamically
1696
 
    corrects it)</li>
1697
 
 
1698
 
    <li>There are other examples on the <a href=
1699
 
    "http://www.sqlite.org/cvstrac/wiki?p=VirtualTables">SQLite page</a></li>
 
1719
    <li>Translating to/from information stored in other formats (eg a csv/ini format file)</li>
 
1720
 
 
1721
    <li>Accessing the data remotely (eg you could make a table that backends into <a href=
 
1722
    "http://www.josephson.org/projects/pyamazon/">Amazon's API</a></li>
 
1723
 
 
1724
    <li>Dynamic information (eg currently running processes, files and directories, objects in your program)</li>
 
1725
 
 
1726
    <li>Information that needs reformatting (eg if you have complex rules about how to convert strings to/from Unicode
 
1727
    in the dataset)</li>
 
1728
 
 
1729
    <li>Information that isn't relationally correct (eg if you have data that has ended up with duplicate "unique" keys
 
1730
    with code that dynamically corrects it)</li>
 
1731
 
 
1732
    <li>There are other examples on the <a href="http://www.sqlite.org/cvstrac/wiki?p=VirtualTables">SQLite
 
1733
    page</a></li>
1700
1734
  </ul>
1701
1735
 
1702
 
  <p>You need to have 3 types of object. A module, a virtual table and a
1703
 
  cursor. These are documented below. You can also read the <a href=
1704
 
  "http://www.sqlite.org/cvstrac/wiki?p=VirtualTableMethods">SQLite C method
1705
 
  documentation</a>. At the C, they are just one set of methods. At the
1706
 
  Python/apsw level, they are split over the 3 types of object. The leading
1707
 
  <tt><i>x</i></tt> is ommitted in Python. You can return SQLite error codes
1708
 
  (eg <code>SQLITE_READONLY</code>) by raising the appropriate exceptions (eg
1709
 
  <code>apsw.ReadOnlyError</code>).</p>
 
1736
  <p>You need to have 3 types of object. A module, a virtual table and a cursor. These are documented below. You can
 
1737
  also read the <a href="http://www.sqlite.org/cvstrac/wiki?p=VirtualTableMethods">SQLite C method documentation</a>.
 
1738
  At the C, they are just one set of methods. At the Python/apsw level, they are split over the 3 types of object. The
 
1739
  leading <tt><i>x</i></tt> is ommitted in Python. You can return SQLite error codes (eg <code>SQLITE_READONLY</code>)
 
1740
  by raising the appropriate exceptions (eg <code>apsw.ReadOnlyError</code>).</p>
1710
1741
 
1711
1742
  <h3>Module</h3>
1712
1743
 
1713
 
  <p>The module is used to create the virtual tables. Once you have a module
1714
 
  object, you register it with a connection by calling
1715
 
  <code>Connection.createmodule("modulename", module_object)</code>. To create
1716
 
  the table, you use SQL: <code>CREATE <b>VIRTUAL</b> TABLE tablename USING
1717
 
  modulename<i>(arg0, arg1, ...)</i></code></p>
 
1744
  <p>The module is used to create the virtual tables. Once you have a module object, you register it with a connection
 
1745
  by calling <code>Connection.createmodule("modulename", module_object)</code>. To create the table, you use SQL:
 
1746
  <code>CREATE <b>VIRTUAL</b> TABLE tablename USING modulename<i>(arg0, arg1, ...)</i></code></p>
1718
1747
 
1719
1748
  <dl>
1720
 
    <dt><strong>Create(connection, modulename, databasename, tablename,
1721
 
    *args)</strong></dt>
 
1749
    <dt><strong>Create(connection, modulename, databasename, tablename, *args)</strong></dt>
1722
1750
 
1723
1751
    <dd>
1724
 
      <p>This is called when a table is first created on a connection. The
1725
 
      optional args are passed from the SQL CREATE statement.</p>
 
1752
      <p>This is called when a table is first created on a connection. The optional args are passed from the SQL CREATE
 
1753
      statement.</p>
1726
1754
 
1727
 
      <p><b>Return</b> two items. The first item should be a string with SQL
1728
 
      specifying the schema for the table. The second item is an Object that
1729
 
      implements the table methods. Later methods in the Table and Cursor
1730
 
      objects will reference the columns by number, starting at zero with
1731
 
      column -1 being the rowid. Every row must have a unique unchanging
1732
 
      integer rowid up to 64bit signed integer.</p>
 
1755
      <p><b>Return</b> two items. The first item should be a string with SQL specifying the schema for the table. The
 
1756
      second item is an Object that implements the table methods. Later methods in the Table and Cursor objects will
 
1757
      reference the columns by number, starting at zero with column -1 being the rowid. Every row must have a unique
 
1758
      unchanging integer rowid up to 64bit signed integer.</p>
1733
1759
    </dd>
1734
1760
 
1735
 
    <dt><strong>Connect(connection, modulename, databasename, tablename,
1736
 
    *args)</strong></dt>
 
1761
    <dt><strong>Connect(connection, modulename, databasename, tablename, *args)</strong></dt>
1737
1762
 
1738
1763
    <dd>
1739
 
      <p>Similar to Create, except it is called to establish a new connection
1740
 
      to an existing table. The paramaters and return are the same. In general
1741
 
      Create is called the first time a table is accessed and is where you are
1742
 
      expect to do heavy initialisation work. Connect can take that initialized
1743
 
      work and reuse it.</p>
 
1764
      <p>Similar to Create, except it is called to establish a new connection to an existing table. The paramaters and
 
1765
      return are the same. In general Create is called the first time a table is accessed and is where you are expect
 
1766
      to do heavy initialisation work. Connect can take that initialized work and reuse it.</p>
1744
1767
    </dd>
1745
1768
  </dl>
1746
1769
 
1747
1770
  <h3>Table</h3>
1748
1771
 
1749
 
  <p>The table contains knowledge of the indices, makes cursors and can perform
1750
 
  transactions.</p>
 
1772
  <p>The table contains knowledge of the indices, makes cursors and can perform transactions.</p>
1751
1773
 
1752
1774
  <dl>
1753
1775
    <dt><strong>Begin() Sync() Commit() Rollback()</strong> (optional)</dt>
1754
1776
 
1755
1777
    <dd>
1756
 
      <p>These functions are used as part of transactions. At the time of
1757
 
      writing they are undocumented in SQLite (see <a href=
 
1778
      <p>These functions are used as part of transactions. At the time of writing they are undocumented in SQLite (see
 
1779
      <a href=
1758
1780
      "http://www.sqlite.org/cvstrac/wiki?p=VirtualTableMethods">www.sqlite.org/cvstrac/wiki?p=VirtualTableMethods</a>.
1759
 
      They do not take any arguments nor return anything. You do not have to
1760
 
      provide these methods.</p>
 
1781
      They do not take any arguments nor return anything. You do not have to provide these methods.</p>
1761
1782
    </dd>
1762
1783
 
1763
1784
    <dt><strong>Disconnect()</strong> (optional)<br />
1764
1785
    <strong>Destroy()</strong></dt>
1765
1786
 
1766
1787
    <dd>
1767
 
      <p>These methods are the opposite of <code>Connect</code> and
1768
 
      <code>Create</code> in the module implementation. They can be considered
1769
 
      destructors for the virtual table instance. It is currently unclear how
1770
 
      SQLite behaves if you return an error (<a href=
1771
 
      "http://www.sqlite.org/cvstrac/tktview?tn=2099">ticket 2099</a>). Note
1772
 
      that SQLite does ignore errors in the Disconnect method. If you do have
1773
 
      one, you will get an exception from the <code>close()</code> method, but
1774
 
      the database will actually be closed.</p>
 
1788
      <p>These methods are the opposite of <code>Connect</code> and <code>Create</code> in the module implementation.
 
1789
      They can be considered destructors for the virtual table instance. It is currently unclear how SQLite behaves if
 
1790
      you return an error (<a href="http://www.sqlite.org/cvstrac/tktview?tn=2099">ticket 2099</a>). Note that SQLite
 
1791
      does ignore errors in the Disconnect method. If you do have one, you will get an exception from the
 
1792
      <code>close()</code> method, but the database will actually be closed.</p>
1775
1793
    </dd>
1776
1794
 
1777
1795
    <dt><strong>Open()</strong></dt>
1780
1798
      <p>Returns a new cursor object.</p>
1781
1799
    </dd>
1782
1800
 
1783
 
    <dt><strong>FindFunction(nfuncargs, funcname)</strong> <i>not implemented
1784
 
    yet</i></dt>
1785
 
 
1786
 
    <dd>
1787
 
      <p>Lets you provide an alternate function implementation for the table.
1788
 
      This is currently not implemented in apsw because of incomplete
1789
 
      information in SQLite to make it safe (<a href=
 
1801
    <dt><strong>Rename(newname)</strong> (optional)</dt>
 
1802
 
 
1803
    <dd>
 
1804
      <p>Notification that the table will be given a new name. If you return without raising an exception, then SQLite
 
1805
      renames the table (you don't have to do anything). If you raise an exception then the renaming is prevented.</p>
 
1806
    </dd>
 
1807
 
 
1808
    <dt><strong>FindFunction(nfuncargs, funcname)</strong> <i>not implemented yet</i></dt>
 
1809
 
 
1810
    <dd>
 
1811
      <p>Lets you provide an alternate function implementation for the table. This is currently not implemented in apsw
 
1812
      because of incomplete information in SQLite to make it safe (<a href=
1790
1813
      "http://www.sqlite.org/cvstrac/tktview?tn=2095">ticket 2095</a>).</p>
1791
1814
    </dd>
1792
1815
 
1801
1824
    <dt><strong>UpdateInsertRow(rowid, fields)</strong></dt>
1802
1825
 
1803
1826
    <dd>
1804
 
      <p>Create a new row. fields is a tuple the same size as the number of
1805
 
      columns in your table containing a value for each column. rowid is the
1806
 
      rowid to give the row. If rowid is None then you must make up a rowid you
1807
 
      want.</p>
 
1827
      <p>Create a new row. fields is a tuple the same size as the number of columns in your table containing a value
 
1828
      for each column. rowid is the rowid to give the row. If rowid is None then you must make up a rowid you want.</p>
1808
1829
 
1809
1830
      <p><b>Return</b> the new rowid (if rowid was None), else ignored</p>
1810
1831
    </dd>
1812
1833
    <dt><strong>UpdateChangeRow(rowid, newrowid, fields)</strong></dt>
1813
1834
 
1814
1835
    <dd>
1815
 
      <p>Change an existing row of the table with the values in fields. fields
1816
 
      is a tuple the same size as the number of columns in your table
1817
 
      containing a value for each column. If newrowid is not the same as rowid
1818
 
      then you also have to change the rowid (this would happen for a query
1819
 
      like <code>UPDATE table SET rowid=rowid+100 WHERE ...</code>)</p>
 
1836
      <p>Change an existing row of the table with the values in fields. fields is a tuple the same size as the number
 
1837
      of columns in your table containing a value for each column. If newrowid is not the same as rowid then you also
 
1838
      have to change the rowid (this would happen for a query like <code>UPDATE table SET rowid=rowid+100 WHERE
 
1839
      ...</code>)</p>
1820
1840
 
1821
1841
      <p><b>Return</b> None (ignored)</p>
1822
1842
    </dd>
1826
1846
    <dd>
1827
1847
      <blockquote>
1828
1848
        This is a complex method and even has its <a href=
1829
 
        "http://www.sqlite.org/cvstrac/wiki?p=VirtualTableBestIndexMethod">own
1830
 
        page</a> in the SQLite documentation. To get going initially, just
1831
 
        return <code>None</code> and you will be fine. Implementing this method
1832
 
        reduces the number of rows scanned in your table to satisfy queries,
1833
 
        but only if you have an index or index like mechanism available.
 
1849
        "http://www.sqlite.org/cvstrac/wiki?p=VirtualTableBestIndexMethod">own page</a> in the SQLite documentation. To
 
1850
        get going initially, just return <code>None</code> and you will be fine. Implementing this method reduces the
 
1851
        number of rows scanned in your table to satisfy queries, but only if you have an index or index like mechanism
 
1852
        available.
1834
1853
 
1835
 
        <p><b>Note</b> The implementation of this method differs slightly from
1836
 
        the <a href=
1837
 
        "http://www.sqlite.org/cvstrac/wiki?p=VirtualTableBestIndexMethod">SQLite
1838
 
        documentation</a> for the C API. You are not passed "unusable"
1839
 
        constraints. The argv/constraintarg positions are not off by one. In
1840
 
        the C api, you have to return position 1 to get something passed to
1841
 
        Filter in position 0. With the APSW implementation, you return position
1842
 
        0 to get Filter arg 0, position 1 to get Filter arg 1 etc.</p>
 
1854
        <p><b>Note</b> The implementation of this method differs slightly from the <a href=
 
1855
        "http://www.sqlite.org/cvstrac/wiki?p=VirtualTableBestIndexMethod">SQLite documentation</a> for the C API. You
 
1856
        are not passed "unusable" constraints. The argv/constraintarg positions are not off by one. In the C api, you
 
1857
        have to return position 1 to get something passed to Filter in position 0. With the APSW implementation, you
 
1858
        return position 0 to get Filter arg 0, position 1 to get Filter arg 1 etc.</p>
1843
1859
      </blockquote>
1844
1860
 
1845
 
      <p>The purpose of this method is to ask if you have the ability to
1846
 
      determine if a row meets certain constraints that doesn't involve
1847
 
      visiting every row. An example constraint is
1848
 
      <code>price&nbsp;&gt;&nbsp;74.99</code>. In a traditional SQL database,
1849
 
      queries with constraints can be speeded up <a href=
1850
 
      "http://www.sqlite.org/lang_createindex.html">with indices</a>. If you
1851
 
      return None, then SQLite will visit every row in your table and evaluate
1852
 
      the constraint itself. Your index choice returned from BestIndex will
1853
 
      also be passed to the Filter method on your cursor object. Note that
1854
 
      SQLite may call this method multiple times trying to find the most
1855
 
      efficient way of answering a query. You will be passed the contraints as
1856
 
      a sequence of tuples containing two items. The first item is the column
1857
 
      number and the second item is the operation.</p>
 
1861
      <p>The purpose of this method is to ask if you have the ability to determine if a row meets certain constraints
 
1862
      that doesn't involve visiting every row. An example constraint is <code>price&nbsp;&gt;&nbsp;74.99</code>. In a
 
1863
      traditional SQL database, queries with constraints can be speeded up <a href=
 
1864
      "http://www.sqlite.org/lang_createindex.html">with indices</a>. If you return None, then SQLite will visit every
 
1865
      row in your table and evaluate the constraint itself. Your index choice returned from BestIndex will also be
 
1866
      passed to the Filter method on your cursor object. Note that SQLite may call this method multiple times trying to
 
1867
      find the most efficient way of answering a query. You will be passed the contraints as a sequence of tuples
 
1868
      containing two items. The first item is the column number and the second item is the operation.</p>
1858
1869
 
1859
1870
      <blockquote>
1860
 
        Example query: <code>select * from foo where price&gt;74.99 and
1861
 
        quantity&lt;=10 and customer=="Acme Widgets"</code>.
 
1871
        Example query: <code>select * from foo where price&gt;74.99 and quantity&lt;=10 and customer=="Acme
 
1872
        Widgets"</code>.
1862
1873
 
1863
 
        <p>If customer is column 0, price column 2 and quantity column 5, then
1864
 
        constraints will be:</p>
 
1874
        <p>If customer is column 0, price column 2 and quantity column 5, then constraints will be:</p>
1865
1875
        <pre>
1866
1876
   (2, apsw.SQLITE_INDEX_CONSTRAINT_GT),
1867
1877
   (5, apsw.SQLITE_INDEX_CONSTRAINT_LE),
1868
1878
   (0, apsw.SQLITE_INDEX_CONSTRAINT_EQ)
 
1879
 
1869
1880
</pre>
1870
1881
 
1871
 
        <p>Note that you do not get the value of the constraint (eg "Acme
1872
 
        Widgets", 74.99 and 10 in this example).</p>
 
1882
        <p>Note that you do not get the value of the constraint (eg "Acme Widgets", 74.99 and 10 in this example).</p>
1873
1883
      </blockquote>
1874
1884
 
1875
 
      <p>The first item you return is None if you don't have an appropriate
1876
 
      index for any of the constraints and SQLite should iterate over every
1877
 
      row. If you do have a suitable index then you return as the first item a
1878
 
      sequence the same length as constraints with the members mapping to the
1879
 
      constraints in order. Each item can be one of None, an integer or a tuple
1880
 
      of an integer and a boolean.</p>
 
1885
      <p>The first item you return is None if you don't have an appropriate index for any of the constraints and SQLite
 
1886
      should iterate over every row. If you do have a suitable index then you return as the first item a sequence the
 
1887
      same length as constraints with the members mapping to the constraints in order. Each item can be one of None, an
 
1888
      integer or a tuple of an integer and a boolean.</p>
1881
1889
 
1882
1890
      <dl>
1883
1891
        <dt>None</dt>
1884
1892
 
1885
 
        <dd>This means you have no index for that constraint. SQLite will have
1886
 
        to iterate over every row for it.</dd>
 
1893
        <dd>This means you have no index for that constraint. SQLite will have to iterate over every row for it.</dd>
1887
1894
 
1888
1895
        <dt>integer</dt>
1889
1896
 
1890
 
        <dd>This is the argument number for the constraintargs being passed
1891
 
        into the Filter function of your cursor (the values "Acme Widgets",
1892
 
        74.99 and 10 in the example).</dd>
 
1897
        <dd>This is the argument number for the constraintargs being passed into the Filter function of your cursor
 
1898
        (the values "Acme Widgets", 74.99 and 10 in the example).</dd>
1893
1899
 
1894
1900
        <dt>(integer, boolean)</dt>
1895
1901
 
1896
 
        <dd>By default SQLite will check what you return. For example if you
1897
 
        said that you had an index on price, SQLite will still check that each
1898
 
        row you returned is greater than 74.99. If you set the boolean to False
1899
 
        then SQLite won't do that double checking.</dd>
 
1902
        <dd>By default SQLite will check what you return. For example if you said that you had an index on price,
 
1903
        SQLite will still check that each row you returned is greater than 74.99. If you set the boolean to False then
 
1904
        SQLite won't do that double checking.</dd>
1900
1905
      </dl>
1901
1906
 
1902
1907
      <blockquote>
1903
 
        Example query: <code>select * from foo where price&gt;74.99 and
1904
 
        quantity&le;10 and customer=="Acme Widgets"</code>.
1905
 
 
1906
 
        <p>Customer is column 0, price column 2 and quantity column 5. You can
1907
 
        index on customer equality and price.</p>
1908
 
 
1909
 
        <table border="1" cellspacing="5" cellpadding="5">
 
1908
        Example query: <code>select * from foo where price&gt;74.99 and quantity&le;10 and customer=="Acme
 
1909
        Widgets"</code>.
 
1910
 
 
1911
        <p>Customer is column 0, price column 2 and quantity column 5. You can index on customer equality and
 
1912
        price.</p>
 
1913
 
 
1914
        <table border="1" cellspacing="5" cellpadding="5" summary="BestIndex example">
1910
1915
          <tr>
1911
1916
            <th>Constraints (in)</th>
1912
1917
 
1933
1938
        </table>
1934
1939
      </blockquote>
1935
1940
 
1936
 
      <p>When your Filter method in the cursor is called, constraintarg[0] will
1937
 
      be "Acme Widgets" (customer constraint value) and constraintarg[1] will
1938
 
      be 74.99 (price constraint value). You can also return an index number
1939
 
      (integer) and index string to use (SQLite attaches no significance to
1940
 
      these values - they are passed as is to your Cursor.Filter method as a
1941
 
      way for the BestIndex method to let the Cursor.Filter method know which
1942
 
      of your indices or similar mechanism to use.</p>
 
1941
      <p>When your Filter method in the cursor is called, constraintarg[0] will be "Acme Widgets" (customer constraint
 
1942
      value) and constraintarg[1] will be 74.99 (price constraint value). You can also return an index number (integer)
 
1943
      and index string to use (SQLite attaches no significance to these values - they are passed as is to your
 
1944
      Cursor.Filter method as a way for the BestIndex method to let the Cursor.Filter method know which of your indices
 
1945
      or similar mechanism to use.</p>
1943
1946
 
1944
 
      <p>The second argument to BestIndex is a sequence of orderbys because the
1945
 
      query requested the results in a <a href=
1946
 
      "http://sqlite.org/lang_select.html">certain order</a>. If your data is
1947
 
      already in that order then SQLite can give the results back as is. If
1948
 
      not, then SQLite will have to sort the results first.</p>
 
1947
      <p>The second argument to BestIndex is a sequence of orderbys because the query requested the results in a
 
1948
      <a href="http://sqlite.org/lang_select.html">certain order</a>. If your data is already in that order then SQLite
 
1949
      can give the results back as is. If not, then SQLite will have to sort the results first.</p>
1949
1950
 
1950
1951
      <blockquote>
1951
 
        Example query: <code>select * from foo order by price desc, quantity
1952
 
        asc</code>
 
1952
        Example query: <code>select * from foo order by price desc, quantity asc</code>
1953
1953
 
1954
1954
        <p>Price is column 2, quantity column 5 so orderbys will be:</p>
1955
1955
        <pre>
1956
 
  (2, True),  <font color=
1957
 
"blue"># True means descending, False is ascending</font>
 
1956
  (2, True),  <font color="blue"># True means descending, False is ascending</font>
1958
1957
  (5, False)
 
1958
 
1959
1959
</pre>
1960
1960
        <pre>
1961
1961
 
 
1962
 
1962
1963
</pre>
1963
1964
      </blockquote>
1964
1965
 
1965
 
      <p><b>Return</b> You should return up to 5 items. Items not present in
1966
 
      the return have a default value.</p>
 
1966
      <p><b>Return</b> You should return up to 5 items. Items not present in the return have a default value.</p>
1967
1967
 
1968
1968
      <dl>
1969
1969
        <dt>0: constraints used (default None)</dt>
1970
1970
 
1971
 
        <dd>This must either be None or a sequence the same length as
1972
 
        constraints passed in. Each item should be as specified above saying if
1973
 
        that constraint is used, and if so which constraintarg to make the
1974
 
        value be in your Cursor.Filter function.</dd>
 
1971
        <dd>This must either be None or a sequence the same length as constraints passed in. Each item should be as
 
1972
        specified above saying if that constraint is used, and if so which constraintarg to make the value be in your
 
1973
        Cursor.Filter function.</dd>
1975
1974
 
1976
1975
        <dt>1: index number (default zero)</dt>
1977
1976
 
1983
1982
 
1984
1983
        <dt>3: orderby consumed (default False)</dt>
1985
1984
 
1986
 
        <dd>Return True if your output will be in exactly the same order as the
1987
 
        orderbys passed in</dd>
 
1985
        <dd>Return True if your output will be in exactly the same order as the orderbys passed in</dd>
1988
1986
 
1989
1987
        <dt>4: estimated cost (default a huge number)</dt>
1990
1988
 
1991
 
        <dd>Approximately how many disk operations are needed to provide the
1992
 
        results. SQLite uses the cost to optimise queries. For example if the
1993
 
        query includes <code>A or B</code> and A has 2,000 operations and B has
1994
 
        100 then it is best to evaluate B before A.</dd>
 
1989
        <dd>Approximately how many disk operations are needed to provide the results. SQLite uses the cost to optimise
 
1990
        queries. For example if the query includes <code>A or B</code> and A has 2,000 operations and B has 100 then it
 
1991
        is best to evaluate B before A.</dd>
1995
1992
      </dl>
1996
1993
 
1997
1994
      <blockquote>
1998
 
        A complete example. Query is <code>select * from foo where
1999
 
        price&gt;74.99 and quantity&lt;=10 and customer=="Acme Widgets" order
2000
 
        by price desc, quantity asc</code>
 
1995
        A complete example. Query is <code>select * from foo where price&gt;74.99 and quantity&lt;=10 and
 
1996
        customer=="Acme Widgets" order by price desc, quantity asc</code>
2001
1997
 
2002
 
        <p>Customer is column 0, price column 2 and quantity column 5. You can
2003
 
        index on customer equality and price.</p>
 
1998
        <p>Customer is column 0, price column 2 and quantity column 5. You can index on customer equality and
 
1999
        price.</p>
2004
2000
        <pre>
2005
2001
<b>BestIndex</b>(constraints, orderbys)
2006
2002
 
2009
2005
                  (0, apsw.SQLITE_INDEX_CONSTRAINT_EQ)  )
2010
2006
 
2011
2007
<b>orderbys</b>= ( (2, True), (5, False) )
 
2008
 
2012
2009
</pre>
2013
2010
 
2014
2011
        <p>You return</p>
2017
2014
  27,             <font color="blue"># index number</font>
2018
2015
  "idx_pr_cust",  <font color="blue"># index name</font>
2019
2016
  False,          <font color="blue"># results are not in orderbys order</font>
2020
 
  1000            <font color=
2021
 
"blue"># about 1000 disk operations to access index</font>
 
2017
  1000            <font color="blue"># about 1000 disk operations to access index</font>
2022
2018
)
 
2019
 
2023
2020
</pre>
2024
2021
 
2025
2022
        <p>Your Cursor.Filter method will be called with:</p>
2028
2025
"idx_pr_cust",   <font color="blue"># index name you returned</font>
2029
2026
"Acme Widgets",  <font color="blue"># constraintarg[0] - customer</font>  
2030
2027
74.99            <font color="blue"># constraintarg[1] - price </font>
 
2028
 
2031
2029
</pre>
2032
2030
      </blockquote>
2033
2031
 
2034
2032
      <h3>Cursor</h3>
2035
2033
 
2036
 
      <p>Cursors are created by the Open method in the table object. They
2037
 
      iterate over rows returning desired values.</p>
 
2034
      <p>Cursors are created by the Open method in the table object. They iterate over rows returning desired
 
2035
      values.</p>
2038
2036
 
2039
2037
      <dl>
2040
2038
        <dt><strong>Close()</strong></dt>
2041
2039
 
2042
2040
        <dd>
2043
 
          <p>This is the destructor for the cursor. Note that you must cleanup.
2044
 
          The method will not be called again if you raise an exception.</p>
 
2041
          <p>This is the destructor for the cursor. Note that you must cleanup. The method will not be called again if
 
2042
          you raise an exception.</p>
2045
2043
 
2046
2044
          <p><b>Return</b> None (ignored)</p>
2047
2045
        </dd>
2049
2047
        <dt><strong>Filter(indexnum, indexstring, constraintargs)</strong></dt>
2050
2048
 
2051
2049
        <dd>
2052
 
          <p>This method is always called first to initialize an iteration to
2053
 
          the first row of the table. The arguments come from the BestIndex
2054
 
          method in the table object with constraintargs being a tuple of the
2055
 
          constraints you requested. If you always return None in BestIndex
2056
 
          then indexnum will be zero, indexstring will be None and
 
2050
          <p>This method is always called first to initialize an iteration to the first row of the table. The arguments
 
2051
          come from the BestIndex method in the table object with constraintargs being a tuple of the constraints you
 
2052
          requested. If you always return None in BestIndex then indexnum will be zero, indexstring will be None and
2057
2053
          constraintargs will be empty).</p>
2058
2054
 
2059
2055
          <p><b>Return</b> None (ignored)</p>
2062
2058
        <dt><strong>Eof()</strong></dt>
2063
2059
 
2064
2060
        <dd>
2065
 
          <p>Called to ask if we are at the end of the table. It is called
2066
 
          after each call to Filter and Next.</p>
 
2061
          <p>Called to ask if we are at the end of the table. It is called after each call to Filter and Next.</p>
2067
2062
 
2068
 
          <p><b>Return</b> True if the cursor is at a valid row of data, else
2069
 
          False. Note that if you have an exception in this method, or do not
2070
 
          provide it then False will be returned to SQLite.</p>
 
2063
          <p><b>Return</b> True if the cursor is at a valid row of data, else False. Note that if you have an exception
 
2064
          in this method, or do not provide it then False will be returned to SQLite.</p>
2071
2065
        </dd>
2072
2066
 
2073
2067
        <dt><strong>Next()</strong></dt>
2081
2075
        <dt><strong>Rowid()</strong></dt>
2082
2076
 
2083
2077
        <dd>
2084
 
          <p><b>Return</b> the current rowid. This should be an integer up to
2085
 
          64 bits signed.</p>
 
2078
          <p><b>Return</b> the current rowid. This should be an integer up to 64 bits signed.</p>
2086
2079
        </dd>
2087
2080
 
2088
2081
        <dt><strong>Column(number)</strong></dt>
2089
2082
 
2090
2083
        <dd>
2091
 
          <p>Requests the value of the specified column number. Column
2092
 
          numbering starts at zero with -1 being the rowid.</p>
 
2084
          <p>Requests the value of the specified column number. Column numbering starts at zero with -1 being the
 
2085
          rowid.</p>
2093
2086
 
2094
 
          <p><b>Return</b> the value in that column. It must be compatible with
2095
 
          SQLite types (ie one of None, integer, float, string or buffer
2096
 
          (blob))</p>
 
2087
          <p><b>Return</b> the value in that column. It must be compatible with SQLite types (ie one of None, integer,
 
2088
          float, string or buffer (blob))</p>
2097
2089
        </dd>
2098
2090
      </dl>
2099
2091
 
2100
2092
      <h3>Troubleshooting virtual tables</h3>
2101
2093
 
2102
 
      <p>Virtual Tables are a very recent addition to SQLite and haven't been
2103
 
      widely used yet. They do work well if all your routines work
2104
 
      perfectly.</p>
2105
 
 
2106
 
      <p>A big help is using the local variables recipe as described in
2107
 
      <a href="#augmentedstacktraces">augmented stack traces</a> which will
2108
 
      give you more details in errors. You may also find errors compounding.
2109
 
      For example if you have an error in the Filter method of a cursor, SQLite
2110
 
      then closes the cursor. If you also return an error in the Close method
2111
 
      then the first error may mask the second or vice versa.</p>
2112
 
 
2113
 
      <p>Also note that SQLite may ignore responses from your methods if they
2114
 
      don't make sense. For example in BestIndex, if you set multiple arguments
2115
 
      to have the same constraintargs position then your Filter won't receive
 
2094
      <p>Virtual Tables are a very recent addition to SQLite and haven't been widely used yet. They do work well if all
 
2095
      your routines work perfectly.</p>
 
2096
 
 
2097
      <p>A big help is using the local variables recipe as described in <a href="#augmentedstacktraces">augmented stack
 
2098
      traces</a> which will give you more details in errors. You may also find errors compounding. For example if you
 
2099
      have an error in the Filter method of a cursor, SQLite then closes the cursor. If you also return an error in the
 
2100
      Close method then the first error may mask the second or vice versa.</p>
 
2101
 
 
2102
      <p>Also note that SQLite may ignore responses from your methods if they don't make sense. For example in
 
2103
      BestIndex, if you set multiple arguments to have the same constraintargs position then your Filter won't receive
2116
2104
      any constraintargs at all.</p>
2117
2105
 
2118
2106
      <h1><a name="Exceptions" id="Exceptions">Exceptions</a></h1>
2119
2107
 
2120
 
      <p>All exception types have <code>apsw.Error</code> as a parent. The
2121
 
      following exceptions can happen:</p>
 
2108
      <p>All exception types have <code>apsw.Error</code> as a parent. The following exceptions can happen:</p>
2122
2109
 
2123
2110
      <dl>
2124
2111
        <dt>ThreadingViolationError</dt>
2125
2112
 
2126
2113
        <dd>
2127
 
          <p>You have used an object allocated in one thread in a different
2128
 
          thread. All objects (Connection, Cursor) must be used in the same
2129
 
          thread they were allocated in.</p>
 
2114
          <p>You have used an object concurrently in two threads. For example you may try to use the same cursor in two
 
2115
          different threads at the same time, or tried to close the same connection in two threads at the same
 
2116
          time.</p>
2130
2117
        </dd>
2131
2118
 
2132
2119
        <dt>IncompleteExecutionError</dt>
2133
2120
 
2134
2121
        <dd>
2135
 
          <p>You have tried to start a new SQL execute call before executing
2136
 
          all the previous ones. See the <a href="#executionmodel">execution
2137
 
          model</a> for more details.</p>
 
2122
          <p>You have tried to start a new SQL execute call before executing all the previous ones. See the <a href=
 
2123
          "#executionmodel">execution model</a> for more details.</p>
2138
2124
        </dd>
2139
2125
 
2140
2126
        <dt>ConnectionNotClosedError</dt>
2141
2127
 
2142
2128
        <dd>
2143
 
          <p>The destructor for a Connection was called, but close() hadn't
2144
 
          been called on the Connection. Destructors aren't allowed to return
2145
 
          exceptions, so what actually happens is that
2146
 
          <code>sys.excepthook</code> is called with this exception so you can
2147
 
          find where it is happening in your code. The database will also be
2148
 
          left open and hence leak memory and potentially file descriptors.</p>
 
2129
          <p>This exception is no longer generated.</p>
2149
2130
        </dd>
2150
2131
 
2151
2132
        <dt>ConnectionClosedError</dt>
2152
2133
 
2153
2134
        <dd>
2154
 
          <p>You have called close() on a Connection and then continued to use
2155
 
          it.</p>
 
2135
          <p>You have called close() on a Connection and then continued to use it.</p>
2156
2136
        </dd>
2157
2137
 
2158
2138
        <dt>BindingsError</dt>
2159
2139
 
2160
2140
        <dd>
2161
 
          <p>There is an incorrect number of bindings when using tuples. Or you
2162
 
          supplied a dictionary of bindings and not all bindings were named in
2163
 
          the SQL statement. For example
2164
 
          <code>select&nbsp;*&nbsp;from&nbsp;foo&nbsp;where&nbsp;x=:name&nbsp;and&nbsp;y=?</code>.
2165
 
          You should either use colon name style or question mark style in a
2166
 
          query but not both.</p>
 
2141
          <p>There is an incorrect number of bindings when using tuples. Or you supplied a dictionary of bindings and
 
2142
          not all bindings were named in the SQL statement. For example
 
2143
          <code>select&nbsp;*&nbsp;from&nbsp;foo&nbsp;where&nbsp;x=:name&nbsp;and&nbsp;y=?</code>. You should either
 
2144
          use colon name style or question mark style in a query but not both.</p>
2167
2145
 
2168
 
          <p><b>Note</b> It is not considered an error to have missing keys in
2169
 
          a dictionary. For example <code>cursor.execute("insert into foo
2170
 
          values($a,:b,$c)", {'a': 1})</code> is perfectly valid (note
2171
 
          <tt>b</tt> and <b>c</b> are not in the dict). For missing keys,
2172
 
          None/NULL will be used. This is so you don't have to add lots of
2173
 
          spurious values to the supplied dict. If your schema requires every
2174
 
          column have a value, then SQLite will generate an error due to some
2175
 
          values being None/NULL so that case will be caught.</p>
 
2146
          <p><b>Note</b> It is not considered an error to have missing keys in a dictionary. For example
 
2147
          <code>cursor.execute("insert into foo values($a,:b,$c)", {'a': 1})</code> is perfectly valid (note <tt>b</tt>
 
2148
          and <b>c</b> are not in the dict). For missing keys, None/NULL will be used. This is so you don't have to add
 
2149
          lots of spurious values to the supplied dict. If your schema requires every column have a value, then SQLite
 
2150
          will generate an error due to some values being None/NULL so that case will be caught.</p>
2176
2151
        </dd>
2177
2152
 
2178
2153
        <dt>ExecutionCompleteError</dt>
2184
2159
        <dt>ExecTraceAbort</dt>
2185
2160
 
2186
2161
        <dd>
2187
 
          <p>The <a href="#executiontracer">execution tracer</a> returned False
2188
 
          so execution was aborted.</p>
 
2162
          <p>The <a href="#executiontracer">execution tracer</a> returned False so execution was aborted.</p>
2189
2163
        </dd>
2190
2164
 
2191
2165
        <dt>ExtensionLoadingError</dt>
2197
2171
      </dl>
2198
2172
 
2199
2173
      <p>The table lists which Exception classes correspond to which <a href=
2200
 
      "http://www.sqlite.org/capi3ref.html#result-codes">SQLite error
2201
 
      codes</a>. APSW runs with <a href=
2202
 
      "http://www.sqlite.org/cvstrac/wiki?p=ExtendedResultCodes">extended
2203
 
      result codes</a> turned on. If you get the <code>result</code> member of
2204
 
      an exception instance then you will get the plain error code. The
2205
 
      <code>extendedresult</code> member of an exception instance will get you
2206
 
      the extended error code.</p>
 
2174
      "http://sqlite.org/c3ref/c_abort.html">SQLite error codes</a>. APSW runs with <a href=
 
2175
      "http://sqlite.org/c3ref/c_ioerr_blocked.html">extended result codes</a> turned on. If you get the
 
2176
      <code>result</code> member of an exception instance then you will get the plain error code. The
 
2177
      <code>extendedresult</code> member of an exception instance will get you the extended error code.</p>
2207
2178
 
2208
2179
      <blockquote>
2209
2180
        <!-- This is derived from exc_descriptors in the source -->
2402
2373
          </tr>
2403
2374
        </table>
2404
2375
 
2405
 
        <p>Codes in <i>italics</i> are no longer used by SQLite (according to
2406
 
        headers in 3.2.7).</p>
 
2376
        <p>Codes in <i>italics</i> are no longer used by SQLite (according to headers in 3.2.7).</p>
2407
2377
      </blockquote>
2408
2378
 
2409
 
      <h2><a name="augmentedstacktraces" id="augmentedstacktraces">Augmented
2410
 
      stack traces</a></h2>
2411
 
 
2412
 
      <p>When an exception occurs, Python does not include frames from
2413
 
      non-Python code (ie the C code called from Python). This can make it more
2414
 
      difficult to work out what was going on when an exception occurred for
2415
 
      example when there are callbacks to collations, functions or virtual
2416
 
      tables, triggers firing etc.</p>
2417
 
 
2418
 
      <p>This is an example showing the difference between the tracebacks you
2419
 
      would have got with earlier versions of apsw and the augmented
2420
 
      traceback.</p>
 
2379
      <h2><a name="augmentedstacktraces" id="augmentedstacktraces">Augmented stack traces</a></h2>
 
2380
 
 
2381
      <p>When an exception occurs, Python does not include frames from non-Python code (ie the C code called from
 
2382
      Python). This can make it more difficult to work out what was going on when an exception occurred for example
 
2383
      when there are callbacks to collations, functions or virtual tables, triggers firing etc.</p>
 
2384
 
 
2385
      <p>This is an example showing the difference between the tracebacks you would have got with earlier versions of
 
2386
      apsw and the augmented traceback.</p>
2421
2387
 
2422
2388
      <p><b>Code</b></p>
2423
2389
      <pre>
2432
2398
cursor=con.cursor()
2433
2399
cursor.execute("create table bar(x,y,z);insert into bar values(1,2,3)")
2434
2400
cursor.execute("select foo(1) from bar")
 
2401
 
2435
2402
</pre>
2436
2403
 
2437
2404
      <table cellpadding="3" cellspacing="3">
2468
2435
        </tr>
2469
2436
      </table>
2470
2437
 
2471
 
      <p>In the original traceback you can't even see that code in apsw was
2472
 
      involved. The augmented traceback shows that there were indeed two
2473
 
      function calls within apsw and gives you line numbers should you need to
2474
 
      examine the code. Also note how you are told that the call was in
2475
 
      <code>user-defined-scalar-FOO</code> (all function names are
2476
 
      uppercased).</p>
 
2438
      <p>In the original traceback you can't even see that code in apsw was involved. The augmented traceback shows
 
2439
      that there were indeed two function calls within apsw and gives you line numbers should you need to examine the
 
2440
      code. Also note how you are told that the call was in <code>user-defined-scalar-FOO</code> (all function names
 
2441
      are uppercased).</p>
2477
2442
 
2478
 
      <p><i>But wait, there is more!!!</i> In order to further aid
2479
 
      troubleshooting, the augmented stack traces make additional information
2480
 
      available. Each frame in the traceback has local variables defined with
2481
 
      more information. You can print out the variables using <a href=
2482
 
      "http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52215">ASPN
2483
 
      recipe 52215</a>.</p>
 
2443
      <p><i>But wait, there is more!!!</i> In order to further aid troubleshooting, the augmented stack traces make
 
2444
      additional information available. Each frame in the traceback has local variables defined with more information.
 
2445
      You can print out the variables using <a href=
 
2446
      "http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52215">ASPN recipe 52215</a>.</p>
2484
2447
 
2485
2448
      <blockquote>
2486
 
        <p>In the recipe, the initial code in <code>print_exc_plus</code> is
2487
 
        far more complicated than need be, and also won't work correctly with
2488
 
        all tracebacks (it depends on f_prev being set which isn't always the
2489
 
        case). Change the function to start like this:</p>
 
2449
        <p>In the recipe, the initial code in <code>print_exc_plus</code> is far more complicated than need be, and
 
2450
        also won't work correctly with all tracebacks (it depends on f_prev being set which isn't always the case).
 
2451
        Change the function to start like this:</p>
2490
2452
 
2491
2453
        <blockquote>
2492
2454
          <pre>
2499
2461
 
2500
2462
    traceback.print_exc()
2501
2463
    print "Locals by frame, innermost last"
 
2464
 
2502
2465
</pre>
2503
2466
        </blockquote>
2504
2467
      </blockquote>
2505
2468
 
2506
 
      <p>Here is a far more complex example from some <a href=
2507
 
      "#VirtualTables">virtual tables</a> code I was writing. The BestIndex
2508
 
      method in my code had returned an incorrect value. The augmented
2509
 
      traceback includes local variables using recipe 52215. I can see what was
2510
 
      passed in to my method, what I returned and which item was erroneous. The
 
2469
      <p>Here is a far more complex example from some <a href="#VirtualTables">virtual tables</a> code I was writing.
 
2470
      The BestIndex method in my code had returned an incorrect value. The augmented traceback includes local variables
 
2471
      using recipe 52215. I can see what was passed in to my method, what I returned and which item was erroneous. The
2511
2472
      original traceback is almost completely useless.</p>
2512
2473
 
2513
2474
      <table cellpadding="3" cellspacing="3">
2565
2526
 
2566
2527
      <h1><a name="Types" id="Types">Types</a></h1>
2567
2528
 
2568
 
      <p>Read about <a href="http://www.sqlite.org/datatype3.html">SQLite 3
2569
 
      types</a>. ASPW always maintains the correct type for values, and never
2570
 
      converts them to something else. Note however that SQLite may convert
2571
 
      types based on column affinity as described in that link. ASPW requires
2572
 
      that all values supplied are one of the corresponding Python/SQLite types
2573
 
      (or a subclass).</p>
 
2529
      <p>Read about <a href="http://www.sqlite.org/datatype3.html">SQLite 3 types</a>. ASPW always maintains the
 
2530
      correct type for values, and never converts them to something else. Note however that SQLite may convert types
 
2531
      based on column affinity as described in that link. ASPW requires that all values supplied are one of the
 
2532
      corresponding Python/SQLite types (or a subclass).</p>
2574
2533
 
2575
2534
      <ul>
2576
2535
        <li>
2578
2537
        </li>
2579
2538
 
2580
2539
        <li>
2581
 
          <p>Python int or long is INTEGER in SQLite. The value represented
2582
 
          must fit within a 64 bit signed quantity (long long at the C level)
2583
 
          or an exception is generated. (Don't worry - aspw only uses the long
2584
 
          type when values are too large to fit in ints).</p>
2585
 
        </li>
2586
 
 
2587
 
        <li>
2588
 
          <p>Python's float type is used for REAL in SQLite. (At the C level
2589
 
          they are both 8 byte quantities and there is no loss of
2590
 
          precision).</p>
2591
 
        </li>
2592
 
 
2593
 
        <li>
2594
 
          <p>Python's string or unicode is used for TEXT in SQLite. (ASPW
2595
 
          automatically uses Python's string type for ASCII text and Unicode
2596
 
          for other text.)</p>
 
2540
          <p>Python int or long is INTEGER in SQLite. The value represented must fit within a 64 bit signed quantity
 
2541
          (long long at the C level) or an exception is generated. (Don't worry - aspw only uses the long type when
 
2542
          values are too large to fit in ints).</p>
 
2543
        </li>
 
2544
 
 
2545
        <li>
 
2546
          <p>Python's float type is used for REAL in SQLite. (At the C level they are both 8 byte quantities and there
 
2547
          is no loss of precision).</p>
 
2548
        </li>
 
2549
 
 
2550
        <li>
 
2551
          <p>Python's string or unicode is used for TEXT in SQLite. (ASPW automatically uses Python's string type for
 
2552
          ASCII text and Unicode for other text.)</p>
2597
2553
        </li>
2598
2554
 
2599
2555
        <li>
2603
2559
 
2604
2560
      <h1><a name="Unicode" id="Unicode">Unicode</a></h1>
2605
2561
 
2606
 
      <p>All SQLite strings are Unicode. The actual binary representations can
2607
 
      be UTF8, or UTF16 in either byte order. ASPW uses the UTF8 interface to
2608
 
      SQLite which results in the binary string representation in your database
2609
 
      defaulting to UTF8 as well. All this is totally transparent to your
2610
 
      Python code.</p>
2611
 
 
2612
 
      <p>Everywhere strings are used (eg as database values, SQL statements,
2613
 
      bindings names, user defined functions) you can use Unicode strings. You
2614
 
      can also use the bare Python string class, and ASPW will automatically
2615
 
      call the unicode converter if any non-ascii characters are present.</p>
2616
 
 
2617
 
      <p>All strings that APSW reads from SQLite are returned as
2618
 
      Unicode strings, even if they only contain ASCII characters.</p>
2619
 
 
2620
 
      <h1><a name="threading" id="threading">Multi-threading and
2621
 
      re-entrancy</a></h1>
2622
 
 
2623
 
      <p>ASPW lets you use SQLite in multi-threaded programs and will let other
2624
 
      threads execute while SQLite is working. (Technically the <a href=
2625
 
      "http://www.python.org/doc/2.3.4/api/threads.html">GIL</a> is released
2626
 
      when <a href=
2627
 
      "http://www.sqlite.org/capi3ref.html#sqlite3_step">sqlite3_step</a> or
2628
 
      <a href=
2629
 
      "http://www.sqlite.org/capi3ref.html#sqlite3_open">sqlite3_open</a> are
2630
 
      running. The GIL is re-acquired while user defined functions, collations
2631
 
      and the various hooks/handlers run.)</p>
2632
 
 
2633
 
      <p>Note that you cannot use the same Connection object in multiple
2634
 
      threads. You must allocate a new Connection object per thread. (This is a
2635
 
      requirement of SQLite). A cursor object can only be used in the same
2636
 
      thread as it was allocated. (Also an SQLite requirement). Fortunately
2637
 
      ASPW will check this for you and throw a ThreadingViolationError if you
2638
 
      try to use objects in the wrong thread. Note that your destructors also
2639
 
      need to run in the creation thread.</p>
2640
 
 
2641
 
      <p>If you have multiple threads and/or multiple programs accessing the
2642
 
      same database then there may be contention for the file. SQLite will
2643
 
      return SQLITE_BUSY which will be raised as BusyError. You can call
2644
 
      Connection.setbusytimeout to set how long SQLite will retry for or
2645
 
      Connection.setbusyhandler to install your own busy handler. Note that
2646
 
      SQLite won't call the busy handler or timeout if it believes a deadlock
2647
 
      has arisen. SQLite's locking and concurrency is described <a href=
2648
 
      "http://www.sqlite.org/lockingv3.html">here</a></p>
2649
 
 
2650
 
      <p>A cursor object can only be executing one query at a time. You cannot
2651
 
      issue a new query from inside a trace function or from a user defined
2652
 
      function or collation since these are called while executing a query. You
2653
 
      can however make new cursors and use those without issue. You may want to
2654
 
      remember the Connection object when you set your trace or user defined
2655
 
      functions.</p>
 
2562
      <p>All SQLite strings are Unicode. The actual binary representations can be UTF8, or UTF16 in either byte order.
 
2563
      ASPW uses the UTF8 interface to SQLite which results in the binary string representation in your database
 
2564
      defaulting to UTF8 as well. All this is totally transparent to your Python code.</p>
 
2565
 
 
2566
      <p>Everywhere strings are used (eg as database values, SQL statements, bindings names, user defined functions)
 
2567
      you can use Unicode strings. You can also use the bare Python string class, and ASPW will automatically call the
 
2568
      unicode converter if any non-ascii characters are present.</p>
 
2569
 
 
2570
      <p>When returning values from SQLite, ASPW always uses the Python unicode class.</p>
 
2571
 
 
2572
      <h1><a name="threading" id="threading">Multi-threading and re-entrancy</a></h1>
 
2573
 
 
2574
      <p>ASPW lets you use SQLite in multi-threaded programs and will let other threads execute while SQLite is
 
2575
      working. (Technically the <a href="http://www.python.org/doc/2.3.4/api/threads.html">GIL</a> is released when
 
2576
      <a href="http://sqlite.org/c3ref/prepare.html">sqlite3_prepare_v2</a>, <a href=
 
2577
      "http://sqlite.org/c3ref/step.html">sqlite3_step</a> or <a href=
 
2578
      "http://sqlite.org/c3ref/open.html">sqlite3_open_v2</a> are running, as well as many other functions that could
 
2579
      take more than a trivial amount of time. The GIL is re-acquired while user defined functions, collations and the
 
2580
      various hooks/handlers run.)</p>
 
2581
 
 
2582
      <p>Note that you cannot use the same cursor object in multiple threads concurrently to execute statements. APSW
 
2583
      will detect this and throw an exception. It is safe to use the object serially (eg calling <code>execute</code>
 
2584
      in one thread and <code>next</code> in another. You also can't do things like try to close a Connection
 
2585
      concurrently in two threads.</p>
 
2586
 
 
2587
      <p>If you have multiple threads and/or multiple programs accessing the same database then there may be contention
 
2588
      for the file. SQLite will return SQLITE_BUSY which will be raised as BusyError. You can call
 
2589
      Connection.setbusytimeout to set how long SQLite will retry for or Connection.setbusyhandler to install your own
 
2590
      busy handler. Note that SQLite won't call the busy handler or timeout if it believes a deadlock has arisen.
 
2591
      SQLite's locking and concurrency is described <a href="http://www.sqlite.org/lockingv3.html">here</a></p>
 
2592
 
 
2593
      <p>A cursor object can only be executing one query at a time. You cannot issue a new query from inside a trace
 
2594
      function or from a user defined function or collation since these are called while executing a query. You can
 
2595
      however make new cursors and use those without issue. You may want to remember the Connection object when you set
 
2596
      your trace or user defined functions.</p>
2656
2597
 
2657
2598
      <h1><a name="tracers" id="tracers">Tracing</a></h1>
2658
2599
 
2659
 
      <p>You can install tracers on a cursor as an easy way of seeing exactly
2660
 
      what gets executed and what is returned. The tracers can also abort
2661
 
      execution and cause different values to be returned. This is very useful
2662
 
      for diagnostics and testing without having to modify your main code.</p>
2663
 
 
2664
 
      <p><b>Note</b>: You cannot issue new execute statements against the
2665
 
      cursor your tracer was called from. If you would like to make more
2666
 
      queries in the tracer then do them from a new cursor object.</p>
2667
 
 
2668
 
      <h2><a name="executiontracer" id="executiontracer">Execution
2669
 
      Tracer</a></h2>
2670
 
 
2671
 
      <p>The execution tracer is called after an SQL statement has been
2672
 
      prepared. (ie syntax errors will have caused an exception during
2673
 
      preparation so you won't see them with a tracer). It is called with two
2674
 
      arguments. The first is a string which is the SQL statement about to be
2675
 
      executed, and the second is the bindings used for that statement (and can
2676
 
      be None). If the return value evaluates to False/None then execution is
2677
 
      aborted with an ExecTraceAbort exception. See the <a href=
2678
 
      "#example-exectrace">example above</a>.</p>
 
2600
      <p>You can install tracers on a cursor as an easy way of seeing exactly what gets executed and what is returned.
 
2601
      The tracers can also abort execution and cause different values to be returned. This is very useful for
 
2602
      diagnostics and testing without having to modify your main code.</p>
 
2603
 
 
2604
      <p><b>Note</b>: You cannot issue new execute statements against the cursor your tracer was called from. If you
 
2605
      would like to make more queries in the tracer then do them from a new cursor object.</p>
 
2606
 
 
2607
      <h2><a name="executiontracer" id="executiontracer">Execution Tracer</a></h2>
 
2608
 
 
2609
      <p>The execution tracer is called after an SQL statement has been prepared. (ie syntax errors will have caused an
 
2610
      exception during preparation so you won't see them with a tracer). It is called with two arguments. The first is
 
2611
      a string which is the SQL statement about to be executed, and the second is the bindings used for that statement
 
2612
      (and can be None). If the return value evaluates to False/None then execution is aborted with an ExecTraceAbort
 
2613
      exception. See the <a href="#example-exectrace">example above</a>.</p>
2679
2614
 
2680
2615
      <h2><a name="rowtracer" id="rowtracer">Row Tracer</a></h2>
2681
2616
 
2682
 
      <p>The row tracer is called before each row is returned. The arguments
2683
 
      are the items about to be returned. Whatever you return from the tracer
2684
 
      is what is actually returned. If you return None then the whole row is
 
2617
      <p>The row tracer is called before each row is returned. The arguments are the items about to be returned.
 
2618
      Whatever you return from the tracer is what is actually returned. If you return None then the whole row is
2685
2619
      skipped. See the <a href="#example-rowtrace">example above</a>.</p>
2686
2620
 
2687
2621
      <h1><a name="64bitpy25">64 bit hosts, Python 2.5</a></h1>
2688
2622
 
2689
 
      <p>Prior to Python 2.5, you were still limited to 32 bit quantities for
2690
 
      items in Python such as the length of strings, number of items in a
2691
 
      sequence etc. APSW will work correctly with those items in Python 2.5
2692
 
      that use 64 bits. Unfortunately SQLite is limited to 32 bit quantities
2693
 
      for strings, blobs, number of columns etc. Consequently you will get a
2694
 
      TooBig exception from APSW which checks if strings/buffers longer than
2695
 
      1GB or 2GB (depends on internal storage) are used. See SQLite ticket
2696
 
      <a href="http://www.sqlite.org/cvstrac/tktview?tn=2125">2125</a>.</p>
 
2623
      <p>Prior to Python 2.5, you were still limited to 32 bit quantities for items in Python such as the length of
 
2624
      strings, number of items in a sequence etc. APSW will work correctly with those items in Python 2.5 that use 64
 
2625
      bits. Unfortunately SQLite is limited to 32 bit quantities for strings, blobs, number of columns etc.
 
2626
      Consequently you will get a TooBig exception from APSW which checks if strings/buffers longer than 1GB or 2GB
 
2627
      (depends on internal storage) are used. See SQLite ticket <a href=
 
2628
      "http://www.sqlite.org/cvstrac/tktview?tn=2125">2125</a>.</p>
2697
2629
 
2698
2630
      <h1><a name="executionmodel" id="executionmodel">Execution model</a></h1>
2699
2631
 
2700
 
      <p>This section only matters if you give multiple SQL statements in one
2701
 
      go to <code>cursor.execute()</code>. (Statements are seperated by
2702
 
      semi-colons.)</p>
2703
 
 
2704
 
      <p>SQLite does execution in two steps. First a statement is prepared,
2705
 
      which verifies the syntax, tables and fields and converts the statement
2706
 
      into an internal representation. The prepared statement is then run.
2707
 
      Execution stops when a row is available, there is an error or the
2708
 
      statement is complete.</p>
2709
 
 
2710
 
      <p>The <code>cursor.execute()</code> method automatically does the
2711
 
      preparing and starts execution. If none of the statements return rows
2712
 
      then execution will go to the end. If a row is returned then you need to
2713
 
      call cursor.next() to get the row values. Execution will resume as
2714
 
      necessary to satisfy <code>next()</code> calls.</p>
2715
 
 
2716
 
      <p>However this means that if you don't read the rows returned then the
2717
 
      rest of your statements won't be executed. APSW will detect unexecuted
2718
 
      previous statements and generate an exception. For example:</p>
 
2632
      <p>This section only matters if you give multiple SQL statements in one go to <code>cursor.execute()</code>.
 
2633
      (Statements are seperated by semi-colons.)</p>
 
2634
 
 
2635
      <p>SQLite does execution in two steps. First a statement is prepared, which verifies the syntax, tables and
 
2636
      fields and converts the statement into an internal representation. The prepared statement is then run. Execution
 
2637
      stops when a row is available, there is an error or the statement is complete.</p>
 
2638
 
 
2639
      <p>The <code>cursor.execute()</code> method automatically does the preparing and starts execution. If none of the
 
2640
      statements return rows then execution will go to the end. If a row is returned then you need to call
 
2641
      cursor.next() to get the row values. Execution will resume as necessary to satisfy <code>next()</code> calls.</p>
 
2642
 
 
2643
      <p>However this means that if you don't read the rows returned then the rest of your statements won't be
 
2644
      executed. APSW will detect unexecuted previous statements and generate an exception. For example:</p>
2719
2645
 
2720
2646
      <blockquote>
2721
2647
        <pre>
2724
2650
Traceback (most recent call last):
2725
2651
  File "&lt;stdin&gt;", line 1, in ?
2726
2652
apsw.IncompleteExecutionError: Error: there are still remaining sql statements to execute
 
2653
 
2727
2654
</pre>
2728
2655
      </blockquote>
2729
2656
 
2730
 
      <p>Because I didn't read the results of <code>select * from foo</code>
2731
 
      then the following create table command didn't have a chance to get
2732
 
      executed. On the next execute that condition is detected and an exception
2733
 
      raised.</p>
 
2657
      <p>Because I didn't read the results of <code>select * from foo</code> then the following create table command
 
2658
      didn't have a chance to get executed. On the next execute that condition is detected and an exception raised.</p>
2734
2659
 
2735
2660
      <h1><a name="dbapinotes" id="dbapinotes">DBAPI notes</a></h1>
2736
2661
 
2737
 
      <p>DBAPI is defined in <a href=
2738
 
      "http://www.python.org/peps/pep-0249.html">PEP 249</a>. This section
2739
 
      desribes how APSW complies or differs from it.</p>
 
2662
      <p>DBAPI is defined in <a href="http://www.python.org/peps/pep-0249.html">PEP 249</a>. This section desribes how
 
2663
      APSW complies or differs from it.</p>
2740
2664
 
2741
2665
      <h2><a name="dbapimodiface" id="dbapimodiface">Module Interface</a></h2>
2742
2666
 
2743
 
      <p>There is no connect method. Use the Connection constructor instead,
2744
 
      which only takes one parameter - the name of the database.</p>
2745
 
 
2746
 
      <p>The Connection object and any cursors must all be used in the same
2747
 
      thread they were allocated from. You cannot use them in different threads
2748
 
      even if you protect them with mutexes.</p>
2749
 
 
2750
 
      <p>Three different paramstyles are supported. You can use qmark ('...
2751
 
      WHERE name=?'), numeric ('... WHERE name=?4') and named ('... WHERE
2752
 
      name=:name' or '... WHERE name=$name'). Note that SQLite numbers
2753
 
      parameters from one not zero.</p>
 
2667
      <p>There is no connect method. Use the Connection constructor instead, which only takes one parameter - the name
 
2668
      of the database.</p>
 
2669
 
 
2670
      <p>The Connection object and any cursors must all be used in the same thread they were allocated from. You cannot
 
2671
      use them in different threads even if you protect them with mutexes.</p>
 
2672
 
 
2673
      <p>Three different paramstyles are supported. You can use qmark ('... WHERE name=?'), numeric ('... WHERE
 
2674
      name=?4') and named ('... WHERE name=:name' or '... WHERE name=$name'). Note that SQLite numbers parameters from
 
2675
      one not zero.</p>
2754
2676
 
2755
2677
      <p>The DBAPI exceptions are not used.</p>
2756
2678
 
2757
 
      <h2><a name="dpapiconnectioniface" id="dpapiconnectioniface">Connection
2758
 
      Objects</a></h2>
2759
 
 
2760
 
      <p>There are no commit or rollback methods. You should use
2761
 
      cursor.execute("COMMIT") etc. The <a href=
2762
 
      "http://www.sqlite.org/lockingv3.html">SQLite documentation</a> has more
2763
 
      details.</p>
2764
 
 
2765
 
      <p>Several methods that are defined in DBAPI to be on the cursor are
2766
 
      instead on the Connection object, since this is where SQLite actually
2767
 
      stores the information. Doing operations in any other cursor attached to
2768
 
      the same Connection object does update their values, and this makes you
2769
 
      aware of that.</p>
2770
 
 
2771
 
      <h2><a name="dbapicursoriface" id="dbapicursoriface">Cursor
2772
 
      Objects</a></h2>
2773
 
 
2774
 
      <p>Use getdescription() instead of description. This information is only
2775
 
      obtained on request.</p>
 
2679
      <h2><a name="dpapiconnectioniface" id="dpapiconnectioniface">Connection Objects</a></h2>
 
2680
 
 
2681
      <p>There are no commit or rollback methods. You should use cursor.execute("COMMIT") etc. The <a href=
 
2682
      "http://www.sqlite.org/lockingv3.html">SQLite documentation</a> has more details.</p>
 
2683
 
 
2684
      <p>Several methods that are defined in DBAPI to be on the cursor are instead on the Connection object, since this
 
2685
      is where SQLite actually stores the information. Doing operations in any other cursor attached to the same
 
2686
      Connection object does update their values, and this makes you aware of that.</p>
 
2687
 
 
2688
      <h2><a name="dbapicursoriface" id="dbapicursoriface">Cursor Objects</a></h2>
 
2689
 
 
2690
      <p>Use getdescription() instead of description. This information is only obtained on request.</p>
2776
2691
 
2777
2692
      <p>There is no rowcount.</p>
2778
2693
 
2779
 
      <p>callproc is not implemented as SQLite doesn't support stored
2780
 
      procedures.</p>
2781
 
 
2782
 
      <p>execute returns the Cursor object and you can use it as an iterator to
2783
 
      get the results (if any).</p>
2784
 
 
2785
 
      <p>executemany returns the Cursor object and you can use it as an
2786
 
      iterator to get the results (if any).</p>
2787
 
 
2788
 
      <p>fetchone is not available. Use the cursor as an iterator, or call
2789
 
      next() which raises StopIteration when there are no more results.</p>
2790
 
 
2791
 
      <p>fetchmany is not available. Call next() for however many results you
2792
 
      want.</p>
2793
 
 
2794
 
      <p>fetchall is not available. Call next() or use a list comprehension
2795
 
      such as <code>[row for row in cursor.execute("....")]</code>.</p>
 
2694
      <p>callproc is not implemented as SQLite doesn't support stored procedures.</p>
 
2695
 
 
2696
      <p>execute returns the Cursor object and you can use it as an iterator to get the results (if any).</p>
 
2697
 
 
2698
      <p>executemany returns the Cursor object and you can use it as an iterator to get the results (if any).</p>
 
2699
 
 
2700
      <p>fetchone is not available. Use the cursor as an iterator, or call next() which raises StopIteration when there
 
2701
      are no more results.</p>
 
2702
 
 
2703
      <p>fetchmany is not available. Call next() for however many results you want.</p>
 
2704
 
 
2705
      <p>fetchall is not available. Call next() or use a list comprehension such as <code>[row for row in
 
2706
      cursor.execute("....")]</code>.</p>
2796
2707
 
2797
2708
      <p>nextset is not applicable or implemented.</p>
2798
2709
 
2799
2710
      <p>arraysize is not available as fetchmany isn't.</p>
2800
2711
 
2801
 
      <p>Neither setinputsizes or setoutputsize are applicable or
2802
 
      implemented.</p>
 
2712
      <p>Neither setinputsizes or setoutputsize are applicable or implemented.</p>
2803
2713
 
2804
2714
      <h2><a name="dpapitypes" id="dpapitypes">Type objects</a></h2>
2805
2715
 
2806
 
      <p>None of the date or time methods are available since SQLite 3 does not
2807
 
      have a native date or time type.</p>
 
2716
      <p>None of the date or time methods are available since SQLite 3 does not have a native date or time type.</p>
2808
2717
 
2809
2718
      <p>Use the standard Python buffer class for BLOBs.</p>
2810
2719
 
2811
 
      <h2><a name="dbapiextensions" id="dbapiextensions">Optional DB API
2812
 
      Extensions</a></h2>
 
2720
      <h2><a name="dbapiextensions" id="dbapiextensions">Optional DB API Extensions</a></h2>
2813
2721
 
2814
2722
      <p>rownumber is not available.</p>
2815
2723
 
2816
2724
      <p>Exception classes are not available as attributes of Connection.</p>
2817
2725
 
2818
 
      <p>Use Cursor.getconnection() to get the associated Connection
2819
 
      object.</p>
 
2726
      <p>Use Cursor.getconnection() to get the associated Connection object.</p>
2820
2727
 
2821
2728
      <p>scroll and messages are not available.</p>
2822
2729
 
2823
 
      <p>The Cursor object supports the iterator protocol and this is the only
2824
 
      way of getting information back.</p>
 
2730
      <p>The Cursor object supports the iterator protocol and this is the only way of getting information back.</p>
2825
2731
 
2826
 
      <p>To get the last inserted row id, call
2827
 
      <code>Connection.last_insert_rowid()</code>. That stores the id from the
2828
 
      last insert on any Cursor associated with the the Connection. You can
2829
 
      also add <code>select last_insert_rowid()</code> to the end of your
2830
 
      execute statements.</p>
 
2732
      <p>To get the last inserted row id, call <code>Connection.last_insert_rowid()</code>. That stores the id from the
 
2733
      last insert on any Cursor associated with the the Connection. You can also add <code>select
 
2734
      last_insert_rowid()</code> to the end of your execute statements.</p>
2831
2735
 
2832
2736
      <p>There is no errorhandler attribute.</p>
2833
2737
 
2834
 
      <h1><a name="pysqlitediffs" id="pysqlitediffs">pysqlite
2835
 
      differences</a></h1>
2836
 
 
2837
 
      <p><a href="http://pysqlite.org/">pysqlite</a> already provides a DBAPI
2838
 
      compliant wrapper over SQLite 2 and 3. APSW only wraps SQLite 3. I
2839
 
      suggest using APSW when you want to directly use SQLite and its
2840
 
      functionality or are using your code to deal with database independence
2841
 
      rather than DBAPI.</p>
2842
 
 
2843
 
      <p>APSW has the following enhancements/differences over pysqlite 2
2844
 
      (wrapping SQLite 3):</p>
 
2738
      <h1><a name="pysqlitediffs" id="pysqlitediffs">pysqlite differences</a></h1>
 
2739
 
 
2740
      <p><a href="http://pysqlite.org/">pysqlite</a> already provides a DBAPI compliant wrapper over SQLite 2 and 3.
 
2741
      APSW only wraps SQLite 3. I suggest using APSW when you want to directly use SQLite and its functionality or are
 
2742
      using your code to deal with database independence rather than DBAPI.</p>
 
2743
 
 
2744
      <p>APSW has the following enhancements/differences over pysqlite 2 (wrapping SQLite 3):</p>
2845
2745
 
2846
2746
      <ul>
2847
 
        <li>APSW gives all functionality of SQLite including <a href=
2848
 
        "#VirtualTables">virtual tables</a></li>
 
2747
        <li>APSW gives all functionality of SQLite including <a href="#VirtualTables">virtual tables</a></li>
2849
2748
 
2850
 
        <li>APSW is a single file for the extension, apsw.pyd on Windows and
2851
 
        apsw.so on Unix/Mac. There are no other files needed and the build
2852
 
        instructions show you how to include SQLite statically in this file.
2853
 
        You can put this file anywhere your Python session can reach. pysqlite
2854
 
        is one binary file and several .py files, all of which need to be
2855
 
        available.</li>
 
2749
        <li>APSW is a single file for the extension, apsw.pyd on Windows and apsw.so on Unix/Mac. There are no other
 
2750
        files needed and the build instructions show you how to include SQLite statically in this file. You can put
 
2751
        this file anywhere your Python session can reach. pysqlite is one binary file and several .py files, all of
 
2752
        which need to be available.</li>
2856
2753
 
2857
2754
        <li>
2858
 
          <p>*Nothing* happens behind your back. By default pysqlite tries to
2859
 
          manage transactions by parsing your SQL for you, but you can turn it
2860
 
          off. This can result in very unexpected behaviour with pysqlite.</p>
 
2755
          <p>*Nothing* happens behind your back. By default pysqlite tries to manage transactions by parsing your SQL
 
2756
          for you, but you can turn it off. This can result in very unexpected behaviour with pysqlite.</p>
2861
2757
        </li>
2862
2758
 
2863
2759
        <li>
2864
 
          <p>SQLite's Manifest typing is used, which limits values to being
2865
 
          supplied as integer (32/64 bit), string (utf8/unicode), double,
2866
 
          null/None and BLOB. (An exception happens if you don't supply values
2867
 
          in one of the supported types.) APSW doesn't do any type conversion
2868
 
          or co-ercion. Note that SQLite will under <a href=
2869
 
          "http://www.sqlite.org/datatype3.html">some circumstances</a>.
2870
 
          pysqlite does have a mechanism for <a href=
 
2760
          <p>SQLite's Manifest typing is used, which limits values to being supplied as integer (32/64 bit), string
 
2761
          (utf8/unicode), double, null/None and BLOB. (An exception happens if you don't supply values in one of the
 
2762
          supported types.) APSW doesn't do any type conversion or co-ercion. Note that SQLite will under <a href=
 
2763
          "http://www.sqlite.org/datatype3.html">some circumstances</a>. pysqlite does have a mechanism for <a href=
2871
2764
          "http://initd.org/pub/software/pysqlite/doc/usage-guide.html#using-adapters-to-store-additional-python-types-in-sqlite-databases">
2872
 
          marshalling your own types</a> but you'll need to be careful if
2873
 
          sharing the database with code in another language.</p>
2874
 
        </li>
2875
 
 
2876
 
        <li>
2877
 
          <p>APSW <b>always</b> handles Unicode correctly (this was one of the
2878
 
          major reasons for writing it in the first place). pysqlite has since
2879
 
          fixed many of its issues but you are still <a href=
2880
 
          "http://initd.org/tracker/pysqlite/ticket/153">stuck with
2881
 
          some</a>.</p>
2882
 
        </li>
2883
 
 
2884
 
        <li>
2885
 
          <p>You can use semi-colons at the end of commands and you can have
2886
 
          multiple commands in the execute string in APSW. There are no
2887
 
          restrictions on the type of commands used. For example this will work
2888
 
          fine in APSW but is not allowed in pysqlite:</p>
 
2765
          marshalling your own types</a> but you'll need to be careful if sharing the database with code in another
 
2766
          language.</p>
 
2767
        </li>
 
2768
 
 
2769
        <li>
 
2770
          <p>APSW <b>always</b> handles Unicode correctly (this was one of the major reasons for writing it in the
 
2771
          first place). pysqlite has since fixed many of its issues but you are still <a href=
 
2772
          "http://initd.org/tracker/pysqlite/ticket/153">stuck with some</a>.</p>
 
2773
        </li>
 
2774
 
 
2775
        <li>
 
2776
          <p>You can use semi-colons at the end of commands and you can have multiple commands in the execute string in
 
2777
          APSW. There are no restrictions on the type of commands used. For example this will work fine in APSW but is
 
2778
          not allowed in pysqlite:</p>
2889
2779
 
2890
2780
          <blockquote>
2891
2781
            <pre>
2899
2789
                       (1,2,3,4,5,6,7,8,9,10)): 
2900
2790
                           print row
2901
2791
        
 
2792
 
2902
2793
</pre>
2903
2794
 
2904
2795
            <p>And the output as you would expect:</p>
2908
2799
(4, 5, 6) 
2909
2800
(7, 8) 
2910
2801
(9, 10)
 
2802
 
2911
2803
</pre>
2912
2804
          </blockquote>
2913
2805
        </li>
2914
2806
 
2915
2807
        <li>
2916
 
          <p>The cursor object is an iterator and returns itself from execute.
2917
 
          (The latest SQLite has now copied this feature).</p>
 
2808
          <p>The cursor object is an iterator and returns itself from execute. (The latest SQLite has now copied this
 
2809
          feature).</p>
2918
2810
        </li>
2919
2811
 
2920
2812
        <li>
2921
 
          <p><code>cursor.executemany()</code> also works with statements that
2922
 
          return data such as selects, and you can have multiple
2923
 
          statements.</p>
 
2813
          <p><code>cursor.executemany()</code> also works with statements that return data such as selects, and you can
 
2814
          have multiple statements.</p>
2924
2815
        </li>
2925
2816
 
2926
 
        <li>pysqlite swallows exceptions in your callbacks making it far harder
2927
 
        to debug problems. That also prevents you from raising exceptions in
2928
 
        your callbacks to be handled in your code that called SQLite. pysqlite
2929
 
        does let you turn on printing of tracebacks, but that is a poor
2930
 
        substitute. apsw does the right thing as demonstrated by this example.
 
2817
        <li>pysqlite swallows exceptions in your callbacks making it far harder to debug problems. That also prevents
 
2818
        you from raising exceptions in your callbacks to be handled in your code that called SQLite. pysqlite does let
 
2819
        you turn on printing of tracebacks, but that is a poor substitute. apsw does the right thing as demonstrated by
 
2820
        this example.
2931
2821
 
2932
2822
          <blockquote>
2933
2823
            <table border="1px" cellpadding="5" cellspacing="5">
2993
2883
          </blockquote>
2994
2884
        </li>
2995
2885
 
2996
 
        <li>APSW has enhanced debuggability. More details are available than
2997
 
        just what is printed out when exceptions happen like above. See
2998
 
        <a href="#augmentedstacktraces">augmented stack traces</a>. If you
2999
 
        forget to close a Connection then you get a traceback of where the
3000
 
        problem is (interceptable via <code>sys.excepthook</code>) and are also
3001
 
        told where Connection was allocated.</li>
 
2886
        <li>APSW has enhanced debuggability. More details are available than just what is printed out when exceptions
 
2887
        happen like above. See <a href="#augmentedstacktraces">augmented stack traces</a>. If you forget to close a
 
2888
        Connection then you get a traceback of where the problem is (interceptable via <code>sys.excepthook</code>) and
 
2889
        are also told where Connection was allocated.</li>
3002
2890
 
3003
2891
        <li>
3004
2892
          <p>You can implement tracers and other hooks in Python.</p>
3005
2893
        </li>
3006
2894
 
3007
2895
        <li>
3008
 
          <p>The APSW test suite is larger and tests more functionality. Code
3009
 
          coverage by the test suite is 94%. pysqlite is good at 81% for C code
3010
 
          although there are several places that coverage can be improved. I
3011
 
          haven't measured code coverage for pysqlite's Python code.</p>
 
2896
          <p>The APSW test suite is larger and tests more functionality. Code coverage by the test suite is 95%.
 
2897
          pysqlite is good at 81% for C code although there are several places that coverage can be improved. I haven't
 
2898
          measured code coverage for pysqlite's Python code.</p>
3012
2899
 
3013
 
          <p>In both cases, some of the non-covered code lines require that the
3014
 
          Python interpretter or SQLite run out of memory so 100% coverage
3015
 
          isn't possible.</p>
 
2900
          <p>In both cases, some of the non-covered code lines require that the Python interpretter or SQLite run out
 
2901
          of memory so 100% coverage isn't possible.</p>
3016
2902
        </li>
3017
2903
      </ul>
3018
2904
 
3019
 
      <h1><a name="copyrightlicense" id="copyrightlicense">Copyright and
3020
 
      License</a></h1>
3021
 
 
3022
 
      <p>Copyright (C) 2004-2007 Roger Binns <a href=
3023
 
      "mailto:rogerb@rogerbinns.com">rogerb@rogerbinns.com</a></p>
3024
 
 
3025
 
      <p>This software is provided 'as-is', without any express or implied
3026
 
      warranty. In no event will the authors be held liable for any damages
3027
 
      arising from the use of this software.</p>
3028
 
 
3029
 
      <p>Permission is granted to anyone to use this software for any purpose,
3030
 
      including commercial applications, and to alter it and redistribute it
3031
 
      freely, subject to the following restrictions:</p>
 
2905
      <h1><a name="copyrightlicense" id="copyrightlicense">Copyright and License</a></h1>
 
2906
 
 
2907
      <p>Copyright (C) 2004-2008 Roger Binns <a href="mailto:rogerb@rogerbinns.com">rogerb@rogerbinns.com</a></p>
 
2908
 
 
2909
      <p>This software is provided 'as-is', without any express or implied warranty. In no event will the authors be
 
2910
      held liable for any damages arising from the use of this software.</p>
 
2911
 
 
2912
      <p>Permission is granted to anyone to use this software for any purpose, including commercial applications, and
 
2913
      to alter it and redistribute it freely, subject to the following restrictions:</p>
3032
2914
 
3033
2915
      <blockquote>
3034
2916
        <ol>
3035
2917
          <li>
3036
 
            <p>The origin of this software must not be misrepresented; you must
3037
 
            not claim that you wrote the original software. If you use this
3038
 
            software in a product, an acknowledgment in the product
3039
 
            documentation would be appreciated but is not required.</p>
3040
 
          </li>
3041
 
 
3042
 
          <li>
3043
 
            <p>Altered source versions must be plainly marked as such, and must
3044
 
            not be misrepresented as being the original software.</p>
3045
 
          </li>
3046
 
 
3047
 
          <li>
3048
 
            <p>This notice may not be removed or altered from any source
3049
 
            distribution.</p>
 
2918
            <p>The origin of this software must not be misrepresented; you must not claim that you wrote the original
 
2919
            software. If you use this software in a product, an acknowledgment in the product documentation would be
 
2920
            appreciated but is not required.</p>
 
2921
          </li>
 
2922
 
 
2923
          <li>
 
2924
            <p>Altered source versions must be plainly marked as such, and must not be misrepresented as being the
 
2925
            original software.</p>
 
2926
          </li>
 
2927
 
 
2928
          <li>
 
2929
            <p>This notice may not be removed or altered from any source distribution.</p>
3050
2930
          </li>
3051
2931
        </ol>
3052
2932
      </blockquote>
3053
2933
 
3054
2934
      <h1><a name="verhistory" id="verhistory">Version History</a></h1>
3055
2935
 
 
2936
      <h2><a name="359r2">3.5.9-r2</a></h2>
 
2937
 
 
2938
      <p>APSW now works with Python 3 (you need 3.0b1 or later).</p>
 
2939
 
 
2940
      <p>(<a href="http://code.google.com/p/apsw/issues/detail?id=17">Issue 17</a>) Removed the <tt>SQLITE_MAX_*</tt>
 
2941
      constants since they could be unreliable (eg APSW can't tell what a shared library was compiled with). A
 
2942
      workaround is documented in the <a href="#Connection_limit">Connection.limit</a> section.</p>
 
2943
 
 
2944
      <h2><a name="359r1">3.5.9-r1</a></h2>
 
2945
 
 
2946
      <p>APSW is now hosted at <a href="http://code.google.com/p/apsw">http://code.google.com/p/apsw</a>.</p>
 
2947
 
 
2948
      <p>You can use this with SQLite 3.5.9 onwards.</p>
 
2949
 
 
2950
      <p>SQLite now provides the source all <a href=
 
2951
      "http://www.sqlite.org/cvstrac/wiki?p=TheAmalgamation">amalgamated</a> into one file which improves performance
 
2952
      and makes compilation and linking of SQLite far easier. The build instructions are updated.</p>
 
2953
 
 
2954
      <ul>
 
2955
        <li>SQLITE_COPY authorizer code and SQLITE_PROTOCOL error code are no longer used by SQLite, but the values are
 
2956
        left in apsw for backwards compatibility</li>
 
2957
 
 
2958
        <li>SQLITE_IOERR_DELETE, SQLITE_IOERR_BLOCKED and SQLITE_IOERR_NOMEM added</li>
 
2959
 
 
2960
        <li>Connection.interrupt can be called from any thread</li>
 
2961
 
 
2962
        <li>SQLite has implementation limits on string and blob lengths (roughly constrained to fitting within a signed
 
2963
        32 bit integer - less than 2GB) which weren't checked. Using a 64 bit Python 2.5+ (as I do) it would have been
 
2964
        possible to destroy memory and crash the program. Consequently APSW has length checks to ensure it doesn't
 
2965
        happen. SQLite now has further <a href="http://www.sqlite.org/limits.html">limits checking</a> which cover
 
2966
        other things as well such as maximum number of virtual machine opcodes, maximum number of variables etc. These
 
2967
        are very useful if you are taking in SQL statements from elsewhere. Call Connection.limit()</li>
 
2968
 
 
2969
        <li>A rename method was added for virtual tables.</li>
 
2970
 
 
2971
        <li>SQLite 3.5 removed the requirement that all operations on a connection be done in the same thread.
 
2972
        Consequently all code that enforced the restriction has been removed from APSW.</li>
 
2973
 
 
2974
        <li>You no longer have to call close() for connections. This was previously a requirement to ensure that the
 
2975
        correct thread was used. It is however still a good idea to do so since you can catch exceptions when close()
 
2976
        is called but not if you let the destructor do the closing.</li>
 
2977
 
 
2978
        <li>SQLite now has incremental <a href="#blobio">blob I/O</a></li>
 
2979
 
 
2980
        <li><a href="http://code.google.com/p/apsw/issues/detail?id=4">Issue 4</a> which could lead to generic error
 
2981
        messages was fixed in SQLite 3.5.9.</li>
 
2982
 
 
2983
        <li>Fixed <a href="http://code.google.com/p/apsw/issues/detail?id=1">Issue 1</a> error in example code for
 
2984
        virtual tables which caused filename errors on Windows.</li>
 
2985
 
 
2986
        <li>Fixed <a href="http://code.google.com/p/apsw/issues/detail?id=15">Issue 15</a> releasing the GIL around
 
2987
        calls to sqlite3_prepare.</li>
 
2988
 
 
2989
        <li>Fixed <a href="http://code.google.com/p/apsw/issues/detail?id=7">Issue 7</a> ensuring that extension module
 
2990
        filenames are converted to utf8.</li>
 
2991
 
 
2992
        <li>Use the sqlite3_open_v2 interface which allows specifying which vfs to use. This release does not allow you
 
2993
        to write your own vfs as the SQLite vfs interface is being changed for SQLite 3.6.</li>
 
2994
 
 
2995
        <li>Used new SQLite functions that keep track of when virtual tables and collations are no longer used so they
 
2996
        can be released. Previously APSW also had to keep track duplicating effort.</li>
 
2997
 
 
2998
        <li>Improved test coverage a few more percent.</li>
 
2999
 
 
3000
        <li>The statement cache now defaults to the same number of entries as pysqlite (100). You can however specify
 
3001
        more or less as needed.</li>
 
3002
 
 
3003
        <li>collationneeded was implemented.</li>
 
3004
      </ul>
 
3005
 
3056
3006
      <h2><a name="3313r1">3.3.13-r1</a></h2>
3057
3007
 
3058
 
      <p>As of this release, APSW is now co-hosted with pysqlite meaning there
3059
 
      is one site to go to for your Python SQLite bindings. Start at <a href=
 
3008
      <p>As of this release, APSW is now co-hosted with pysqlite meaning there is one site to go to for your Python
 
3009
      SQLite bindings. Start at <a href=
3060
3010
      "http://initd.org/tracker/pysqlite/wiki/">http://initd.org/tracker/pysqlite/wiki</a></p>
3061
3011
 
3062
 
      <p>You can use this with SQLite 3.3.13 onwards. There were no API changes
3063
 
      in SQLite 3.3.10 to 3.3.13 although some internal bugs were fixed and the
3064
 
      3.3.13 release is recommended over the earlier version.</p>
 
3012
      <p>You can use this with SQLite 3.3.13 onwards. There were no API changes in SQLite 3.3.10 to 3.3.13 although
 
3013
      some internal bugs were fixed and the 3.3.13 release is recommended over the earlier version.</p>
3065
3014
 
3066
3015
      <p>Thanks to Ed Pasma for highlighting these issues.</p>
3067
3016
 
3068
3017
      <ul>
3069
 
        <li><tt>Connection.interrupt</tt> can be safely called from any
3070
 
        thread.</li>
3071
 
 
3072
 
        <li>Empty statements or those consisting entirely of whitespace do not
3073
 
        cause misuse errors (internally SQLite started returned NULL pointers
3074
 
        for those statements, and sqlite3_step didn't like being passed the
3075
 
        NULL pointer).</li>
3076
 
 
3077
 
        <li>Changed special handling of SQLITE_BUSY error to be the same as
3078
 
        other errors. The special handling previously let you restart on
3079
 
        receiving busy, but also hung onto statements which could result in
3080
 
        other statements getting busy errors.</li>
 
3018
        <li><tt>Connection.interrupt</tt> can be safely called from any thread.</li>
 
3019
 
 
3020
        <li>Empty statements or those consisting entirely of whitespace do not cause misuse errors (internally SQLite
 
3021
        started returned NULL pointers for those statements, and sqlite3_step didn't like being passed the NULL
 
3022
        pointer).</li>
 
3023
 
 
3024
        <li>Changed special handling of SQLITE_BUSY error to be the same as other errors. The special handling
 
3025
        previously let you restart on receiving busy, but also hung onto statements which could result in other
 
3026
        statements getting busy errors.</li>
3081
3027
      </ul>
3082
3028
 
3083
3029
      <h2><a name="3310r1">3.3.10-r1</a></h2>
3085
3031
      <p>You can use this with SQLite 3.3.10 onwards.</p>
3086
3032
 
3087
3033
      <ul>
3088
 
        <li>Added a statement cache that works in conjunction with the
3089
 
        sqlite3_prepare_v2 API. A few issues were exposed in SQLite and hence
3090
 
        you must use SQLite 3.3.10 or later.</li>
 
3034
        <li>Added a statement cache that works in conjunction with the sqlite3_prepare_v2 API. A few issues were
 
3035
        exposed in SQLite and hence you must use SQLite 3.3.10 or later.</li>
3091
3036
      </ul>
3092
3037
 
3093
3038
      <h2><a name="339r1">3.3.9-r1</a></h2>
3095
3040
      <p>You can use this with SQLite 3.3.9 onwards.</p>
3096
3041
 
3097
3042
      <ul>
3098
 
        <li>SQLite added <a href=
3099
 
        "http://sqlite.org/capi3ref.html#sqlite3_prepare_v2">sqlite3_prepare_v2</a>
3100
 
        API. The net effect of this API update is that you will not get
3101
 
        SQLITE_SCHEMA any more. SQLite will handle it internally.</li>
 
3043
        <li>SQLite added <a href="http://sqlite.org/c3ref/prepare.html">sqlite3_prepare_v2</a> API. The net effect of
 
3044
        this API update is that you will not get SQLITE_SCHEMA any more. SQLite will handle it internally.</li>
3102
3045
      </ul>
3103
3046
 
3104
3047
      <h2><a name="338r1">3.3.8-r1</a></h2>
3105
3048
 
3106
 
      <p>You can use this with SQLite 3.3.8 onwards. There was an incompatible
3107
 
      API change for virtual tables in SQLite 3.3.8.</p>
 
3049
      <p>You can use this with SQLite 3.3.8 onwards. There was an incompatible API change for virtual tables in SQLite
 
3050
      3.3.8.</p>
3108
3051
 
3109
3052
      <ul>
3110
3053
        <li>Virtual tables updated for new api</li>
3111
3054
 
3112
 
        <li>You must call close() on connections. You can also call close on
3113
 
        cursors, but it usually isn't necessary.</li>
 
3055
        <li>You must call close() on connections. You can also call close on cursors, but it usually isn't
 
3056
        necessary.</li>
3114
3057
 
3115
3058
        <li>All strings are returned as unicode</li>
3116
3059
 
3117
 
        <li>PyErr_WriteUnraisable was used for errors in destructors.
3118
 
        Unfortunately it is almost completely useless, merely printing str() of
3119
 
        the object and exception. This doesn't help in finding where in your
3120
 
        code the issue arose so you could fix it. An internal APSW
3121
 
        implementation generates a traceback and calls
3122
 
        <code>sys.excepthook</code>, the default implementation of which prints
3123
 
        the exception and the traceback to sys.stderr. <b>Note</b> the line
3124
 
        number reported in the traceback is often off by 1. This is because the
3125
 
        destructors run "between" lines of code and so the following line is
3126
 
        reported as the current location.</li>
3127
 
 
3128
 
        <li>Authorizer codes SQLITE_CREATE_VTABLE, SQLITE_DROP_VTABLE and
3129
 
        SQLITE_FUNCTION added.</li>
3130
 
 
3131
 
        <li>SQLite <a href=
3132
 
        "http://www.sqlite.org/cvstrac/wiki?p=ExtendedResultCodes">extended
3133
 
        result codes</a> are available - see <a href=
3134
 
        "#Exceptions">Exceptions</a> for more detail.</li>
3135
 
 
3136
 
        <li><a href="#Module_variables">Connection hooks</a> added so you can
3137
 
        easily register functions, virtual tables or similar items with each
3138
 
        Connection as it is created.</li>
3139
 
 
3140
 
        <li>Added <a href="#Module_constants">mapping dicts</a> which makes it
3141
 
        easy to map the various constants between strings and ints.</li>
 
3060
        <li>PyErr_WriteUnraisable was used for errors in destructors. Unfortunately it is almost completely useless,
 
3061
        merely printing str() of the object and exception. This doesn't help in finding where in your code the issue
 
3062
        arose so you could fix it. An internal APSW implementation generates a traceback and calls
 
3063
        <code>sys.excepthook</code>, the default implementation of which prints the exception and the traceback to
 
3064
        sys.stderr. <b>Note</b> the line number reported in the traceback is often off by 1. This is because the
 
3065
        destructors run "between" lines of code and so the following line is reported as the current location.</li>
 
3066
 
 
3067
        <li>Authorizer codes SQLITE_CREATE_VTABLE, SQLITE_DROP_VTABLE and SQLITE_FUNCTION added.</li>
 
3068
 
 
3069
        <li>SQLite <a href="http://www.sqlite.org/cvstrac/wiki?p=ExtendedResultCodes">extended result codes</a> are
 
3070
        available - see <a href="#Exceptions">Exceptions</a> for more detail.</li>
 
3071
 
 
3072
        <li><a href="#Module_variables">Connection hooks</a> added so you can easily register functions, virtual tables
 
3073
        or similar items with each Connection as it is created.</li>
 
3074
 
 
3075
        <li>Added <a href="#Module_constants">mapping dicts</a> which makes it easy to map the various constants
 
3076
        between strings and ints.</li>
3142
3077
      </ul>
3143
3078
 
3144
3079
      <h2><a name="337r1">3.3.7-r1</a></h2>
3145
3080
 
3146
3081
      <p><i>Never released as 3.3.8 came along</i></p>
3147
3082
 
3148
 
      <p>You can use this release against SQLite 3.3.7. There were no changes
3149
 
      in the SQLite 3.3.6 API from 3.3.5. In SQLite 3.3.7 an API was added that
3150
 
      allowed removing a chunk of duplicate code. Also added were <a href=
3151
 
      "http://www.sqlite.org/cvstrac/wiki?p=VirtualTables">Virtual Tables</a>
3152
 
      and loading of external modules (shared libraries). APSW had the
3153
 
      following changes:</p>
 
3083
      <p>You can use this release against SQLite 3.3.7. There were no changes in the SQLite 3.3.6 API from 3.3.5. In
 
3084
      SQLite 3.3.7 an API was added that allowed removing a chunk of duplicate code. Also added were <a href=
 
3085
      "http://www.sqlite.org/cvstrac/wiki?p=VirtualTables">Virtual Tables</a> and loading of external modules (shared
 
3086
      libraries). APSW had the following changes:</p>
3154
3087
 
3155
3088
      <ul>
3156
3089
        <li>Even more test cases added (you can't have too many tests :-)</li>
3157
3090
 
3158
 
        <li>When exceptions occur, dummy frames are added to the traceback in
3159
 
        the C code. This makes it a lot easier to tell why code was called if
3160
 
        you encounter an exception. See <a href=
3161
 
        "#augmentedstacktraces">augmented stack traces</a> for details.</li>
 
3091
        <li>When exceptions occur, dummy frames are added to the traceback in the C code. This makes it a lot easier to
 
3092
        tell why code was called if you encounter an exception. See <a href="#augmentedstacktraces">augmented stack
 
3093
        traces</a> for details.</li>
3162
3094
 
3163
 
        <li>String values (traditional and Unicode) work correctly if they have
3164
 
        embedded NULL characters (ie not truncated at the NULL).</li>
 
3095
        <li>String values (traditional and Unicode) work correctly if they have embedded NULL characters (ie not
 
3096
        truncated at the NULL).</li>
3165
3097
 
3166
3098
        <li>You can load SQLite shared library extensions.</li>
3167
3099
      </ul>
3168
3100
 
3169
3101
      <h2><a name="335r1">3.3.5-r1</a></h2>
3170
3102
 
3171
 
      <p>You can use this release against any release of SQLite 3 from 3.3.5
3172
 
      onwards. A bug was also fixed when reporting an error during the cleanup
3173
 
      of an aggregate function if there had also been an error in the step
3174
 
      function. (PyErr_WriteUnraisable(NULL) crashed on some versions of Python
3175
 
      but not others.)</p>
3176
 
 
3177
 
      <p>SQLite added several functions for returning metadata about result
3178
 
      column sets. You have to compile SQLite with
3179
 
      <tt>SQLITE_ENABLE_COLUMN_METADATA</tt> to get them. This is not the
3180
 
      default for SQLite. I don't believe these are generally useful except in
3181
 
      some corner cases and so they aren't wrapped. However please shout if you
3182
 
      do need them. Note that <tt>cursor.getdescription</tt> will already give
3183
 
      you generally useful information. (Also see the <a href=
3184
 
      "http://sqlite.org/pragma.html">pragmas</a>).</p>
3185
 
 
3186
 
      <p>The test code has been converted into using the unittest module. Run
3187
 
      <tt>python tests.py -v</tt> to get the tests run. There should be no
3188
 
      errors.</p>
3189
 
 
3190
 
      <p>Updated code to work correctly with new Py_ssize_t introduced in
3191
 
      Python 2.5. See <a href="#64bitpy25">64 bit hosts, Python 2.5</a> for
3192
 
      more details on how Python and SQLite handle 64 bit sized items.</p>
3193
 
 
3194
 
      <p>The following functions were added to SQLite and are wrapped. They are
3195
 
      all functions defined on the <a href="#Connection">Connection</a>
3196
 
      object.</p>
 
3103
      <p>You can use this release against any release of SQLite 3 from 3.3.5 onwards. A bug was also fixed when
 
3104
      reporting an error during the cleanup of an aggregate function if there had also been an error in the step
 
3105
      function. (PyErr_WriteUnraisable(NULL) crashed on some versions of Python but not others.)</p>
 
3106
 
 
3107
      <p>SQLite added several functions for returning metadata about result column sets. You have to compile SQLite
 
3108
      with <tt>SQLITE_ENABLE_COLUMN_METADATA</tt> to get them. This is not the default for SQLite. I don't believe
 
3109
      these are generally useful except in some corner cases and so they aren't wrapped. However please shout if you do
 
3110
      need them. Note that <tt>cursor.getdescription</tt> will already give you generally useful information. (Also see
 
3111
      the <a href="http://sqlite.org/pragma.html">pragmas</a>).</p>
 
3112
 
 
3113
      <p>The test code has been converted into using the unittest module. Run <tt>python tests.py -v</tt> to get the
 
3114
      tests run. There should be no errors.</p>
 
3115
 
 
3116
      <p>Updated code to work correctly with new Py_ssize_t introduced in Python 2.5. See <a href="#64bitpy25">64 bit
 
3117
      hosts, Python 2.5</a> for more details on how Python and SQLite handle 64 bit sized items.</p>
 
3118
 
 
3119
      <p>The following functions were added to SQLite and are wrapped. They are all functions defined on the <a href=
 
3120
      "#Connection">Connection</a> object.</p>
3197
3121
 
3198
3122
      <ul>
3199
 
        <li><a href=
3200
 
        "http://sqlite.org/capi3ref.html#sqlite3_update_hook">sqlite3_update_hook</a></li>
3201
 
 
3202
 
        <li><a href=
3203
 
        "http://sqlite.org/capi3ref.html#sqlite3_rollback_hook">sqlite3_rollback_hook</a></li>
3204
 
 
3205
 
        <li><a href=
3206
 
        "http://sqlite.org/capi3ref.html#sqlite3_enable_shared_cache">sqlite3_enable_shared_cache</a>
 
3123
        <li><a href="http://sqlite.org/capi3ref.html#sqlite3_update_hook">sqlite3_update_hook</a></li>
 
3124
 
 
3125
        <li><a href="http://sqlite.org/capi3ref.html#sqlite3_rollback_hook">sqlite3_rollback_hook</a></li>
 
3126
 
 
3127
        <li><a href="http://sqlite.org/capi3ref.html#sqlite3_enable_shared_cache">sqlite3_enable_shared_cache</a>
3207
3128
        (Module level method)</li>
3208
3129
 
3209
 
        <li><a href=
3210
 
        "http://sqlite.org/capi3ref.html#sqlite3_get_autocommit">sqlite3_get_autocommit</a>
3211
 
        (Connection level method)</li>
 
3130
        <li><a href="http://sqlite.org/capi3ref.html#sqlite3_get_autocommit">sqlite3_get_autocommit</a> (Connection
 
3131
        level method)</li>
3212
3132
 
3213
 
        <li>sqlite3_profile (experimental, not documented on SQLite site) This
3214
 
        callback is run at the end of each statement execution telling you how
3215
 
        long it took)</li>
 
3133
        <li>sqlite3_profile (experimental, not documented on SQLite site) This callback is run at the end of each
 
3134
        statement execution telling you how long it took)</li>
3216
3135
      </ul>
3217
3136
 
3218
 
      <p>The following functions were added/changed in SQLite C API but are not
3219
 
      useful to be wrapped.</p>
 
3137
      <p>The following functions were added/changed in SQLite C API but are not useful to be wrapped.</p>
3220
3138
 
3221
3139
      <ul>
3222
3140
        <li>sqlite3_value_numeric_type (query if a result is numeric)</li>
3223
3141
 
3224
 
        <li><a href=
3225
 
        "http://sqlite.org/capi3ref.html#sqlite3_global_recover">sqlite3_global_recover</a>
3226
 
        (already deprecated)</li>
3227
 
 
3228
 
        <li><a href=
3229
 
        "http://sqlite.org/capi3ref.html#sqlite3_release_memory">sqlite3_release_memory</a>
3230
 
        (requires non-default compile flag)</li>
3231
 
 
3232
 
        <li><a href=
3233
 
        "http://sqlite.org/capi3ref.html#sqlite3_soft_heap_limit">sqlite3_soft_heap_limit</a>
3234
 
        (requires non-default compile flag)</li>
3235
 
 
3236
 
        <li><a href=
3237
 
        "http://sqlite.org/capi3ref.html#sqlite3_db_handle">sqlite3_db_handle</a>
3238
 
        (use cursor.getconnection())</li>
 
3142
        <li><a href="http://sqlite.org/capi3ref.html#sqlite3_global_recover">sqlite3_global_recover</a> (already
 
3143
        deprecated)</li>
 
3144
 
 
3145
        <li><a href="http://sqlite.org/capi3ref.html#sqlite3_release_memory">sqlite3_release_memory</a> (requires
 
3146
        non-default compile flag)</li>
 
3147
 
 
3148
        <li><a href="http://sqlite.org/capi3ref.html#sqlite3_soft_heap_limit">sqlite3_soft_heap_limit</a> (requires
 
3149
        non-default compile flag)</li>
 
3150
 
 
3151
        <li><a href="http://sqlite.org/capi3ref.html#sqlite3_db_handle">sqlite3_db_handle</a> (use
 
3152
        cursor.getconnection())</li>
3239
3153
      </ul>
3240
3154
 
3241
3155
      <h2><a name="327r1">3.2.7-r1</a></h2>
3242
3156
 
3243
3157
      <p>You can use this release against any release of SQLite 3.</p>
3244
3158
 
3245
 
      <p>SQLite 3.2.7 has several bug fixes. The undocumented experimental
3246
 
      function <code>sqlite3_profile</code> was added, but it not present in
3247
 
      apsw yet.</p>
 
3159
      <p>SQLite 3.2.7 has several bug fixes. The undocumented experimental function <code>sqlite3_profile</code> was
 
3160
      added, but it not present in apsw yet.</p>
3248
3161
 
3249
3162
      <ul>
3250
 
        <li>The author of pysqlite has improved it considerably since APSW was
3251
 
        originally written. The differences section has been updated to reflect
3252
 
        those improvements in pysqlite.</li>
3253
 
 
3254
 
        <li>SQLITE_INTERNAL and SQLITE_NOTFOUND error codes are not used
3255
 
        according to 3.2.7 header file. They are still present in APSW for
3256
 
        backwards compatibility.</li>
3257
 
 
3258
 
        <li>Changed the build instructions so configure is run on non-Windows
3259
 
        platforms.</li>
3260
 
 
3261
 
        <li>Fixed a bug caused by an overly helpful error message trying to
3262
 
        tell you how many bindings you supplied that crashed if you didn't
3263
 
        supply any.</li>
3264
 
 
3265
 
        <li>Changed when an error in the step function for an aggregate is
3266
 
        reported due to limitations in SQLite.</li>
 
3163
        <li>The author of pysqlite has improved it considerably since APSW was originally written. The differences
 
3164
        section has been updated to reflect those improvements in pysqlite.</li>
 
3165
 
 
3166
        <li>SQLITE_INTERNAL and SQLITE_NOTFOUND error codes are not used according to 3.2.7 header file. They are still
 
3167
        present in APSW for backwards compatibility.</li>
 
3168
 
 
3169
        <li>Changed the build instructions so configure is run on non-Windows platforms.</li>
 
3170
 
 
3171
        <li>Fixed a bug caused by an overly helpful error message trying to tell you how many bindings you supplied
 
3172
        that crashed if you didn't supply any.</li>
 
3173
 
 
3174
        <li>Changed when an error in the step function for an aggregate is reported due to limitations in SQLite.</li>
3267
3175
      </ul>
3268
3176
 
3269
3177
      <h2><a name="322r1">3.2.2-r1</a></h2>
3270
3178
 
3271
3179
      <p>You can use this release against any release of SQLite 3.</p>
3272
3180
 
3273
 
      <p>SQLite 3.2.2 API removed <code>sqlite3_global_recover</code>. That
3274
 
      function was not wrapped in APSW. Note that SQLite 3.2.2 contains a bug
3275
 
      fix that applies when you use 64 bit integer primary keys (32 bit ints
3276
 
      are fine).</p>
 
3181
      <p>SQLite 3.2.2 API removed <code>sqlite3_global_recover</code>. That function was not wrapped in APSW. Note that
 
3182
      SQLite 3.2.2 contains a bug fix that applies when you use 64 bit integer primary keys (32 bit ints are fine).</p>
3277
3183
 
3278
3184
      <h2><a name="321r1">3.2.1-r1</a></h2>
3279
3185
 
3280
3186
      <p>You can use this release against any release of SQLite 3.</p>
3281
3187
 
3282
3188
      <ul>
3283
 
        <li>There are no changes in APSW except to correct an error in the
3284
 
        example code (collations are registered against the connection not the
3285
 
        cursor)</li>
 
3189
        <li>There are no changes in APSW except to correct an error in the example code (collations are registered
 
3190
        against the connection not the cursor)</li>
3286
3191
      </ul>
3287
3192
 
3288
 
      <p>SQLite 3.2.1 had one addition in the stable C API, which was a new
3289
 
      function named <code>sqlite3_global_recover</code>. That function is not
3290
 
      applicable for wrapping in APSW.</p>
 
3193
      <p>SQLite 3.2.1 had one addition in the stable C API, which was a new function named
 
3194
      <code>sqlite3_global_recover</code>. That function is not applicable for wrapping in APSW.</p>
3291
3195
 
3292
3196
      <h2><a name="313r1">3.1.3-r1</a></h2>
3293
3197
 
3294
3198
      <p>You can use this release against any release of SQLite 3.</p>
3295
3199
 
3296
3200
      <ul>
3297
 
        <li>The text string returned by apsw.Error used to say
3298
 
        "apsw.APSWException" and has been changed to "apsw.Error". This is
3299
 
        purely cosmetic and helps make clear what the class is. (The old string
3300
 
        was what the original class name was in an earlier version of the
3301
 
        code.)</li>
3302
 
 
3303
 
        <li>Added <code>SQLITE_ALTER_TABLE</code> and
3304
 
        <code>SQLITE_REINDEX</code> constants for the authorizer function.
3305
 
        (These constants were introduced in SQLite 3.1.3).</li>
3306
 
 
3307
 
        <li>Changed various C++-isms into standard C (eg // comments and the
3308
 
        placing of some CHECK_THREAD macro calls)</li>
3309
 
 
3310
 
        <li>Added module level function <code>apswversion</code> which returns
3311
 
        the version of APSW.</li>
 
3201
        <li>The text string returned by apsw.Error used to say "apsw.APSWException" and has been changed to
 
3202
        "apsw.Error". This is purely cosmetic and helps make clear what the class is. (The old string was what the
 
3203
        original class name was in an earlier version of the code.)</li>
 
3204
 
 
3205
        <li>Added <code>SQLITE_ALTER_TABLE</code> and <code>SQLITE_REINDEX</code> constants for the authorizer
 
3206
        function. (These constants were introduced in SQLite 3.1.3).</li>
 
3207
 
 
3208
        <li>Changed various C++-isms into standard C (eg // comments and the placing of some CHECK_THREAD macro
 
3209
        calls)</li>
 
3210
 
 
3211
        <li>Added module level function <code>apswversion</code> which returns the version of APSW.</li>
3312
3212
      </ul>
3313
3213
 
3314
 
      <p>SQLite 3.1.3 had no changes in the stable C API other than what is
3315
 
      mentioned above. There were some new experimental functions added which
3316
 
      are not currently documented on the SQLite website, which are not wrapped
3317
 
      by APSW. Please contact me if you believe they will remain in SQLite and
3318
 
      you would like them wrapped:</p>
 
3214
      <p>SQLite 3.1.3 had no changes in the stable C API other than what is mentioned above. There were some new
 
3215
      experimental functions added which are not currently documented on the SQLite website, which are not wrapped by
 
3216
      APSW. Please contact me if you believe they will remain in SQLite and you would like them wrapped:</p>
3319
3217
 
3320
3218
      <ul>
3321
 
        <li><code>sqlite3_sleep</code> An alternative function which sleeps for
3322
 
        a specified number of milliseconds can be provided. By default SQLite
3323
 
        just uses the standard operating system call.</li>
3324
 
 
3325
 
        <li><code>sqlite3_expired</code> This function is internal to statement
3326
 
        execution. It would apply to the implementation of Cursor.executemany
3327
 
        and could in theory provide a marginal improvement in performance.</li>
3328
 
 
3329
 
        <li>A global variable <code>sqlite3_temp_directory</code> can be used
3330
 
        before any databases are opened to set where temporary files are
3331
 
        created. By default SQLite just uses the standard operating system
3332
 
        mechanisms.</li>
 
3219
        <li><code>sqlite3_sleep</code> An alternative function which sleeps for a specified number of milliseconds can
 
3220
        be provided. By default SQLite just uses the standard operating system call.</li>
 
3221
 
 
3222
        <li><code>sqlite3_expired</code> This function is internal to statement execution. It would apply to the
 
3223
        implementation of Cursor.executemany and could in theory provide a marginal improvement in performance.</li>
 
3224
 
 
3225
        <li>A global variable <code>sqlite3_temp_directory</code> can be used before any databases are opened to set
 
3226
        where temporary files are created. By default SQLite just uses the standard operating system mechanisms.</li>
3333
3227
      </ul>
3334
3228
 
3335
3229
      <h2><a name="308r3">3.0.8-r3</a></h2>
3336
3230
 
3337
 
      <p>There are no functional changes. The only changes were to correct some
3338
 
      variable names in the example code (they were cut and pasted from the
3339
 
      test code which used different names) and to make the source zip file
3340
 
      extract its contents into a sub-directory which is the more typical way
3341
 
      of packaging that sort of thing.</p>
 
3231
      <p>There are no functional changes. The only changes were to correct some variable names in the example code
 
3232
      (they were cut and pasted from the test code which used different names) and to make the source zip file extract
 
3233
      its contents into a sub-directory which is the more typical way of packaging that sort of thing.</p>
3342
3234
 
3343
3235
      <h2><a name="308r2">3.0.8-r2</a></h2>
3344
3236
 
3345
 
      <p>All remaining functionality in the C API for SQLite 3.0.8 is now
3346
 
      available.</p>
 
3237
      <p>All remaining functionality in the C API for SQLite 3.0.8 is now available.</p>
3347
3238
 
3348
3239
      <p>Finished this documentation.</p>
3349
3240