xref: /sqlite-3.40.0/src/tclsqlite.c (revision 37db03bf)
175897234Sdrh /*
2b19a2bc6Sdrh ** 2001 September 15
375897234Sdrh **
4b19a2bc6Sdrh ** The author disclaims copyright to this source code.  In place of
5b19a2bc6Sdrh ** a legal notice, here is a blessing:
675897234Sdrh **
7b19a2bc6Sdrh **    May you do good and not evil.
8b19a2bc6Sdrh **    May you find forgiveness for yourself and forgive others.
9b19a2bc6Sdrh **    May you share freely, never taking more than you give.
1075897234Sdrh **
1175897234Sdrh *************************************************************************
12bd08af48Sdrh ** A TCL Interface to SQLite.  Append this file to sqlite3.c and
13bd08af48Sdrh ** compile the whole thing to build a TCL-enabled version of SQLite.
1457a0227fSdrh **
1557a0227fSdrh ** Compile-time options:
1657a0227fSdrh **
1757a0227fSdrh **  -DTCLSH=1             Add a "main()" routine that works as a tclsh.
1857a0227fSdrh **
1957a0227fSdrh **  -DSQLITE_TCLMD5       When used in conjuction with -DTCLSH=1, add
2057a0227fSdrh **                        four new commands to the TCL interpreter for
2157a0227fSdrh **                        generating MD5 checksums:  md5, md5file,
2257a0227fSdrh **                        md5-10x8, and md5file-10x8.
2357a0227fSdrh **
2457a0227fSdrh **  -DSQLITE_TEST         When used in conjuction with -DTCLSH=1, add
2557a0227fSdrh **                        hundreds of new commands used for testing
2657a0227fSdrh **                        SQLite.  This option implies -DSQLITE_TCLMD5.
2775897234Sdrh */
28bd08af48Sdrh #include "tcl.h"
29b4e9af9fSdanielk1977 #include <errno.h>
306d31316cSdrh 
31bd08af48Sdrh /*
32bd08af48Sdrh ** Some additional include files are needed if this file is not
33bd08af48Sdrh ** appended to the amalgamation.
34bd08af48Sdrh */
35bd08af48Sdrh #ifndef SQLITE_AMALGAMATION
3665e8c82eSdrh # include "sqlite3.h"
3775897234Sdrh # include <stdlib.h>
3875897234Sdrh # include <string.h>
39ce927065Sdrh # include <assert.h>
4065e8c82eSdrh   typedef unsigned char u8;
41bd08af48Sdrh #endif
42eb206381Sdrh #include <ctype.h>
4375897234Sdrh 
44ad6e1370Sdrh /*
45ad6e1370Sdrh  * Windows needs to know which symbols to export.  Unix does not.
46ad6e1370Sdrh  * BUILD_sqlite should be undefined for Unix.
47ad6e1370Sdrh  */
48ad6e1370Sdrh #ifdef BUILD_sqlite
49ad6e1370Sdrh #undef TCL_STORAGE_CLASS
50ad6e1370Sdrh #define TCL_STORAGE_CLASS DLLEXPORT
51ad6e1370Sdrh #endif /* BUILD_sqlite */
5229bc4615Sdrh 
53a21c6b6fSdanielk1977 #define NUM_PREPARED_STMTS 10
54fb7e7651Sdrh #define MAX_PREPARED_STMTS 100
55fb7e7651Sdrh 
5675897234Sdrh /*
5798808babSdrh ** If TCL uses UTF-8 and SQLite is configured to use iso8859, then we
5898808babSdrh ** have to do a translation when going between the two.  Set the
5998808babSdrh ** UTF_TRANSLATION_NEEDED macro to indicate that we need to do
6098808babSdrh ** this translation.
6198808babSdrh */
6298808babSdrh #if defined(TCL_UTF_MAX) && !defined(SQLITE_UTF8)
6398808babSdrh # define UTF_TRANSLATION_NEEDED 1
6498808babSdrh #endif
6598808babSdrh 
6698808babSdrh /*
67cabb0819Sdrh ** New SQL functions can be created as TCL scripts.  Each such function
68cabb0819Sdrh ** is described by an instance of the following structure.
69cabb0819Sdrh */
70cabb0819Sdrh typedef struct SqlFunc SqlFunc;
71cabb0819Sdrh struct SqlFunc {
72cabb0819Sdrh   Tcl_Interp *interp;   /* The TCL interpret to execute the function */
73d1e4733dSdrh   Tcl_Obj *pScript;     /* The Tcl_Obj representation of the script */
74d1e4733dSdrh   int useEvalObjv;      /* True if it is safe to use Tcl_EvalObjv */
75d1e4733dSdrh   char *zName;          /* Name of this function */
76cabb0819Sdrh   SqlFunc *pNext;       /* Next function on the list of them all */
77cabb0819Sdrh };
78cabb0819Sdrh 
79cabb0819Sdrh /*
800202b29eSdanielk1977 ** New collation sequences function can be created as TCL scripts.  Each such
810202b29eSdanielk1977 ** function is described by an instance of the following structure.
820202b29eSdanielk1977 */
830202b29eSdanielk1977 typedef struct SqlCollate SqlCollate;
840202b29eSdanielk1977 struct SqlCollate {
850202b29eSdanielk1977   Tcl_Interp *interp;   /* The TCL interpret to execute the function */
860202b29eSdanielk1977   char *zScript;        /* The script to be run */
870202b29eSdanielk1977   SqlCollate *pNext;    /* Next function on the list of them all */
880202b29eSdanielk1977 };
890202b29eSdanielk1977 
900202b29eSdanielk1977 /*
91fb7e7651Sdrh ** Prepared statements are cached for faster execution.  Each prepared
92fb7e7651Sdrh ** statement is described by an instance of the following structure.
93fb7e7651Sdrh */
94fb7e7651Sdrh typedef struct SqlPreparedStmt SqlPreparedStmt;
95fb7e7651Sdrh struct SqlPreparedStmt {
96fb7e7651Sdrh   SqlPreparedStmt *pNext;  /* Next in linked list */
97fb7e7651Sdrh   SqlPreparedStmt *pPrev;  /* Previous on the list */
98fb7e7651Sdrh   sqlite3_stmt *pStmt;     /* The prepared statement */
99fb7e7651Sdrh   int nSql;                /* chars in zSql[] */
100d0e2a854Sdanielk1977   const char *zSql;        /* Text of the SQL statement */
1014a4c11aaSdan   int nParm;               /* Size of apParm array */
1024a4c11aaSdan   Tcl_Obj **apParm;        /* Array of referenced object pointers */
103fb7e7651Sdrh };
104fb7e7651Sdrh 
105d0441796Sdanielk1977 typedef struct IncrblobChannel IncrblobChannel;
106d0441796Sdanielk1977 
107fb7e7651Sdrh /*
108bec3f402Sdrh ** There is one instance of this structure for each SQLite database
109bec3f402Sdrh ** that has been opened by the SQLite TCL interface.
110bec3f402Sdrh */
111bec3f402Sdrh typedef struct SqliteDb SqliteDb;
112bec3f402Sdrh struct SqliteDb {
113dddca286Sdrh   sqlite3 *db;               /* The "real" database structure. MUST BE FIRST */
114bec3f402Sdrh   Tcl_Interp *interp;        /* The interpreter used for this database */
1156d31316cSdrh   char *zBusy;               /* The busy callback routine */
116aa940eacSdrh   char *zCommit;             /* The commit hook callback routine */
117b5a20d3cSdrh   char *zTrace;              /* The trace callback routine */
11819e2d37fSdrh   char *zProfile;            /* The profile callback routine */
119348bb5d6Sdanielk1977   char *zProgress;           /* The progress callback routine */
120e22a334bSdrh   char *zAuth;               /* The authorization callback routine */
1211f1549f8Sdrh   int disableAuth;           /* Disable the authorizer if it exists */
12255c45f2eSdanielk1977   char *zNull;               /* Text to substitute for an SQL NULL value */
123cabb0819Sdrh   SqlFunc *pFunc;            /* List of SQL functions */
12494eb6a14Sdanielk1977   Tcl_Obj *pUpdateHook;      /* Update hook script (if any) */
12546c47d46Sdan   Tcl_Obj *pPreUpdateHook;   /* Pre-update hook script (if any) */
12671fd80bfSdanielk1977   Tcl_Obj *pRollbackHook;    /* Rollback hook script (if any) */
1275def0843Sdrh   Tcl_Obj *pWalHook;         /* WAL hook script (if any) */
128404ca075Sdanielk1977   Tcl_Obj *pUnlockNotify;    /* Unlock notify script (if any) */
1290202b29eSdanielk1977   SqlCollate *pCollate;      /* List of SQL collation functions */
1306f8a503dSdanielk1977   int rc;                    /* Return code of most recent sqlite3_exec() */
1317cedc8d4Sdanielk1977   Tcl_Obj *pCollateNeeded;   /* Collation needed script */
132fb7e7651Sdrh   SqlPreparedStmt *stmtList; /* List of prepared statements*/
133fb7e7651Sdrh   SqlPreparedStmt *stmtLast; /* Last statement in the list */
134fb7e7651Sdrh   int maxStmt;               /* The next maximum number of stmtList */
135fb7e7651Sdrh   int nStmt;                 /* Number of statements in stmtList */
136d0441796Sdanielk1977   IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */
1373c379b01Sdrh   int nStep, nSort, nIndex;  /* Statistics for most recent operation */
138cd38d520Sdanielk1977   int nTransaction;          /* Number of nested [transaction] methods */
13998808babSdrh };
140297ecf14Sdrh 
141b4e9af9fSdanielk1977 struct IncrblobChannel {
142d0441796Sdanielk1977   sqlite3_blob *pBlob;      /* sqlite3 blob handle */
143dcbb5d3fSdanielk1977   SqliteDb *pDb;            /* Associated database connection */
144b4e9af9fSdanielk1977   int iSeek;                /* Current seek offset */
145d0441796Sdanielk1977   Tcl_Channel channel;      /* Channel identifier */
146d0441796Sdanielk1977   IncrblobChannel *pNext;   /* Linked list of all open incrblob channels */
147d0441796Sdanielk1977   IncrblobChannel *pPrev;   /* Linked list of all open incrblob channels */
148b4e9af9fSdanielk1977 };
149b4e9af9fSdanielk1977 
150ea678832Sdrh /*
151ea678832Sdrh ** Compute a string length that is limited to what can be stored in
152ea678832Sdrh ** lower 30 bits of a 32-bit signed integer.
153ea678832Sdrh */
1544f21c4afSdrh static int strlen30(const char *z){
155ea678832Sdrh   const char *z2 = z;
156ea678832Sdrh   while( *z2 ){ z2++; }
157ea678832Sdrh   return 0x3fffffff & (int)(z2 - z);
158ea678832Sdrh }
159ea678832Sdrh 
160ea678832Sdrh 
16132a0d8bbSdanielk1977 #ifndef SQLITE_OMIT_INCRBLOB
162b4e9af9fSdanielk1977 /*
163d0441796Sdanielk1977 ** Close all incrblob channels opened using database connection pDb.
164d0441796Sdanielk1977 ** This is called when shutting down the database connection.
165d0441796Sdanielk1977 */
166d0441796Sdanielk1977 static void closeIncrblobChannels(SqliteDb *pDb){
167d0441796Sdanielk1977   IncrblobChannel *p;
168d0441796Sdanielk1977   IncrblobChannel *pNext;
169d0441796Sdanielk1977 
170d0441796Sdanielk1977   for(p=pDb->pIncrblob; p; p=pNext){
171d0441796Sdanielk1977     pNext = p->pNext;
172d0441796Sdanielk1977 
173d0441796Sdanielk1977     /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
174d0441796Sdanielk1977     ** which deletes the IncrblobChannel structure at *p. So do not
175d0441796Sdanielk1977     ** call Tcl_Free() here.
176d0441796Sdanielk1977     */
177d0441796Sdanielk1977     Tcl_UnregisterChannel(pDb->interp, p->channel);
178d0441796Sdanielk1977   }
179d0441796Sdanielk1977 }
180d0441796Sdanielk1977 
181d0441796Sdanielk1977 /*
182b4e9af9fSdanielk1977 ** Close an incremental blob channel.
183b4e9af9fSdanielk1977 */
184b4e9af9fSdanielk1977 static int incrblobClose(ClientData instanceData, Tcl_Interp *interp){
185b4e9af9fSdanielk1977   IncrblobChannel *p = (IncrblobChannel *)instanceData;
18692d4d7a9Sdanielk1977   int rc = sqlite3_blob_close(p->pBlob);
18792d4d7a9Sdanielk1977   sqlite3 *db = p->pDb->db;
188d0441796Sdanielk1977 
189d0441796Sdanielk1977   /* Remove the channel from the SqliteDb.pIncrblob list. */
190d0441796Sdanielk1977   if( p->pNext ){
191d0441796Sdanielk1977     p->pNext->pPrev = p->pPrev;
192d0441796Sdanielk1977   }
193d0441796Sdanielk1977   if( p->pPrev ){
194d0441796Sdanielk1977     p->pPrev->pNext = p->pNext;
195d0441796Sdanielk1977   }
196d0441796Sdanielk1977   if( p->pDb->pIncrblob==p ){
197d0441796Sdanielk1977     p->pDb->pIncrblob = p->pNext;
198d0441796Sdanielk1977   }
199d0441796Sdanielk1977 
20092d4d7a9Sdanielk1977   /* Free the IncrblobChannel structure */
201b4e9af9fSdanielk1977   Tcl_Free((char *)p);
20292d4d7a9Sdanielk1977 
20392d4d7a9Sdanielk1977   if( rc!=SQLITE_OK ){
20492d4d7a9Sdanielk1977     Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
20592d4d7a9Sdanielk1977     return TCL_ERROR;
20692d4d7a9Sdanielk1977   }
207b4e9af9fSdanielk1977   return TCL_OK;
208b4e9af9fSdanielk1977 }
209b4e9af9fSdanielk1977 
210b4e9af9fSdanielk1977 /*
211b4e9af9fSdanielk1977 ** Read data from an incremental blob channel.
212b4e9af9fSdanielk1977 */
213b4e9af9fSdanielk1977 static int incrblobInput(
214b4e9af9fSdanielk1977   ClientData instanceData,
215b4e9af9fSdanielk1977   char *buf,
216b4e9af9fSdanielk1977   int bufSize,
217b4e9af9fSdanielk1977   int *errorCodePtr
218b4e9af9fSdanielk1977 ){
219b4e9af9fSdanielk1977   IncrblobChannel *p = (IncrblobChannel *)instanceData;
220b4e9af9fSdanielk1977   int nRead = bufSize;         /* Number of bytes to read */
221b4e9af9fSdanielk1977   int nBlob;                   /* Total size of the blob */
222b4e9af9fSdanielk1977   int rc;                      /* sqlite error code */
223b4e9af9fSdanielk1977 
224b4e9af9fSdanielk1977   nBlob = sqlite3_blob_bytes(p->pBlob);
225b4e9af9fSdanielk1977   if( (p->iSeek+nRead)>nBlob ){
226b4e9af9fSdanielk1977     nRead = nBlob-p->iSeek;
227b4e9af9fSdanielk1977   }
228b4e9af9fSdanielk1977   if( nRead<=0 ){
229b4e9af9fSdanielk1977     return 0;
230b4e9af9fSdanielk1977   }
231b4e9af9fSdanielk1977 
232b4e9af9fSdanielk1977   rc = sqlite3_blob_read(p->pBlob, (void *)buf, nRead, p->iSeek);
233b4e9af9fSdanielk1977   if( rc!=SQLITE_OK ){
234b4e9af9fSdanielk1977     *errorCodePtr = rc;
235b4e9af9fSdanielk1977     return -1;
236b4e9af9fSdanielk1977   }
237b4e9af9fSdanielk1977 
238b4e9af9fSdanielk1977   p->iSeek += nRead;
239b4e9af9fSdanielk1977   return nRead;
240b4e9af9fSdanielk1977 }
241b4e9af9fSdanielk1977 
242d0441796Sdanielk1977 /*
243d0441796Sdanielk1977 ** Write data to an incremental blob channel.
244d0441796Sdanielk1977 */
245b4e9af9fSdanielk1977 static int incrblobOutput(
246b4e9af9fSdanielk1977   ClientData instanceData,
247b4e9af9fSdanielk1977   CONST char *buf,
248b4e9af9fSdanielk1977   int toWrite,
249b4e9af9fSdanielk1977   int *errorCodePtr
250b4e9af9fSdanielk1977 ){
251b4e9af9fSdanielk1977   IncrblobChannel *p = (IncrblobChannel *)instanceData;
252b4e9af9fSdanielk1977   int nWrite = toWrite;        /* Number of bytes to write */
253b4e9af9fSdanielk1977   int nBlob;                   /* Total size of the blob */
254b4e9af9fSdanielk1977   int rc;                      /* sqlite error code */
255b4e9af9fSdanielk1977 
256b4e9af9fSdanielk1977   nBlob = sqlite3_blob_bytes(p->pBlob);
257b4e9af9fSdanielk1977   if( (p->iSeek+nWrite)>nBlob ){
258b4e9af9fSdanielk1977     *errorCodePtr = EINVAL;
259b4e9af9fSdanielk1977     return -1;
260b4e9af9fSdanielk1977   }
261b4e9af9fSdanielk1977   if( nWrite<=0 ){
262b4e9af9fSdanielk1977     return 0;
263b4e9af9fSdanielk1977   }
264b4e9af9fSdanielk1977 
265b4e9af9fSdanielk1977   rc = sqlite3_blob_write(p->pBlob, (void *)buf, nWrite, p->iSeek);
266b4e9af9fSdanielk1977   if( rc!=SQLITE_OK ){
267b4e9af9fSdanielk1977     *errorCodePtr = EIO;
268b4e9af9fSdanielk1977     return -1;
269b4e9af9fSdanielk1977   }
270b4e9af9fSdanielk1977 
271b4e9af9fSdanielk1977   p->iSeek += nWrite;
272b4e9af9fSdanielk1977   return nWrite;
273b4e9af9fSdanielk1977 }
274b4e9af9fSdanielk1977 
275b4e9af9fSdanielk1977 /*
276b4e9af9fSdanielk1977 ** Seek an incremental blob channel.
277b4e9af9fSdanielk1977 */
278b4e9af9fSdanielk1977 static int incrblobSeek(
279b4e9af9fSdanielk1977   ClientData instanceData,
280b4e9af9fSdanielk1977   long offset,
281b4e9af9fSdanielk1977   int seekMode,
282b4e9af9fSdanielk1977   int *errorCodePtr
283b4e9af9fSdanielk1977 ){
284b4e9af9fSdanielk1977   IncrblobChannel *p = (IncrblobChannel *)instanceData;
285b4e9af9fSdanielk1977 
286b4e9af9fSdanielk1977   switch( seekMode ){
287b4e9af9fSdanielk1977     case SEEK_SET:
288b4e9af9fSdanielk1977       p->iSeek = offset;
289b4e9af9fSdanielk1977       break;
290b4e9af9fSdanielk1977     case SEEK_CUR:
291b4e9af9fSdanielk1977       p->iSeek += offset;
292b4e9af9fSdanielk1977       break;
293b4e9af9fSdanielk1977     case SEEK_END:
294b4e9af9fSdanielk1977       p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset;
295b4e9af9fSdanielk1977       break;
296b4e9af9fSdanielk1977 
297b4e9af9fSdanielk1977     default: assert(!"Bad seekMode");
298b4e9af9fSdanielk1977   }
299b4e9af9fSdanielk1977 
300b4e9af9fSdanielk1977   return p->iSeek;
301b4e9af9fSdanielk1977 }
302b4e9af9fSdanielk1977 
303b4e9af9fSdanielk1977 
304b4e9af9fSdanielk1977 static void incrblobWatch(ClientData instanceData, int mode){
305b4e9af9fSdanielk1977   /* NO-OP */
306b4e9af9fSdanielk1977 }
307b4e9af9fSdanielk1977 static int incrblobHandle(ClientData instanceData, int dir, ClientData *hPtr){
308b4e9af9fSdanielk1977   return TCL_ERROR;
309b4e9af9fSdanielk1977 }
310b4e9af9fSdanielk1977 
311b4e9af9fSdanielk1977 static Tcl_ChannelType IncrblobChannelType = {
312b4e9af9fSdanielk1977   "incrblob",                        /* typeName                             */
313b4e9af9fSdanielk1977   TCL_CHANNEL_VERSION_2,             /* version                              */
314b4e9af9fSdanielk1977   incrblobClose,                     /* closeProc                            */
315b4e9af9fSdanielk1977   incrblobInput,                     /* inputProc                            */
316b4e9af9fSdanielk1977   incrblobOutput,                    /* outputProc                           */
317b4e9af9fSdanielk1977   incrblobSeek,                      /* seekProc                             */
318b4e9af9fSdanielk1977   0,                                 /* setOptionProc                        */
319b4e9af9fSdanielk1977   0,                                 /* getOptionProc                        */
320b4e9af9fSdanielk1977   incrblobWatch,                     /* watchProc (this is a no-op)          */
321b4e9af9fSdanielk1977   incrblobHandle,                    /* getHandleProc (always returns error) */
322b4e9af9fSdanielk1977   0,                                 /* close2Proc                           */
323b4e9af9fSdanielk1977   0,                                 /* blockModeProc                        */
324b4e9af9fSdanielk1977   0,                                 /* flushProc                            */
325b4e9af9fSdanielk1977   0,                                 /* handlerProc                          */
326b4e9af9fSdanielk1977   0,                                 /* wideSeekProc                         */
327b4e9af9fSdanielk1977 };
328b4e9af9fSdanielk1977 
329b4e9af9fSdanielk1977 /*
330b4e9af9fSdanielk1977 ** Create a new incrblob channel.
331b4e9af9fSdanielk1977 */
332b4e9af9fSdanielk1977 static int createIncrblobChannel(
333b4e9af9fSdanielk1977   Tcl_Interp *interp,
334b4e9af9fSdanielk1977   SqliteDb *pDb,
335b4e9af9fSdanielk1977   const char *zDb,
336b4e9af9fSdanielk1977   const char *zTable,
337b4e9af9fSdanielk1977   const char *zColumn,
3388cbadb02Sdanielk1977   sqlite_int64 iRow,
3398cbadb02Sdanielk1977   int isReadonly
340b4e9af9fSdanielk1977 ){
341b4e9af9fSdanielk1977   IncrblobChannel *p;
3428cbadb02Sdanielk1977   sqlite3 *db = pDb->db;
343b4e9af9fSdanielk1977   sqlite3_blob *pBlob;
344b4e9af9fSdanielk1977   int rc;
3458cbadb02Sdanielk1977   int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE);
346b4e9af9fSdanielk1977 
347b4e9af9fSdanielk1977   /* This variable is used to name the channels: "incrblob_[incr count]" */
348b4e9af9fSdanielk1977   static int count = 0;
349b4e9af9fSdanielk1977   char zChannel[64];
350b4e9af9fSdanielk1977 
3518cbadb02Sdanielk1977   rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob);
352b4e9af9fSdanielk1977   if( rc!=SQLITE_OK ){
353b4e9af9fSdanielk1977     Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
354b4e9af9fSdanielk1977     return TCL_ERROR;
355b4e9af9fSdanielk1977   }
356b4e9af9fSdanielk1977 
357b4e9af9fSdanielk1977   p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel));
358b4e9af9fSdanielk1977   p->iSeek = 0;
359b4e9af9fSdanielk1977   p->pBlob = pBlob;
360b4e9af9fSdanielk1977 
3615bb3eb9bSdrh   sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count);
362d0441796Sdanielk1977   p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags);
363d0441796Sdanielk1977   Tcl_RegisterChannel(interp, p->channel);
364b4e9af9fSdanielk1977 
365d0441796Sdanielk1977   /* Link the new channel into the SqliteDb.pIncrblob list. */
366d0441796Sdanielk1977   p->pNext = pDb->pIncrblob;
367d0441796Sdanielk1977   p->pPrev = 0;
368d0441796Sdanielk1977   if( p->pNext ){
369d0441796Sdanielk1977     p->pNext->pPrev = p;
370d0441796Sdanielk1977   }
371d0441796Sdanielk1977   pDb->pIncrblob = p;
372d0441796Sdanielk1977   p->pDb = pDb;
373d0441796Sdanielk1977 
374d0441796Sdanielk1977   Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE);
375b4e9af9fSdanielk1977   return TCL_OK;
376b4e9af9fSdanielk1977 }
37732a0d8bbSdanielk1977 #else  /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
37832a0d8bbSdanielk1977   #define closeIncrblobChannels(pDb)
37932a0d8bbSdanielk1977 #endif
380b4e9af9fSdanielk1977 
3816d31316cSdrh /*
382d1e4733dSdrh ** Look at the script prefix in pCmd.  We will be executing this script
383d1e4733dSdrh ** after first appending one or more arguments.  This routine analyzes
384d1e4733dSdrh ** the script to see if it is safe to use Tcl_EvalObjv() on the script
385d1e4733dSdrh ** rather than the more general Tcl_EvalEx().  Tcl_EvalObjv() is much
386d1e4733dSdrh ** faster.
387d1e4733dSdrh **
388d1e4733dSdrh ** Scripts that are safe to use with Tcl_EvalObjv() consists of a
389d1e4733dSdrh ** command name followed by zero or more arguments with no [...] or $
390d1e4733dSdrh ** or {...} or ; to be seen anywhere.  Most callback scripts consist
391d1e4733dSdrh ** of just a single procedure name and they meet this requirement.
392d1e4733dSdrh */
393d1e4733dSdrh static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
394d1e4733dSdrh   /* We could try to do something with Tcl_Parse().  But we will instead
395d1e4733dSdrh   ** just do a search for forbidden characters.  If any of the forbidden
396d1e4733dSdrh   ** characters appear in pCmd, we will report the string as unsafe.
397d1e4733dSdrh   */
398d1e4733dSdrh   const char *z;
399d1e4733dSdrh   int n;
400d1e4733dSdrh   z = Tcl_GetStringFromObj(pCmd, &n);
401d1e4733dSdrh   while( n-- > 0 ){
402d1e4733dSdrh     int c = *(z++);
403d1e4733dSdrh     if( c=='$' || c=='[' || c==';' ) return 0;
404d1e4733dSdrh   }
405d1e4733dSdrh   return 1;
406d1e4733dSdrh }
407d1e4733dSdrh 
408d1e4733dSdrh /*
409d1e4733dSdrh ** Find an SqlFunc structure with the given name.  Or create a new
410d1e4733dSdrh ** one if an existing one cannot be found.  Return a pointer to the
411d1e4733dSdrh ** structure.
412d1e4733dSdrh */
413d1e4733dSdrh static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
414d1e4733dSdrh   SqlFunc *p, *pNew;
415d1e4733dSdrh   int i;
4164f21c4afSdrh   pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + strlen30(zName) + 1 );
417d1e4733dSdrh   pNew->zName = (char*)&pNew[1];
418d1e4733dSdrh   for(i=0; zName[i]; i++){ pNew->zName[i] = tolower(zName[i]); }
419d1e4733dSdrh   pNew->zName[i] = 0;
420d1e4733dSdrh   for(p=pDb->pFunc; p; p=p->pNext){
421d1e4733dSdrh     if( strcmp(p->zName, pNew->zName)==0 ){
422d1e4733dSdrh       Tcl_Free((char*)pNew);
423d1e4733dSdrh       return p;
424d1e4733dSdrh     }
425d1e4733dSdrh   }
426d1e4733dSdrh   pNew->interp = pDb->interp;
427d1e4733dSdrh   pNew->pScript = 0;
428d1e4733dSdrh   pNew->pNext = pDb->pFunc;
429d1e4733dSdrh   pDb->pFunc = pNew;
430d1e4733dSdrh   return pNew;
431d1e4733dSdrh }
432d1e4733dSdrh 
433d1e4733dSdrh /*
434fb7e7651Sdrh ** Finalize and free a list of prepared statements
435fb7e7651Sdrh */
436fb7e7651Sdrh static void flushStmtCache( SqliteDb *pDb ){
437fb7e7651Sdrh   SqlPreparedStmt *pPreStmt;
438fb7e7651Sdrh 
439fb7e7651Sdrh   while(  pDb->stmtList ){
440fb7e7651Sdrh     sqlite3_finalize( pDb->stmtList->pStmt );
441fb7e7651Sdrh     pPreStmt = pDb->stmtList;
442fb7e7651Sdrh     pDb->stmtList = pDb->stmtList->pNext;
443fb7e7651Sdrh     Tcl_Free( (char*)pPreStmt );
444fb7e7651Sdrh   }
445fb7e7651Sdrh   pDb->nStmt = 0;
446fb7e7651Sdrh   pDb->stmtLast = 0;
447fb7e7651Sdrh }
448fb7e7651Sdrh 
449fb7e7651Sdrh /*
450895d7472Sdrh ** TCL calls this procedure when an sqlite3 database command is
451895d7472Sdrh ** deleted.
45275897234Sdrh */
45375897234Sdrh static void DbDeleteCmd(void *db){
454bec3f402Sdrh   SqliteDb *pDb = (SqliteDb*)db;
455fb7e7651Sdrh   flushStmtCache(pDb);
456d0441796Sdanielk1977   closeIncrblobChannels(pDb);
4576f8a503dSdanielk1977   sqlite3_close(pDb->db);
458cabb0819Sdrh   while( pDb->pFunc ){
459cabb0819Sdrh     SqlFunc *pFunc = pDb->pFunc;
460cabb0819Sdrh     pDb->pFunc = pFunc->pNext;
461d1e4733dSdrh     Tcl_DecrRefCount(pFunc->pScript);
462cabb0819Sdrh     Tcl_Free((char*)pFunc);
463cabb0819Sdrh   }
4640202b29eSdanielk1977   while( pDb->pCollate ){
4650202b29eSdanielk1977     SqlCollate *pCollate = pDb->pCollate;
4660202b29eSdanielk1977     pDb->pCollate = pCollate->pNext;
4670202b29eSdanielk1977     Tcl_Free((char*)pCollate);
4680202b29eSdanielk1977   }
469bec3f402Sdrh   if( pDb->zBusy ){
470bec3f402Sdrh     Tcl_Free(pDb->zBusy);
471bec3f402Sdrh   }
472b5a20d3cSdrh   if( pDb->zTrace ){
473b5a20d3cSdrh     Tcl_Free(pDb->zTrace);
4740d1a643aSdrh   }
47519e2d37fSdrh   if( pDb->zProfile ){
47619e2d37fSdrh     Tcl_Free(pDb->zProfile);
47719e2d37fSdrh   }
478e22a334bSdrh   if( pDb->zAuth ){
479e22a334bSdrh     Tcl_Free(pDb->zAuth);
480e22a334bSdrh   }
48155c45f2eSdanielk1977   if( pDb->zNull ){
48255c45f2eSdanielk1977     Tcl_Free(pDb->zNull);
48355c45f2eSdanielk1977   }
48494eb6a14Sdanielk1977   if( pDb->pUpdateHook ){
48594eb6a14Sdanielk1977     Tcl_DecrRefCount(pDb->pUpdateHook);
48694eb6a14Sdanielk1977   }
48746c47d46Sdan   if( pDb->pPreUpdateHook ){
48846c47d46Sdan     Tcl_DecrRefCount(pDb->pPreUpdateHook);
48946c47d46Sdan   }
49071fd80bfSdanielk1977   if( pDb->pRollbackHook ){
49171fd80bfSdanielk1977     Tcl_DecrRefCount(pDb->pRollbackHook);
49271fd80bfSdanielk1977   }
4935def0843Sdrh   if( pDb->pWalHook ){
4945def0843Sdrh     Tcl_DecrRefCount(pDb->pWalHook);
4958d22a174Sdan   }
49694eb6a14Sdanielk1977   if( pDb->pCollateNeeded ){
49794eb6a14Sdanielk1977     Tcl_DecrRefCount(pDb->pCollateNeeded);
49894eb6a14Sdanielk1977   }
499bec3f402Sdrh   Tcl_Free((char*)pDb);
500bec3f402Sdrh }
501bec3f402Sdrh 
502bec3f402Sdrh /*
503bec3f402Sdrh ** This routine is called when a database file is locked while trying
504bec3f402Sdrh ** to execute SQL.
505bec3f402Sdrh */
5062a764eb0Sdanielk1977 static int DbBusyHandler(void *cd, int nTries){
507bec3f402Sdrh   SqliteDb *pDb = (SqliteDb*)cd;
508bec3f402Sdrh   int rc;
509bec3f402Sdrh   char zVal[30];
510bec3f402Sdrh 
5115bb3eb9bSdrh   sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries);
512d1e4733dSdrh   rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
513bec3f402Sdrh   if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
514bec3f402Sdrh     return 0;
515bec3f402Sdrh   }
516bec3f402Sdrh   return 1;
51775897234Sdrh }
51875897234Sdrh 
51926e4a8b1Sdrh #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
52075897234Sdrh /*
521348bb5d6Sdanielk1977 ** This routine is invoked as the 'progress callback' for the database.
522348bb5d6Sdanielk1977 */
523348bb5d6Sdanielk1977 static int DbProgressHandler(void *cd){
524348bb5d6Sdanielk1977   SqliteDb *pDb = (SqliteDb*)cd;
525348bb5d6Sdanielk1977   int rc;
526348bb5d6Sdanielk1977 
527348bb5d6Sdanielk1977   assert( pDb->zProgress );
528348bb5d6Sdanielk1977   rc = Tcl_Eval(pDb->interp, pDb->zProgress);
529348bb5d6Sdanielk1977   if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
530348bb5d6Sdanielk1977     return 1;
531348bb5d6Sdanielk1977   }
532348bb5d6Sdanielk1977   return 0;
533348bb5d6Sdanielk1977 }
53426e4a8b1Sdrh #endif
535348bb5d6Sdanielk1977 
536d1167393Sdrh #ifndef SQLITE_OMIT_TRACE
537348bb5d6Sdanielk1977 /*
538b5a20d3cSdrh ** This routine is called by the SQLite trace handler whenever a new
539b5a20d3cSdrh ** block of SQL is executed.  The TCL script in pDb->zTrace is executed.
5400d1a643aSdrh */
541b5a20d3cSdrh static void DbTraceHandler(void *cd, const char *zSql){
5420d1a643aSdrh   SqliteDb *pDb = (SqliteDb*)cd;
543b5a20d3cSdrh   Tcl_DString str;
5440d1a643aSdrh 
545b5a20d3cSdrh   Tcl_DStringInit(&str);
546b5a20d3cSdrh   Tcl_DStringAppend(&str, pDb->zTrace, -1);
547b5a20d3cSdrh   Tcl_DStringAppendElement(&str, zSql);
548b5a20d3cSdrh   Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
549b5a20d3cSdrh   Tcl_DStringFree(&str);
550b5a20d3cSdrh   Tcl_ResetResult(pDb->interp);
5510d1a643aSdrh }
552d1167393Sdrh #endif
5530d1a643aSdrh 
554d1167393Sdrh #ifndef SQLITE_OMIT_TRACE
5550d1a643aSdrh /*
55619e2d37fSdrh ** This routine is called by the SQLite profile handler after a statement
55719e2d37fSdrh ** SQL has executed.  The TCL script in pDb->zProfile is evaluated.
55819e2d37fSdrh */
55919e2d37fSdrh static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
56019e2d37fSdrh   SqliteDb *pDb = (SqliteDb*)cd;
56119e2d37fSdrh   Tcl_DString str;
56219e2d37fSdrh   char zTm[100];
56319e2d37fSdrh 
56419e2d37fSdrh   sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
56519e2d37fSdrh   Tcl_DStringInit(&str);
56619e2d37fSdrh   Tcl_DStringAppend(&str, pDb->zProfile, -1);
56719e2d37fSdrh   Tcl_DStringAppendElement(&str, zSql);
56819e2d37fSdrh   Tcl_DStringAppendElement(&str, zTm);
56919e2d37fSdrh   Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
57019e2d37fSdrh   Tcl_DStringFree(&str);
57119e2d37fSdrh   Tcl_ResetResult(pDb->interp);
57219e2d37fSdrh }
573d1167393Sdrh #endif
57419e2d37fSdrh 
57519e2d37fSdrh /*
576aa940eacSdrh ** This routine is called when a transaction is committed.  The
577aa940eacSdrh ** TCL script in pDb->zCommit is executed.  If it returns non-zero or
578aa940eacSdrh ** if it throws an exception, the transaction is rolled back instead
579aa940eacSdrh ** of being committed.
580aa940eacSdrh */
581aa940eacSdrh static int DbCommitHandler(void *cd){
582aa940eacSdrh   SqliteDb *pDb = (SqliteDb*)cd;
583aa940eacSdrh   int rc;
584aa940eacSdrh 
585aa940eacSdrh   rc = Tcl_Eval(pDb->interp, pDb->zCommit);
586aa940eacSdrh   if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
587aa940eacSdrh     return 1;
588aa940eacSdrh   }
589aa940eacSdrh   return 0;
590aa940eacSdrh }
591aa940eacSdrh 
59271fd80bfSdanielk1977 static void DbRollbackHandler(void *clientData){
59371fd80bfSdanielk1977   SqliteDb *pDb = (SqliteDb*)clientData;
59471fd80bfSdanielk1977   assert(pDb->pRollbackHook);
59571fd80bfSdanielk1977   if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
59671fd80bfSdanielk1977     Tcl_BackgroundError(pDb->interp);
59771fd80bfSdanielk1977   }
59871fd80bfSdanielk1977 }
59971fd80bfSdanielk1977 
6005def0843Sdrh /*
6015def0843Sdrh ** This procedure handles wal_hook callbacks.
6025def0843Sdrh */
6035def0843Sdrh static int DbWalHandler(
6048d22a174Sdan   void *clientData,
6058d22a174Sdan   sqlite3 *db,
6068d22a174Sdan   const char *zDb,
6078d22a174Sdan   int nEntry
6088d22a174Sdan ){
6095def0843Sdrh   int ret = SQLITE_OK;
6108d22a174Sdan   Tcl_Obj *p;
6118d22a174Sdan   SqliteDb *pDb = (SqliteDb*)clientData;
6128d22a174Sdan   Tcl_Interp *interp = pDb->interp;
6135def0843Sdrh   assert(pDb->pWalHook);
6148d22a174Sdan 
6155def0843Sdrh   p = Tcl_DuplicateObj(pDb->pWalHook);
6168d22a174Sdan   Tcl_IncrRefCount(p);
6178d22a174Sdan   Tcl_ListObjAppendElement(interp, p, Tcl_NewStringObj(zDb, -1));
6188d22a174Sdan   Tcl_ListObjAppendElement(interp, p, Tcl_NewIntObj(nEntry));
6198d22a174Sdan   if( TCL_OK!=Tcl_EvalObjEx(interp, p, 0)
6208d22a174Sdan    || TCL_OK!=Tcl_GetIntFromObj(interp, Tcl_GetObjResult(interp), &ret)
6218d22a174Sdan   ){
6228d22a174Sdan     Tcl_BackgroundError(interp);
6238d22a174Sdan   }
6248d22a174Sdan   Tcl_DecrRefCount(p);
6258d22a174Sdan 
6268d22a174Sdan   return ret;
6278d22a174Sdan }
6288d22a174Sdan 
629bcf4f484Sdrh #if defined(SQLITE_TEST) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
630404ca075Sdanielk1977 static void setTestUnlockNotifyVars(Tcl_Interp *interp, int iArg, int nArg){
631404ca075Sdanielk1977   char zBuf[64];
632404ca075Sdanielk1977   sprintf(zBuf, "%d", iArg);
633404ca075Sdanielk1977   Tcl_SetVar(interp, "sqlite_unlock_notify_arg", zBuf, TCL_GLOBAL_ONLY);
634404ca075Sdanielk1977   sprintf(zBuf, "%d", nArg);
635404ca075Sdanielk1977   Tcl_SetVar(interp, "sqlite_unlock_notify_argcount", zBuf, TCL_GLOBAL_ONLY);
636404ca075Sdanielk1977 }
637404ca075Sdanielk1977 #else
638404ca075Sdanielk1977 # define setTestUnlockNotifyVars(x,y,z)
639404ca075Sdanielk1977 #endif
640404ca075Sdanielk1977 
64169910da9Sdrh #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
642404ca075Sdanielk1977 static void DbUnlockNotify(void **apArg, int nArg){
643404ca075Sdanielk1977   int i;
644404ca075Sdanielk1977   for(i=0; i<nArg; i++){
645404ca075Sdanielk1977     const int flags = (TCL_EVAL_GLOBAL|TCL_EVAL_DIRECT);
646404ca075Sdanielk1977     SqliteDb *pDb = (SqliteDb *)apArg[i];
647404ca075Sdanielk1977     setTestUnlockNotifyVars(pDb->interp, i, nArg);
648404ca075Sdanielk1977     assert( pDb->pUnlockNotify);
649404ca075Sdanielk1977     Tcl_EvalObjEx(pDb->interp, pDb->pUnlockNotify, flags);
650404ca075Sdanielk1977     Tcl_DecrRefCount(pDb->pUnlockNotify);
651404ca075Sdanielk1977     pDb->pUnlockNotify = 0;
652404ca075Sdanielk1977   }
653404ca075Sdanielk1977 }
65469910da9Sdrh #endif
655404ca075Sdanielk1977 
65646c47d46Sdan /*
65746c47d46Sdan ** Pre-update hook callback.
65846c47d46Sdan */
65946c47d46Sdan static void DbPreUpdateHandler(
66046c47d46Sdan   void *p,
66146c47d46Sdan   sqlite3 *db,
66246c47d46Sdan   int op,
66346c47d46Sdan   const char *zDb,
66446c47d46Sdan   const char *zTbl,
66546c47d46Sdan   sqlite_int64 iKey1,
66646c47d46Sdan   sqlite_int64 iKey2
66746c47d46Sdan ){
66846c47d46Sdan   SqliteDb *pDb = (SqliteDb *)p;
66946c47d46Sdan   Tcl_Obj *pCmd;
67046c47d46Sdan   static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"};
67146c47d46Sdan 
67246c47d46Sdan   assert( (SQLITE_DELETE-1)/9 == 0 );
67346c47d46Sdan   assert( (SQLITE_INSERT-1)/9 == 1 );
67446c47d46Sdan   assert( (SQLITE_UPDATE-1)/9 == 2 );
67546c47d46Sdan   assert( pDb->pPreUpdateHook );
67646c47d46Sdan   assert( db==pDb->db );
67746c47d46Sdan   assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
67846c47d46Sdan 
67946c47d46Sdan   pCmd = Tcl_DuplicateObj(pDb->pPreUpdateHook);
68046c47d46Sdan   Tcl_IncrRefCount(pCmd);
68146c47d46Sdan   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
68246c47d46Sdan   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
68346c47d46Sdan   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
68446c47d46Sdan   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey1));
68546c47d46Sdan   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey2));
68646c47d46Sdan   Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
68746c47d46Sdan   Tcl_DecrRefCount(pCmd);
68846c47d46Sdan }
68946c47d46Sdan 
69094eb6a14Sdanielk1977 static void DbUpdateHandler(
69194eb6a14Sdanielk1977   void *p,
69294eb6a14Sdanielk1977   int op,
69394eb6a14Sdanielk1977   const char *zDb,
69494eb6a14Sdanielk1977   const char *zTbl,
69594eb6a14Sdanielk1977   sqlite_int64 rowid
69694eb6a14Sdanielk1977 ){
69794eb6a14Sdanielk1977   SqliteDb *pDb = (SqliteDb *)p;
69894eb6a14Sdanielk1977   Tcl_Obj *pCmd;
69946c47d46Sdan   static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"};
70046c47d46Sdan 
70146c47d46Sdan   assert( (SQLITE_DELETE-1)/9 == 0 );
70246c47d46Sdan   assert( (SQLITE_INSERT-1)/9 == 1 );
70346c47d46Sdan   assert( (SQLITE_UPDATE-1)/9 == 2 );
70494eb6a14Sdanielk1977 
70594eb6a14Sdanielk1977   assert( pDb->pUpdateHook );
70694eb6a14Sdanielk1977   assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
70794eb6a14Sdanielk1977 
70894eb6a14Sdanielk1977   pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
70994eb6a14Sdanielk1977   Tcl_IncrRefCount(pCmd);
71046c47d46Sdan   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
71194eb6a14Sdanielk1977   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
71294eb6a14Sdanielk1977   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
71394eb6a14Sdanielk1977   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
71494eb6a14Sdanielk1977   Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
715efdde169Sdrh   Tcl_DecrRefCount(pCmd);
71694eb6a14Sdanielk1977 }
71794eb6a14Sdanielk1977 
7187cedc8d4Sdanielk1977 static void tclCollateNeeded(
7197cedc8d4Sdanielk1977   void *pCtx,
7209bb575fdSdrh   sqlite3 *db,
7217cedc8d4Sdanielk1977   int enc,
7227cedc8d4Sdanielk1977   const char *zName
7237cedc8d4Sdanielk1977 ){
7247cedc8d4Sdanielk1977   SqliteDb *pDb = (SqliteDb *)pCtx;
7257cedc8d4Sdanielk1977   Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
7267cedc8d4Sdanielk1977   Tcl_IncrRefCount(pScript);
7277cedc8d4Sdanielk1977   Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
7287cedc8d4Sdanielk1977   Tcl_EvalObjEx(pDb->interp, pScript, 0);
7297cedc8d4Sdanielk1977   Tcl_DecrRefCount(pScript);
7307cedc8d4Sdanielk1977 }
7317cedc8d4Sdanielk1977 
732aa940eacSdrh /*
7330202b29eSdanielk1977 ** This routine is called to evaluate an SQL collation function implemented
7340202b29eSdanielk1977 ** using TCL script.
7350202b29eSdanielk1977 */
7360202b29eSdanielk1977 static int tclSqlCollate(
7370202b29eSdanielk1977   void *pCtx,
7380202b29eSdanielk1977   int nA,
7390202b29eSdanielk1977   const void *zA,
7400202b29eSdanielk1977   int nB,
7410202b29eSdanielk1977   const void *zB
7420202b29eSdanielk1977 ){
7430202b29eSdanielk1977   SqlCollate *p = (SqlCollate *)pCtx;
7440202b29eSdanielk1977   Tcl_Obj *pCmd;
7450202b29eSdanielk1977 
7460202b29eSdanielk1977   pCmd = Tcl_NewStringObj(p->zScript, -1);
7470202b29eSdanielk1977   Tcl_IncrRefCount(pCmd);
7480202b29eSdanielk1977   Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
7490202b29eSdanielk1977   Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
750d1e4733dSdrh   Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
7510202b29eSdanielk1977   Tcl_DecrRefCount(pCmd);
7520202b29eSdanielk1977   return (atoi(Tcl_GetStringResult(p->interp)));
7530202b29eSdanielk1977 }
7540202b29eSdanielk1977 
7550202b29eSdanielk1977 /*
756cabb0819Sdrh ** This routine is called to evaluate an SQL function implemented
757cabb0819Sdrh ** using TCL script.
758cabb0819Sdrh */
7590ae8b831Sdanielk1977 static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
7606f8a503dSdanielk1977   SqlFunc *p = sqlite3_user_data(context);
761d1e4733dSdrh   Tcl_Obj *pCmd;
762cabb0819Sdrh   int i;
763cabb0819Sdrh   int rc;
764cabb0819Sdrh 
765d1e4733dSdrh   if( argc==0 ){
766d1e4733dSdrh     /* If there are no arguments to the function, call Tcl_EvalObjEx on the
767d1e4733dSdrh     ** script object directly.  This allows the TCL compiler to generate
768d1e4733dSdrh     ** bytecode for the command on the first invocation and thus make
769d1e4733dSdrh     ** subsequent invocations much faster. */
770d1e4733dSdrh     pCmd = p->pScript;
771d1e4733dSdrh     Tcl_IncrRefCount(pCmd);
772d1e4733dSdrh     rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
773d1e4733dSdrh     Tcl_DecrRefCount(pCmd);
77451ad0ecdSdanielk1977   }else{
775d1e4733dSdrh     /* If there are arguments to the function, make a shallow copy of the
776d1e4733dSdrh     ** script object, lappend the arguments, then evaluate the copy.
777d1e4733dSdrh     **
778d1e4733dSdrh     ** By "shallow" copy, we mean a only the outer list Tcl_Obj is duplicated.
779d1e4733dSdrh     ** The new Tcl_Obj contains pointers to the original list elements.
780d1e4733dSdrh     ** That way, when Tcl_EvalObjv() is run and shimmers the first element
781d1e4733dSdrh     ** of the list to tclCmdNameType, that alternate representation will
782d1e4733dSdrh     ** be preserved and reused on the next invocation.
783d1e4733dSdrh     */
784d1e4733dSdrh     Tcl_Obj **aArg;
785d1e4733dSdrh     int nArg;
786d1e4733dSdrh     if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
787d1e4733dSdrh       sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
788d1e4733dSdrh       return;
789d1e4733dSdrh     }
790d1e4733dSdrh     pCmd = Tcl_NewListObj(nArg, aArg);
791d1e4733dSdrh     Tcl_IncrRefCount(pCmd);
792d1e4733dSdrh     for(i=0; i<argc; i++){
793d1e4733dSdrh       sqlite3_value *pIn = argv[i];
794d1e4733dSdrh       Tcl_Obj *pVal;
795d1e4733dSdrh 
796d1e4733dSdrh       /* Set pVal to contain the i'th column of this row. */
797d1e4733dSdrh       switch( sqlite3_value_type(pIn) ){
798d1e4733dSdrh         case SQLITE_BLOB: {
799d1e4733dSdrh           int bytes = sqlite3_value_bytes(pIn);
800d1e4733dSdrh           pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
801d1e4733dSdrh           break;
802d1e4733dSdrh         }
803d1e4733dSdrh         case SQLITE_INTEGER: {
804d1e4733dSdrh           sqlite_int64 v = sqlite3_value_int64(pIn);
805d1e4733dSdrh           if( v>=-2147483647 && v<=2147483647 ){
806d1e4733dSdrh             pVal = Tcl_NewIntObj(v);
807d1e4733dSdrh           }else{
808d1e4733dSdrh             pVal = Tcl_NewWideIntObj(v);
809d1e4733dSdrh           }
810d1e4733dSdrh           break;
811d1e4733dSdrh         }
812d1e4733dSdrh         case SQLITE_FLOAT: {
813d1e4733dSdrh           double r = sqlite3_value_double(pIn);
814d1e4733dSdrh           pVal = Tcl_NewDoubleObj(r);
815d1e4733dSdrh           break;
816d1e4733dSdrh         }
817d1e4733dSdrh         case SQLITE_NULL: {
818d1e4733dSdrh           pVal = Tcl_NewStringObj("", 0);
819d1e4733dSdrh           break;
820d1e4733dSdrh         }
821d1e4733dSdrh         default: {
822d1e4733dSdrh           int bytes = sqlite3_value_bytes(pIn);
82300fd957bSdanielk1977           pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
824d1e4733dSdrh           break;
82551ad0ecdSdanielk1977         }
826cabb0819Sdrh       }
827d1e4733dSdrh       rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
828d1e4733dSdrh       if( rc ){
829d1e4733dSdrh         Tcl_DecrRefCount(pCmd);
830d1e4733dSdrh         sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
831d1e4733dSdrh         return;
832d1e4733dSdrh       }
833d1e4733dSdrh     }
834d1e4733dSdrh     if( !p->useEvalObjv ){
835d1e4733dSdrh       /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
836d1e4733dSdrh       ** is a list without a string representation.  To prevent this from
837d1e4733dSdrh       ** happening, make sure pCmd has a valid string representation */
838d1e4733dSdrh       Tcl_GetString(pCmd);
839d1e4733dSdrh     }
840d1e4733dSdrh     rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
841d1e4733dSdrh     Tcl_DecrRefCount(pCmd);
842d1e4733dSdrh   }
843562e8d3cSdanielk1977 
844c7f269d5Sdrh   if( rc && rc!=TCL_RETURN ){
8457e18c259Sdanielk1977     sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
846cabb0819Sdrh   }else{
847c7f269d5Sdrh     Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
848c7f269d5Sdrh     int n;
849c7f269d5Sdrh     u8 *data;
8504a4c11aaSdan     const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
851c7f269d5Sdrh     char c = zType[0];
852df0bddaeSdrh     if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
853d1e4733dSdrh       /* Only return a BLOB type if the Tcl variable is a bytearray and
854df0bddaeSdrh       ** has no string representation. */
855c7f269d5Sdrh       data = Tcl_GetByteArrayFromObj(pVar, &n);
856c7f269d5Sdrh       sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
857985e0c63Sdrh     }else if( c=='b' && strcmp(zType,"boolean")==0 ){
858c7f269d5Sdrh       Tcl_GetIntFromObj(0, pVar, &n);
859c7f269d5Sdrh       sqlite3_result_int(context, n);
860c7f269d5Sdrh     }else if( c=='d' && strcmp(zType,"double")==0 ){
861c7f269d5Sdrh       double r;
862c7f269d5Sdrh       Tcl_GetDoubleFromObj(0, pVar, &r);
863c7f269d5Sdrh       sqlite3_result_double(context, r);
864985e0c63Sdrh     }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
865985e0c63Sdrh           (c=='i' && strcmp(zType,"int")==0) ){
866df0bddaeSdrh       Tcl_WideInt v;
867df0bddaeSdrh       Tcl_GetWideIntFromObj(0, pVar, &v);
868df0bddaeSdrh       sqlite3_result_int64(context, v);
869c7f269d5Sdrh     }else{
87000fd957bSdanielk1977       data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
87100fd957bSdanielk1977       sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
872c7f269d5Sdrh     }
873cabb0819Sdrh   }
874cabb0819Sdrh }
875895d7472Sdrh 
876e22a334bSdrh #ifndef SQLITE_OMIT_AUTHORIZATION
877e22a334bSdrh /*
878e22a334bSdrh ** This is the authentication function.  It appends the authentication
879e22a334bSdrh ** type code and the two arguments to zCmd[] then invokes the result
880e22a334bSdrh ** on the interpreter.  The reply is examined to determine if the
881e22a334bSdrh ** authentication fails or succeeds.
882e22a334bSdrh */
883e22a334bSdrh static int auth_callback(
884e22a334bSdrh   void *pArg,
885e22a334bSdrh   int code,
886e22a334bSdrh   const char *zArg1,
887e22a334bSdrh   const char *zArg2,
888e22a334bSdrh   const char *zArg3,
889e22a334bSdrh   const char *zArg4
890e22a334bSdrh ){
891e22a334bSdrh   char *zCode;
892e22a334bSdrh   Tcl_DString str;
893e22a334bSdrh   int rc;
894e22a334bSdrh   const char *zReply;
895e22a334bSdrh   SqliteDb *pDb = (SqliteDb*)pArg;
8961f1549f8Sdrh   if( pDb->disableAuth ) return SQLITE_OK;
897e22a334bSdrh 
898e22a334bSdrh   switch( code ){
899e22a334bSdrh     case SQLITE_COPY              : zCode="SQLITE_COPY"; break;
900e22a334bSdrh     case SQLITE_CREATE_INDEX      : zCode="SQLITE_CREATE_INDEX"; break;
901e22a334bSdrh     case SQLITE_CREATE_TABLE      : zCode="SQLITE_CREATE_TABLE"; break;
902e22a334bSdrh     case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
903e22a334bSdrh     case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
904e22a334bSdrh     case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
905e22a334bSdrh     case SQLITE_CREATE_TEMP_VIEW  : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
906e22a334bSdrh     case SQLITE_CREATE_TRIGGER    : zCode="SQLITE_CREATE_TRIGGER"; break;
907e22a334bSdrh     case SQLITE_CREATE_VIEW       : zCode="SQLITE_CREATE_VIEW"; break;
908e22a334bSdrh     case SQLITE_DELETE            : zCode="SQLITE_DELETE"; break;
909e22a334bSdrh     case SQLITE_DROP_INDEX        : zCode="SQLITE_DROP_INDEX"; break;
910e22a334bSdrh     case SQLITE_DROP_TABLE        : zCode="SQLITE_DROP_TABLE"; break;
911e22a334bSdrh     case SQLITE_DROP_TEMP_INDEX   : zCode="SQLITE_DROP_TEMP_INDEX"; break;
912e22a334bSdrh     case SQLITE_DROP_TEMP_TABLE   : zCode="SQLITE_DROP_TEMP_TABLE"; break;
913e22a334bSdrh     case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
914e22a334bSdrh     case SQLITE_DROP_TEMP_VIEW    : zCode="SQLITE_DROP_TEMP_VIEW"; break;
915e22a334bSdrh     case SQLITE_DROP_TRIGGER      : zCode="SQLITE_DROP_TRIGGER"; break;
916e22a334bSdrh     case SQLITE_DROP_VIEW         : zCode="SQLITE_DROP_VIEW"; break;
917e22a334bSdrh     case SQLITE_INSERT            : zCode="SQLITE_INSERT"; break;
918e22a334bSdrh     case SQLITE_PRAGMA            : zCode="SQLITE_PRAGMA"; break;
919e22a334bSdrh     case SQLITE_READ              : zCode="SQLITE_READ"; break;
920e22a334bSdrh     case SQLITE_SELECT            : zCode="SQLITE_SELECT"; break;
921e22a334bSdrh     case SQLITE_TRANSACTION       : zCode="SQLITE_TRANSACTION"; break;
922e22a334bSdrh     case SQLITE_UPDATE            : zCode="SQLITE_UPDATE"; break;
92381e293b4Sdrh     case SQLITE_ATTACH            : zCode="SQLITE_ATTACH"; break;
92481e293b4Sdrh     case SQLITE_DETACH            : zCode="SQLITE_DETACH"; break;
9251c8c23ccSdanielk1977     case SQLITE_ALTER_TABLE       : zCode="SQLITE_ALTER_TABLE"; break;
9261d54df88Sdanielk1977     case SQLITE_REINDEX           : zCode="SQLITE_REINDEX"; break;
927e6e04969Sdrh     case SQLITE_ANALYZE           : zCode="SQLITE_ANALYZE"; break;
928f1a381e7Sdanielk1977     case SQLITE_CREATE_VTABLE     : zCode="SQLITE_CREATE_VTABLE"; break;
929f1a381e7Sdanielk1977     case SQLITE_DROP_VTABLE       : zCode="SQLITE_DROP_VTABLE"; break;
9305169bbc6Sdrh     case SQLITE_FUNCTION          : zCode="SQLITE_FUNCTION"; break;
931ab9b703fSdanielk1977     case SQLITE_SAVEPOINT         : zCode="SQLITE_SAVEPOINT"; break;
932e22a334bSdrh     default                       : zCode="????"; break;
933e22a334bSdrh   }
934e22a334bSdrh   Tcl_DStringInit(&str);
935e22a334bSdrh   Tcl_DStringAppend(&str, pDb->zAuth, -1);
936e22a334bSdrh   Tcl_DStringAppendElement(&str, zCode);
937e22a334bSdrh   Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
938e22a334bSdrh   Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
939e22a334bSdrh   Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
940e22a334bSdrh   Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
941e22a334bSdrh   rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
942e22a334bSdrh   Tcl_DStringFree(&str);
943e22a334bSdrh   zReply = Tcl_GetStringResult(pDb->interp);
944e22a334bSdrh   if( strcmp(zReply,"SQLITE_OK")==0 ){
945e22a334bSdrh     rc = SQLITE_OK;
946e22a334bSdrh   }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
947e22a334bSdrh     rc = SQLITE_DENY;
948e22a334bSdrh   }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
949e22a334bSdrh     rc = SQLITE_IGNORE;
950e22a334bSdrh   }else{
951e22a334bSdrh     rc = 999;
952e22a334bSdrh   }
953e22a334bSdrh   return rc;
954e22a334bSdrh }
955e22a334bSdrh #endif /* SQLITE_OMIT_AUTHORIZATION */
956cabb0819Sdrh 
957cabb0819Sdrh /*
958ef2cb63eSdanielk1977 ** zText is a pointer to text obtained via an sqlite3_result_text()
959ef2cb63eSdanielk1977 ** or similar interface. This routine returns a Tcl string object,
960ef2cb63eSdanielk1977 ** reference count set to 0, containing the text. If a translation
961ef2cb63eSdanielk1977 ** between iso8859 and UTF-8 is required, it is preformed.
962ef2cb63eSdanielk1977 */
963ef2cb63eSdanielk1977 static Tcl_Obj *dbTextToObj(char const *zText){
964ef2cb63eSdanielk1977   Tcl_Obj *pVal;
965ef2cb63eSdanielk1977 #ifdef UTF_TRANSLATION_NEEDED
966ef2cb63eSdanielk1977   Tcl_DString dCol;
967ef2cb63eSdanielk1977   Tcl_DStringInit(&dCol);
968ef2cb63eSdanielk1977   Tcl_ExternalToUtfDString(NULL, zText, -1, &dCol);
969ef2cb63eSdanielk1977   pVal = Tcl_NewStringObj(Tcl_DStringValue(&dCol), -1);
970ef2cb63eSdanielk1977   Tcl_DStringFree(&dCol);
971ef2cb63eSdanielk1977 #else
972ef2cb63eSdanielk1977   pVal = Tcl_NewStringObj(zText, -1);
973ef2cb63eSdanielk1977 #endif
974ef2cb63eSdanielk1977   return pVal;
975ef2cb63eSdanielk1977 }
976ef2cb63eSdanielk1977 
977ef2cb63eSdanielk1977 /*
9781067fe11Stpoindex ** This routine reads a line of text from FILE in, stores
9791067fe11Stpoindex ** the text in memory obtained from malloc() and returns a pointer
9801067fe11Stpoindex ** to the text.  NULL is returned at end of file, or if malloc()
9811067fe11Stpoindex ** fails.
9821067fe11Stpoindex **
9831067fe11Stpoindex ** The interface is like "readline" but no command-line editing
9841067fe11Stpoindex ** is done.
9851067fe11Stpoindex **
9861067fe11Stpoindex ** copied from shell.c from '.import' command
9871067fe11Stpoindex */
9881067fe11Stpoindex static char *local_getline(char *zPrompt, FILE *in){
9891067fe11Stpoindex   char *zLine;
9901067fe11Stpoindex   int nLine;
9911067fe11Stpoindex   int n;
9921067fe11Stpoindex   int eol;
9931067fe11Stpoindex 
9941067fe11Stpoindex   nLine = 100;
9951067fe11Stpoindex   zLine = malloc( nLine );
9961067fe11Stpoindex   if( zLine==0 ) return 0;
9971067fe11Stpoindex   n = 0;
9981067fe11Stpoindex   eol = 0;
9991067fe11Stpoindex   while( !eol ){
10001067fe11Stpoindex     if( n+100>nLine ){
10011067fe11Stpoindex       nLine = nLine*2 + 100;
10021067fe11Stpoindex       zLine = realloc(zLine, nLine);
10031067fe11Stpoindex       if( zLine==0 ) return 0;
10041067fe11Stpoindex     }
10051067fe11Stpoindex     if( fgets(&zLine[n], nLine - n, in)==0 ){
10061067fe11Stpoindex       if( n==0 ){
10071067fe11Stpoindex         free(zLine);
10081067fe11Stpoindex         return 0;
10091067fe11Stpoindex       }
10101067fe11Stpoindex       zLine[n] = 0;
10111067fe11Stpoindex       eol = 1;
10121067fe11Stpoindex       break;
10131067fe11Stpoindex     }
10141067fe11Stpoindex     while( zLine[n] ){ n++; }
10151067fe11Stpoindex     if( n>0 && zLine[n-1]=='\n' ){
10161067fe11Stpoindex       n--;
10171067fe11Stpoindex       zLine[n] = 0;
10181067fe11Stpoindex       eol = 1;
10191067fe11Stpoindex     }
10201067fe11Stpoindex   }
10211067fe11Stpoindex   zLine = realloc( zLine, n+1 );
10221067fe11Stpoindex   return zLine;
10231067fe11Stpoindex }
10241067fe11Stpoindex 
10258e556520Sdanielk1977 
10268e556520Sdanielk1977 /*
10274a4c11aaSdan ** This function is part of the implementation of the command:
10288e556520Sdanielk1977 **
10294a4c11aaSdan **   $db transaction [-deferred|-immediate|-exclusive] SCRIPT
10308e556520Sdanielk1977 **
10314a4c11aaSdan ** It is invoked after evaluating the script SCRIPT to commit or rollback
10324a4c11aaSdan ** the transaction or savepoint opened by the [transaction] command.
10334a4c11aaSdan */
10344a4c11aaSdan static int DbTransPostCmd(
10354a4c11aaSdan   ClientData data[],                   /* data[0] is the Sqlite3Db* for $db */
10364a4c11aaSdan   Tcl_Interp *interp,                  /* Tcl interpreter */
10374a4c11aaSdan   int result                           /* Result of evaluating SCRIPT */
10384a4c11aaSdan ){
10394a4c11aaSdan   static const char *azEnd[] = {
10404a4c11aaSdan     "RELEASE _tcl_transaction",        /* rc==TCL_ERROR, nTransaction!=0 */
10414a4c11aaSdan     "COMMIT",                          /* rc!=TCL_ERROR, nTransaction==0 */
10424a4c11aaSdan     "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction",
10434a4c11aaSdan     "ROLLBACK"                         /* rc==TCL_ERROR, nTransaction==0 */
10444a4c11aaSdan   };
10454a4c11aaSdan   SqliteDb *pDb = (SqliteDb*)data[0];
10464a4c11aaSdan   int rc = result;
10474a4c11aaSdan   const char *zEnd;
10484a4c11aaSdan 
10494a4c11aaSdan   pDb->nTransaction--;
10504a4c11aaSdan   zEnd = azEnd[(rc==TCL_ERROR)*2 + (pDb->nTransaction==0)];
10514a4c11aaSdan 
10524a4c11aaSdan   pDb->disableAuth++;
10534a4c11aaSdan   if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){
10544a4c11aaSdan       /* This is a tricky scenario to handle. The most likely cause of an
10554a4c11aaSdan       ** error is that the exec() above was an attempt to commit the
10564a4c11aaSdan       ** top-level transaction that returned SQLITE_BUSY. Or, less likely,
10574a4c11aaSdan       ** that an IO-error has occured. In either case, throw a Tcl exception
10584a4c11aaSdan       ** and try to rollback the transaction.
10594a4c11aaSdan       **
10604a4c11aaSdan       ** But it could also be that the user executed one or more BEGIN,
10614a4c11aaSdan       ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing
10624a4c11aaSdan       ** this method's logic. Not clear how this would be best handled.
10634a4c11aaSdan       */
10644a4c11aaSdan     if( rc!=TCL_ERROR ){
10654a4c11aaSdan       Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
10664a4c11aaSdan       rc = TCL_ERROR;
10674a4c11aaSdan     }
10684a4c11aaSdan     sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
10694a4c11aaSdan   }
10704a4c11aaSdan   pDb->disableAuth--;
10714a4c11aaSdan 
10724a4c11aaSdan   return rc;
10734a4c11aaSdan }
10744a4c11aaSdan 
10754a4c11aaSdan /*
10764a4c11aaSdan ** Search the cache for a prepared-statement object that implements the
10774a4c11aaSdan ** first SQL statement in the buffer pointed to by parameter zIn. If
10784a4c11aaSdan ** no such prepared-statement can be found, allocate and prepare a new
10794a4c11aaSdan ** one. In either case, bind the current values of the relevant Tcl
10804a4c11aaSdan ** variables to any $var, :var or @var variables in the statement. Before
10814a4c11aaSdan ** returning, set *ppPreStmt to point to the prepared-statement object.
10824a4c11aaSdan **
10834a4c11aaSdan ** Output parameter *pzOut is set to point to the next SQL statement in
10844a4c11aaSdan ** buffer zIn, or to the '\0' byte at the end of zIn if there is no
10854a4c11aaSdan ** next statement.
10864a4c11aaSdan **
10874a4c11aaSdan ** If successful, TCL_OK is returned. Otherwise, TCL_ERROR is returned
10884a4c11aaSdan ** and an error message loaded into interpreter pDb->interp.
10894a4c11aaSdan */
10904a4c11aaSdan static int dbPrepareAndBind(
10914a4c11aaSdan   SqliteDb *pDb,                  /* Database object */
10924a4c11aaSdan   char const *zIn,                /* SQL to compile */
10934a4c11aaSdan   char const **pzOut,             /* OUT: Pointer to next SQL statement */
10944a4c11aaSdan   SqlPreparedStmt **ppPreStmt     /* OUT: Object used to cache statement */
10954a4c11aaSdan ){
10964a4c11aaSdan   const char *zSql = zIn;         /* Pointer to first SQL statement in zIn */
10974a4c11aaSdan   sqlite3_stmt *pStmt;            /* Prepared statement object */
10984a4c11aaSdan   SqlPreparedStmt *pPreStmt;      /* Pointer to cached statement */
10994a4c11aaSdan   int nSql;                       /* Length of zSql in bytes */
11004a4c11aaSdan   int nVar;                       /* Number of variables in statement */
11014a4c11aaSdan   int iParm = 0;                  /* Next free entry in apParm */
11024a4c11aaSdan   int i;
11034a4c11aaSdan   Tcl_Interp *interp = pDb->interp;
11044a4c11aaSdan 
11054a4c11aaSdan   *ppPreStmt = 0;
11064a4c11aaSdan 
11074a4c11aaSdan   /* Trim spaces from the start of zSql and calculate the remaining length. */
11084a4c11aaSdan   while( isspace(zSql[0]) ){ zSql++; }
11094a4c11aaSdan   nSql = strlen30(zSql);
11104a4c11aaSdan 
11114a4c11aaSdan   for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pPreStmt->pNext){
11124a4c11aaSdan     int n = pPreStmt->nSql;
11134a4c11aaSdan     if( nSql>=n
11144a4c11aaSdan         && memcmp(pPreStmt->zSql, zSql, n)==0
11154a4c11aaSdan         && (zSql[n]==0 || zSql[n-1]==';')
11164a4c11aaSdan     ){
11174a4c11aaSdan       pStmt = pPreStmt->pStmt;
11184a4c11aaSdan       *pzOut = &zSql[pPreStmt->nSql];
11194a4c11aaSdan 
11204a4c11aaSdan       /* When a prepared statement is found, unlink it from the
11214a4c11aaSdan       ** cache list.  It will later be added back to the beginning
11224a4c11aaSdan       ** of the cache list in order to implement LRU replacement.
11234a4c11aaSdan       */
11244a4c11aaSdan       if( pPreStmt->pPrev ){
11254a4c11aaSdan         pPreStmt->pPrev->pNext = pPreStmt->pNext;
11264a4c11aaSdan       }else{
11274a4c11aaSdan         pDb->stmtList = pPreStmt->pNext;
11284a4c11aaSdan       }
11294a4c11aaSdan       if( pPreStmt->pNext ){
11304a4c11aaSdan         pPreStmt->pNext->pPrev = pPreStmt->pPrev;
11314a4c11aaSdan       }else{
11324a4c11aaSdan         pDb->stmtLast = pPreStmt->pPrev;
11334a4c11aaSdan       }
11344a4c11aaSdan       pDb->nStmt--;
11354a4c11aaSdan       nVar = sqlite3_bind_parameter_count(pStmt);
11364a4c11aaSdan       break;
11374a4c11aaSdan     }
11384a4c11aaSdan   }
11394a4c11aaSdan 
11404a4c11aaSdan   /* If no prepared statement was found. Compile the SQL text. Also allocate
11414a4c11aaSdan   ** a new SqlPreparedStmt structure.  */
11424a4c11aaSdan   if( pPreStmt==0 ){
11434a4c11aaSdan     int nByte;
11444a4c11aaSdan 
11454a4c11aaSdan     if( SQLITE_OK!=sqlite3_prepare_v2(pDb->db, zSql, -1, &pStmt, pzOut) ){
11464a4c11aaSdan       Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
11474a4c11aaSdan       return TCL_ERROR;
11484a4c11aaSdan     }
11494a4c11aaSdan     if( pStmt==0 ){
11504a4c11aaSdan       if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
11514a4c11aaSdan         /* A compile-time error in the statement. */
11524a4c11aaSdan         Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
11534a4c11aaSdan         return TCL_ERROR;
11544a4c11aaSdan       }else{
11554a4c11aaSdan         /* The statement was a no-op.  Continue to the next statement
11564a4c11aaSdan         ** in the SQL string.
11574a4c11aaSdan         */
11584a4c11aaSdan         return TCL_OK;
11594a4c11aaSdan       }
11604a4c11aaSdan     }
11614a4c11aaSdan 
11624a4c11aaSdan     assert( pPreStmt==0 );
11634a4c11aaSdan     nVar = sqlite3_bind_parameter_count(pStmt);
11644a4c11aaSdan     nByte = sizeof(SqlPreparedStmt) + nVar*sizeof(Tcl_Obj *);
11654a4c11aaSdan     pPreStmt = (SqlPreparedStmt*)Tcl_Alloc(nByte);
11664a4c11aaSdan     memset(pPreStmt, 0, nByte);
11674a4c11aaSdan 
11684a4c11aaSdan     pPreStmt->pStmt = pStmt;
11694a4c11aaSdan     pPreStmt->nSql = (*pzOut - zSql);
11704a4c11aaSdan     pPreStmt->zSql = sqlite3_sql(pStmt);
11714a4c11aaSdan     pPreStmt->apParm = (Tcl_Obj **)&pPreStmt[1];
11724a4c11aaSdan   }
11734a4c11aaSdan   assert( pPreStmt );
11744a4c11aaSdan   assert( strlen30(pPreStmt->zSql)==pPreStmt->nSql );
11754a4c11aaSdan   assert( 0==memcmp(pPreStmt->zSql, zSql, pPreStmt->nSql) );
11764a4c11aaSdan 
11774a4c11aaSdan   /* Bind values to parameters that begin with $ or : */
11784a4c11aaSdan   for(i=1; i<=nVar; i++){
11794a4c11aaSdan     const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
11804a4c11aaSdan     if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){
11814a4c11aaSdan       Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
11824a4c11aaSdan       if( pVar ){
11834a4c11aaSdan         int n;
11844a4c11aaSdan         u8 *data;
11854a4c11aaSdan         const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
11864a4c11aaSdan         char c = zType[0];
11874a4c11aaSdan         if( zVar[0]=='@' ||
11884a4c11aaSdan            (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){
11894a4c11aaSdan           /* Load a BLOB type if the Tcl variable is a bytearray and
11904a4c11aaSdan           ** it has no string representation or the host
11914a4c11aaSdan           ** parameter name begins with "@". */
11924a4c11aaSdan           data = Tcl_GetByteArrayFromObj(pVar, &n);
11934a4c11aaSdan           sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
11944a4c11aaSdan           Tcl_IncrRefCount(pVar);
11954a4c11aaSdan           pPreStmt->apParm[iParm++] = pVar;
11964a4c11aaSdan         }else if( c=='b' && strcmp(zType,"boolean")==0 ){
11974a4c11aaSdan           Tcl_GetIntFromObj(interp, pVar, &n);
11984a4c11aaSdan           sqlite3_bind_int(pStmt, i, n);
11994a4c11aaSdan         }else if( c=='d' && strcmp(zType,"double")==0 ){
12004a4c11aaSdan           double r;
12014a4c11aaSdan           Tcl_GetDoubleFromObj(interp, pVar, &r);
12024a4c11aaSdan           sqlite3_bind_double(pStmt, i, r);
12034a4c11aaSdan         }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
12044a4c11aaSdan               (c=='i' && strcmp(zType,"int")==0) ){
12054a4c11aaSdan           Tcl_WideInt v;
12064a4c11aaSdan           Tcl_GetWideIntFromObj(interp, pVar, &v);
12074a4c11aaSdan           sqlite3_bind_int64(pStmt, i, v);
12084a4c11aaSdan         }else{
12094a4c11aaSdan           data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
12104a4c11aaSdan           sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
12114a4c11aaSdan           Tcl_IncrRefCount(pVar);
12124a4c11aaSdan           pPreStmt->apParm[iParm++] = pVar;
12134a4c11aaSdan         }
12144a4c11aaSdan       }else{
12154a4c11aaSdan         sqlite3_bind_null(pStmt, i);
12164a4c11aaSdan       }
12174a4c11aaSdan     }
12184a4c11aaSdan   }
12194a4c11aaSdan   pPreStmt->nParm = iParm;
12204a4c11aaSdan   *ppPreStmt = pPreStmt;
1221937d0deaSdan 
12224a4c11aaSdan   return TCL_OK;
12234a4c11aaSdan }
12244a4c11aaSdan 
12254a4c11aaSdan 
12264a4c11aaSdan /*
12274a4c11aaSdan ** Release a statement reference obtained by calling dbPrepareAndBind().
12284a4c11aaSdan ** There should be exactly one call to this function for each call to
12294a4c11aaSdan ** dbPrepareAndBind().
12304a4c11aaSdan **
12314a4c11aaSdan ** If the discard parameter is non-zero, then the statement is deleted
12324a4c11aaSdan ** immediately. Otherwise it is added to the LRU list and may be returned
12334a4c11aaSdan ** by a subsequent call to dbPrepareAndBind().
12344a4c11aaSdan */
12354a4c11aaSdan static void dbReleaseStmt(
12364a4c11aaSdan   SqliteDb *pDb,                  /* Database handle */
12374a4c11aaSdan   SqlPreparedStmt *pPreStmt,      /* Prepared statement handle to release */
12384a4c11aaSdan   int discard                     /* True to delete (not cache) the pPreStmt */
12394a4c11aaSdan ){
12404a4c11aaSdan   int i;
12414a4c11aaSdan 
12424a4c11aaSdan   /* Free the bound string and blob parameters */
12434a4c11aaSdan   for(i=0; i<pPreStmt->nParm; i++){
12444a4c11aaSdan     Tcl_DecrRefCount(pPreStmt->apParm[i]);
12454a4c11aaSdan   }
12464a4c11aaSdan   pPreStmt->nParm = 0;
12474a4c11aaSdan 
12484a4c11aaSdan   if( pDb->maxStmt<=0 || discard ){
12494a4c11aaSdan     /* If the cache is turned off, deallocated the statement */
12504a4c11aaSdan     sqlite3_finalize(pPreStmt->pStmt);
12514a4c11aaSdan     Tcl_Free((char *)pPreStmt);
12524a4c11aaSdan   }else{
12534a4c11aaSdan     /* Add the prepared statement to the beginning of the cache list. */
12544a4c11aaSdan     pPreStmt->pNext = pDb->stmtList;
12554a4c11aaSdan     pPreStmt->pPrev = 0;
12564a4c11aaSdan     if( pDb->stmtList ){
12574a4c11aaSdan      pDb->stmtList->pPrev = pPreStmt;
12584a4c11aaSdan     }
12594a4c11aaSdan     pDb->stmtList = pPreStmt;
12604a4c11aaSdan     if( pDb->stmtLast==0 ){
12614a4c11aaSdan       assert( pDb->nStmt==0 );
12624a4c11aaSdan       pDb->stmtLast = pPreStmt;
12634a4c11aaSdan     }else{
12644a4c11aaSdan       assert( pDb->nStmt>0 );
12654a4c11aaSdan     }
12664a4c11aaSdan     pDb->nStmt++;
12674a4c11aaSdan 
12684a4c11aaSdan     /* If we have too many statement in cache, remove the surplus from
12694a4c11aaSdan     ** the end of the cache list.  */
12704a4c11aaSdan     while( pDb->nStmt>pDb->maxStmt ){
12714a4c11aaSdan       sqlite3_finalize(pDb->stmtLast->pStmt);
12724a4c11aaSdan       pDb->stmtLast = pDb->stmtLast->pPrev;
12734a4c11aaSdan       Tcl_Free((char*)pDb->stmtLast->pNext);
12744a4c11aaSdan       pDb->stmtLast->pNext = 0;
12754a4c11aaSdan       pDb->nStmt--;
12764a4c11aaSdan     }
12774a4c11aaSdan   }
12784a4c11aaSdan }
12794a4c11aaSdan 
12804a4c11aaSdan /*
12814a4c11aaSdan ** Structure used with dbEvalXXX() functions:
12824a4c11aaSdan **
12834a4c11aaSdan **   dbEvalInit()
12844a4c11aaSdan **   dbEvalStep()
12854a4c11aaSdan **   dbEvalFinalize()
12864a4c11aaSdan **   dbEvalRowInfo()
12874a4c11aaSdan **   dbEvalColumnValue()
12884a4c11aaSdan */
12894a4c11aaSdan typedef struct DbEvalContext DbEvalContext;
12904a4c11aaSdan struct DbEvalContext {
12914a4c11aaSdan   SqliteDb *pDb;                  /* Database handle */
12924a4c11aaSdan   Tcl_Obj *pSql;                  /* Object holding string zSql */
12934a4c11aaSdan   const char *zSql;               /* Remaining SQL to execute */
12944a4c11aaSdan   SqlPreparedStmt *pPreStmt;      /* Current statement */
12954a4c11aaSdan   int nCol;                       /* Number of columns returned by pStmt */
12964a4c11aaSdan   Tcl_Obj *pArray;                /* Name of array variable */
12974a4c11aaSdan   Tcl_Obj **apColName;            /* Array of column names */
12984a4c11aaSdan };
12994a4c11aaSdan 
13004a4c11aaSdan /*
13014a4c11aaSdan ** Release any cache of column names currently held as part of
13024a4c11aaSdan ** the DbEvalContext structure passed as the first argument.
13034a4c11aaSdan */
13044a4c11aaSdan static void dbReleaseColumnNames(DbEvalContext *p){
13054a4c11aaSdan   if( p->apColName ){
13064a4c11aaSdan     int i;
13074a4c11aaSdan     for(i=0; i<p->nCol; i++){
13084a4c11aaSdan       Tcl_DecrRefCount(p->apColName[i]);
13094a4c11aaSdan     }
13104a4c11aaSdan     Tcl_Free((char *)p->apColName);
13114a4c11aaSdan     p->apColName = 0;
13124a4c11aaSdan   }
13134a4c11aaSdan   p->nCol = 0;
13144a4c11aaSdan }
13154a4c11aaSdan 
13164a4c11aaSdan /*
13174a4c11aaSdan ** Initialize a DbEvalContext structure.
13188e556520Sdanielk1977 **
13198e556520Sdanielk1977 ** If pArray is not NULL, then it contains the name of a Tcl array
13208e556520Sdanielk1977 ** variable. The "*" member of this array is set to a list containing
13214a4c11aaSdan ** the names of the columns returned by the statement as part of each
13224a4c11aaSdan ** call to dbEvalStep(), in order from left to right. e.g. if the names
13234a4c11aaSdan ** of the returned columns are a, b and c, it does the equivalent of the
13244a4c11aaSdan ** tcl command:
13258e556520Sdanielk1977 **
13268e556520Sdanielk1977 **     set ${pArray}(*) {a b c}
13278e556520Sdanielk1977 */
13284a4c11aaSdan static void dbEvalInit(
13294a4c11aaSdan   DbEvalContext *p,               /* Pointer to structure to initialize */
13304a4c11aaSdan   SqliteDb *pDb,                  /* Database handle */
13314a4c11aaSdan   Tcl_Obj *pSql,                  /* Object containing SQL script */
13324a4c11aaSdan   Tcl_Obj *pArray                 /* Name of Tcl array to set (*) element of */
13338e556520Sdanielk1977 ){
13344a4c11aaSdan   memset(p, 0, sizeof(DbEvalContext));
13354a4c11aaSdan   p->pDb = pDb;
13364a4c11aaSdan   p->zSql = Tcl_GetString(pSql);
13374a4c11aaSdan   p->pSql = pSql;
13384a4c11aaSdan   Tcl_IncrRefCount(pSql);
13394a4c11aaSdan   if( pArray ){
13404a4c11aaSdan     p->pArray = pArray;
13414a4c11aaSdan     Tcl_IncrRefCount(pArray);
13424a4c11aaSdan   }
13434a4c11aaSdan }
13448e556520Sdanielk1977 
13454a4c11aaSdan /*
13464a4c11aaSdan ** Obtain information about the row that the DbEvalContext passed as the
13474a4c11aaSdan ** first argument currently points to.
13484a4c11aaSdan */
13494a4c11aaSdan static void dbEvalRowInfo(
13504a4c11aaSdan   DbEvalContext *p,               /* Evaluation context */
13514a4c11aaSdan   int *pnCol,                     /* OUT: Number of column names */
13524a4c11aaSdan   Tcl_Obj ***papColName           /* OUT: Array of column names */
13534a4c11aaSdan ){
13548e556520Sdanielk1977   /* Compute column names */
13554a4c11aaSdan   if( 0==p->apColName ){
13564a4c11aaSdan     sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
13574a4c11aaSdan     int i;                        /* Iterator variable */
13584a4c11aaSdan     int nCol;                     /* Number of columns returned by pStmt */
13594a4c11aaSdan     Tcl_Obj **apColName = 0;      /* Array of column names */
13604a4c11aaSdan 
13614a4c11aaSdan     p->nCol = nCol = sqlite3_column_count(pStmt);
13624a4c11aaSdan     if( nCol>0 && (papColName || p->pArray) ){
13634a4c11aaSdan       apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
13648e556520Sdanielk1977       for(i=0; i<nCol; i++){
13658e556520Sdanielk1977         apColName[i] = dbTextToObj(sqlite3_column_name(pStmt,i));
13668e556520Sdanielk1977         Tcl_IncrRefCount(apColName[i]);
13678e556520Sdanielk1977       }
13684a4c11aaSdan       p->apColName = apColName;
13694a4c11aaSdan     }
13708e556520Sdanielk1977 
13718e556520Sdanielk1977     /* If results are being stored in an array variable, then create
13728e556520Sdanielk1977     ** the array(*) entry for that array
13738e556520Sdanielk1977     */
13744a4c11aaSdan     if( p->pArray ){
13754a4c11aaSdan       Tcl_Interp *interp = p->pDb->interp;
13768e556520Sdanielk1977       Tcl_Obj *pColList = Tcl_NewObj();
13778e556520Sdanielk1977       Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
13784a4c11aaSdan 
13798e556520Sdanielk1977       for(i=0; i<nCol; i++){
13808e556520Sdanielk1977         Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
13818e556520Sdanielk1977       }
13828e556520Sdanielk1977       Tcl_IncrRefCount(pStar);
13834a4c11aaSdan       Tcl_ObjSetVar2(interp, p->pArray, pStar, pColList, 0);
13848e556520Sdanielk1977       Tcl_DecrRefCount(pStar);
13858e556520Sdanielk1977     }
13868e556520Sdanielk1977   }
13878e556520Sdanielk1977 
13884a4c11aaSdan   if( papColName ){
13894a4c11aaSdan     *papColName = p->apColName;
13904a4c11aaSdan   }
13914a4c11aaSdan   if( pnCol ){
13924a4c11aaSdan     *pnCol = p->nCol;
13934a4c11aaSdan   }
13944a4c11aaSdan }
13954a4c11aaSdan 
13964a4c11aaSdan /*
13974a4c11aaSdan ** Return one of TCL_OK, TCL_BREAK or TCL_ERROR. If TCL_ERROR is
13984a4c11aaSdan ** returned, then an error message is stored in the interpreter before
13994a4c11aaSdan ** returning.
14004a4c11aaSdan **
14014a4c11aaSdan ** A return value of TCL_OK means there is a row of data available. The
14024a4c11aaSdan ** data may be accessed using dbEvalRowInfo() and dbEvalColumnValue(). This
14034a4c11aaSdan ** is analogous to a return of SQLITE_ROW from sqlite3_step(). If TCL_BREAK
14044a4c11aaSdan ** is returned, then the SQL script has finished executing and there are
14054a4c11aaSdan ** no further rows available. This is similar to SQLITE_DONE.
14064a4c11aaSdan */
14074a4c11aaSdan static int dbEvalStep(DbEvalContext *p){
14084a4c11aaSdan   while( p->zSql[0] || p->pPreStmt ){
14094a4c11aaSdan     int rc;
14104a4c11aaSdan     if( p->pPreStmt==0 ){
14114a4c11aaSdan       rc = dbPrepareAndBind(p->pDb, p->zSql, &p->zSql, &p->pPreStmt);
14124a4c11aaSdan       if( rc!=TCL_OK ) return rc;
14134a4c11aaSdan     }else{
14144a4c11aaSdan       int rcs;
14154a4c11aaSdan       SqliteDb *pDb = p->pDb;
14164a4c11aaSdan       SqlPreparedStmt *pPreStmt = p->pPreStmt;
14174a4c11aaSdan       sqlite3_stmt *pStmt = pPreStmt->pStmt;
14184a4c11aaSdan 
14194a4c11aaSdan       rcs = sqlite3_step(pStmt);
14204a4c11aaSdan       if( rcs==SQLITE_ROW ){
14214a4c11aaSdan         return TCL_OK;
14224a4c11aaSdan       }
14234a4c11aaSdan       if( p->pArray ){
14244a4c11aaSdan         dbEvalRowInfo(p, 0, 0);
14254a4c11aaSdan       }
14264a4c11aaSdan       rcs = sqlite3_reset(pStmt);
14274a4c11aaSdan 
14284a4c11aaSdan       pDb->nStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_FULLSCAN_STEP,1);
14294a4c11aaSdan       pDb->nSort = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_SORT,1);
14303c379b01Sdrh       pDb->nIndex = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_AUTOINDEX,1);
14314a4c11aaSdan       dbReleaseColumnNames(p);
14324a4c11aaSdan       p->pPreStmt = 0;
14334a4c11aaSdan 
14344a4c11aaSdan       if( rcs!=SQLITE_OK ){
14354a4c11aaSdan         /* If a run-time error occurs, report the error and stop reading
14364a4c11aaSdan         ** the SQL.  */
14374a4c11aaSdan         Tcl_SetObjResult(pDb->interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
14384a4c11aaSdan         dbReleaseStmt(pDb, pPreStmt, 1);
14394a4c11aaSdan         return TCL_ERROR;
14404a4c11aaSdan       }else{
14414a4c11aaSdan         dbReleaseStmt(pDb, pPreStmt, 0);
14424a4c11aaSdan       }
14434a4c11aaSdan     }
14444a4c11aaSdan   }
14454a4c11aaSdan 
14464a4c11aaSdan   /* Finished */
14474a4c11aaSdan   return TCL_BREAK;
14484a4c11aaSdan }
14494a4c11aaSdan 
14504a4c11aaSdan /*
14514a4c11aaSdan ** Free all resources currently held by the DbEvalContext structure passed
14524a4c11aaSdan ** as the first argument. There should be exactly one call to this function
14534a4c11aaSdan ** for each call to dbEvalInit().
14544a4c11aaSdan */
14554a4c11aaSdan static void dbEvalFinalize(DbEvalContext *p){
14564a4c11aaSdan   if( p->pPreStmt ){
14574a4c11aaSdan     sqlite3_reset(p->pPreStmt->pStmt);
14584a4c11aaSdan     dbReleaseStmt(p->pDb, p->pPreStmt, 0);
14594a4c11aaSdan     p->pPreStmt = 0;
14604a4c11aaSdan   }
14614a4c11aaSdan   if( p->pArray ){
14624a4c11aaSdan     Tcl_DecrRefCount(p->pArray);
14634a4c11aaSdan     p->pArray = 0;
14644a4c11aaSdan   }
14654a4c11aaSdan   Tcl_DecrRefCount(p->pSql);
14664a4c11aaSdan   dbReleaseColumnNames(p);
14674a4c11aaSdan }
14684a4c11aaSdan 
14694a4c11aaSdan /*
14704a4c11aaSdan ** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains
14714a4c11aaSdan ** the value for the iCol'th column of the row currently pointed to by
14724a4c11aaSdan ** the DbEvalContext structure passed as the first argument.
14734a4c11aaSdan */
14744a4c11aaSdan static Tcl_Obj *dbEvalColumnValue(DbEvalContext *p, int iCol){
14754a4c11aaSdan   sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
14764a4c11aaSdan   switch( sqlite3_column_type(pStmt, iCol) ){
14774a4c11aaSdan     case SQLITE_BLOB: {
14784a4c11aaSdan       int bytes = sqlite3_column_bytes(pStmt, iCol);
14794a4c11aaSdan       const char *zBlob = sqlite3_column_blob(pStmt, iCol);
14804a4c11aaSdan       if( !zBlob ) bytes = 0;
14814a4c11aaSdan       return Tcl_NewByteArrayObj((u8*)zBlob, bytes);
14824a4c11aaSdan     }
14834a4c11aaSdan     case SQLITE_INTEGER: {
14844a4c11aaSdan       sqlite_int64 v = sqlite3_column_int64(pStmt, iCol);
14854a4c11aaSdan       if( v>=-2147483647 && v<=2147483647 ){
14864a4c11aaSdan         return Tcl_NewIntObj(v);
14874a4c11aaSdan       }else{
14884a4c11aaSdan         return Tcl_NewWideIntObj(v);
14894a4c11aaSdan       }
14904a4c11aaSdan     }
14914a4c11aaSdan     case SQLITE_FLOAT: {
14924a4c11aaSdan       return Tcl_NewDoubleObj(sqlite3_column_double(pStmt, iCol));
14934a4c11aaSdan     }
14944a4c11aaSdan     case SQLITE_NULL: {
14954a4c11aaSdan       return dbTextToObj(p->pDb->zNull);
14964a4c11aaSdan     }
14974a4c11aaSdan   }
14984a4c11aaSdan 
14994a4c11aaSdan   return dbTextToObj((char *)sqlite3_column_text(pStmt, iCol));
15004a4c11aaSdan }
15014a4c11aaSdan 
15024a4c11aaSdan /*
15034a4c11aaSdan ** If using Tcl version 8.6 or greater, use the NR functions to avoid
15044a4c11aaSdan ** recursive evalution of scripts by the [db eval] and [db trans]
15054a4c11aaSdan ** commands. Even if the headers used while compiling the extension
15064a4c11aaSdan ** are 8.6 or newer, the code still tests the Tcl version at runtime.
15074a4c11aaSdan ** This allows stubs-enabled builds to be used with older Tcl libraries.
15084a4c11aaSdan */
15094a4c11aaSdan #if TCL_MAJOR_VERSION>8 || (TCL_MAJOR_VERSION==8 && TCL_MINOR_VERSION>=6)
1510a2c8a95bSdrh # define SQLITE_TCL_NRE 1
15114a4c11aaSdan static int DbUseNre(void){
15124a4c11aaSdan   int major, minor;
15134a4c11aaSdan   Tcl_GetVersion(&major, &minor, 0, 0);
15144a4c11aaSdan   return( (major==8 && minor>=6) || major>8 );
15154a4c11aaSdan }
15164a4c11aaSdan #else
15174a4c11aaSdan /*
15184a4c11aaSdan ** Compiling using headers earlier than 8.6. In this case NR cannot be
15194a4c11aaSdan ** used, so DbUseNre() to always return zero. Add #defines for the other
15204a4c11aaSdan ** Tcl_NRxxx() functions to prevent them from causing compilation errors,
15214a4c11aaSdan ** even though the only invocations of them are within conditional blocks
15224a4c11aaSdan ** of the form:
15234a4c11aaSdan **
15244a4c11aaSdan **   if( DbUseNre() ) { ... }
15254a4c11aaSdan */
1526a2c8a95bSdrh # define SQLITE_TCL_NRE 0
15274a4c11aaSdan # define DbUseNre() 0
15284a4c11aaSdan # define Tcl_NRAddCallback(a,b,c,d,e,f) 0
15294a4c11aaSdan # define Tcl_NREvalObj(a,b,c) 0
15304a4c11aaSdan # define Tcl_NRCreateCommand(a,b,c,d,e,f) 0
15314a4c11aaSdan #endif
15324a4c11aaSdan 
15334a4c11aaSdan /*
15344a4c11aaSdan ** This function is part of the implementation of the command:
15354a4c11aaSdan **
15364a4c11aaSdan **   $db eval SQL ?ARRAYNAME? SCRIPT
15374a4c11aaSdan */
15384a4c11aaSdan static int DbEvalNextCmd(
15394a4c11aaSdan   ClientData data[],                   /* data[0] is the (DbEvalContext*) */
15404a4c11aaSdan   Tcl_Interp *interp,                  /* Tcl interpreter */
15414a4c11aaSdan   int result                           /* Result so far */
15424a4c11aaSdan ){
15434a4c11aaSdan   int rc = result;                     /* Return code */
15444a4c11aaSdan 
15454a4c11aaSdan   /* The first element of the data[] array is a pointer to a DbEvalContext
15464a4c11aaSdan   ** structure allocated using Tcl_Alloc(). The second element of data[]
15474a4c11aaSdan   ** is a pointer to a Tcl_Obj containing the script to run for each row
15484a4c11aaSdan   ** returned by the queries encapsulated in data[0]. */
15494a4c11aaSdan   DbEvalContext *p = (DbEvalContext *)data[0];
15504a4c11aaSdan   Tcl_Obj *pScript = (Tcl_Obj *)data[1];
15514a4c11aaSdan   Tcl_Obj *pArray = p->pArray;
15524a4c11aaSdan 
15534a4c11aaSdan   while( (rc==TCL_OK || rc==TCL_CONTINUE) && TCL_OK==(rc = dbEvalStep(p)) ){
15544a4c11aaSdan     int i;
15554a4c11aaSdan     int nCol;
15564a4c11aaSdan     Tcl_Obj **apColName;
15574a4c11aaSdan     dbEvalRowInfo(p, &nCol, &apColName);
15584a4c11aaSdan     for(i=0; i<nCol; i++){
15594a4c11aaSdan       Tcl_Obj *pVal = dbEvalColumnValue(p, i);
15604a4c11aaSdan       if( pArray==0 ){
15614a4c11aaSdan         Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
15624a4c11aaSdan       }else{
15634a4c11aaSdan         Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
15644a4c11aaSdan       }
15654a4c11aaSdan     }
15664a4c11aaSdan 
15674a4c11aaSdan     /* The required interpreter variables are now populated with the data
15684a4c11aaSdan     ** from the current row. If using NRE, schedule callbacks to evaluate
15694a4c11aaSdan     ** script pScript, then to invoke this function again to fetch the next
15704a4c11aaSdan     ** row (or clean up if there is no next row or the script throws an
15714a4c11aaSdan     ** exception). After scheduling the callbacks, return control to the
15724a4c11aaSdan     ** caller.
15734a4c11aaSdan     **
15744a4c11aaSdan     ** If not using NRE, evaluate pScript directly and continue with the
15754a4c11aaSdan     ** next iteration of this while(...) loop.  */
15764a4c11aaSdan     if( DbUseNre() ){
15774a4c11aaSdan       Tcl_NRAddCallback(interp, DbEvalNextCmd, (void*)p, (void*)pScript, 0, 0);
15784a4c11aaSdan       return Tcl_NREvalObj(interp, pScript, 0);
15794a4c11aaSdan     }else{
15804a4c11aaSdan       rc = Tcl_EvalObjEx(interp, pScript, 0);
15814a4c11aaSdan     }
15824a4c11aaSdan   }
15834a4c11aaSdan 
15844a4c11aaSdan   Tcl_DecrRefCount(pScript);
15854a4c11aaSdan   dbEvalFinalize(p);
15864a4c11aaSdan   Tcl_Free((char *)p);
15874a4c11aaSdan 
15884a4c11aaSdan   if( rc==TCL_OK || rc==TCL_BREAK ){
15894a4c11aaSdan     Tcl_ResetResult(interp);
15904a4c11aaSdan     rc = TCL_OK;
15914a4c11aaSdan   }
15924a4c11aaSdan   return rc;
15938e556520Sdanielk1977 }
15948e556520Sdanielk1977 
15951067fe11Stpoindex /*
159646c47d46Sdan ** This function is used by the implementations of the following database
159746c47d46Sdan ** handle sub-commands:
159846c47d46Sdan **
159946c47d46Sdan **   $db update_hook ?SCRIPT?
160046c47d46Sdan **   $db wal_hook ?SCRIPT?
160146c47d46Sdan **   $db commit_hook ?SCRIPT?
160246c47d46Sdan **   $db preupdate hook ?SCRIPT?
160346c47d46Sdan */
160446c47d46Sdan static void DbHookCmd(
160546c47d46Sdan   Tcl_Interp *interp,             /* Tcl interpreter */
160646c47d46Sdan   SqliteDb *pDb,                  /* Database handle */
160746c47d46Sdan   Tcl_Obj *pArg,                  /* SCRIPT argument (or NULL) */
160846c47d46Sdan   Tcl_Obj **ppHook                /* Pointer to member of SqliteDb */
160946c47d46Sdan ){
161046c47d46Sdan   sqlite3 *db = pDb->db;
161146c47d46Sdan 
161246c47d46Sdan   if( *ppHook ){
161346c47d46Sdan     Tcl_SetObjResult(interp, *ppHook);
161446c47d46Sdan     if( pArg ){
161546c47d46Sdan       Tcl_DecrRefCount(*ppHook);
161646c47d46Sdan       *ppHook = 0;
161746c47d46Sdan     }
161846c47d46Sdan   }
161946c47d46Sdan   if( pArg ){
162046c47d46Sdan     assert( !(*ppHook) );
162146c47d46Sdan     if( Tcl_GetCharLength(pArg)>0 ){
162246c47d46Sdan       *ppHook = pArg;
162346c47d46Sdan       Tcl_IncrRefCount(*ppHook);
162446c47d46Sdan     }
162546c47d46Sdan   }
162646c47d46Sdan 
162746c47d46Sdan   sqlite3_preupdate_hook(db, (pDb->pPreUpdateHook?DbPreUpdateHandler:0), pDb);
162846c47d46Sdan   sqlite3_update_hook(db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
162946c47d46Sdan   sqlite3_rollback_hook(db, (pDb->pRollbackHook?DbRollbackHandler:0), pDb);
163046c47d46Sdan   sqlite3_wal_hook(db, (pDb->pWalHook?DbWalHandler:0), pDb);
163146c47d46Sdan }
163246c47d46Sdan 
163346c47d46Sdan /*
163475897234Sdrh ** The "sqlite" command below creates a new Tcl command for each
163575897234Sdrh ** connection it opens to an SQLite database.  This routine is invoked
163675897234Sdrh ** whenever one of those connection-specific commands is executed
163775897234Sdrh ** in Tcl.  For example, if you run Tcl code like this:
163875897234Sdrh **
16399bb575fdSdrh **       sqlite3 db1  "my_database"
164075897234Sdrh **       db1 close
164175897234Sdrh **
164275897234Sdrh ** The first command opens a connection to the "my_database" database
164375897234Sdrh ** and calls that connection "db1".  The second command causes this
164475897234Sdrh ** subroutine to be invoked.
164575897234Sdrh */
16466d31316cSdrh static int DbObjCmd(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
1647bec3f402Sdrh   SqliteDb *pDb = (SqliteDb*)cd;
16486d31316cSdrh   int choice;
164922fbcb8dSdrh   int rc = TCL_OK;
16500de8c112Sdrh   static const char *DB_strs[] = {
1651dc2c4915Sdrh     "authorizer",         "backup",            "busy",
1652dc2c4915Sdrh     "cache",              "changes",           "close",
1653dc2c4915Sdrh     "collate",            "collation_needed",  "commit_hook",
1654dc2c4915Sdrh     "complete",           "copy",              "enable_load_extension",
1655dc2c4915Sdrh     "errorcode",          "eval",              "exists",
1656dc2c4915Sdrh     "function",           "incrblob",          "interrupt",
1657833bf968Sdrh     "last_insert_rowid",  "nullvalue",         "onecolumn",
165846c47d46Sdan     "preupdate",
1659833bf968Sdrh     "profile",            "progress",          "rekey",
1660833bf968Sdrh     "restore",            "rollback_hook",     "status",
1661833bf968Sdrh     "timeout",            "total_changes",     "trace",
16626566ebe1Sdan     "transaction",        "unlock_notify",     "update_hook",
1663833bf968Sdrh     "version",            "wal_hook",          0
16646d31316cSdrh   };
1665411995dcSdrh   enum DB_enum {
1666dc2c4915Sdrh     DB_AUTHORIZER,        DB_BACKUP,           DB_BUSY,
1667dc2c4915Sdrh     DB_CACHE,             DB_CHANGES,          DB_CLOSE,
1668dc2c4915Sdrh     DB_COLLATE,           DB_COLLATION_NEEDED, DB_COMMIT_HOOK,
1669dc2c4915Sdrh     DB_COMPLETE,          DB_COPY,             DB_ENABLE_LOAD_EXTENSION,
1670dc2c4915Sdrh     DB_ERRORCODE,         DB_EVAL,             DB_EXISTS,
1671dc2c4915Sdrh     DB_FUNCTION,          DB_INCRBLOB,         DB_INTERRUPT,
1672833bf968Sdrh     DB_LAST_INSERT_ROWID, DB_NULLVALUE,        DB_ONECOLUMN,
167346c47d46Sdan     DB_PREUPDATE,
1674833bf968Sdrh     DB_PROFILE,           DB_PROGRESS,         DB_REKEY,
1675833bf968Sdrh     DB_RESTORE,           DB_ROLLBACK_HOOK,    DB_STATUS,
1676833bf968Sdrh     DB_TIMEOUT,           DB_TOTAL_CHANGES,    DB_TRACE,
16776566ebe1Sdan     DB_TRANSACTION,       DB_UNLOCK_NOTIFY,    DB_UPDATE_HOOK,
1678833bf968Sdrh     DB_VERSION,           DB_WAL_HOOK
16796d31316cSdrh   };
16801067fe11Stpoindex   /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
16816d31316cSdrh 
16826d31316cSdrh   if( objc<2 ){
16836d31316cSdrh     Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
168475897234Sdrh     return TCL_ERROR;
168575897234Sdrh   }
1686411995dcSdrh   if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
16876d31316cSdrh     return TCL_ERROR;
16886d31316cSdrh   }
16896d31316cSdrh 
1690411995dcSdrh   switch( (enum DB_enum)choice ){
169175897234Sdrh 
1692e22a334bSdrh   /*    $db authorizer ?CALLBACK?
1693e22a334bSdrh   **
1694e22a334bSdrh   ** Invoke the given callback to authorize each SQL operation as it is
1695e22a334bSdrh   ** compiled.  5 arguments are appended to the callback before it is
1696e22a334bSdrh   ** invoked:
1697e22a334bSdrh   **
1698e22a334bSdrh   **   (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
1699e22a334bSdrh   **   (2) First descriptive name (depends on authorization type)
1700e22a334bSdrh   **   (3) Second descriptive name
1701e22a334bSdrh   **   (4) Name of the database (ex: "main", "temp")
1702e22a334bSdrh   **   (5) Name of trigger that is doing the access
1703e22a334bSdrh   **
1704e22a334bSdrh   ** The callback should return on of the following strings: SQLITE_OK,
1705e22a334bSdrh   ** SQLITE_IGNORE, or SQLITE_DENY.  Any other return value is an error.
1706e22a334bSdrh   **
1707e22a334bSdrh   ** If this method is invoked with no arguments, the current authorization
1708e22a334bSdrh   ** callback string is returned.
1709e22a334bSdrh   */
1710e22a334bSdrh   case DB_AUTHORIZER: {
17111211de37Sdrh #ifdef SQLITE_OMIT_AUTHORIZATION
17121211de37Sdrh     Tcl_AppendResult(interp, "authorization not available in this build", 0);
17131211de37Sdrh     return TCL_ERROR;
17141211de37Sdrh #else
1715e22a334bSdrh     if( objc>3 ){
1716e22a334bSdrh       Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
17170f14e2ebSdrh       return TCL_ERROR;
1718e22a334bSdrh     }else if( objc==2 ){
1719b5a20d3cSdrh       if( pDb->zAuth ){
1720e22a334bSdrh         Tcl_AppendResult(interp, pDb->zAuth, 0);
1721e22a334bSdrh       }
1722e22a334bSdrh     }else{
1723e22a334bSdrh       char *zAuth;
1724e22a334bSdrh       int len;
1725e22a334bSdrh       if( pDb->zAuth ){
1726e22a334bSdrh         Tcl_Free(pDb->zAuth);
1727e22a334bSdrh       }
1728e22a334bSdrh       zAuth = Tcl_GetStringFromObj(objv[2], &len);
1729e22a334bSdrh       if( zAuth && len>0 ){
1730e22a334bSdrh         pDb->zAuth = Tcl_Alloc( len + 1 );
17315bb3eb9bSdrh         memcpy(pDb->zAuth, zAuth, len+1);
1732e22a334bSdrh       }else{
1733e22a334bSdrh         pDb->zAuth = 0;
1734e22a334bSdrh       }
1735e22a334bSdrh       if( pDb->zAuth ){
1736e22a334bSdrh         pDb->interp = interp;
17376f8a503dSdanielk1977         sqlite3_set_authorizer(pDb->db, auth_callback, pDb);
1738e22a334bSdrh       }else{
17396f8a503dSdanielk1977         sqlite3_set_authorizer(pDb->db, 0, 0);
1740e22a334bSdrh       }
1741e22a334bSdrh     }
17421211de37Sdrh #endif
1743e22a334bSdrh     break;
1744e22a334bSdrh   }
1745e22a334bSdrh 
1746dc2c4915Sdrh   /*    $db backup ?DATABASE? FILENAME
1747dc2c4915Sdrh   **
1748dc2c4915Sdrh   ** Open or create a database file named FILENAME.  Transfer the
1749dc2c4915Sdrh   ** content of local database DATABASE (default: "main") into the
1750dc2c4915Sdrh   ** FILENAME database.
1751dc2c4915Sdrh   */
1752dc2c4915Sdrh   case DB_BACKUP: {
1753dc2c4915Sdrh     const char *zDestFile;
1754dc2c4915Sdrh     const char *zSrcDb;
1755dc2c4915Sdrh     sqlite3 *pDest;
1756dc2c4915Sdrh     sqlite3_backup *pBackup;
1757dc2c4915Sdrh 
1758dc2c4915Sdrh     if( objc==3 ){
1759dc2c4915Sdrh       zSrcDb = "main";
1760dc2c4915Sdrh       zDestFile = Tcl_GetString(objv[2]);
1761dc2c4915Sdrh     }else if( objc==4 ){
1762dc2c4915Sdrh       zSrcDb = Tcl_GetString(objv[2]);
1763dc2c4915Sdrh       zDestFile = Tcl_GetString(objv[3]);
1764dc2c4915Sdrh     }else{
1765dc2c4915Sdrh       Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
1766dc2c4915Sdrh       return TCL_ERROR;
1767dc2c4915Sdrh     }
1768dc2c4915Sdrh     rc = sqlite3_open(zDestFile, &pDest);
1769dc2c4915Sdrh     if( rc!=SQLITE_OK ){
1770dc2c4915Sdrh       Tcl_AppendResult(interp, "cannot open target database: ",
1771dc2c4915Sdrh            sqlite3_errmsg(pDest), (char*)0);
1772dc2c4915Sdrh       sqlite3_close(pDest);
1773dc2c4915Sdrh       return TCL_ERROR;
1774dc2c4915Sdrh     }
1775dc2c4915Sdrh     pBackup = sqlite3_backup_init(pDest, "main", pDb->db, zSrcDb);
1776dc2c4915Sdrh     if( pBackup==0 ){
1777dc2c4915Sdrh       Tcl_AppendResult(interp, "backup failed: ",
1778dc2c4915Sdrh            sqlite3_errmsg(pDest), (char*)0);
1779dc2c4915Sdrh       sqlite3_close(pDest);
1780dc2c4915Sdrh       return TCL_ERROR;
1781dc2c4915Sdrh     }
1782dc2c4915Sdrh     while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
1783dc2c4915Sdrh     sqlite3_backup_finish(pBackup);
1784dc2c4915Sdrh     if( rc==SQLITE_DONE ){
1785dc2c4915Sdrh       rc = TCL_OK;
1786dc2c4915Sdrh     }else{
1787dc2c4915Sdrh       Tcl_AppendResult(interp, "backup failed: ",
1788dc2c4915Sdrh            sqlite3_errmsg(pDest), (char*)0);
1789dc2c4915Sdrh       rc = TCL_ERROR;
1790dc2c4915Sdrh     }
1791dc2c4915Sdrh     sqlite3_close(pDest);
1792dc2c4915Sdrh     break;
1793dc2c4915Sdrh   }
1794dc2c4915Sdrh 
1795bec3f402Sdrh   /*    $db busy ?CALLBACK?
1796bec3f402Sdrh   **
1797bec3f402Sdrh   ** Invoke the given callback if an SQL statement attempts to open
1798bec3f402Sdrh   ** a locked database file.
1799bec3f402Sdrh   */
18006d31316cSdrh   case DB_BUSY: {
18016d31316cSdrh     if( objc>3 ){
18026d31316cSdrh       Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
1803bec3f402Sdrh       return TCL_ERROR;
18046d31316cSdrh     }else if( objc==2 ){
1805bec3f402Sdrh       if( pDb->zBusy ){
1806bec3f402Sdrh         Tcl_AppendResult(interp, pDb->zBusy, 0);
1807bec3f402Sdrh       }
1808bec3f402Sdrh     }else{
18096d31316cSdrh       char *zBusy;
18106d31316cSdrh       int len;
1811bec3f402Sdrh       if( pDb->zBusy ){
1812bec3f402Sdrh         Tcl_Free(pDb->zBusy);
18136d31316cSdrh       }
18146d31316cSdrh       zBusy = Tcl_GetStringFromObj(objv[2], &len);
18156d31316cSdrh       if( zBusy && len>0 ){
18166d31316cSdrh         pDb->zBusy = Tcl_Alloc( len + 1 );
18175bb3eb9bSdrh         memcpy(pDb->zBusy, zBusy, len+1);
18186d31316cSdrh       }else{
1819bec3f402Sdrh         pDb->zBusy = 0;
1820bec3f402Sdrh       }
1821bec3f402Sdrh       if( pDb->zBusy ){
1822bec3f402Sdrh         pDb->interp = interp;
18236f8a503dSdanielk1977         sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
18246d31316cSdrh       }else{
18256f8a503dSdanielk1977         sqlite3_busy_handler(pDb->db, 0, 0);
1826bec3f402Sdrh       }
1827bec3f402Sdrh     }
18286d31316cSdrh     break;
18296d31316cSdrh   }
1830bec3f402Sdrh 
1831fb7e7651Sdrh   /*     $db cache flush
1832fb7e7651Sdrh   **     $db cache size n
1833fb7e7651Sdrh   **
1834fb7e7651Sdrh   ** Flush the prepared statement cache, or set the maximum number of
1835fb7e7651Sdrh   ** cached statements.
1836fb7e7651Sdrh   */
1837fb7e7651Sdrh   case DB_CACHE: {
1838fb7e7651Sdrh     char *subCmd;
1839fb7e7651Sdrh     int n;
1840fb7e7651Sdrh 
1841fb7e7651Sdrh     if( objc<=2 ){
1842fb7e7651Sdrh       Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
1843fb7e7651Sdrh       return TCL_ERROR;
1844fb7e7651Sdrh     }
1845fb7e7651Sdrh     subCmd = Tcl_GetStringFromObj( objv[2], 0 );
1846fb7e7651Sdrh     if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
1847fb7e7651Sdrh       if( objc!=3 ){
1848fb7e7651Sdrh         Tcl_WrongNumArgs(interp, 2, objv, "flush");
1849fb7e7651Sdrh         return TCL_ERROR;
1850fb7e7651Sdrh       }else{
1851fb7e7651Sdrh         flushStmtCache( pDb );
1852fb7e7651Sdrh       }
1853fb7e7651Sdrh     }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
1854fb7e7651Sdrh       if( objc!=4 ){
1855fb7e7651Sdrh         Tcl_WrongNumArgs(interp, 2, objv, "size n");
1856fb7e7651Sdrh         return TCL_ERROR;
1857fb7e7651Sdrh       }else{
1858fb7e7651Sdrh         if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
1859fb7e7651Sdrh           Tcl_AppendResult( interp, "cannot convert \"",
1860fb7e7651Sdrh                Tcl_GetStringFromObj(objv[3],0), "\" to integer", 0);
1861fb7e7651Sdrh           return TCL_ERROR;
1862fb7e7651Sdrh         }else{
1863fb7e7651Sdrh           if( n<0 ){
1864fb7e7651Sdrh             flushStmtCache( pDb );
1865fb7e7651Sdrh             n = 0;
1866fb7e7651Sdrh           }else if( n>MAX_PREPARED_STMTS ){
1867fb7e7651Sdrh             n = MAX_PREPARED_STMTS;
1868fb7e7651Sdrh           }
1869fb7e7651Sdrh           pDb->maxStmt = n;
1870fb7e7651Sdrh         }
1871fb7e7651Sdrh       }
1872fb7e7651Sdrh     }else{
1873fb7e7651Sdrh       Tcl_AppendResult( interp, "bad option \"",
1874191fadcfSdanielk1977           Tcl_GetStringFromObj(objv[2],0), "\": must be flush or size", 0);
1875fb7e7651Sdrh       return TCL_ERROR;
1876fb7e7651Sdrh     }
1877fb7e7651Sdrh     break;
1878fb7e7651Sdrh   }
1879fb7e7651Sdrh 
1880b28af71aSdanielk1977   /*     $db changes
1881c8d30ac1Sdrh   **
1882c8d30ac1Sdrh   ** Return the number of rows that were modified, inserted, or deleted by
1883b28af71aSdanielk1977   ** the most recent INSERT, UPDATE or DELETE statement, not including
1884b28af71aSdanielk1977   ** any changes made by trigger programs.
1885c8d30ac1Sdrh   */
1886c8d30ac1Sdrh   case DB_CHANGES: {
1887c8d30ac1Sdrh     Tcl_Obj *pResult;
1888c8d30ac1Sdrh     if( objc!=2 ){
1889c8d30ac1Sdrh       Tcl_WrongNumArgs(interp, 2, objv, "");
1890c8d30ac1Sdrh       return TCL_ERROR;
1891c8d30ac1Sdrh     }
1892c8d30ac1Sdrh     pResult = Tcl_GetObjResult(interp);
1893b28af71aSdanielk1977     Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
1894f146a776Srdc     break;
1895f146a776Srdc   }
1896f146a776Srdc 
189775897234Sdrh   /*    $db close
189875897234Sdrh   **
189975897234Sdrh   ** Shutdown the database
190075897234Sdrh   */
19016d31316cSdrh   case DB_CLOSE: {
19026d31316cSdrh     Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
19036d31316cSdrh     break;
19046d31316cSdrh   }
190575897234Sdrh 
19060f14e2ebSdrh   /*
19070f14e2ebSdrh   **     $db collate NAME SCRIPT
19080f14e2ebSdrh   **
19090f14e2ebSdrh   ** Create a new SQL collation function called NAME.  Whenever
19100f14e2ebSdrh   ** that function is called, invoke SCRIPT to evaluate the function.
19110f14e2ebSdrh   */
19120f14e2ebSdrh   case DB_COLLATE: {
19130f14e2ebSdrh     SqlCollate *pCollate;
19140f14e2ebSdrh     char *zName;
19150f14e2ebSdrh     char *zScript;
19160f14e2ebSdrh     int nScript;
19170f14e2ebSdrh     if( objc!=4 ){
19180f14e2ebSdrh       Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
19190f14e2ebSdrh       return TCL_ERROR;
19200f14e2ebSdrh     }
19210f14e2ebSdrh     zName = Tcl_GetStringFromObj(objv[2], 0);
19220f14e2ebSdrh     zScript = Tcl_GetStringFromObj(objv[3], &nScript);
19230f14e2ebSdrh     pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
19240f14e2ebSdrh     if( pCollate==0 ) return TCL_ERROR;
19250f14e2ebSdrh     pCollate->interp = interp;
19260f14e2ebSdrh     pCollate->pNext = pDb->pCollate;
19270f14e2ebSdrh     pCollate->zScript = (char*)&pCollate[1];
19280f14e2ebSdrh     pDb->pCollate = pCollate;
19295bb3eb9bSdrh     memcpy(pCollate->zScript, zScript, nScript+1);
19300f14e2ebSdrh     if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
19310f14e2ebSdrh         pCollate, tclSqlCollate) ){
19329636c4e1Sdanielk1977       Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
19330f14e2ebSdrh       return TCL_ERROR;
19340f14e2ebSdrh     }
19350f14e2ebSdrh     break;
19360f14e2ebSdrh   }
19370f14e2ebSdrh 
19380f14e2ebSdrh   /*
19390f14e2ebSdrh   **     $db collation_needed SCRIPT
19400f14e2ebSdrh   **
19410f14e2ebSdrh   ** Create a new SQL collation function called NAME.  Whenever
19420f14e2ebSdrh   ** that function is called, invoke SCRIPT to evaluate the function.
19430f14e2ebSdrh   */
19440f14e2ebSdrh   case DB_COLLATION_NEEDED: {
19450f14e2ebSdrh     if( objc!=3 ){
19460f14e2ebSdrh       Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
19470f14e2ebSdrh       return TCL_ERROR;
19480f14e2ebSdrh     }
19490f14e2ebSdrh     if( pDb->pCollateNeeded ){
19500f14e2ebSdrh       Tcl_DecrRefCount(pDb->pCollateNeeded);
19510f14e2ebSdrh     }
19520f14e2ebSdrh     pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
19530f14e2ebSdrh     Tcl_IncrRefCount(pDb->pCollateNeeded);
19540f14e2ebSdrh     sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
19550f14e2ebSdrh     break;
19560f14e2ebSdrh   }
19570f14e2ebSdrh 
195819e2d37fSdrh   /*    $db commit_hook ?CALLBACK?
195919e2d37fSdrh   **
196019e2d37fSdrh   ** Invoke the given callback just before committing every SQL transaction.
196119e2d37fSdrh   ** If the callback throws an exception or returns non-zero, then the
196219e2d37fSdrh   ** transaction is aborted.  If CALLBACK is an empty string, the callback
196319e2d37fSdrh   ** is disabled.
196419e2d37fSdrh   */
196519e2d37fSdrh   case DB_COMMIT_HOOK: {
196619e2d37fSdrh     if( objc>3 ){
196719e2d37fSdrh       Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
196819e2d37fSdrh       return TCL_ERROR;
196919e2d37fSdrh     }else if( objc==2 ){
197019e2d37fSdrh       if( pDb->zCommit ){
197119e2d37fSdrh         Tcl_AppendResult(interp, pDb->zCommit, 0);
197219e2d37fSdrh       }
197319e2d37fSdrh     }else{
197419e2d37fSdrh       char *zCommit;
197519e2d37fSdrh       int len;
197619e2d37fSdrh       if( pDb->zCommit ){
197719e2d37fSdrh         Tcl_Free(pDb->zCommit);
197819e2d37fSdrh       }
197919e2d37fSdrh       zCommit = Tcl_GetStringFromObj(objv[2], &len);
198019e2d37fSdrh       if( zCommit && len>0 ){
198119e2d37fSdrh         pDb->zCommit = Tcl_Alloc( len + 1 );
19825bb3eb9bSdrh         memcpy(pDb->zCommit, zCommit, len+1);
198319e2d37fSdrh       }else{
198419e2d37fSdrh         pDb->zCommit = 0;
198519e2d37fSdrh       }
198619e2d37fSdrh       if( pDb->zCommit ){
198719e2d37fSdrh         pDb->interp = interp;
198819e2d37fSdrh         sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
198919e2d37fSdrh       }else{
199019e2d37fSdrh         sqlite3_commit_hook(pDb->db, 0, 0);
199119e2d37fSdrh       }
199219e2d37fSdrh     }
199319e2d37fSdrh     break;
199419e2d37fSdrh   }
199519e2d37fSdrh 
199675897234Sdrh   /*    $db complete SQL
199775897234Sdrh   **
199875897234Sdrh   ** Return TRUE if SQL is a complete SQL statement.  Return FALSE if
199975897234Sdrh   ** additional lines of input are needed.  This is similar to the
200075897234Sdrh   ** built-in "info complete" command of Tcl.
200175897234Sdrh   */
20026d31316cSdrh   case DB_COMPLETE: {
2003ccae6026Sdrh #ifndef SQLITE_OMIT_COMPLETE
20046d31316cSdrh     Tcl_Obj *pResult;
20056d31316cSdrh     int isComplete;
20066d31316cSdrh     if( objc!=3 ){
20076d31316cSdrh       Tcl_WrongNumArgs(interp, 2, objv, "SQL");
200875897234Sdrh       return TCL_ERROR;
200975897234Sdrh     }
20106f8a503dSdanielk1977     isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
20116d31316cSdrh     pResult = Tcl_GetObjResult(interp);
20126d31316cSdrh     Tcl_SetBooleanObj(pResult, isComplete);
2013ccae6026Sdrh #endif
20146d31316cSdrh     break;
20156d31316cSdrh   }
201675897234Sdrh 
201719e2d37fSdrh   /*    $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
201819e2d37fSdrh   **
201919e2d37fSdrh   ** Copy data into table from filename, optionally using SEPARATOR
202019e2d37fSdrh   ** as column separators.  If a column contains a null string, or the
202119e2d37fSdrh   ** value of NULLINDICATOR, a NULL is inserted for the column.
202219e2d37fSdrh   ** conflict-algorithm is one of the sqlite conflict algorithms:
202319e2d37fSdrh   **    rollback, abort, fail, ignore, replace
202419e2d37fSdrh   ** On success, return the number of lines processed, not necessarily same
202519e2d37fSdrh   ** as 'db changes' due to conflict-algorithm selected.
202619e2d37fSdrh   **
202719e2d37fSdrh   ** This code is basically an implementation/enhancement of
202819e2d37fSdrh   ** the sqlite3 shell.c ".import" command.
202919e2d37fSdrh   **
203019e2d37fSdrh   ** This command usage is equivalent to the sqlite2.x COPY statement,
203119e2d37fSdrh   ** which imports file data into a table using the PostgreSQL COPY file format:
203219e2d37fSdrh   **   $db copy $conflit_algo $table_name $filename \t \\N
203319e2d37fSdrh   */
203419e2d37fSdrh   case DB_COPY: {
203519e2d37fSdrh     char *zTable;               /* Insert data into this table */
203619e2d37fSdrh     char *zFile;                /* The file from which to extract data */
203719e2d37fSdrh     char *zConflict;            /* The conflict algorithm to use */
203819e2d37fSdrh     sqlite3_stmt *pStmt;        /* A statement */
203919e2d37fSdrh     int nCol;                   /* Number of columns in the table */
204019e2d37fSdrh     int nByte;                  /* Number of bytes in an SQL string */
204119e2d37fSdrh     int i, j;                   /* Loop counters */
204219e2d37fSdrh     int nSep;                   /* Number of bytes in zSep[] */
204319e2d37fSdrh     int nNull;                  /* Number of bytes in zNull[] */
204419e2d37fSdrh     char *zSql;                 /* An SQL statement */
204519e2d37fSdrh     char *zLine;                /* A single line of input from the file */
204619e2d37fSdrh     char **azCol;               /* zLine[] broken up into columns */
204719e2d37fSdrh     char *zCommit;              /* How to commit changes */
204819e2d37fSdrh     FILE *in;                   /* The input file */
204919e2d37fSdrh     int lineno = 0;             /* Line number of input file */
205019e2d37fSdrh     char zLineNum[80];          /* Line number print buffer */
205119e2d37fSdrh     Tcl_Obj *pResult;           /* interp result */
205219e2d37fSdrh 
205319e2d37fSdrh     char *zSep;
205419e2d37fSdrh     char *zNull;
205519e2d37fSdrh     if( objc<5 || objc>7 ){
205619e2d37fSdrh       Tcl_WrongNumArgs(interp, 2, objv,
205719e2d37fSdrh          "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
205819e2d37fSdrh       return TCL_ERROR;
205919e2d37fSdrh     }
206019e2d37fSdrh     if( objc>=6 ){
206119e2d37fSdrh       zSep = Tcl_GetStringFromObj(objv[5], 0);
206219e2d37fSdrh     }else{
206319e2d37fSdrh       zSep = "\t";
206419e2d37fSdrh     }
206519e2d37fSdrh     if( objc>=7 ){
206619e2d37fSdrh       zNull = Tcl_GetStringFromObj(objv[6], 0);
206719e2d37fSdrh     }else{
206819e2d37fSdrh       zNull = "";
206919e2d37fSdrh     }
207019e2d37fSdrh     zConflict = Tcl_GetStringFromObj(objv[2], 0);
207119e2d37fSdrh     zTable = Tcl_GetStringFromObj(objv[3], 0);
207219e2d37fSdrh     zFile = Tcl_GetStringFromObj(objv[4], 0);
20734f21c4afSdrh     nSep = strlen30(zSep);
20744f21c4afSdrh     nNull = strlen30(zNull);
207519e2d37fSdrh     if( nSep==0 ){
207619e2d37fSdrh       Tcl_AppendResult(interp,"Error: non-null separator required for copy",0);
207719e2d37fSdrh       return TCL_ERROR;
207819e2d37fSdrh     }
20793e59c012Sdrh     if(strcmp(zConflict, "rollback") != 0 &&
20803e59c012Sdrh        strcmp(zConflict, "abort"   ) != 0 &&
20813e59c012Sdrh        strcmp(zConflict, "fail"    ) != 0 &&
20823e59c012Sdrh        strcmp(zConflict, "ignore"  ) != 0 &&
20833e59c012Sdrh        strcmp(zConflict, "replace" ) != 0 ) {
208419e2d37fSdrh       Tcl_AppendResult(interp, "Error: \"", zConflict,
208519e2d37fSdrh             "\", conflict-algorithm must be one of: rollback, "
208619e2d37fSdrh             "abort, fail, ignore, or replace", 0);
208719e2d37fSdrh       return TCL_ERROR;
208819e2d37fSdrh     }
208919e2d37fSdrh     zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
209019e2d37fSdrh     if( zSql==0 ){
209119e2d37fSdrh       Tcl_AppendResult(interp, "Error: no such table: ", zTable, 0);
209219e2d37fSdrh       return TCL_ERROR;
209319e2d37fSdrh     }
20944f21c4afSdrh     nByte = strlen30(zSql);
20953e701a18Sdrh     rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
209619e2d37fSdrh     sqlite3_free(zSql);
209719e2d37fSdrh     if( rc ){
209819e2d37fSdrh       Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
209919e2d37fSdrh       nCol = 0;
210019e2d37fSdrh     }else{
210119e2d37fSdrh       nCol = sqlite3_column_count(pStmt);
210219e2d37fSdrh     }
210319e2d37fSdrh     sqlite3_finalize(pStmt);
210419e2d37fSdrh     if( nCol==0 ) {
210519e2d37fSdrh       return TCL_ERROR;
210619e2d37fSdrh     }
210719e2d37fSdrh     zSql = malloc( nByte + 50 + nCol*2 );
210819e2d37fSdrh     if( zSql==0 ) {
210919e2d37fSdrh       Tcl_AppendResult(interp, "Error: can't malloc()", 0);
211019e2d37fSdrh       return TCL_ERROR;
211119e2d37fSdrh     }
211219e2d37fSdrh     sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
211319e2d37fSdrh          zConflict, zTable);
21144f21c4afSdrh     j = strlen30(zSql);
211519e2d37fSdrh     for(i=1; i<nCol; i++){
211619e2d37fSdrh       zSql[j++] = ',';
211719e2d37fSdrh       zSql[j++] = '?';
211819e2d37fSdrh     }
211919e2d37fSdrh     zSql[j++] = ')';
212019e2d37fSdrh     zSql[j] = 0;
21213e701a18Sdrh     rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
212219e2d37fSdrh     free(zSql);
212319e2d37fSdrh     if( rc ){
212419e2d37fSdrh       Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
212519e2d37fSdrh       sqlite3_finalize(pStmt);
212619e2d37fSdrh       return TCL_ERROR;
212719e2d37fSdrh     }
212819e2d37fSdrh     in = fopen(zFile, "rb");
212919e2d37fSdrh     if( in==0 ){
213019e2d37fSdrh       Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL);
213119e2d37fSdrh       sqlite3_finalize(pStmt);
213219e2d37fSdrh       return TCL_ERROR;
213319e2d37fSdrh     }
213419e2d37fSdrh     azCol = malloc( sizeof(azCol[0])*(nCol+1) );
213519e2d37fSdrh     if( azCol==0 ) {
213619e2d37fSdrh       Tcl_AppendResult(interp, "Error: can't malloc()", 0);
213743617e9aSdrh       fclose(in);
213819e2d37fSdrh       return TCL_ERROR;
213919e2d37fSdrh     }
21403752785fSdrh     (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
214119e2d37fSdrh     zCommit = "COMMIT";
214219e2d37fSdrh     while( (zLine = local_getline(0, in))!=0 ){
214319e2d37fSdrh       char *z;
214419e2d37fSdrh       i = 0;
214519e2d37fSdrh       lineno++;
214619e2d37fSdrh       azCol[0] = zLine;
214719e2d37fSdrh       for(i=0, z=zLine; *z; z++){
214819e2d37fSdrh         if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
214919e2d37fSdrh           *z = 0;
215019e2d37fSdrh           i++;
215119e2d37fSdrh           if( i<nCol ){
215219e2d37fSdrh             azCol[i] = &z[nSep];
215319e2d37fSdrh             z += nSep-1;
215419e2d37fSdrh           }
215519e2d37fSdrh         }
215619e2d37fSdrh       }
215719e2d37fSdrh       if( i+1!=nCol ){
215819e2d37fSdrh         char *zErr;
21594f21c4afSdrh         int nErr = strlen30(zFile) + 200;
21605bb3eb9bSdrh         zErr = malloc(nErr);
2161c1f4494eSdrh         if( zErr ){
21625bb3eb9bSdrh           sqlite3_snprintf(nErr, zErr,
2163955de52cSdanielk1977              "Error: %s line %d: expected %d columns of data but found %d",
216419e2d37fSdrh              zFile, lineno, nCol, i+1);
216519e2d37fSdrh           Tcl_AppendResult(interp, zErr, 0);
216619e2d37fSdrh           free(zErr);
2167c1f4494eSdrh         }
216819e2d37fSdrh         zCommit = "ROLLBACK";
216919e2d37fSdrh         break;
217019e2d37fSdrh       }
217119e2d37fSdrh       for(i=0; i<nCol; i++){
217219e2d37fSdrh         /* check for null data, if so, bind as null */
2173ea678832Sdrh         if( (nNull>0 && strcmp(azCol[i], zNull)==0)
21744f21c4afSdrh           || strlen30(azCol[i])==0
2175ea678832Sdrh         ){
217619e2d37fSdrh           sqlite3_bind_null(pStmt, i+1);
217719e2d37fSdrh         }else{
217819e2d37fSdrh           sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
217919e2d37fSdrh         }
218019e2d37fSdrh       }
218119e2d37fSdrh       sqlite3_step(pStmt);
218219e2d37fSdrh       rc = sqlite3_reset(pStmt);
218319e2d37fSdrh       free(zLine);
218419e2d37fSdrh       if( rc!=SQLITE_OK ){
218519e2d37fSdrh         Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), 0);
218619e2d37fSdrh         zCommit = "ROLLBACK";
218719e2d37fSdrh         break;
218819e2d37fSdrh       }
218919e2d37fSdrh     }
219019e2d37fSdrh     free(azCol);
219119e2d37fSdrh     fclose(in);
219219e2d37fSdrh     sqlite3_finalize(pStmt);
21933752785fSdrh     (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
219419e2d37fSdrh 
219519e2d37fSdrh     if( zCommit[0] == 'C' ){
219619e2d37fSdrh       /* success, set result as number of lines processed */
219719e2d37fSdrh       pResult = Tcl_GetObjResult(interp);
219819e2d37fSdrh       Tcl_SetIntObj(pResult, lineno);
219919e2d37fSdrh       rc = TCL_OK;
220019e2d37fSdrh     }else{
220119e2d37fSdrh       /* failure, append lineno where failed */
22025bb3eb9bSdrh       sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
220319e2d37fSdrh       Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,0);
220419e2d37fSdrh       rc = TCL_ERROR;
220519e2d37fSdrh     }
220619e2d37fSdrh     break;
220719e2d37fSdrh   }
220819e2d37fSdrh 
220975897234Sdrh   /*
22104144905bSdrh   **    $db enable_load_extension BOOLEAN
22114144905bSdrh   **
22124144905bSdrh   ** Turn the extension loading feature on or off.  It if off by
22134144905bSdrh   ** default.
22144144905bSdrh   */
22154144905bSdrh   case DB_ENABLE_LOAD_EXTENSION: {
2216f533acc0Sdrh #ifndef SQLITE_OMIT_LOAD_EXTENSION
22174144905bSdrh     int onoff;
22184144905bSdrh     if( objc!=3 ){
22194144905bSdrh       Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
22204144905bSdrh       return TCL_ERROR;
22214144905bSdrh     }
22224144905bSdrh     if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
22234144905bSdrh       return TCL_ERROR;
22244144905bSdrh     }
22254144905bSdrh     sqlite3_enable_load_extension(pDb->db, onoff);
22264144905bSdrh     break;
2227f533acc0Sdrh #else
2228f533acc0Sdrh     Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
2229f533acc0Sdrh                      0);
2230f533acc0Sdrh     return TCL_ERROR;
2231f533acc0Sdrh #endif
22324144905bSdrh   }
22334144905bSdrh 
22344144905bSdrh   /*
2235dcd997eaSdrh   **    $db errorcode
2236dcd997eaSdrh   **
2237dcd997eaSdrh   ** Return the numeric error code that was returned by the most recent
22386f8a503dSdanielk1977   ** call to sqlite3_exec().
2239dcd997eaSdrh   */
2240dcd997eaSdrh   case DB_ERRORCODE: {
2241f3ce83f5Sdanielk1977     Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
2242dcd997eaSdrh     break;
2243dcd997eaSdrh   }
2244dcd997eaSdrh 
2245dcd997eaSdrh   /*
22464a4c11aaSdan   **    $db exists $sql
22471807ce37Sdrh   **    $db onecolumn $sql
224875897234Sdrh   **
22494a4c11aaSdan   ** The onecolumn method is the equivalent of:
22504a4c11aaSdan   **     lindex [$db eval $sql] 0
22514a4c11aaSdan   */
22524a4c11aaSdan   case DB_EXISTS:
22534a4c11aaSdan   case DB_ONECOLUMN: {
22544a4c11aaSdan     DbEvalContext sEval;
22554a4c11aaSdan     if( objc!=3 ){
22564a4c11aaSdan       Tcl_WrongNumArgs(interp, 2, objv, "SQL");
22574a4c11aaSdan       return TCL_ERROR;
22584a4c11aaSdan     }
22594a4c11aaSdan 
22604a4c11aaSdan     dbEvalInit(&sEval, pDb, objv[2], 0);
22614a4c11aaSdan     rc = dbEvalStep(&sEval);
22624a4c11aaSdan     if( choice==DB_ONECOLUMN ){
22634a4c11aaSdan       if( rc==TCL_OK ){
22644a4c11aaSdan         Tcl_SetObjResult(interp, dbEvalColumnValue(&sEval, 0));
22654a4c11aaSdan       }
22664a4c11aaSdan     }else if( rc==TCL_BREAK || rc==TCL_OK ){
22674a4c11aaSdan       Tcl_SetObjResult(interp, Tcl_NewBooleanObj(rc==TCL_OK));
22684a4c11aaSdan     }
22694a4c11aaSdan     dbEvalFinalize(&sEval);
22704a4c11aaSdan 
22714a4c11aaSdan     if( rc==TCL_BREAK ){
22724a4c11aaSdan       rc = TCL_OK;
22734a4c11aaSdan     }
22744a4c11aaSdan     break;
22754a4c11aaSdan   }
22764a4c11aaSdan 
22774a4c11aaSdan   /*
22784a4c11aaSdan   **    $db eval $sql ?array? ?{  ...code... }?
22794a4c11aaSdan   **
228075897234Sdrh   ** The SQL statement in $sql is evaluated.  For each row, the values are
2281bec3f402Sdrh   ** placed in elements of the array named "array" and ...code... is executed.
228275897234Sdrh   ** If "array" and "code" are omitted, then no callback is every invoked.
228375897234Sdrh   ** If "array" is an empty string, then the values are placed in variables
228475897234Sdrh   ** that have the same name as the fields extracted by the query.
228575897234Sdrh   */
22864a4c11aaSdan   case DB_EVAL: {
228792febd92Sdrh     if( objc<3 || objc>5 ){
2288895d7472Sdrh       Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
228930ccda10Sdanielk1977       return TCL_ERROR;
229030ccda10Sdanielk1977     }
22914a4c11aaSdan 
229292febd92Sdrh     if( objc==3 ){
22934a4c11aaSdan       DbEvalContext sEval;
22944a4c11aaSdan       Tcl_Obj *pRet = Tcl_NewObj();
22954a4c11aaSdan       Tcl_IncrRefCount(pRet);
22964a4c11aaSdan       dbEvalInit(&sEval, pDb, objv[2], 0);
22974a4c11aaSdan       while( TCL_OK==(rc = dbEvalStep(&sEval)) ){
22984a4c11aaSdan         int i;
22994a4c11aaSdan         int nCol;
23004a4c11aaSdan         dbEvalRowInfo(&sEval, &nCol, 0);
230192febd92Sdrh         for(i=0; i<nCol; i++){
23024a4c11aaSdan           Tcl_ListObjAppendElement(interp, pRet, dbEvalColumnValue(&sEval, i));
230392febd92Sdrh         }
230430ccda10Sdanielk1977       }
23054a4c11aaSdan       dbEvalFinalize(&sEval);
230690b6bb19Sdrh       if( rc==TCL_BREAK ){
23074a4c11aaSdan         Tcl_SetObjResult(interp, pRet);
230890b6bb19Sdrh         rc = TCL_OK;
230990b6bb19Sdrh       }
2310ef2cb63eSdanielk1977       Tcl_DecrRefCount(pRet);
23114a4c11aaSdan     }else{
23124a4c11aaSdan       ClientData cd[2];
23134a4c11aaSdan       DbEvalContext *p;
23144a4c11aaSdan       Tcl_Obj *pArray = 0;
23154a4c11aaSdan       Tcl_Obj *pScript;
23164a4c11aaSdan 
23174a4c11aaSdan       if( objc==5 && *(char *)Tcl_GetString(objv[3]) ){
23184a4c11aaSdan         pArray = objv[3];
23194a4c11aaSdan       }
23204a4c11aaSdan       pScript = objv[objc-1];
23214a4c11aaSdan       Tcl_IncrRefCount(pScript);
23224a4c11aaSdan 
23234a4c11aaSdan       p = (DbEvalContext *)Tcl_Alloc(sizeof(DbEvalContext));
23244a4c11aaSdan       dbEvalInit(p, pDb, objv[2], pArray);
23254a4c11aaSdan 
23264a4c11aaSdan       cd[0] = (void *)p;
23274a4c11aaSdan       cd[1] = (void *)pScript;
23284a4c11aaSdan       rc = DbEvalNextCmd(cd, interp, TCL_OK);
23291807ce37Sdrh     }
233030ccda10Sdanielk1977     break;
233130ccda10Sdanielk1977   }
2332bec3f402Sdrh 
2333bec3f402Sdrh   /*
2334e3602be8Sdrh   **     $db function NAME [-argcount N] SCRIPT
2335cabb0819Sdrh   **
2336cabb0819Sdrh   ** Create a new SQL function called NAME.  Whenever that function is
2337cabb0819Sdrh   ** called, invoke SCRIPT to evaluate the function.
2338cabb0819Sdrh   */
2339cabb0819Sdrh   case DB_FUNCTION: {
2340cabb0819Sdrh     SqlFunc *pFunc;
2341d1e4733dSdrh     Tcl_Obj *pScript;
2342cabb0819Sdrh     char *zName;
2343e3602be8Sdrh     int nArg = -1;
2344e3602be8Sdrh     if( objc==6 ){
2345e3602be8Sdrh       const char *z = Tcl_GetString(objv[3]);
23464f21c4afSdrh       int n = strlen30(z);
2347e3602be8Sdrh       if( n>2 && strncmp(z, "-argcount",n)==0 ){
2348e3602be8Sdrh         if( Tcl_GetIntFromObj(interp, objv[4], &nArg) ) return TCL_ERROR;
2349e3602be8Sdrh         if( nArg<0 ){
2350e3602be8Sdrh           Tcl_AppendResult(interp, "number of arguments must be non-negative",
2351e3602be8Sdrh                            (char*)0);
2352cabb0819Sdrh           return TCL_ERROR;
2353cabb0819Sdrh         }
2354e3602be8Sdrh       }
2355e3602be8Sdrh       pScript = objv[5];
2356e3602be8Sdrh     }else if( objc!=4 ){
2357e3602be8Sdrh       Tcl_WrongNumArgs(interp, 2, objv, "NAME [-argcount N] SCRIPT");
2358e3602be8Sdrh       return TCL_ERROR;
2359e3602be8Sdrh     }else{
2360d1e4733dSdrh       pScript = objv[3];
2361e3602be8Sdrh     }
2362e3602be8Sdrh     zName = Tcl_GetStringFromObj(objv[2], 0);
2363d1e4733dSdrh     pFunc = findSqlFunc(pDb, zName);
2364cabb0819Sdrh     if( pFunc==0 ) return TCL_ERROR;
2365d1e4733dSdrh     if( pFunc->pScript ){
2366d1e4733dSdrh       Tcl_DecrRefCount(pFunc->pScript);
2367d1e4733dSdrh     }
2368d1e4733dSdrh     pFunc->pScript = pScript;
2369d1e4733dSdrh     Tcl_IncrRefCount(pScript);
2370d1e4733dSdrh     pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
2371e3602be8Sdrh     rc = sqlite3_create_function(pDb->db, zName, nArg, SQLITE_UTF8,
2372d8123366Sdanielk1977         pFunc, tclSqlFunc, 0, 0);
2373fb7e7651Sdrh     if( rc!=SQLITE_OK ){
2374fb7e7651Sdrh       rc = TCL_ERROR;
23759636c4e1Sdanielk1977       Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
2376fb7e7651Sdrh     }
2377cabb0819Sdrh     break;
2378cabb0819Sdrh   }
2379cabb0819Sdrh 
2380cabb0819Sdrh   /*
23818cbadb02Sdanielk1977   **     $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
2382b4e9af9fSdanielk1977   */
2383b4e9af9fSdanielk1977   case DB_INCRBLOB: {
238432a0d8bbSdanielk1977 #ifdef SQLITE_OMIT_INCRBLOB
238532a0d8bbSdanielk1977     Tcl_AppendResult(interp, "incrblob not available in this build", 0);
238632a0d8bbSdanielk1977     return TCL_ERROR;
238732a0d8bbSdanielk1977 #else
23888cbadb02Sdanielk1977     int isReadonly = 0;
2389b4e9af9fSdanielk1977     const char *zDb = "main";
2390b4e9af9fSdanielk1977     const char *zTable;
2391b4e9af9fSdanielk1977     const char *zColumn;
2392b4e9af9fSdanielk1977     sqlite_int64 iRow;
2393b4e9af9fSdanielk1977 
23948cbadb02Sdanielk1977     /* Check for the -readonly option */
23958cbadb02Sdanielk1977     if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
23968cbadb02Sdanielk1977       isReadonly = 1;
23978cbadb02Sdanielk1977     }
23988cbadb02Sdanielk1977 
23998cbadb02Sdanielk1977     if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
24008cbadb02Sdanielk1977       Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
2401b4e9af9fSdanielk1977       return TCL_ERROR;
2402b4e9af9fSdanielk1977     }
2403b4e9af9fSdanielk1977 
24048cbadb02Sdanielk1977     if( objc==(6+isReadonly) ){
2405b4e9af9fSdanielk1977       zDb = Tcl_GetString(objv[2]);
2406b4e9af9fSdanielk1977     }
2407b4e9af9fSdanielk1977     zTable = Tcl_GetString(objv[objc-3]);
2408b4e9af9fSdanielk1977     zColumn = Tcl_GetString(objv[objc-2]);
2409b4e9af9fSdanielk1977     rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
2410b4e9af9fSdanielk1977 
2411b4e9af9fSdanielk1977     if( rc==TCL_OK ){
24128cbadb02Sdanielk1977       rc = createIncrblobChannel(
24138cbadb02Sdanielk1977           interp, pDb, zDb, zTable, zColumn, iRow, isReadonly
24148cbadb02Sdanielk1977       );
2415b4e9af9fSdanielk1977     }
241632a0d8bbSdanielk1977 #endif
2417b4e9af9fSdanielk1977     break;
2418b4e9af9fSdanielk1977   }
2419b4e9af9fSdanielk1977 
2420b4e9af9fSdanielk1977   /*
2421f11bded5Sdrh   **     $db interrupt
2422f11bded5Sdrh   **
2423f11bded5Sdrh   ** Interrupt the execution of the inner-most SQL interpreter.  This
2424f11bded5Sdrh   ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
2425f11bded5Sdrh   */
2426f11bded5Sdrh   case DB_INTERRUPT: {
2427f11bded5Sdrh     sqlite3_interrupt(pDb->db);
2428f11bded5Sdrh     break;
2429f11bded5Sdrh   }
2430f11bded5Sdrh 
2431f11bded5Sdrh   /*
243219e2d37fSdrh   **     $db nullvalue ?STRING?
243319e2d37fSdrh   **
243419e2d37fSdrh   ** Change text used when a NULL comes back from the database. If ?STRING?
243519e2d37fSdrh   ** is not present, then the current string used for NULL is returned.
243619e2d37fSdrh   ** If STRING is present, then STRING is returned.
243719e2d37fSdrh   **
243819e2d37fSdrh   */
243919e2d37fSdrh   case DB_NULLVALUE: {
244019e2d37fSdrh     if( objc!=2 && objc!=3 ){
244119e2d37fSdrh       Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
244219e2d37fSdrh       return TCL_ERROR;
244319e2d37fSdrh     }
244419e2d37fSdrh     if( objc==3 ){
244519e2d37fSdrh       int len;
244619e2d37fSdrh       char *zNull = Tcl_GetStringFromObj(objv[2], &len);
244719e2d37fSdrh       if( pDb->zNull ){
244819e2d37fSdrh         Tcl_Free(pDb->zNull);
244919e2d37fSdrh       }
245019e2d37fSdrh       if( zNull && len>0 ){
245119e2d37fSdrh         pDb->zNull = Tcl_Alloc( len + 1 );
245219e2d37fSdrh         strncpy(pDb->zNull, zNull, len);
245319e2d37fSdrh         pDb->zNull[len] = '\0';
245419e2d37fSdrh       }else{
245519e2d37fSdrh         pDb->zNull = 0;
245619e2d37fSdrh       }
245719e2d37fSdrh     }
245819e2d37fSdrh     Tcl_SetObjResult(interp, dbTextToObj(pDb->zNull));
245919e2d37fSdrh     break;
246019e2d37fSdrh   }
246119e2d37fSdrh 
246219e2d37fSdrh   /*
2463af9ff33aSdrh   **     $db last_insert_rowid
2464af9ff33aSdrh   **
2465af9ff33aSdrh   ** Return an integer which is the ROWID for the most recent insert.
2466af9ff33aSdrh   */
2467af9ff33aSdrh   case DB_LAST_INSERT_ROWID: {
2468af9ff33aSdrh     Tcl_Obj *pResult;
2469f7e678d6Sdrh     Tcl_WideInt rowid;
2470af9ff33aSdrh     if( objc!=2 ){
2471af9ff33aSdrh       Tcl_WrongNumArgs(interp, 2, objv, "");
2472af9ff33aSdrh       return TCL_ERROR;
2473af9ff33aSdrh     }
24746f8a503dSdanielk1977     rowid = sqlite3_last_insert_rowid(pDb->db);
2475af9ff33aSdrh     pResult = Tcl_GetObjResult(interp);
2476f7e678d6Sdrh     Tcl_SetWideIntObj(pResult, rowid);
2477af9ff33aSdrh     break;
2478af9ff33aSdrh   }
2479af9ff33aSdrh 
2480af9ff33aSdrh   /*
24814a4c11aaSdan   ** The DB_ONECOLUMN method is implemented together with DB_EXISTS.
24825d9d7576Sdrh   */
24831807ce37Sdrh 
24841807ce37Sdrh   /*    $db progress ?N CALLBACK?
24851807ce37Sdrh   **
24861807ce37Sdrh   ** Invoke the given callback every N virtual machine opcodes while executing
24871807ce37Sdrh   ** queries.
24881807ce37Sdrh   */
24891807ce37Sdrh   case DB_PROGRESS: {
24901807ce37Sdrh     if( objc==2 ){
24911807ce37Sdrh       if( pDb->zProgress ){
24921807ce37Sdrh         Tcl_AppendResult(interp, pDb->zProgress, 0);
24935d9d7576Sdrh       }
24941807ce37Sdrh     }else if( objc==4 ){
24951807ce37Sdrh       char *zProgress;
24961807ce37Sdrh       int len;
24971807ce37Sdrh       int N;
24981807ce37Sdrh       if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
24991807ce37Sdrh         return TCL_ERROR;
25001807ce37Sdrh       };
25011807ce37Sdrh       if( pDb->zProgress ){
25021807ce37Sdrh         Tcl_Free(pDb->zProgress);
25031807ce37Sdrh       }
25041807ce37Sdrh       zProgress = Tcl_GetStringFromObj(objv[3], &len);
25051807ce37Sdrh       if( zProgress && len>0 ){
25061807ce37Sdrh         pDb->zProgress = Tcl_Alloc( len + 1 );
25075bb3eb9bSdrh         memcpy(pDb->zProgress, zProgress, len+1);
25081807ce37Sdrh       }else{
25091807ce37Sdrh         pDb->zProgress = 0;
25101807ce37Sdrh       }
25111807ce37Sdrh #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
25121807ce37Sdrh       if( pDb->zProgress ){
25131807ce37Sdrh         pDb->interp = interp;
25141807ce37Sdrh         sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
25151807ce37Sdrh       }else{
25161807ce37Sdrh         sqlite3_progress_handler(pDb->db, 0, 0, 0);
25171807ce37Sdrh       }
25181807ce37Sdrh #endif
25191807ce37Sdrh     }else{
25201807ce37Sdrh       Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
25211807ce37Sdrh       return TCL_ERROR;
25225d9d7576Sdrh     }
25235d9d7576Sdrh     break;
25245d9d7576Sdrh   }
25255d9d7576Sdrh 
252619e2d37fSdrh   /*    $db profile ?CALLBACK?
252719e2d37fSdrh   **
252819e2d37fSdrh   ** Make arrangements to invoke the CALLBACK routine after each SQL statement
252919e2d37fSdrh   ** that has run.  The text of the SQL and the amount of elapse time are
253019e2d37fSdrh   ** appended to CALLBACK before the script is run.
253119e2d37fSdrh   */
253219e2d37fSdrh   case DB_PROFILE: {
253319e2d37fSdrh     if( objc>3 ){
253419e2d37fSdrh       Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
253519e2d37fSdrh       return TCL_ERROR;
253619e2d37fSdrh     }else if( objc==2 ){
253719e2d37fSdrh       if( pDb->zProfile ){
253819e2d37fSdrh         Tcl_AppendResult(interp, pDb->zProfile, 0);
253919e2d37fSdrh       }
254019e2d37fSdrh     }else{
254119e2d37fSdrh       char *zProfile;
254219e2d37fSdrh       int len;
254319e2d37fSdrh       if( pDb->zProfile ){
254419e2d37fSdrh         Tcl_Free(pDb->zProfile);
254519e2d37fSdrh       }
254619e2d37fSdrh       zProfile = Tcl_GetStringFromObj(objv[2], &len);
254719e2d37fSdrh       if( zProfile && len>0 ){
254819e2d37fSdrh         pDb->zProfile = Tcl_Alloc( len + 1 );
25495bb3eb9bSdrh         memcpy(pDb->zProfile, zProfile, len+1);
255019e2d37fSdrh       }else{
255119e2d37fSdrh         pDb->zProfile = 0;
255219e2d37fSdrh       }
2553bb201344Sshaneh #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
255419e2d37fSdrh       if( pDb->zProfile ){
255519e2d37fSdrh         pDb->interp = interp;
255619e2d37fSdrh         sqlite3_profile(pDb->db, DbProfileHandler, pDb);
255719e2d37fSdrh       }else{
255819e2d37fSdrh         sqlite3_profile(pDb->db, 0, 0);
255919e2d37fSdrh       }
256019e2d37fSdrh #endif
256119e2d37fSdrh     }
256219e2d37fSdrh     break;
256319e2d37fSdrh   }
256419e2d37fSdrh 
25655d9d7576Sdrh   /*
256622fbcb8dSdrh   **     $db rekey KEY
256722fbcb8dSdrh   **
256822fbcb8dSdrh   ** Change the encryption key on the currently open database.
256922fbcb8dSdrh   */
257022fbcb8dSdrh   case DB_REKEY: {
257122fbcb8dSdrh     int nKey;
257222fbcb8dSdrh     void *pKey;
257322fbcb8dSdrh     if( objc!=3 ){
257422fbcb8dSdrh       Tcl_WrongNumArgs(interp, 2, objv, "KEY");
257522fbcb8dSdrh       return TCL_ERROR;
257622fbcb8dSdrh     }
257722fbcb8dSdrh     pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
25789eb9e26bSdrh #ifdef SQLITE_HAS_CODEC
25792011d5f5Sdrh     rc = sqlite3_rekey(pDb->db, pKey, nKey);
258022fbcb8dSdrh     if( rc ){
2581f20b21c8Sdanielk1977       Tcl_AppendResult(interp, sqlite3ErrStr(rc), 0);
258222fbcb8dSdrh       rc = TCL_ERROR;
258322fbcb8dSdrh     }
258422fbcb8dSdrh #endif
258522fbcb8dSdrh     break;
258622fbcb8dSdrh   }
258722fbcb8dSdrh 
2588dc2c4915Sdrh   /*    $db restore ?DATABASE? FILENAME
2589dc2c4915Sdrh   **
2590dc2c4915Sdrh   ** Open a database file named FILENAME.  Transfer the content
2591dc2c4915Sdrh   ** of FILENAME into the local database DATABASE (default: "main").
2592dc2c4915Sdrh   */
2593dc2c4915Sdrh   case DB_RESTORE: {
2594dc2c4915Sdrh     const char *zSrcFile;
2595dc2c4915Sdrh     const char *zDestDb;
2596dc2c4915Sdrh     sqlite3 *pSrc;
2597dc2c4915Sdrh     sqlite3_backup *pBackup;
2598dc2c4915Sdrh     int nTimeout = 0;
2599dc2c4915Sdrh 
2600dc2c4915Sdrh     if( objc==3 ){
2601dc2c4915Sdrh       zDestDb = "main";
2602dc2c4915Sdrh       zSrcFile = Tcl_GetString(objv[2]);
2603dc2c4915Sdrh     }else if( objc==4 ){
2604dc2c4915Sdrh       zDestDb = Tcl_GetString(objv[2]);
2605dc2c4915Sdrh       zSrcFile = Tcl_GetString(objv[3]);
2606dc2c4915Sdrh     }else{
2607dc2c4915Sdrh       Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
2608dc2c4915Sdrh       return TCL_ERROR;
2609dc2c4915Sdrh     }
2610dc2c4915Sdrh     rc = sqlite3_open_v2(zSrcFile, &pSrc, SQLITE_OPEN_READONLY, 0);
2611dc2c4915Sdrh     if( rc!=SQLITE_OK ){
2612dc2c4915Sdrh       Tcl_AppendResult(interp, "cannot open source database: ",
2613dc2c4915Sdrh            sqlite3_errmsg(pSrc), (char*)0);
2614dc2c4915Sdrh       sqlite3_close(pSrc);
2615dc2c4915Sdrh       return TCL_ERROR;
2616dc2c4915Sdrh     }
2617dc2c4915Sdrh     pBackup = sqlite3_backup_init(pDb->db, zDestDb, pSrc, "main");
2618dc2c4915Sdrh     if( pBackup==0 ){
2619dc2c4915Sdrh       Tcl_AppendResult(interp, "restore failed: ",
2620dc2c4915Sdrh            sqlite3_errmsg(pDb->db), (char*)0);
2621dc2c4915Sdrh       sqlite3_close(pSrc);
2622dc2c4915Sdrh       return TCL_ERROR;
2623dc2c4915Sdrh     }
2624dc2c4915Sdrh     while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
2625dc2c4915Sdrh               || rc==SQLITE_BUSY ){
2626dc2c4915Sdrh       if( rc==SQLITE_BUSY ){
2627dc2c4915Sdrh         if( nTimeout++ >= 3 ) break;
2628dc2c4915Sdrh         sqlite3_sleep(100);
2629dc2c4915Sdrh       }
2630dc2c4915Sdrh     }
2631dc2c4915Sdrh     sqlite3_backup_finish(pBackup);
2632dc2c4915Sdrh     if( rc==SQLITE_DONE ){
2633dc2c4915Sdrh       rc = TCL_OK;
2634dc2c4915Sdrh     }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
2635dc2c4915Sdrh       Tcl_AppendResult(interp, "restore failed: source database busy",
2636dc2c4915Sdrh                        (char*)0);
2637dc2c4915Sdrh       rc = TCL_ERROR;
2638dc2c4915Sdrh     }else{
2639dc2c4915Sdrh       Tcl_AppendResult(interp, "restore failed: ",
2640dc2c4915Sdrh            sqlite3_errmsg(pDb->db), (char*)0);
2641dc2c4915Sdrh       rc = TCL_ERROR;
2642dc2c4915Sdrh     }
2643dc2c4915Sdrh     sqlite3_close(pSrc);
2644dc2c4915Sdrh     break;
2645dc2c4915Sdrh   }
2646dc2c4915Sdrh 
264722fbcb8dSdrh   /*
26483c379b01Sdrh   **     $db status (step|sort|autoindex)
2649d1d38488Sdrh   **
2650d1d38488Sdrh   ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or
2651d1d38488Sdrh   ** SQLITE_STMTSTATUS_SORT for the most recent eval.
2652d1d38488Sdrh   */
2653d1d38488Sdrh   case DB_STATUS: {
2654d1d38488Sdrh     int v;
2655d1d38488Sdrh     const char *zOp;
2656d1d38488Sdrh     if( objc!=3 ){
26571c320a43Sdrh       Tcl_WrongNumArgs(interp, 2, objv, "(step|sort|autoindex)");
2658d1d38488Sdrh       return TCL_ERROR;
2659d1d38488Sdrh     }
2660d1d38488Sdrh     zOp = Tcl_GetString(objv[2]);
2661d1d38488Sdrh     if( strcmp(zOp, "step")==0 ){
2662d1d38488Sdrh       v = pDb->nStep;
2663d1d38488Sdrh     }else if( strcmp(zOp, "sort")==0 ){
2664d1d38488Sdrh       v = pDb->nSort;
26653c379b01Sdrh     }else if( strcmp(zOp, "autoindex")==0 ){
26663c379b01Sdrh       v = pDb->nIndex;
2667d1d38488Sdrh     }else{
26683c379b01Sdrh       Tcl_AppendResult(interp,
26693c379b01Sdrh             "bad argument: should be autoindex, step, or sort",
2670d1d38488Sdrh             (char*)0);
2671d1d38488Sdrh       return TCL_ERROR;
2672d1d38488Sdrh     }
2673d1d38488Sdrh     Tcl_SetObjResult(interp, Tcl_NewIntObj(v));
2674d1d38488Sdrh     break;
2675d1d38488Sdrh   }
2676d1d38488Sdrh 
2677d1d38488Sdrh   /*
2678bec3f402Sdrh   **     $db timeout MILLESECONDS
2679bec3f402Sdrh   **
2680bec3f402Sdrh   ** Delay for the number of milliseconds specified when a file is locked.
2681bec3f402Sdrh   */
26826d31316cSdrh   case DB_TIMEOUT: {
2683bec3f402Sdrh     int ms;
26846d31316cSdrh     if( objc!=3 ){
26856d31316cSdrh       Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
2686bec3f402Sdrh       return TCL_ERROR;
268775897234Sdrh     }
26886d31316cSdrh     if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
26896f8a503dSdanielk1977     sqlite3_busy_timeout(pDb->db, ms);
26906d31316cSdrh     break;
269175897234Sdrh   }
2692b5a20d3cSdrh 
26930f14e2ebSdrh   /*
26940f14e2ebSdrh   **     $db total_changes
26950f14e2ebSdrh   **
26960f14e2ebSdrh   ** Return the number of rows that were modified, inserted, or deleted
26970f14e2ebSdrh   ** since the database handle was created.
26980f14e2ebSdrh   */
26990f14e2ebSdrh   case DB_TOTAL_CHANGES: {
27000f14e2ebSdrh     Tcl_Obj *pResult;
27010f14e2ebSdrh     if( objc!=2 ){
27020f14e2ebSdrh       Tcl_WrongNumArgs(interp, 2, objv, "");
27030f14e2ebSdrh       return TCL_ERROR;
27040f14e2ebSdrh     }
27050f14e2ebSdrh     pResult = Tcl_GetObjResult(interp);
27060f14e2ebSdrh     Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
27070f14e2ebSdrh     break;
27080f14e2ebSdrh   }
27090f14e2ebSdrh 
2710b5a20d3cSdrh   /*    $db trace ?CALLBACK?
2711b5a20d3cSdrh   **
2712b5a20d3cSdrh   ** Make arrangements to invoke the CALLBACK routine for each SQL statement
2713b5a20d3cSdrh   ** that is executed.  The text of the SQL is appended to CALLBACK before
2714b5a20d3cSdrh   ** it is executed.
2715b5a20d3cSdrh   */
2716b5a20d3cSdrh   case DB_TRACE: {
2717b5a20d3cSdrh     if( objc>3 ){
2718b5a20d3cSdrh       Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2719b97759edSdrh       return TCL_ERROR;
2720b5a20d3cSdrh     }else if( objc==2 ){
2721b5a20d3cSdrh       if( pDb->zTrace ){
2722b5a20d3cSdrh         Tcl_AppendResult(interp, pDb->zTrace, 0);
2723b5a20d3cSdrh       }
2724b5a20d3cSdrh     }else{
2725b5a20d3cSdrh       char *zTrace;
2726b5a20d3cSdrh       int len;
2727b5a20d3cSdrh       if( pDb->zTrace ){
2728b5a20d3cSdrh         Tcl_Free(pDb->zTrace);
2729b5a20d3cSdrh       }
2730b5a20d3cSdrh       zTrace = Tcl_GetStringFromObj(objv[2], &len);
2731b5a20d3cSdrh       if( zTrace && len>0 ){
2732b5a20d3cSdrh         pDb->zTrace = Tcl_Alloc( len + 1 );
27335bb3eb9bSdrh         memcpy(pDb->zTrace, zTrace, len+1);
2734b5a20d3cSdrh       }else{
2735b5a20d3cSdrh         pDb->zTrace = 0;
2736b5a20d3cSdrh       }
2737bb201344Sshaneh #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
2738b5a20d3cSdrh       if( pDb->zTrace ){
2739b5a20d3cSdrh         pDb->interp = interp;
27406f8a503dSdanielk1977         sqlite3_trace(pDb->db, DbTraceHandler, pDb);
2741b5a20d3cSdrh       }else{
27426f8a503dSdanielk1977         sqlite3_trace(pDb->db, 0, 0);
2743b5a20d3cSdrh       }
274419e2d37fSdrh #endif
2745b5a20d3cSdrh     }
2746b5a20d3cSdrh     break;
2747b5a20d3cSdrh   }
2748b5a20d3cSdrh 
27493d21423cSdrh   /*    $db transaction [-deferred|-immediate|-exclusive] SCRIPT
27503d21423cSdrh   **
27513d21423cSdrh   ** Start a new transaction (if we are not already in the midst of a
27523d21423cSdrh   ** transaction) and execute the TCL script SCRIPT.  After SCRIPT
27533d21423cSdrh   ** completes, either commit the transaction or roll it back if SCRIPT
27543d21423cSdrh   ** throws an exception.  Or if no new transation was started, do nothing.
27553d21423cSdrh   ** pass the exception on up the stack.
27563d21423cSdrh   **
27573d21423cSdrh   ** This command was inspired by Dave Thomas's talk on Ruby at the
27583d21423cSdrh   ** 2005 O'Reilly Open Source Convention (OSCON).
27593d21423cSdrh   */
27603d21423cSdrh   case DB_TRANSACTION: {
27613d21423cSdrh     Tcl_Obj *pScript;
2762cd38d520Sdanielk1977     const char *zBegin = "SAVEPOINT _tcl_transaction";
27633d21423cSdrh     if( objc!=3 && objc!=4 ){
27643d21423cSdrh       Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
27653d21423cSdrh       return TCL_ERROR;
27663d21423cSdrh     }
2767cd38d520Sdanielk1977 
27684a4c11aaSdan     if( pDb->nTransaction==0 && objc==4 ){
27693d21423cSdrh       static const char *TTYPE_strs[] = {
2770ce604012Sdrh         "deferred",   "exclusive",  "immediate", 0
27713d21423cSdrh       };
27723d21423cSdrh       enum TTYPE_enum {
27733d21423cSdrh         TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
27743d21423cSdrh       };
27753d21423cSdrh       int ttype;
2776b5555e7eSdrh       if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
27773d21423cSdrh                               0, &ttype) ){
27783d21423cSdrh         return TCL_ERROR;
27793d21423cSdrh       }
27803d21423cSdrh       switch( (enum TTYPE_enum)ttype ){
27813d21423cSdrh         case TTYPE_DEFERRED:    /* no-op */;                 break;
27823d21423cSdrh         case TTYPE_EXCLUSIVE:   zBegin = "BEGIN EXCLUSIVE";  break;
27833d21423cSdrh         case TTYPE_IMMEDIATE:   zBegin = "BEGIN IMMEDIATE";  break;
27843d21423cSdrh       }
27853d21423cSdrh     }
2786cd38d520Sdanielk1977     pScript = objv[objc-1];
2787cd38d520Sdanielk1977 
27884a4c11aaSdan     /* Run the SQLite BEGIN command to open a transaction or savepoint. */
27891f1549f8Sdrh     pDb->disableAuth++;
2790cd38d520Sdanielk1977     rc = sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
27911f1549f8Sdrh     pDb->disableAuth--;
2792cd38d520Sdanielk1977     if( rc!=SQLITE_OK ){
2793cd38d520Sdanielk1977       Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
2794cd38d520Sdanielk1977       return TCL_ERROR;
27953d21423cSdrh     }
2796cd38d520Sdanielk1977     pDb->nTransaction++;
2797cd38d520Sdanielk1977 
27984a4c11aaSdan     /* If using NRE, schedule a callback to invoke the script pScript, then
27994a4c11aaSdan     ** a second callback to commit (or rollback) the transaction or savepoint
28004a4c11aaSdan     ** opened above. If not using NRE, evaluate the script directly, then
28014a4c11aaSdan     ** call function DbTransPostCmd() to commit (or rollback) the transaction
28024a4c11aaSdan     ** or savepoint.  */
28034a4c11aaSdan     if( DbUseNre() ){
28044a4c11aaSdan       Tcl_NRAddCallback(interp, DbTransPostCmd, cd, 0, 0, 0);
28054a4c11aaSdan       Tcl_NREvalObj(interp, pScript, 0);
28063d21423cSdrh     }else{
28074a4c11aaSdan       rc = DbTransPostCmd(&cd, interp, Tcl_EvalObjEx(interp, pScript, 0));
28083d21423cSdrh     }
28093d21423cSdrh     break;
28103d21423cSdrh   }
28113d21423cSdrh 
281294eb6a14Sdanielk1977   /*
2813404ca075Sdanielk1977   **    $db unlock_notify ?script?
2814404ca075Sdanielk1977   */
2815404ca075Sdanielk1977   case DB_UNLOCK_NOTIFY: {
2816404ca075Sdanielk1977 #ifndef SQLITE_ENABLE_UNLOCK_NOTIFY
2817404ca075Sdanielk1977     Tcl_AppendResult(interp, "unlock_notify not available in this build", 0);
2818404ca075Sdanielk1977     rc = TCL_ERROR;
2819404ca075Sdanielk1977 #else
2820404ca075Sdanielk1977     if( objc!=2 && objc!=3 ){
2821404ca075Sdanielk1977       Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
2822404ca075Sdanielk1977       rc = TCL_ERROR;
2823404ca075Sdanielk1977     }else{
2824404ca075Sdanielk1977       void (*xNotify)(void **, int) = 0;
2825404ca075Sdanielk1977       void *pNotifyArg = 0;
2826404ca075Sdanielk1977 
2827404ca075Sdanielk1977       if( pDb->pUnlockNotify ){
2828404ca075Sdanielk1977         Tcl_DecrRefCount(pDb->pUnlockNotify);
2829404ca075Sdanielk1977         pDb->pUnlockNotify = 0;
2830404ca075Sdanielk1977       }
2831404ca075Sdanielk1977 
2832404ca075Sdanielk1977       if( objc==3 ){
2833404ca075Sdanielk1977         xNotify = DbUnlockNotify;
2834404ca075Sdanielk1977         pNotifyArg = (void *)pDb;
2835404ca075Sdanielk1977         pDb->pUnlockNotify = objv[2];
2836404ca075Sdanielk1977         Tcl_IncrRefCount(pDb->pUnlockNotify);
2837404ca075Sdanielk1977       }
2838404ca075Sdanielk1977 
2839404ca075Sdanielk1977       if( sqlite3_unlock_notify(pDb->db, xNotify, pNotifyArg) ){
2840404ca075Sdanielk1977         Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
2841404ca075Sdanielk1977         rc = TCL_ERROR;
2842404ca075Sdanielk1977       }
2843404ca075Sdanielk1977     }
2844404ca075Sdanielk1977 #endif
2845404ca075Sdanielk1977     break;
2846404ca075Sdanielk1977   }
2847404ca075Sdanielk1977 
284846c47d46Sdan   case DB_PREUPDATE: {
2849*37db03bfSdan     static const char *azSub[] = {"count", "hook", "new", "old", 0};
285046c47d46Sdan     enum DbPreupdateSubCmd {
2851*37db03bfSdan       PRE_COUNT, PRE_HOOK, PRE_NEW, PRE_OLD
285246c47d46Sdan     };
285346c47d46Sdan     int iSub;
285446c47d46Sdan 
285546c47d46Sdan     if( objc<3 ){
285646c47d46Sdan       Tcl_WrongNumArgs(interp, 2, objv, "SUB-COMMAND ?ARGS?");
285746c47d46Sdan     }
285846c47d46Sdan     if( Tcl_GetIndexFromObj(interp, objv[2], azSub, "sub-command", 0, &iSub) ){
285946c47d46Sdan       return TCL_ERROR;
286046c47d46Sdan     }
286146c47d46Sdan 
286246c47d46Sdan     switch( (enum DbPreupdateSubCmd)iSub ){
286346c47d46Sdan       case PRE_COUNT: {
286446c47d46Sdan         int nCol = sqlite3_preupdate_count(pDb->db);
286546c47d46Sdan         Tcl_SetObjResult(interp, Tcl_NewIntObj(nCol));
286646c47d46Sdan         break;
286746c47d46Sdan       }
286846c47d46Sdan 
286946c47d46Sdan       case PRE_HOOK: {
287046c47d46Sdan         if( objc>4 ){
287146c47d46Sdan           Tcl_WrongNumArgs(interp, 2, objv, "hook ?SCRIPT?");
287246c47d46Sdan           return TCL_ERROR;
287346c47d46Sdan         }
287446c47d46Sdan         DbHookCmd(interp, pDb, (objc==4 ? objv[3] : 0), &pDb->pPreUpdateHook);
287546c47d46Sdan         break;
287646c47d46Sdan       }
287746c47d46Sdan 
2878*37db03bfSdan       case PRE_NEW:
287946c47d46Sdan       case PRE_OLD: {
288046c47d46Sdan         int iIdx;
2881*37db03bfSdan         sqlite3_value *pValue;
288246c47d46Sdan         if( objc!=4 ){
288346c47d46Sdan           Tcl_WrongNumArgs(interp, 3, objv, "INDEX");
288446c47d46Sdan           return TCL_ERROR;
288546c47d46Sdan         }
288646c47d46Sdan         if( Tcl_GetIntFromObj(interp, objv[3], &iIdx) ){
288746c47d46Sdan           return TCL_ERROR;
288846c47d46Sdan         }
288946c47d46Sdan 
2890*37db03bfSdan         if( iSub==PRE_OLD ){
289146c47d46Sdan           rc = sqlite3_preupdate_old(pDb->db, iIdx, &pValue);
2892*37db03bfSdan         }else{
2893*37db03bfSdan           assert( iSub==PRE_NEW );
2894*37db03bfSdan           rc = sqlite3_preupdate_new(pDb->db, iIdx, &pValue);
2895*37db03bfSdan         }
2896*37db03bfSdan 
289746c47d46Sdan         if( rc==SQLITE_OK ){
289846c47d46Sdan           Tcl_Obj *pObj = Tcl_NewStringObj(sqlite3_value_text(pValue), -1);
289946c47d46Sdan           Tcl_SetObjResult(interp, pObj);
2900*37db03bfSdan         }else{
290146c47d46Sdan           Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
290246c47d46Sdan           return TCL_ERROR;
290346c47d46Sdan         }
290446c47d46Sdan       }
290546c47d46Sdan     }
290646c47d46Sdan 
290746c47d46Sdan     break;
290846c47d46Sdan   }
290946c47d46Sdan 
2910404ca075Sdanielk1977   /*
2911833bf968Sdrh   **    $db wal_hook ?script?
291294eb6a14Sdanielk1977   **    $db update_hook ?script?
291371fd80bfSdanielk1977   **    $db rollback_hook ?script?
291494eb6a14Sdanielk1977   */
2915833bf968Sdrh   case DB_WAL_HOOK:
291671fd80bfSdanielk1977   case DB_UPDATE_HOOK:
29176566ebe1Sdan   case DB_ROLLBACK_HOOK: {
291846c47d46Sdan     sqlite3 *db = pDb->db;
291971fd80bfSdanielk1977 
292071fd80bfSdanielk1977     /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
292171fd80bfSdanielk1977     ** whether [$db update_hook] or [$db rollback_hook] was invoked.
292271fd80bfSdanielk1977     */
292371fd80bfSdanielk1977     Tcl_Obj **ppHook;
292446c47d46Sdan     if( choice==DB_WAL_HOOK ) ppHook = &pDb->pWalHook;
292546c47d46Sdan     if( choice==DB_UPDATE_HOOK ) ppHook = &pDb->pUpdateHook;
292646c47d46Sdan     if( choice==DB_ROLLBACK_HOOK ) ppHook = &pDb->pRollbackHook;
292746c47d46Sdan     if( objc>3 ){
292894eb6a14Sdanielk1977        Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
292994eb6a14Sdanielk1977        return TCL_ERROR;
293094eb6a14Sdanielk1977     }
293171fd80bfSdanielk1977 
293246c47d46Sdan     DbHookCmd(interp, pDb, (objc==3 ? objv[2] : 0), ppHook);
293394eb6a14Sdanielk1977     break;
293494eb6a14Sdanielk1977   }
293594eb6a14Sdanielk1977 
29364397de57Sdanielk1977   /*    $db version
29374397de57Sdanielk1977   **
29384397de57Sdanielk1977   ** Return the version string for this database.
29394397de57Sdanielk1977   */
29404397de57Sdanielk1977   case DB_VERSION: {
29414397de57Sdanielk1977     Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
29424397de57Sdanielk1977     break;
29434397de57Sdanielk1977   }
29444397de57Sdanielk1977 
29451067fe11Stpoindex 
29466d31316cSdrh   } /* End of the SWITCH statement */
294722fbcb8dSdrh   return rc;
294875897234Sdrh }
294975897234Sdrh 
2950a2c8a95bSdrh #if SQLITE_TCL_NRE
2951a2c8a95bSdrh /*
2952a2c8a95bSdrh ** Adaptor that provides an objCmd interface to the NRE-enabled
2953a2c8a95bSdrh ** interface implementation.
2954a2c8a95bSdrh */
2955a2c8a95bSdrh static int DbObjCmdAdaptor(
2956a2c8a95bSdrh   void *cd,
2957a2c8a95bSdrh   Tcl_Interp *interp,
2958a2c8a95bSdrh   int objc,
2959a2c8a95bSdrh   Tcl_Obj *const*objv
2960a2c8a95bSdrh ){
2961a2c8a95bSdrh   return Tcl_NRCallObjProc(interp, DbObjCmd, cd, objc, objv);
2962a2c8a95bSdrh }
2963a2c8a95bSdrh #endif /* SQLITE_TCL_NRE */
2964a2c8a95bSdrh 
296575897234Sdrh /*
29663570ad93Sdrh **   sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
29679a6284c1Sdanielk1977 **                           ?-create BOOLEAN? ?-nomutex BOOLEAN?
296875897234Sdrh **
296975897234Sdrh ** This is the main Tcl command.  When the "sqlite" Tcl command is
297075897234Sdrh ** invoked, this routine runs to process that command.
297175897234Sdrh **
297275897234Sdrh ** The first argument, DBNAME, is an arbitrary name for a new
297375897234Sdrh ** database connection.  This command creates a new command named
297475897234Sdrh ** DBNAME that is used to control that connection.  The database
297575897234Sdrh ** connection is deleted when the DBNAME command is deleted.
297675897234Sdrh **
29773570ad93Sdrh ** The second argument is the name of the database file.
2978fbc3eab8Sdrh **
297975897234Sdrh */
298022fbcb8dSdrh static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
2981bec3f402Sdrh   SqliteDb *p;
298222fbcb8dSdrh   void *pKey = 0;
298322fbcb8dSdrh   int nKey = 0;
298422fbcb8dSdrh   const char *zArg;
298575897234Sdrh   char *zErrMsg;
29863570ad93Sdrh   int i;
298722fbcb8dSdrh   const char *zFile;
29883570ad93Sdrh   const char *zVfs = 0;
2989d9da78a2Sdrh   int flags;
2990882e8e4dSdrh   Tcl_DString translatedFilename;
2991d9da78a2Sdrh 
2992d9da78a2Sdrh   /* In normal use, each TCL interpreter runs in a single thread.  So
2993d9da78a2Sdrh   ** by default, we can turn of mutexing on SQLite database connections.
2994d9da78a2Sdrh   ** However, for testing purposes it is useful to have mutexes turned
2995d9da78a2Sdrh   ** on.  So, by default, mutexes default off.  But if compiled with
2996d9da78a2Sdrh   ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on.
2997d9da78a2Sdrh   */
2998d9da78a2Sdrh #ifdef SQLITE_TCL_DEFAULT_FULLMUTEX
2999d9da78a2Sdrh   flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
3000d9da78a2Sdrh #else
3001d9da78a2Sdrh   flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX;
3002d9da78a2Sdrh #endif
3003d9da78a2Sdrh 
300422fbcb8dSdrh   if( objc==2 ){
300522fbcb8dSdrh     zArg = Tcl_GetStringFromObj(objv[1], 0);
300622fbcb8dSdrh     if( strcmp(zArg,"-version")==0 ){
30076f8a503dSdanielk1977       Tcl_AppendResult(interp,sqlite3_version,0);
3008647cb0e1Sdrh       return TCL_OK;
3009647cb0e1Sdrh     }
30109eb9e26bSdrh     if( strcmp(zArg,"-has-codec")==0 ){
30119eb9e26bSdrh #ifdef SQLITE_HAS_CODEC
301222fbcb8dSdrh       Tcl_AppendResult(interp,"1",0);
301322fbcb8dSdrh #else
301422fbcb8dSdrh       Tcl_AppendResult(interp,"0",0);
301522fbcb8dSdrh #endif
301622fbcb8dSdrh       return TCL_OK;
301722fbcb8dSdrh     }
3018fbc3eab8Sdrh   }
30193570ad93Sdrh   for(i=3; i+1<objc; i+=2){
30203570ad93Sdrh     zArg = Tcl_GetString(objv[i]);
302122fbcb8dSdrh     if( strcmp(zArg,"-key")==0 ){
30223570ad93Sdrh       pKey = Tcl_GetByteArrayFromObj(objv[i+1], &nKey);
30233570ad93Sdrh     }else if( strcmp(zArg, "-vfs")==0 ){
30243c3dd7b9Sdan       zVfs = Tcl_GetString(objv[i+1]);
30253570ad93Sdrh     }else if( strcmp(zArg, "-readonly")==0 ){
30263570ad93Sdrh       int b;
30273570ad93Sdrh       if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
30283570ad93Sdrh       if( b ){
302933f4e02aSdrh         flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
30303570ad93Sdrh         flags |= SQLITE_OPEN_READONLY;
30313570ad93Sdrh       }else{
30323570ad93Sdrh         flags &= ~SQLITE_OPEN_READONLY;
30333570ad93Sdrh         flags |= SQLITE_OPEN_READWRITE;
30343570ad93Sdrh       }
30353570ad93Sdrh     }else if( strcmp(zArg, "-create")==0 ){
30363570ad93Sdrh       int b;
30373570ad93Sdrh       if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
303833f4e02aSdrh       if( b && (flags & SQLITE_OPEN_READONLY)==0 ){
30393570ad93Sdrh         flags |= SQLITE_OPEN_CREATE;
30403570ad93Sdrh       }else{
30413570ad93Sdrh         flags &= ~SQLITE_OPEN_CREATE;
30423570ad93Sdrh       }
30439a6284c1Sdanielk1977     }else if( strcmp(zArg, "-nomutex")==0 ){
30449a6284c1Sdanielk1977       int b;
30459a6284c1Sdanielk1977       if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
30469a6284c1Sdanielk1977       if( b ){
30479a6284c1Sdanielk1977         flags |= SQLITE_OPEN_NOMUTEX;
3048039963adSdrh         flags &= ~SQLITE_OPEN_FULLMUTEX;
30499a6284c1Sdanielk1977       }else{
30509a6284c1Sdanielk1977         flags &= ~SQLITE_OPEN_NOMUTEX;
30519a6284c1Sdanielk1977       }
3052039963adSdrh    }else if( strcmp(zArg, "-fullmutex")==0 ){
3053039963adSdrh       int b;
3054039963adSdrh       if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3055039963adSdrh       if( b ){
3056039963adSdrh         flags |= SQLITE_OPEN_FULLMUTEX;
3057039963adSdrh         flags &= ~SQLITE_OPEN_NOMUTEX;
3058039963adSdrh       }else{
3059039963adSdrh         flags &= ~SQLITE_OPEN_FULLMUTEX;
3060039963adSdrh       }
30613570ad93Sdrh     }else{
30623570ad93Sdrh       Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
30633570ad93Sdrh       return TCL_ERROR;
306422fbcb8dSdrh     }
306522fbcb8dSdrh   }
30663570ad93Sdrh   if( objc<3 || (objc&1)!=1 ){
306722fbcb8dSdrh     Tcl_WrongNumArgs(interp, 1, objv,
30683570ad93Sdrh       "HANDLE FILENAME ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
3069039963adSdrh       " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN?"
30709eb9e26bSdrh #ifdef SQLITE_HAS_CODEC
30713570ad93Sdrh       " ?-key CODECKEY?"
307222fbcb8dSdrh #endif
307322fbcb8dSdrh     );
307475897234Sdrh     return TCL_ERROR;
307575897234Sdrh   }
307675897234Sdrh   zErrMsg = 0;
30774cdc9e84Sdrh   p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
307875897234Sdrh   if( p==0 ){
3079bec3f402Sdrh     Tcl_SetResult(interp, "malloc failed", TCL_STATIC);
3080bec3f402Sdrh     return TCL_ERROR;
3081bec3f402Sdrh   }
3082bec3f402Sdrh   memset(p, 0, sizeof(*p));
308322fbcb8dSdrh   zFile = Tcl_GetStringFromObj(objv[2], 0);
3084882e8e4dSdrh   zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
30853570ad93Sdrh   sqlite3_open_v2(zFile, &p->db, flags, zVfs);
3086882e8e4dSdrh   Tcl_DStringFree(&translatedFilename);
308780290863Sdanielk1977   if( SQLITE_OK!=sqlite3_errcode(p->db) ){
30889404d50eSdrh     zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
308980290863Sdanielk1977     sqlite3_close(p->db);
309080290863Sdanielk1977     p->db = 0;
309180290863Sdanielk1977   }
30922011d5f5Sdrh #ifdef SQLITE_HAS_CODEC
3093f3a65f7eSdrh   if( p->db ){
30942011d5f5Sdrh     sqlite3_key(p->db, pKey, nKey);
3095f3a65f7eSdrh   }
3096eb8ed70dSdrh #endif
3097bec3f402Sdrh   if( p->db==0 ){
309875897234Sdrh     Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
3099bec3f402Sdrh     Tcl_Free((char*)p);
31009404d50eSdrh     sqlite3_free(zErrMsg);
310175897234Sdrh     return TCL_ERROR;
310275897234Sdrh   }
3103fb7e7651Sdrh   p->maxStmt = NUM_PREPARED_STMTS;
31045169bbc6Sdrh   p->interp = interp;
310522fbcb8dSdrh   zArg = Tcl_GetStringFromObj(objv[1], 0);
31064a4c11aaSdan   if( DbUseNre() ){
3107a2c8a95bSdrh     Tcl_NRCreateCommand(interp, zArg, DbObjCmdAdaptor, DbObjCmd,
3108a2c8a95bSdrh                         (char*)p, DbDeleteCmd);
31094a4c11aaSdan   }else{
311022fbcb8dSdrh     Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
31114a4c11aaSdan   }
311275897234Sdrh   return TCL_OK;
311375897234Sdrh }
311475897234Sdrh 
311575897234Sdrh /*
311690ca9753Sdrh ** Provide a dummy Tcl_InitStubs if we are using this as a static
311790ca9753Sdrh ** library.
311890ca9753Sdrh */
311990ca9753Sdrh #ifndef USE_TCL_STUBS
312090ca9753Sdrh # undef  Tcl_InitStubs
312190ca9753Sdrh # define Tcl_InitStubs(a,b,c)
312290ca9753Sdrh #endif
312390ca9753Sdrh 
312490ca9753Sdrh /*
312529bc4615Sdrh ** Make sure we have a PACKAGE_VERSION macro defined.  This will be
312629bc4615Sdrh ** defined automatically by the TEA makefile.  But other makefiles
312729bc4615Sdrh ** do not define it.
312829bc4615Sdrh */
312929bc4615Sdrh #ifndef PACKAGE_VERSION
313029bc4615Sdrh # define PACKAGE_VERSION SQLITE_VERSION
313129bc4615Sdrh #endif
313229bc4615Sdrh 
313329bc4615Sdrh /*
313475897234Sdrh ** Initialize this module.
313575897234Sdrh **
313675897234Sdrh ** This Tcl module contains only a single new Tcl command named "sqlite".
313775897234Sdrh ** (Hence there is no namespace.  There is no point in using a namespace
313875897234Sdrh ** if the extension only supplies one new name!)  The "sqlite" command is
313975897234Sdrh ** used to open a new SQLite database.  See the DbMain() routine above
314075897234Sdrh ** for additional information.
3141b652f432Sdrh **
3142b652f432Sdrh ** The EXTERN macros are required by TCL in order to work on windows.
314375897234Sdrh */
3144b652f432Sdrh EXTERN int Sqlite3_Init(Tcl_Interp *interp){
314592febd92Sdrh   Tcl_InitStubs(interp, "8.4", 0);
3146ef4ac8f9Sdrh   Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
314729bc4615Sdrh   Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
31481cca0d22Sdrh 
31491cca0d22Sdrh #ifndef SQLITE_3_SUFFIX_ONLY
31501cca0d22Sdrh   /* The "sqlite" alias is undocumented.  It is here only to support
31511cca0d22Sdrh   ** legacy scripts.  All new scripts should use only the "sqlite3"
31521cca0d22Sdrh   ** command.
31531cca0d22Sdrh   */
315449766d6cSdrh   Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
31554c0f1649Sdrh #endif
31561cca0d22Sdrh 
315790ca9753Sdrh   return TCL_OK;
315890ca9753Sdrh }
3159b652f432Sdrh EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3160b652f432Sdrh EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
3161b652f432Sdrh EXTERN int Tclsqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
3162b652f432Sdrh EXTERN int Sqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3163b652f432Sdrh EXTERN int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3164b652f432Sdrh EXTERN int Sqlite3_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3165b652f432Sdrh EXTERN int Tclsqlite3_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK;}
3166e2c3a659Sdrh 
316749766d6cSdrh 
316849766d6cSdrh #ifndef SQLITE_3_SUFFIX_ONLY
3169a3e63c4aSdan int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3170a3e63c4aSdan int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3171a3e63c4aSdan int Sqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
3172a3e63c4aSdan int Tclsqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
3173a3e63c4aSdan int Sqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3174a3e63c4aSdan int Tclsqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3175a3e63c4aSdan int Sqlite_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3176a3e63c4aSdan int Tclsqlite_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK;}
317749766d6cSdrh #endif
317875897234Sdrh 
31793e27c026Sdrh #ifdef TCLSH
31803e27c026Sdrh /*****************************************************************************
318157a0227fSdrh ** All of the code that follows is used to build standalone TCL interpreters
318257a0227fSdrh ** that are statically linked with SQLite.  Enable these by compiling
318357a0227fSdrh ** with -DTCLSH=n where n can be 1 or 2.  An n of 1 generates a standard
318457a0227fSdrh ** tclsh but with SQLite built in.  An n of 2 generates the SQLite space
318557a0227fSdrh ** analysis program.
318675897234Sdrh */
3187348784efSdrh 
318857a0227fSdrh #if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
318957a0227fSdrh /*
319057a0227fSdrh  * This code implements the MD5 message-digest algorithm.
319157a0227fSdrh  * The algorithm is due to Ron Rivest.  This code was
319257a0227fSdrh  * written by Colin Plumb in 1993, no copyright is claimed.
319357a0227fSdrh  * This code is in the public domain; do with it what you wish.
319457a0227fSdrh  *
319557a0227fSdrh  * Equivalent code is available from RSA Data Security, Inc.
319657a0227fSdrh  * This code has been tested against that, and is equivalent,
319757a0227fSdrh  * except that you don't need to include two pages of legalese
319857a0227fSdrh  * with every copy.
319957a0227fSdrh  *
320057a0227fSdrh  * To compute the message digest of a chunk of bytes, declare an
320157a0227fSdrh  * MD5Context structure, pass it to MD5Init, call MD5Update as
320257a0227fSdrh  * needed on buffers full of bytes, and then call MD5Final, which
320357a0227fSdrh  * will fill a supplied 16-byte array with the digest.
320457a0227fSdrh  */
320557a0227fSdrh 
320657a0227fSdrh /*
320757a0227fSdrh  * If compiled on a machine that doesn't have a 32-bit integer,
320857a0227fSdrh  * you just set "uint32" to the appropriate datatype for an
320957a0227fSdrh  * unsigned 32-bit integer.  For example:
321057a0227fSdrh  *
321157a0227fSdrh  *       cc -Duint32='unsigned long' md5.c
321257a0227fSdrh  *
321357a0227fSdrh  */
321457a0227fSdrh #ifndef uint32
321557a0227fSdrh #  define uint32 unsigned int
321657a0227fSdrh #endif
321757a0227fSdrh 
321857a0227fSdrh struct MD5Context {
321957a0227fSdrh   int isInit;
322057a0227fSdrh   uint32 buf[4];
322157a0227fSdrh   uint32 bits[2];
322257a0227fSdrh   unsigned char in[64];
322357a0227fSdrh };
322457a0227fSdrh typedef struct MD5Context MD5Context;
322557a0227fSdrh 
322657a0227fSdrh /*
322757a0227fSdrh  * Note: this code is harmless on little-endian machines.
322857a0227fSdrh  */
322957a0227fSdrh static void byteReverse (unsigned char *buf, unsigned longs){
323057a0227fSdrh         uint32 t;
323157a0227fSdrh         do {
323257a0227fSdrh                 t = (uint32)((unsigned)buf[3]<<8 | buf[2]) << 16 |
323357a0227fSdrh                             ((unsigned)buf[1]<<8 | buf[0]);
323457a0227fSdrh                 *(uint32 *)buf = t;
323557a0227fSdrh                 buf += 4;
323657a0227fSdrh         } while (--longs);
323757a0227fSdrh }
323857a0227fSdrh /* The four core functions - F1 is optimized somewhat */
323957a0227fSdrh 
324057a0227fSdrh /* #define F1(x, y, z) (x & y | ~x & z) */
324157a0227fSdrh #define F1(x, y, z) (z ^ (x & (y ^ z)))
324257a0227fSdrh #define F2(x, y, z) F1(z, x, y)
324357a0227fSdrh #define F3(x, y, z) (x ^ y ^ z)
324457a0227fSdrh #define F4(x, y, z) (y ^ (x | ~z))
324557a0227fSdrh 
324657a0227fSdrh /* This is the central step in the MD5 algorithm. */
324757a0227fSdrh #define MD5STEP(f, w, x, y, z, data, s) \
324857a0227fSdrh         ( w += f(x, y, z) + data,  w = w<<s | w>>(32-s),  w += x )
324957a0227fSdrh 
325057a0227fSdrh /*
325157a0227fSdrh  * The core of the MD5 algorithm, this alters an existing MD5 hash to
325257a0227fSdrh  * reflect the addition of 16 longwords of new data.  MD5Update blocks
325357a0227fSdrh  * the data and converts bytes into longwords for this routine.
325457a0227fSdrh  */
325557a0227fSdrh static void MD5Transform(uint32 buf[4], const uint32 in[16]){
325657a0227fSdrh         register uint32 a, b, c, d;
325757a0227fSdrh 
325857a0227fSdrh         a = buf[0];
325957a0227fSdrh         b = buf[1];
326057a0227fSdrh         c = buf[2];
326157a0227fSdrh         d = buf[3];
326257a0227fSdrh 
326357a0227fSdrh         MD5STEP(F1, a, b, c, d, in[ 0]+0xd76aa478,  7);
326457a0227fSdrh         MD5STEP(F1, d, a, b, c, in[ 1]+0xe8c7b756, 12);
326557a0227fSdrh         MD5STEP(F1, c, d, a, b, in[ 2]+0x242070db, 17);
326657a0227fSdrh         MD5STEP(F1, b, c, d, a, in[ 3]+0xc1bdceee, 22);
326757a0227fSdrh         MD5STEP(F1, a, b, c, d, in[ 4]+0xf57c0faf,  7);
326857a0227fSdrh         MD5STEP(F1, d, a, b, c, in[ 5]+0x4787c62a, 12);
326957a0227fSdrh         MD5STEP(F1, c, d, a, b, in[ 6]+0xa8304613, 17);
327057a0227fSdrh         MD5STEP(F1, b, c, d, a, in[ 7]+0xfd469501, 22);
327157a0227fSdrh         MD5STEP(F1, a, b, c, d, in[ 8]+0x698098d8,  7);
327257a0227fSdrh         MD5STEP(F1, d, a, b, c, in[ 9]+0x8b44f7af, 12);
327357a0227fSdrh         MD5STEP(F1, c, d, a, b, in[10]+0xffff5bb1, 17);
327457a0227fSdrh         MD5STEP(F1, b, c, d, a, in[11]+0x895cd7be, 22);
327557a0227fSdrh         MD5STEP(F1, a, b, c, d, in[12]+0x6b901122,  7);
327657a0227fSdrh         MD5STEP(F1, d, a, b, c, in[13]+0xfd987193, 12);
327757a0227fSdrh         MD5STEP(F1, c, d, a, b, in[14]+0xa679438e, 17);
327857a0227fSdrh         MD5STEP(F1, b, c, d, a, in[15]+0x49b40821, 22);
327957a0227fSdrh 
328057a0227fSdrh         MD5STEP(F2, a, b, c, d, in[ 1]+0xf61e2562,  5);
328157a0227fSdrh         MD5STEP(F2, d, a, b, c, in[ 6]+0xc040b340,  9);
328257a0227fSdrh         MD5STEP(F2, c, d, a, b, in[11]+0x265e5a51, 14);
328357a0227fSdrh         MD5STEP(F2, b, c, d, a, in[ 0]+0xe9b6c7aa, 20);
328457a0227fSdrh         MD5STEP(F2, a, b, c, d, in[ 5]+0xd62f105d,  5);
328557a0227fSdrh         MD5STEP(F2, d, a, b, c, in[10]+0x02441453,  9);
328657a0227fSdrh         MD5STEP(F2, c, d, a, b, in[15]+0xd8a1e681, 14);
328757a0227fSdrh         MD5STEP(F2, b, c, d, a, in[ 4]+0xe7d3fbc8, 20);
328857a0227fSdrh         MD5STEP(F2, a, b, c, d, in[ 9]+0x21e1cde6,  5);
328957a0227fSdrh         MD5STEP(F2, d, a, b, c, in[14]+0xc33707d6,  9);
329057a0227fSdrh         MD5STEP(F2, c, d, a, b, in[ 3]+0xf4d50d87, 14);
329157a0227fSdrh         MD5STEP(F2, b, c, d, a, in[ 8]+0x455a14ed, 20);
329257a0227fSdrh         MD5STEP(F2, a, b, c, d, in[13]+0xa9e3e905,  5);
329357a0227fSdrh         MD5STEP(F2, d, a, b, c, in[ 2]+0xfcefa3f8,  9);
329457a0227fSdrh         MD5STEP(F2, c, d, a, b, in[ 7]+0x676f02d9, 14);
329557a0227fSdrh         MD5STEP(F2, b, c, d, a, in[12]+0x8d2a4c8a, 20);
329657a0227fSdrh 
329757a0227fSdrh         MD5STEP(F3, a, b, c, d, in[ 5]+0xfffa3942,  4);
329857a0227fSdrh         MD5STEP(F3, d, a, b, c, in[ 8]+0x8771f681, 11);
329957a0227fSdrh         MD5STEP(F3, c, d, a, b, in[11]+0x6d9d6122, 16);
330057a0227fSdrh         MD5STEP(F3, b, c, d, a, in[14]+0xfde5380c, 23);
330157a0227fSdrh         MD5STEP(F3, a, b, c, d, in[ 1]+0xa4beea44,  4);
330257a0227fSdrh         MD5STEP(F3, d, a, b, c, in[ 4]+0x4bdecfa9, 11);
330357a0227fSdrh         MD5STEP(F3, c, d, a, b, in[ 7]+0xf6bb4b60, 16);
330457a0227fSdrh         MD5STEP(F3, b, c, d, a, in[10]+0xbebfbc70, 23);
330557a0227fSdrh         MD5STEP(F3, a, b, c, d, in[13]+0x289b7ec6,  4);
330657a0227fSdrh         MD5STEP(F3, d, a, b, c, in[ 0]+0xeaa127fa, 11);
330757a0227fSdrh         MD5STEP(F3, c, d, a, b, in[ 3]+0xd4ef3085, 16);
330857a0227fSdrh         MD5STEP(F3, b, c, d, a, in[ 6]+0x04881d05, 23);
330957a0227fSdrh         MD5STEP(F3, a, b, c, d, in[ 9]+0xd9d4d039,  4);
331057a0227fSdrh         MD5STEP(F3, d, a, b, c, in[12]+0xe6db99e5, 11);
331157a0227fSdrh         MD5STEP(F3, c, d, a, b, in[15]+0x1fa27cf8, 16);
331257a0227fSdrh         MD5STEP(F3, b, c, d, a, in[ 2]+0xc4ac5665, 23);
331357a0227fSdrh 
331457a0227fSdrh         MD5STEP(F4, a, b, c, d, in[ 0]+0xf4292244,  6);
331557a0227fSdrh         MD5STEP(F4, d, a, b, c, in[ 7]+0x432aff97, 10);
331657a0227fSdrh         MD5STEP(F4, c, d, a, b, in[14]+0xab9423a7, 15);
331757a0227fSdrh         MD5STEP(F4, b, c, d, a, in[ 5]+0xfc93a039, 21);
331857a0227fSdrh         MD5STEP(F4, a, b, c, d, in[12]+0x655b59c3,  6);
331957a0227fSdrh         MD5STEP(F4, d, a, b, c, in[ 3]+0x8f0ccc92, 10);
332057a0227fSdrh         MD5STEP(F4, c, d, a, b, in[10]+0xffeff47d, 15);
332157a0227fSdrh         MD5STEP(F4, b, c, d, a, in[ 1]+0x85845dd1, 21);
332257a0227fSdrh         MD5STEP(F4, a, b, c, d, in[ 8]+0x6fa87e4f,  6);
332357a0227fSdrh         MD5STEP(F4, d, a, b, c, in[15]+0xfe2ce6e0, 10);
332457a0227fSdrh         MD5STEP(F4, c, d, a, b, in[ 6]+0xa3014314, 15);
332557a0227fSdrh         MD5STEP(F4, b, c, d, a, in[13]+0x4e0811a1, 21);
332657a0227fSdrh         MD5STEP(F4, a, b, c, d, in[ 4]+0xf7537e82,  6);
332757a0227fSdrh         MD5STEP(F4, d, a, b, c, in[11]+0xbd3af235, 10);
332857a0227fSdrh         MD5STEP(F4, c, d, a, b, in[ 2]+0x2ad7d2bb, 15);
332957a0227fSdrh         MD5STEP(F4, b, c, d, a, in[ 9]+0xeb86d391, 21);
333057a0227fSdrh 
333157a0227fSdrh         buf[0] += a;
333257a0227fSdrh         buf[1] += b;
333357a0227fSdrh         buf[2] += c;
333457a0227fSdrh         buf[3] += d;
333557a0227fSdrh }
333657a0227fSdrh 
333757a0227fSdrh /*
333857a0227fSdrh  * Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious
333957a0227fSdrh  * initialization constants.
334057a0227fSdrh  */
334157a0227fSdrh static void MD5Init(MD5Context *ctx){
334257a0227fSdrh         ctx->isInit = 1;
334357a0227fSdrh         ctx->buf[0] = 0x67452301;
334457a0227fSdrh         ctx->buf[1] = 0xefcdab89;
334557a0227fSdrh         ctx->buf[2] = 0x98badcfe;
334657a0227fSdrh         ctx->buf[3] = 0x10325476;
334757a0227fSdrh         ctx->bits[0] = 0;
334857a0227fSdrh         ctx->bits[1] = 0;
334957a0227fSdrh }
335057a0227fSdrh 
335157a0227fSdrh /*
335257a0227fSdrh  * Update context to reflect the concatenation of another buffer full
335357a0227fSdrh  * of bytes.
335457a0227fSdrh  */
335557a0227fSdrh static
335657a0227fSdrh void MD5Update(MD5Context *ctx, const unsigned char *buf, unsigned int len){
335757a0227fSdrh         uint32 t;
335857a0227fSdrh 
335957a0227fSdrh         /* Update bitcount */
336057a0227fSdrh 
336157a0227fSdrh         t = ctx->bits[0];
336257a0227fSdrh         if ((ctx->bits[0] = t + ((uint32)len << 3)) < t)
336357a0227fSdrh                 ctx->bits[1]++; /* Carry from low to high */
336457a0227fSdrh         ctx->bits[1] += len >> 29;
336557a0227fSdrh 
336657a0227fSdrh         t = (t >> 3) & 0x3f;    /* Bytes already in shsInfo->data */
336757a0227fSdrh 
336857a0227fSdrh         /* Handle any leading odd-sized chunks */
336957a0227fSdrh 
337057a0227fSdrh         if ( t ) {
337157a0227fSdrh                 unsigned char *p = (unsigned char *)ctx->in + t;
337257a0227fSdrh 
337357a0227fSdrh                 t = 64-t;
337457a0227fSdrh                 if (len < t) {
337557a0227fSdrh                         memcpy(p, buf, len);
337657a0227fSdrh                         return;
337757a0227fSdrh                 }
337857a0227fSdrh                 memcpy(p, buf, t);
337957a0227fSdrh                 byteReverse(ctx->in, 16);
338057a0227fSdrh                 MD5Transform(ctx->buf, (uint32 *)ctx->in);
338157a0227fSdrh                 buf += t;
338257a0227fSdrh                 len -= t;
338357a0227fSdrh         }
338457a0227fSdrh 
338557a0227fSdrh         /* Process data in 64-byte chunks */
338657a0227fSdrh 
338757a0227fSdrh         while (len >= 64) {
338857a0227fSdrh                 memcpy(ctx->in, buf, 64);
338957a0227fSdrh                 byteReverse(ctx->in, 16);
339057a0227fSdrh                 MD5Transform(ctx->buf, (uint32 *)ctx->in);
339157a0227fSdrh                 buf += 64;
339257a0227fSdrh                 len -= 64;
339357a0227fSdrh         }
339457a0227fSdrh 
339557a0227fSdrh         /* Handle any remaining bytes of data. */
339657a0227fSdrh 
339757a0227fSdrh         memcpy(ctx->in, buf, len);
339857a0227fSdrh }
339957a0227fSdrh 
340057a0227fSdrh /*
340157a0227fSdrh  * Final wrapup - pad to 64-byte boundary with the bit pattern
340257a0227fSdrh  * 1 0* (64-bit count of bits processed, MSB-first)
340357a0227fSdrh  */
340457a0227fSdrh static void MD5Final(unsigned char digest[16], MD5Context *ctx){
340557a0227fSdrh         unsigned count;
340657a0227fSdrh         unsigned char *p;
340757a0227fSdrh 
340857a0227fSdrh         /* Compute number of bytes mod 64 */
340957a0227fSdrh         count = (ctx->bits[0] >> 3) & 0x3F;
341057a0227fSdrh 
341157a0227fSdrh         /* Set the first char of padding to 0x80.  This is safe since there is
341257a0227fSdrh            always at least one byte free */
341357a0227fSdrh         p = ctx->in + count;
341457a0227fSdrh         *p++ = 0x80;
341557a0227fSdrh 
341657a0227fSdrh         /* Bytes of padding needed to make 64 bytes */
341757a0227fSdrh         count = 64 - 1 - count;
341857a0227fSdrh 
341957a0227fSdrh         /* Pad out to 56 mod 64 */
342057a0227fSdrh         if (count < 8) {
342157a0227fSdrh                 /* Two lots of padding:  Pad the first block to 64 bytes */
342257a0227fSdrh                 memset(p, 0, count);
342357a0227fSdrh                 byteReverse(ctx->in, 16);
342457a0227fSdrh                 MD5Transform(ctx->buf, (uint32 *)ctx->in);
342557a0227fSdrh 
342657a0227fSdrh                 /* Now fill the next block with 56 bytes */
342757a0227fSdrh                 memset(ctx->in, 0, 56);
342857a0227fSdrh         } else {
342957a0227fSdrh                 /* Pad block to 56 bytes */
343057a0227fSdrh                 memset(p, 0, count-8);
343157a0227fSdrh         }
343257a0227fSdrh         byteReverse(ctx->in, 14);
343357a0227fSdrh 
343457a0227fSdrh         /* Append length in bits and transform */
343557a0227fSdrh         ((uint32 *)ctx->in)[ 14 ] = ctx->bits[0];
343657a0227fSdrh         ((uint32 *)ctx->in)[ 15 ] = ctx->bits[1];
343757a0227fSdrh 
343857a0227fSdrh         MD5Transform(ctx->buf, (uint32 *)ctx->in);
343957a0227fSdrh         byteReverse((unsigned char *)ctx->buf, 4);
344057a0227fSdrh         memcpy(digest, ctx->buf, 16);
344157a0227fSdrh         memset(ctx, 0, sizeof(ctx));    /* In case it is sensitive */
344257a0227fSdrh }
344357a0227fSdrh 
344457a0227fSdrh /*
344557a0227fSdrh ** Convert a 128-bit MD5 digest into a 32-digit base-16 number.
344657a0227fSdrh */
344757a0227fSdrh static void MD5DigestToBase16(unsigned char *digest, char *zBuf){
344857a0227fSdrh   static char const zEncode[] = "0123456789abcdef";
344957a0227fSdrh   int i, j;
345057a0227fSdrh 
345157a0227fSdrh   for(j=i=0; i<16; i++){
345257a0227fSdrh     int a = digest[i];
345357a0227fSdrh     zBuf[j++] = zEncode[(a>>4)&0xf];
345457a0227fSdrh     zBuf[j++] = zEncode[a & 0xf];
345557a0227fSdrh   }
345657a0227fSdrh   zBuf[j] = 0;
345757a0227fSdrh }
345857a0227fSdrh 
345957a0227fSdrh 
346057a0227fSdrh /*
346157a0227fSdrh ** Convert a 128-bit MD5 digest into sequency of eight 5-digit integers
346257a0227fSdrh ** each representing 16 bits of the digest and separated from each
346357a0227fSdrh ** other by a "-" character.
346457a0227fSdrh */
346557a0227fSdrh static void MD5DigestToBase10x8(unsigned char digest[16], char zDigest[50]){
346657a0227fSdrh   int i, j;
346757a0227fSdrh   unsigned int x;
346857a0227fSdrh   for(i=j=0; i<16; i+=2){
346957a0227fSdrh     x = digest[i]*256 + digest[i+1];
347057a0227fSdrh     if( i>0 ) zDigest[j++] = '-';
347157a0227fSdrh     sprintf(&zDigest[j], "%05u", x);
347257a0227fSdrh     j += 5;
347357a0227fSdrh   }
347457a0227fSdrh   zDigest[j] = 0;
347557a0227fSdrh }
347657a0227fSdrh 
347757a0227fSdrh /*
347857a0227fSdrh ** A TCL command for md5.  The argument is the text to be hashed.  The
347957a0227fSdrh ** Result is the hash in base64.
348057a0227fSdrh */
348157a0227fSdrh static int md5_cmd(void*cd, Tcl_Interp *interp, int argc, const char **argv){
348257a0227fSdrh   MD5Context ctx;
348357a0227fSdrh   unsigned char digest[16];
348457a0227fSdrh   char zBuf[50];
348557a0227fSdrh   void (*converter)(unsigned char*, char*);
348657a0227fSdrh 
348757a0227fSdrh   if( argc!=2 ){
348857a0227fSdrh     Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
348957a0227fSdrh         " TEXT\"", 0);
349057a0227fSdrh     return TCL_ERROR;
349157a0227fSdrh   }
349257a0227fSdrh   MD5Init(&ctx);
349357a0227fSdrh   MD5Update(&ctx, (unsigned char*)argv[1], (unsigned)strlen(argv[1]));
349457a0227fSdrh   MD5Final(digest, &ctx);
349557a0227fSdrh   converter = (void(*)(unsigned char*,char*))cd;
349657a0227fSdrh   converter(digest, zBuf);
349757a0227fSdrh   Tcl_AppendResult(interp, zBuf, (char*)0);
349857a0227fSdrh   return TCL_OK;
349957a0227fSdrh }
350057a0227fSdrh 
350157a0227fSdrh /*
350257a0227fSdrh ** A TCL command to take the md5 hash of a file.  The argument is the
350357a0227fSdrh ** name of the file.
350457a0227fSdrh */
350557a0227fSdrh static int md5file_cmd(void*cd, Tcl_Interp*interp, int argc, const char **argv){
350657a0227fSdrh   FILE *in;
350757a0227fSdrh   MD5Context ctx;
350857a0227fSdrh   void (*converter)(unsigned char*, char*);
350957a0227fSdrh   unsigned char digest[16];
351057a0227fSdrh   char zBuf[10240];
351157a0227fSdrh 
351257a0227fSdrh   if( argc!=2 ){
351357a0227fSdrh     Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
351457a0227fSdrh         " FILENAME\"", 0);
351557a0227fSdrh     return TCL_ERROR;
351657a0227fSdrh   }
351757a0227fSdrh   in = fopen(argv[1],"rb");
351857a0227fSdrh   if( in==0 ){
351957a0227fSdrh     Tcl_AppendResult(interp,"unable to open file \"", argv[1],
352057a0227fSdrh          "\" for reading", 0);
352157a0227fSdrh     return TCL_ERROR;
352257a0227fSdrh   }
352357a0227fSdrh   MD5Init(&ctx);
352457a0227fSdrh   for(;;){
352557a0227fSdrh     int n;
352657a0227fSdrh     n = fread(zBuf, 1, sizeof(zBuf), in);
352757a0227fSdrh     if( n<=0 ) break;
352857a0227fSdrh     MD5Update(&ctx, (unsigned char*)zBuf, (unsigned)n);
352957a0227fSdrh   }
353057a0227fSdrh   fclose(in);
353157a0227fSdrh   MD5Final(digest, &ctx);
353257a0227fSdrh   converter = (void(*)(unsigned char*,char*))cd;
353357a0227fSdrh   converter(digest, zBuf);
353457a0227fSdrh   Tcl_AppendResult(interp, zBuf, (char*)0);
353557a0227fSdrh   return TCL_OK;
353657a0227fSdrh }
353757a0227fSdrh 
353857a0227fSdrh /*
353957a0227fSdrh ** Register the four new TCL commands for generating MD5 checksums
354057a0227fSdrh ** with the TCL interpreter.
354157a0227fSdrh */
354257a0227fSdrh int Md5_Init(Tcl_Interp *interp){
354357a0227fSdrh   Tcl_CreateCommand(interp, "md5", (Tcl_CmdProc*)md5_cmd,
354457a0227fSdrh                     MD5DigestToBase16, 0);
354557a0227fSdrh   Tcl_CreateCommand(interp, "md5-10x8", (Tcl_CmdProc*)md5_cmd,
354657a0227fSdrh                     MD5DigestToBase10x8, 0);
354757a0227fSdrh   Tcl_CreateCommand(interp, "md5file", (Tcl_CmdProc*)md5file_cmd,
354857a0227fSdrh                     MD5DigestToBase16, 0);
354957a0227fSdrh   Tcl_CreateCommand(interp, "md5file-10x8", (Tcl_CmdProc*)md5file_cmd,
355057a0227fSdrh                     MD5DigestToBase10x8, 0);
355157a0227fSdrh   return TCL_OK;
355257a0227fSdrh }
355357a0227fSdrh #endif /* defined(SQLITE_TEST) || defined(SQLITE_TCLMD5) */
355457a0227fSdrh 
355557a0227fSdrh #if defined(SQLITE_TEST)
355657a0227fSdrh /*
355757a0227fSdrh ** During testing, the special md5sum() aggregate function is available.
355857a0227fSdrh ** inside SQLite.  The following routines implement that function.
355957a0227fSdrh */
356057a0227fSdrh static void md5step(sqlite3_context *context, int argc, sqlite3_value **argv){
356157a0227fSdrh   MD5Context *p;
356257a0227fSdrh   int i;
356357a0227fSdrh   if( argc<1 ) return;
356457a0227fSdrh   p = sqlite3_aggregate_context(context, sizeof(*p));
356557a0227fSdrh   if( p==0 ) return;
356657a0227fSdrh   if( !p->isInit ){
356757a0227fSdrh     MD5Init(p);
356857a0227fSdrh   }
356957a0227fSdrh   for(i=0; i<argc; i++){
357057a0227fSdrh     const char *zData = (char*)sqlite3_value_text(argv[i]);
357157a0227fSdrh     if( zData ){
357257a0227fSdrh       MD5Update(p, (unsigned char*)zData, strlen(zData));
357357a0227fSdrh     }
357457a0227fSdrh   }
357557a0227fSdrh }
357657a0227fSdrh static void md5finalize(sqlite3_context *context){
357757a0227fSdrh   MD5Context *p;
357857a0227fSdrh   unsigned char digest[16];
357957a0227fSdrh   char zBuf[33];
358057a0227fSdrh   p = sqlite3_aggregate_context(context, sizeof(*p));
358157a0227fSdrh   MD5Final(digest,p);
358257a0227fSdrh   MD5DigestToBase16(digest, zBuf);
358357a0227fSdrh   sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
358457a0227fSdrh }
358557a0227fSdrh int Md5_Register(sqlite3 *db){
358657a0227fSdrh   int rc = sqlite3_create_function(db, "md5sum", -1, SQLITE_UTF8, 0, 0,
358757a0227fSdrh                                  md5step, md5finalize);
358857a0227fSdrh   sqlite3_overload_function(db, "md5sum", -1);  /* To exercise this API */
358957a0227fSdrh   return rc;
359057a0227fSdrh }
359157a0227fSdrh #endif /* defined(SQLITE_TEST) */
359257a0227fSdrh 
359357a0227fSdrh 
3594348784efSdrh /*
35953e27c026Sdrh ** If the macro TCLSH is one, then put in code this for the
35963e27c026Sdrh ** "main" routine that will initialize Tcl and take input from
35973570ad93Sdrh ** standard input, or if a file is named on the command line
35983570ad93Sdrh ** the TCL interpreter reads and evaluates that file.
3599348784efSdrh */
36003e27c026Sdrh #if TCLSH==1
3601348784efSdrh static char zMainloop[] =
3602348784efSdrh   "set line {}\n"
3603348784efSdrh   "while {![eof stdin]} {\n"
3604348784efSdrh     "if {$line!=\"\"} {\n"
3605348784efSdrh       "puts -nonewline \"> \"\n"
3606348784efSdrh     "} else {\n"
3607348784efSdrh       "puts -nonewline \"% \"\n"
3608348784efSdrh     "}\n"
3609348784efSdrh     "flush stdout\n"
3610348784efSdrh     "append line [gets stdin]\n"
3611348784efSdrh     "if {[info complete $line]} {\n"
3612348784efSdrh       "if {[catch {uplevel #0 $line} result]} {\n"
3613348784efSdrh         "puts stderr \"Error: $result\"\n"
3614348784efSdrh       "} elseif {$result!=\"\"} {\n"
3615348784efSdrh         "puts $result\n"
3616348784efSdrh       "}\n"
3617348784efSdrh       "set line {}\n"
3618348784efSdrh     "} else {\n"
3619348784efSdrh       "append line \\n\n"
3620348784efSdrh     "}\n"
3621348784efSdrh   "}\n"
3622348784efSdrh ;
36233e27c026Sdrh #endif
36243a0f13ffSdrh #if TCLSH==2
36253a0f13ffSdrh static char zMainloop[] =
36263a0f13ffSdrh #include "spaceanal_tcl.h"
36273a0f13ffSdrh ;
36283a0f13ffSdrh #endif
36293e27c026Sdrh 
3630c1a60c51Sdan #ifdef SQLITE_TEST
3631c1a60c51Sdan static void init_all(Tcl_Interp *);
3632c1a60c51Sdan static int init_all_cmd(
3633c1a60c51Sdan   ClientData cd,
3634c1a60c51Sdan   Tcl_Interp *interp,
3635c1a60c51Sdan   int objc,
3636c1a60c51Sdan   Tcl_Obj *CONST objv[]
3637c1a60c51Sdan ){
36380a549071Sdanielk1977 
3639c1a60c51Sdan   Tcl_Interp *slave;
3640c1a60c51Sdan   if( objc!=2 ){
3641c1a60c51Sdan     Tcl_WrongNumArgs(interp, 1, objv, "SLAVE");
3642c1a60c51Sdan     return TCL_ERROR;
3643c1a60c51Sdan   }
36440a549071Sdanielk1977 
3645c1a60c51Sdan   slave = Tcl_GetSlave(interp, Tcl_GetString(objv[1]));
3646c1a60c51Sdan   if( !slave ){
3647c1a60c51Sdan     return TCL_ERROR;
3648c1a60c51Sdan   }
3649c1a60c51Sdan 
3650c1a60c51Sdan   init_all(slave);
3651c1a60c51Sdan   return TCL_OK;
3652c1a60c51Sdan }
3653c1a60c51Sdan #endif
3654c1a60c51Sdan 
3655c1a60c51Sdan /*
3656c1a60c51Sdan ** Configure the interpreter passed as the first argument to have access
3657c1a60c51Sdan ** to the commands and linked variables that make up:
3658c1a60c51Sdan **
3659c1a60c51Sdan **   * the [sqlite3] extension itself,
3660c1a60c51Sdan **
3661c1a60c51Sdan **   * If SQLITE_TCLMD5 or SQLITE_TEST is defined, the Md5 commands, and
3662c1a60c51Sdan **
3663c1a60c51Sdan **   * If SQLITE_TEST is set, the various test interfaces used by the Tcl
3664c1a60c51Sdan **     test suite.
3665c1a60c51Sdan */
3666c1a60c51Sdan static void init_all(Tcl_Interp *interp){
366738f8271fSdrh   Sqlite3_Init(interp);
3668c1a60c51Sdan 
366957a0227fSdrh #if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
367057a0227fSdrh   Md5_Init(interp);
367157a0227fSdrh #endif
3672c1a60c51Sdan 
3673d9b0257aSdrh #ifdef SQLITE_TEST
3674d1bf3512Sdrh   {
36752f999a67Sdrh     extern int Sqliteconfig_Init(Tcl_Interp*);
3676d1bf3512Sdrh     extern int Sqlitetest1_Init(Tcl_Interp*);
36775c4d9703Sdrh     extern int Sqlitetest2_Init(Tcl_Interp*);
36785c4d9703Sdrh     extern int Sqlitetest3_Init(Tcl_Interp*);
3679a6064dcfSdrh     extern int Sqlitetest4_Init(Tcl_Interp*);
3680998b56c3Sdanielk1977     extern int Sqlitetest5_Init(Tcl_Interp*);
36819c06c953Sdrh     extern int Sqlitetest6_Init(Tcl_Interp*);
368229c636bcSdrh     extern int Sqlitetest7_Init(Tcl_Interp*);
3683b9bb7c18Sdrh     extern int Sqlitetest8_Init(Tcl_Interp*);
3684a713f2c3Sdanielk1977     extern int Sqlitetest9_Init(Tcl_Interp*);
36852366940dSdrh     extern int Sqlitetestasync_Init(Tcl_Interp*);
36861409be69Sdrh     extern int Sqlitetest_autoext_Init(Tcl_Interp*);
36870a7a9155Sdan     extern int Sqlitetest_demovfs_Init(Tcl_Interp *);
3688984bfaa4Sdrh     extern int Sqlitetest_func_Init(Tcl_Interp*);
368915926590Sdrh     extern int Sqlitetest_hexio_Init(Tcl_Interp*);
3690e1ab2193Sdan     extern int Sqlitetest_init_Init(Tcl_Interp*);
36912f999a67Sdrh     extern int Sqlitetest_malloc_Init(Tcl_Interp*);
36921a9ed0b2Sdanielk1977     extern int Sqlitetest_mutex_Init(Tcl_Interp*);
36932f999a67Sdrh     extern int Sqlitetestschema_Init(Tcl_Interp*);
36942f999a67Sdrh     extern int Sqlitetestsse_Init(Tcl_Interp*);
36952f999a67Sdrh     extern int Sqlitetesttclvar_Init(Tcl_Interp*);
369644918fa0Sdanielk1977     extern int SqlitetestThread_Init(Tcl_Interp*);
3697a15db353Sdanielk1977     extern int SqlitetestOnefile_Init();
36985d1f5aa6Sdanielk1977     extern int SqlitetestOsinst_Init(Tcl_Interp*);
36990410302eSdanielk1977     extern int Sqlitetestbackup_Init(Tcl_Interp*);
3700522efc62Sdrh     extern int Sqlitetestintarray_Init(Tcl_Interp*);
3701c7991bdfSdan     extern int Sqlitetestvfs_Init(Tcl_Interp *);
3702599e9d21Sdan     extern int SqlitetestStat_Init(Tcl_Interp*);
37039508daa9Sdan     extern int Sqlitetestrtree_Init(Tcl_Interp*);
37048cf35eb4Sdan     extern int Sqlitequota_Init(Tcl_Interp*);
37058a922f75Sshaneh     extern int Sqlitemultiplex_Init(Tcl_Interp*);
3706e336b001Sdan     extern int SqliteSuperlock_Init(Tcl_Interp*);
37074fccf43aSdan #ifdef SQLITE_ENABLE_SESSION
37084fccf43aSdan     extern int TestSession_Init(Tcl_Interp*);
37094fccf43aSdan #endif
37102e66f0b9Sdrh 
3711b29010cdSdan #ifdef SQLITE_ENABLE_ZIPVFS
3712b29010cdSdan     extern int Zipvfs_Init(Tcl_Interp*);
3713b29010cdSdan     Zipvfs_Init(interp);
3714b29010cdSdan #endif
3715b29010cdSdan 
37162f999a67Sdrh     Sqliteconfig_Init(interp);
37176490bebdSdanielk1977     Sqlitetest1_Init(interp);
37185c4d9703Sdrh     Sqlitetest2_Init(interp);
3719de647130Sdrh     Sqlitetest3_Init(interp);
3720fc57d7bfSdanielk1977     Sqlitetest4_Init(interp);
3721998b56c3Sdanielk1977     Sqlitetest5_Init(interp);
37229c06c953Sdrh     Sqlitetest6_Init(interp);
372329c636bcSdrh     Sqlitetest7_Init(interp);
3724b9bb7c18Sdrh     Sqlitetest8_Init(interp);
3725a713f2c3Sdanielk1977     Sqlitetest9_Init(interp);
37262366940dSdrh     Sqlitetestasync_Init(interp);
37271409be69Sdrh     Sqlitetest_autoext_Init(interp);
37280a7a9155Sdan     Sqlitetest_demovfs_Init(interp);
3729984bfaa4Sdrh     Sqlitetest_func_Init(interp);
373015926590Sdrh     Sqlitetest_hexio_Init(interp);
3731e1ab2193Sdan     Sqlitetest_init_Init(interp);
37322f999a67Sdrh     Sqlitetest_malloc_Init(interp);
37331a9ed0b2Sdanielk1977     Sqlitetest_mutex_Init(interp);
37342f999a67Sdrh     Sqlitetestschema_Init(interp);
37352f999a67Sdrh     Sqlitetesttclvar_Init(interp);
373644918fa0Sdanielk1977     SqlitetestThread_Init(interp);
3737a15db353Sdanielk1977     SqlitetestOnefile_Init(interp);
37385d1f5aa6Sdanielk1977     SqlitetestOsinst_Init(interp);
37390410302eSdanielk1977     Sqlitetestbackup_Init(interp);
3740522efc62Sdrh     Sqlitetestintarray_Init(interp);
3741c7991bdfSdan     Sqlitetestvfs_Init(interp);
3742599e9d21Sdan     SqlitetestStat_Init(interp);
37439508daa9Sdan     Sqlitetestrtree_Init(interp);
37448cf35eb4Sdan     Sqlitequota_Init(interp);
37458a922f75Sshaneh     Sqlitemultiplex_Init(interp);
3746e336b001Sdan     SqliteSuperlock_Init(interp);
37474fccf43aSdan #ifdef SQLITE_ENABLE_SESSION
37484fccf43aSdan     TestSession_Init(interp);
37494fccf43aSdan #endif
3750a15db353Sdanielk1977 
3751c1a60c51Sdan     Tcl_CreateObjCommand(interp,"load_testfixture_extensions",init_all_cmd,0,0);
3752c1a60c51Sdan 
375389dec819Sdrh #ifdef SQLITE_SSE
37542e66f0b9Sdrh     Sqlitetestsse_Init(interp);
37552e66f0b9Sdrh #endif
3756d1bf3512Sdrh   }
3757d1bf3512Sdrh #endif
3758c1a60c51Sdan }
3759c1a60c51Sdan 
3760c1a60c51Sdan #define TCLSH_MAIN main   /* Needed to fake out mktclapp */
3761c1a60c51Sdan int TCLSH_MAIN(int argc, char **argv){
3762c1a60c51Sdan   Tcl_Interp *interp;
3763c1a60c51Sdan 
3764c1a60c51Sdan   /* Call sqlite3_shutdown() once before doing anything else. This is to
3765c1a60c51Sdan   ** test that sqlite3_shutdown() can be safely called by a process before
3766c1a60c51Sdan   ** sqlite3_initialize() is. */
3767c1a60c51Sdan   sqlite3_shutdown();
3768c1a60c51Sdan 
37693a0f13ffSdrh #if TCLSH==2
37703a0f13ffSdrh   sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);
37713a0f13ffSdrh #endif
3772c1a60c51Sdan   Tcl_FindExecutable(argv[0]);
3773c1a60c51Sdan 
3774c1a60c51Sdan   interp = Tcl_CreateInterp();
3775c1a60c51Sdan   init_all(interp);
3776c7285978Sdrh   if( argc>=2 ){
3777348784efSdrh     int i;
3778ad42c3a3Sshess     char zArgc[32];
3779ad42c3a3Sshess     sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-(3-TCLSH));
3780ad42c3a3Sshess     Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
3781348784efSdrh     Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
3782348784efSdrh     Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
378361212b69Sdrh     for(i=3-TCLSH; i<argc; i++){
3784348784efSdrh       Tcl_SetVar(interp, "argv", argv[i],
3785348784efSdrh           TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
3786348784efSdrh     }
37873a0f13ffSdrh     if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
37880de8c112Sdrh       const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
3789a81c64a2Sdrh       if( zInfo==0 ) zInfo = Tcl_GetStringResult(interp);
3790c61053b7Sdrh       fprintf(stderr,"%s: %s\n", *argv, zInfo);
3791348784efSdrh       return 1;
3792348784efSdrh     }
37933e27c026Sdrh   }
37943a0f13ffSdrh   if( TCLSH==2 || argc<=1 ){
3795348784efSdrh     Tcl_GlobalEval(interp, zMainloop);
3796348784efSdrh   }
3797348784efSdrh   return 0;
3798348784efSdrh }
3799348784efSdrh #endif /* TCLSH */
3800