xref: /sqlite-3.40.0/src/tclsqlite.c (revision 4fccf43a)
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) */
12721e8d012Sdan   Tcl_Obj *pTransHook;       /* Transaction hook script (if any) */
1285def0843Sdrh   Tcl_Obj *pWalHook;         /* WAL hook script (if any) */
129404ca075Sdanielk1977   Tcl_Obj *pUnlockNotify;    /* Unlock notify script (if any) */
1300202b29eSdanielk1977   SqlCollate *pCollate;      /* List of SQL collation functions */
1316f8a503dSdanielk1977   int rc;                    /* Return code of most recent sqlite3_exec() */
1327cedc8d4Sdanielk1977   Tcl_Obj *pCollateNeeded;   /* Collation needed script */
133fb7e7651Sdrh   SqlPreparedStmt *stmtList; /* List of prepared statements*/
134fb7e7651Sdrh   SqlPreparedStmt *stmtLast; /* Last statement in the list */
135fb7e7651Sdrh   int maxStmt;               /* The next maximum number of stmtList */
136fb7e7651Sdrh   int nStmt;                 /* Number of statements in stmtList */
137d0441796Sdanielk1977   IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */
1383c379b01Sdrh   int nStep, nSort, nIndex;  /* Statistics for most recent operation */
139cd38d520Sdanielk1977   int nTransaction;          /* Number of nested [transaction] methods */
14098808babSdrh };
141297ecf14Sdrh 
142b4e9af9fSdanielk1977 struct IncrblobChannel {
143d0441796Sdanielk1977   sqlite3_blob *pBlob;      /* sqlite3 blob handle */
144dcbb5d3fSdanielk1977   SqliteDb *pDb;            /* Associated database connection */
145b4e9af9fSdanielk1977   int iSeek;                /* Current seek offset */
146d0441796Sdanielk1977   Tcl_Channel channel;      /* Channel identifier */
147d0441796Sdanielk1977   IncrblobChannel *pNext;   /* Linked list of all open incrblob channels */
148d0441796Sdanielk1977   IncrblobChannel *pPrev;   /* Linked list of all open incrblob channels */
149b4e9af9fSdanielk1977 };
150b4e9af9fSdanielk1977 
151ea678832Sdrh /*
152ea678832Sdrh ** Compute a string length that is limited to what can be stored in
153ea678832Sdrh ** lower 30 bits of a 32-bit signed integer.
154ea678832Sdrh */
1554f21c4afSdrh static int strlen30(const char *z){
156ea678832Sdrh   const char *z2 = z;
157ea678832Sdrh   while( *z2 ){ z2++; }
158ea678832Sdrh   return 0x3fffffff & (int)(z2 - z);
159ea678832Sdrh }
160ea678832Sdrh 
161ea678832Sdrh 
16232a0d8bbSdanielk1977 #ifndef SQLITE_OMIT_INCRBLOB
163b4e9af9fSdanielk1977 /*
164d0441796Sdanielk1977 ** Close all incrblob channels opened using database connection pDb.
165d0441796Sdanielk1977 ** This is called when shutting down the database connection.
166d0441796Sdanielk1977 */
167d0441796Sdanielk1977 static void closeIncrblobChannels(SqliteDb *pDb){
168d0441796Sdanielk1977   IncrblobChannel *p;
169d0441796Sdanielk1977   IncrblobChannel *pNext;
170d0441796Sdanielk1977 
171d0441796Sdanielk1977   for(p=pDb->pIncrblob; p; p=pNext){
172d0441796Sdanielk1977     pNext = p->pNext;
173d0441796Sdanielk1977 
174d0441796Sdanielk1977     /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
175d0441796Sdanielk1977     ** which deletes the IncrblobChannel structure at *p. So do not
176d0441796Sdanielk1977     ** call Tcl_Free() here.
177d0441796Sdanielk1977     */
178d0441796Sdanielk1977     Tcl_UnregisterChannel(pDb->interp, p->channel);
179d0441796Sdanielk1977   }
180d0441796Sdanielk1977 }
181d0441796Sdanielk1977 
182d0441796Sdanielk1977 /*
183b4e9af9fSdanielk1977 ** Close an incremental blob channel.
184b4e9af9fSdanielk1977 */
185b4e9af9fSdanielk1977 static int incrblobClose(ClientData instanceData, Tcl_Interp *interp){
186b4e9af9fSdanielk1977   IncrblobChannel *p = (IncrblobChannel *)instanceData;
18792d4d7a9Sdanielk1977   int rc = sqlite3_blob_close(p->pBlob);
18892d4d7a9Sdanielk1977   sqlite3 *db = p->pDb->db;
189d0441796Sdanielk1977 
190d0441796Sdanielk1977   /* Remove the channel from the SqliteDb.pIncrblob list. */
191d0441796Sdanielk1977   if( p->pNext ){
192d0441796Sdanielk1977     p->pNext->pPrev = p->pPrev;
193d0441796Sdanielk1977   }
194d0441796Sdanielk1977   if( p->pPrev ){
195d0441796Sdanielk1977     p->pPrev->pNext = p->pNext;
196d0441796Sdanielk1977   }
197d0441796Sdanielk1977   if( p->pDb->pIncrblob==p ){
198d0441796Sdanielk1977     p->pDb->pIncrblob = p->pNext;
199d0441796Sdanielk1977   }
200d0441796Sdanielk1977 
20192d4d7a9Sdanielk1977   /* Free the IncrblobChannel structure */
202b4e9af9fSdanielk1977   Tcl_Free((char *)p);
20392d4d7a9Sdanielk1977 
20492d4d7a9Sdanielk1977   if( rc!=SQLITE_OK ){
20592d4d7a9Sdanielk1977     Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
20692d4d7a9Sdanielk1977     return TCL_ERROR;
20792d4d7a9Sdanielk1977   }
208b4e9af9fSdanielk1977   return TCL_OK;
209b4e9af9fSdanielk1977 }
210b4e9af9fSdanielk1977 
211b4e9af9fSdanielk1977 /*
212b4e9af9fSdanielk1977 ** Read data from an incremental blob channel.
213b4e9af9fSdanielk1977 */
214b4e9af9fSdanielk1977 static int incrblobInput(
215b4e9af9fSdanielk1977   ClientData instanceData,
216b4e9af9fSdanielk1977   char *buf,
217b4e9af9fSdanielk1977   int bufSize,
218b4e9af9fSdanielk1977   int *errorCodePtr
219b4e9af9fSdanielk1977 ){
220b4e9af9fSdanielk1977   IncrblobChannel *p = (IncrblobChannel *)instanceData;
221b4e9af9fSdanielk1977   int nRead = bufSize;         /* Number of bytes to read */
222b4e9af9fSdanielk1977   int nBlob;                   /* Total size of the blob */
223b4e9af9fSdanielk1977   int rc;                      /* sqlite error code */
224b4e9af9fSdanielk1977 
225b4e9af9fSdanielk1977   nBlob = sqlite3_blob_bytes(p->pBlob);
226b4e9af9fSdanielk1977   if( (p->iSeek+nRead)>nBlob ){
227b4e9af9fSdanielk1977     nRead = nBlob-p->iSeek;
228b4e9af9fSdanielk1977   }
229b4e9af9fSdanielk1977   if( nRead<=0 ){
230b4e9af9fSdanielk1977     return 0;
231b4e9af9fSdanielk1977   }
232b4e9af9fSdanielk1977 
233b4e9af9fSdanielk1977   rc = sqlite3_blob_read(p->pBlob, (void *)buf, nRead, p->iSeek);
234b4e9af9fSdanielk1977   if( rc!=SQLITE_OK ){
235b4e9af9fSdanielk1977     *errorCodePtr = rc;
236b4e9af9fSdanielk1977     return -1;
237b4e9af9fSdanielk1977   }
238b4e9af9fSdanielk1977 
239b4e9af9fSdanielk1977   p->iSeek += nRead;
240b4e9af9fSdanielk1977   return nRead;
241b4e9af9fSdanielk1977 }
242b4e9af9fSdanielk1977 
243d0441796Sdanielk1977 /*
244d0441796Sdanielk1977 ** Write data to an incremental blob channel.
245d0441796Sdanielk1977 */
246b4e9af9fSdanielk1977 static int incrblobOutput(
247b4e9af9fSdanielk1977   ClientData instanceData,
248b4e9af9fSdanielk1977   CONST char *buf,
249b4e9af9fSdanielk1977   int toWrite,
250b4e9af9fSdanielk1977   int *errorCodePtr
251b4e9af9fSdanielk1977 ){
252b4e9af9fSdanielk1977   IncrblobChannel *p = (IncrblobChannel *)instanceData;
253b4e9af9fSdanielk1977   int nWrite = toWrite;        /* Number of bytes to write */
254b4e9af9fSdanielk1977   int nBlob;                   /* Total size of the blob */
255b4e9af9fSdanielk1977   int rc;                      /* sqlite error code */
256b4e9af9fSdanielk1977 
257b4e9af9fSdanielk1977   nBlob = sqlite3_blob_bytes(p->pBlob);
258b4e9af9fSdanielk1977   if( (p->iSeek+nWrite)>nBlob ){
259b4e9af9fSdanielk1977     *errorCodePtr = EINVAL;
260b4e9af9fSdanielk1977     return -1;
261b4e9af9fSdanielk1977   }
262b4e9af9fSdanielk1977   if( nWrite<=0 ){
263b4e9af9fSdanielk1977     return 0;
264b4e9af9fSdanielk1977   }
265b4e9af9fSdanielk1977 
266b4e9af9fSdanielk1977   rc = sqlite3_blob_write(p->pBlob, (void *)buf, nWrite, p->iSeek);
267b4e9af9fSdanielk1977   if( rc!=SQLITE_OK ){
268b4e9af9fSdanielk1977     *errorCodePtr = EIO;
269b4e9af9fSdanielk1977     return -1;
270b4e9af9fSdanielk1977   }
271b4e9af9fSdanielk1977 
272b4e9af9fSdanielk1977   p->iSeek += nWrite;
273b4e9af9fSdanielk1977   return nWrite;
274b4e9af9fSdanielk1977 }
275b4e9af9fSdanielk1977 
276b4e9af9fSdanielk1977 /*
277b4e9af9fSdanielk1977 ** Seek an incremental blob channel.
278b4e9af9fSdanielk1977 */
279b4e9af9fSdanielk1977 static int incrblobSeek(
280b4e9af9fSdanielk1977   ClientData instanceData,
281b4e9af9fSdanielk1977   long offset,
282b4e9af9fSdanielk1977   int seekMode,
283b4e9af9fSdanielk1977   int *errorCodePtr
284b4e9af9fSdanielk1977 ){
285b4e9af9fSdanielk1977   IncrblobChannel *p = (IncrblobChannel *)instanceData;
286b4e9af9fSdanielk1977 
287b4e9af9fSdanielk1977   switch( seekMode ){
288b4e9af9fSdanielk1977     case SEEK_SET:
289b4e9af9fSdanielk1977       p->iSeek = offset;
290b4e9af9fSdanielk1977       break;
291b4e9af9fSdanielk1977     case SEEK_CUR:
292b4e9af9fSdanielk1977       p->iSeek += offset;
293b4e9af9fSdanielk1977       break;
294b4e9af9fSdanielk1977     case SEEK_END:
295b4e9af9fSdanielk1977       p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset;
296b4e9af9fSdanielk1977       break;
297b4e9af9fSdanielk1977 
298b4e9af9fSdanielk1977     default: assert(!"Bad seekMode");
299b4e9af9fSdanielk1977   }
300b4e9af9fSdanielk1977 
301b4e9af9fSdanielk1977   return p->iSeek;
302b4e9af9fSdanielk1977 }
303b4e9af9fSdanielk1977 
304b4e9af9fSdanielk1977 
305b4e9af9fSdanielk1977 static void incrblobWatch(ClientData instanceData, int mode){
306b4e9af9fSdanielk1977   /* NO-OP */
307b4e9af9fSdanielk1977 }
308b4e9af9fSdanielk1977 static int incrblobHandle(ClientData instanceData, int dir, ClientData *hPtr){
309b4e9af9fSdanielk1977   return TCL_ERROR;
310b4e9af9fSdanielk1977 }
311b4e9af9fSdanielk1977 
312b4e9af9fSdanielk1977 static Tcl_ChannelType IncrblobChannelType = {
313b4e9af9fSdanielk1977   "incrblob",                        /* typeName                             */
314b4e9af9fSdanielk1977   TCL_CHANNEL_VERSION_2,             /* version                              */
315b4e9af9fSdanielk1977   incrblobClose,                     /* closeProc                            */
316b4e9af9fSdanielk1977   incrblobInput,                     /* inputProc                            */
317b4e9af9fSdanielk1977   incrblobOutput,                    /* outputProc                           */
318b4e9af9fSdanielk1977   incrblobSeek,                      /* seekProc                             */
319b4e9af9fSdanielk1977   0,                                 /* setOptionProc                        */
320b4e9af9fSdanielk1977   0,                                 /* getOptionProc                        */
321b4e9af9fSdanielk1977   incrblobWatch,                     /* watchProc (this is a no-op)          */
322b4e9af9fSdanielk1977   incrblobHandle,                    /* getHandleProc (always returns error) */
323b4e9af9fSdanielk1977   0,                                 /* close2Proc                           */
324b4e9af9fSdanielk1977   0,                                 /* blockModeProc                        */
325b4e9af9fSdanielk1977   0,                                 /* flushProc                            */
326b4e9af9fSdanielk1977   0,                                 /* handlerProc                          */
327b4e9af9fSdanielk1977   0,                                 /* wideSeekProc                         */
328b4e9af9fSdanielk1977 };
329b4e9af9fSdanielk1977 
330b4e9af9fSdanielk1977 /*
331b4e9af9fSdanielk1977 ** Create a new incrblob channel.
332b4e9af9fSdanielk1977 */
333b4e9af9fSdanielk1977 static int createIncrblobChannel(
334b4e9af9fSdanielk1977   Tcl_Interp *interp,
335b4e9af9fSdanielk1977   SqliteDb *pDb,
336b4e9af9fSdanielk1977   const char *zDb,
337b4e9af9fSdanielk1977   const char *zTable,
338b4e9af9fSdanielk1977   const char *zColumn,
3398cbadb02Sdanielk1977   sqlite_int64 iRow,
3408cbadb02Sdanielk1977   int isReadonly
341b4e9af9fSdanielk1977 ){
342b4e9af9fSdanielk1977   IncrblobChannel *p;
3438cbadb02Sdanielk1977   sqlite3 *db = pDb->db;
344b4e9af9fSdanielk1977   sqlite3_blob *pBlob;
345b4e9af9fSdanielk1977   int rc;
3468cbadb02Sdanielk1977   int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE);
347b4e9af9fSdanielk1977 
348b4e9af9fSdanielk1977   /* This variable is used to name the channels: "incrblob_[incr count]" */
349b4e9af9fSdanielk1977   static int count = 0;
350b4e9af9fSdanielk1977   char zChannel[64];
351b4e9af9fSdanielk1977 
3528cbadb02Sdanielk1977   rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob);
353b4e9af9fSdanielk1977   if( rc!=SQLITE_OK ){
354b4e9af9fSdanielk1977     Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
355b4e9af9fSdanielk1977     return TCL_ERROR;
356b4e9af9fSdanielk1977   }
357b4e9af9fSdanielk1977 
358b4e9af9fSdanielk1977   p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel));
359b4e9af9fSdanielk1977   p->iSeek = 0;
360b4e9af9fSdanielk1977   p->pBlob = pBlob;
361b4e9af9fSdanielk1977 
3625bb3eb9bSdrh   sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count);
363d0441796Sdanielk1977   p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags);
364d0441796Sdanielk1977   Tcl_RegisterChannel(interp, p->channel);
365b4e9af9fSdanielk1977 
366d0441796Sdanielk1977   /* Link the new channel into the SqliteDb.pIncrblob list. */
367d0441796Sdanielk1977   p->pNext = pDb->pIncrblob;
368d0441796Sdanielk1977   p->pPrev = 0;
369d0441796Sdanielk1977   if( p->pNext ){
370d0441796Sdanielk1977     p->pNext->pPrev = p;
371d0441796Sdanielk1977   }
372d0441796Sdanielk1977   pDb->pIncrblob = p;
373d0441796Sdanielk1977   p->pDb = pDb;
374d0441796Sdanielk1977 
375d0441796Sdanielk1977   Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE);
376b4e9af9fSdanielk1977   return TCL_OK;
377b4e9af9fSdanielk1977 }
37832a0d8bbSdanielk1977 #else  /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
37932a0d8bbSdanielk1977   #define closeIncrblobChannels(pDb)
38032a0d8bbSdanielk1977 #endif
381b4e9af9fSdanielk1977 
3826d31316cSdrh /*
383d1e4733dSdrh ** Look at the script prefix in pCmd.  We will be executing this script
384d1e4733dSdrh ** after first appending one or more arguments.  This routine analyzes
385d1e4733dSdrh ** the script to see if it is safe to use Tcl_EvalObjv() on the script
386d1e4733dSdrh ** rather than the more general Tcl_EvalEx().  Tcl_EvalObjv() is much
387d1e4733dSdrh ** faster.
388d1e4733dSdrh **
389d1e4733dSdrh ** Scripts that are safe to use with Tcl_EvalObjv() consists of a
390d1e4733dSdrh ** command name followed by zero or more arguments with no [...] or $
391d1e4733dSdrh ** or {...} or ; to be seen anywhere.  Most callback scripts consist
392d1e4733dSdrh ** of just a single procedure name and they meet this requirement.
393d1e4733dSdrh */
394d1e4733dSdrh static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
395d1e4733dSdrh   /* We could try to do something with Tcl_Parse().  But we will instead
396d1e4733dSdrh   ** just do a search for forbidden characters.  If any of the forbidden
397d1e4733dSdrh   ** characters appear in pCmd, we will report the string as unsafe.
398d1e4733dSdrh   */
399d1e4733dSdrh   const char *z;
400d1e4733dSdrh   int n;
401d1e4733dSdrh   z = Tcl_GetStringFromObj(pCmd, &n);
402d1e4733dSdrh   while( n-- > 0 ){
403d1e4733dSdrh     int c = *(z++);
404d1e4733dSdrh     if( c=='$' || c=='[' || c==';' ) return 0;
405d1e4733dSdrh   }
406d1e4733dSdrh   return 1;
407d1e4733dSdrh }
408d1e4733dSdrh 
409d1e4733dSdrh /*
410d1e4733dSdrh ** Find an SqlFunc structure with the given name.  Or create a new
411d1e4733dSdrh ** one if an existing one cannot be found.  Return a pointer to the
412d1e4733dSdrh ** structure.
413d1e4733dSdrh */
414d1e4733dSdrh static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
415d1e4733dSdrh   SqlFunc *p, *pNew;
416d1e4733dSdrh   int i;
4174f21c4afSdrh   pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + strlen30(zName) + 1 );
418d1e4733dSdrh   pNew->zName = (char*)&pNew[1];
419d1e4733dSdrh   for(i=0; zName[i]; i++){ pNew->zName[i] = tolower(zName[i]); }
420d1e4733dSdrh   pNew->zName[i] = 0;
421d1e4733dSdrh   for(p=pDb->pFunc; p; p=p->pNext){
422d1e4733dSdrh     if( strcmp(p->zName, pNew->zName)==0 ){
423d1e4733dSdrh       Tcl_Free((char*)pNew);
424d1e4733dSdrh       return p;
425d1e4733dSdrh     }
426d1e4733dSdrh   }
427d1e4733dSdrh   pNew->interp = pDb->interp;
428d1e4733dSdrh   pNew->pScript = 0;
429d1e4733dSdrh   pNew->pNext = pDb->pFunc;
430d1e4733dSdrh   pDb->pFunc = pNew;
431d1e4733dSdrh   return pNew;
432d1e4733dSdrh }
433d1e4733dSdrh 
434d1e4733dSdrh /*
435fb7e7651Sdrh ** Finalize and free a list of prepared statements
436fb7e7651Sdrh */
437fb7e7651Sdrh static void flushStmtCache( SqliteDb *pDb ){
438fb7e7651Sdrh   SqlPreparedStmt *pPreStmt;
439fb7e7651Sdrh 
440fb7e7651Sdrh   while(  pDb->stmtList ){
441fb7e7651Sdrh     sqlite3_finalize( pDb->stmtList->pStmt );
442fb7e7651Sdrh     pPreStmt = pDb->stmtList;
443fb7e7651Sdrh     pDb->stmtList = pDb->stmtList->pNext;
444fb7e7651Sdrh     Tcl_Free( (char*)pPreStmt );
445fb7e7651Sdrh   }
446fb7e7651Sdrh   pDb->nStmt = 0;
447fb7e7651Sdrh   pDb->stmtLast = 0;
448fb7e7651Sdrh }
449fb7e7651Sdrh 
450fb7e7651Sdrh /*
451895d7472Sdrh ** TCL calls this procedure when an sqlite3 database command is
452895d7472Sdrh ** deleted.
45375897234Sdrh */
45475897234Sdrh static void DbDeleteCmd(void *db){
455bec3f402Sdrh   SqliteDb *pDb = (SqliteDb*)db;
456fb7e7651Sdrh   flushStmtCache(pDb);
457d0441796Sdanielk1977   closeIncrblobChannels(pDb);
4586f8a503dSdanielk1977   sqlite3_close(pDb->db);
459cabb0819Sdrh   while( pDb->pFunc ){
460cabb0819Sdrh     SqlFunc *pFunc = pDb->pFunc;
461cabb0819Sdrh     pDb->pFunc = pFunc->pNext;
462d1e4733dSdrh     Tcl_DecrRefCount(pFunc->pScript);
463cabb0819Sdrh     Tcl_Free((char*)pFunc);
464cabb0819Sdrh   }
4650202b29eSdanielk1977   while( pDb->pCollate ){
4660202b29eSdanielk1977     SqlCollate *pCollate = pDb->pCollate;
4670202b29eSdanielk1977     pDb->pCollate = pCollate->pNext;
4680202b29eSdanielk1977     Tcl_Free((char*)pCollate);
4690202b29eSdanielk1977   }
470bec3f402Sdrh   if( pDb->zBusy ){
471bec3f402Sdrh     Tcl_Free(pDb->zBusy);
472bec3f402Sdrh   }
473b5a20d3cSdrh   if( pDb->zTrace ){
474b5a20d3cSdrh     Tcl_Free(pDb->zTrace);
4750d1a643aSdrh   }
47619e2d37fSdrh   if( pDb->zProfile ){
47719e2d37fSdrh     Tcl_Free(pDb->zProfile);
47819e2d37fSdrh   }
479e22a334bSdrh   if( pDb->zAuth ){
480e22a334bSdrh     Tcl_Free(pDb->zAuth);
481e22a334bSdrh   }
48255c45f2eSdanielk1977   if( pDb->zNull ){
48355c45f2eSdanielk1977     Tcl_Free(pDb->zNull);
48455c45f2eSdanielk1977   }
48594eb6a14Sdanielk1977   if( pDb->pUpdateHook ){
48694eb6a14Sdanielk1977     Tcl_DecrRefCount(pDb->pUpdateHook);
48794eb6a14Sdanielk1977   }
48846c47d46Sdan   if( pDb->pPreUpdateHook ){
48946c47d46Sdan     Tcl_DecrRefCount(pDb->pPreUpdateHook);
49046c47d46Sdan   }
49171fd80bfSdanielk1977   if( pDb->pRollbackHook ){
49271fd80bfSdanielk1977     Tcl_DecrRefCount(pDb->pRollbackHook);
49371fd80bfSdanielk1977   }
4945def0843Sdrh   if( pDb->pWalHook ){
4955def0843Sdrh     Tcl_DecrRefCount(pDb->pWalHook);
4968d22a174Sdan   }
49794eb6a14Sdanielk1977   if( pDb->pCollateNeeded ){
49894eb6a14Sdanielk1977     Tcl_DecrRefCount(pDb->pCollateNeeded);
49994eb6a14Sdanielk1977   }
500bec3f402Sdrh   Tcl_Free((char*)pDb);
501bec3f402Sdrh }
502bec3f402Sdrh 
503bec3f402Sdrh /*
504bec3f402Sdrh ** This routine is called when a database file is locked while trying
505bec3f402Sdrh ** to execute SQL.
506bec3f402Sdrh */
5072a764eb0Sdanielk1977 static int DbBusyHandler(void *cd, int nTries){
508bec3f402Sdrh   SqliteDb *pDb = (SqliteDb*)cd;
509bec3f402Sdrh   int rc;
510bec3f402Sdrh   char zVal[30];
511bec3f402Sdrh 
5125bb3eb9bSdrh   sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries);
513d1e4733dSdrh   rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
514bec3f402Sdrh   if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
515bec3f402Sdrh     return 0;
516bec3f402Sdrh   }
517bec3f402Sdrh   return 1;
51875897234Sdrh }
51975897234Sdrh 
52026e4a8b1Sdrh #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
52175897234Sdrh /*
522348bb5d6Sdanielk1977 ** This routine is invoked as the 'progress callback' for the database.
523348bb5d6Sdanielk1977 */
524348bb5d6Sdanielk1977 static int DbProgressHandler(void *cd){
525348bb5d6Sdanielk1977   SqliteDb *pDb = (SqliteDb*)cd;
526348bb5d6Sdanielk1977   int rc;
527348bb5d6Sdanielk1977 
528348bb5d6Sdanielk1977   assert( pDb->zProgress );
529348bb5d6Sdanielk1977   rc = Tcl_Eval(pDb->interp, pDb->zProgress);
530348bb5d6Sdanielk1977   if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
531348bb5d6Sdanielk1977     return 1;
532348bb5d6Sdanielk1977   }
533348bb5d6Sdanielk1977   return 0;
534348bb5d6Sdanielk1977 }
53526e4a8b1Sdrh #endif
536348bb5d6Sdanielk1977 
537d1167393Sdrh #ifndef SQLITE_OMIT_TRACE
538348bb5d6Sdanielk1977 /*
539b5a20d3cSdrh ** This routine is called by the SQLite trace handler whenever a new
540b5a20d3cSdrh ** block of SQL is executed.  The TCL script in pDb->zTrace is executed.
5410d1a643aSdrh */
542b5a20d3cSdrh static void DbTraceHandler(void *cd, const char *zSql){
5430d1a643aSdrh   SqliteDb *pDb = (SqliteDb*)cd;
544b5a20d3cSdrh   Tcl_DString str;
5450d1a643aSdrh 
546b5a20d3cSdrh   Tcl_DStringInit(&str);
547b5a20d3cSdrh   Tcl_DStringAppend(&str, pDb->zTrace, -1);
548b5a20d3cSdrh   Tcl_DStringAppendElement(&str, zSql);
549b5a20d3cSdrh   Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
550b5a20d3cSdrh   Tcl_DStringFree(&str);
551b5a20d3cSdrh   Tcl_ResetResult(pDb->interp);
5520d1a643aSdrh }
553d1167393Sdrh #endif
5540d1a643aSdrh 
555d1167393Sdrh #ifndef SQLITE_OMIT_TRACE
5560d1a643aSdrh /*
55719e2d37fSdrh ** This routine is called by the SQLite profile handler after a statement
55819e2d37fSdrh ** SQL has executed.  The TCL script in pDb->zProfile is evaluated.
55919e2d37fSdrh */
56019e2d37fSdrh static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
56119e2d37fSdrh   SqliteDb *pDb = (SqliteDb*)cd;
56219e2d37fSdrh   Tcl_DString str;
56319e2d37fSdrh   char zTm[100];
56419e2d37fSdrh 
56519e2d37fSdrh   sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
56619e2d37fSdrh   Tcl_DStringInit(&str);
56719e2d37fSdrh   Tcl_DStringAppend(&str, pDb->zProfile, -1);
56819e2d37fSdrh   Tcl_DStringAppendElement(&str, zSql);
56919e2d37fSdrh   Tcl_DStringAppendElement(&str, zTm);
57019e2d37fSdrh   Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
57119e2d37fSdrh   Tcl_DStringFree(&str);
57219e2d37fSdrh   Tcl_ResetResult(pDb->interp);
57319e2d37fSdrh }
574d1167393Sdrh #endif
57519e2d37fSdrh 
57619e2d37fSdrh /*
577aa940eacSdrh ** This routine is called when a transaction is committed.  The
578aa940eacSdrh ** TCL script in pDb->zCommit is executed.  If it returns non-zero or
579aa940eacSdrh ** if it throws an exception, the transaction is rolled back instead
580aa940eacSdrh ** of being committed.
581aa940eacSdrh */
582aa940eacSdrh static int DbCommitHandler(void *cd){
583aa940eacSdrh   SqliteDb *pDb = (SqliteDb*)cd;
584aa940eacSdrh   int rc;
585aa940eacSdrh 
586aa940eacSdrh   rc = Tcl_Eval(pDb->interp, pDb->zCommit);
587aa940eacSdrh   if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
588aa940eacSdrh     return 1;
589aa940eacSdrh   }
590aa940eacSdrh   return 0;
591aa940eacSdrh }
592aa940eacSdrh 
59371fd80bfSdanielk1977 static void DbRollbackHandler(void *clientData){
59471fd80bfSdanielk1977   SqliteDb *pDb = (SqliteDb*)clientData;
59571fd80bfSdanielk1977   assert(pDb->pRollbackHook);
59671fd80bfSdanielk1977   if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
59771fd80bfSdanielk1977     Tcl_BackgroundError(pDb->interp);
59871fd80bfSdanielk1977   }
59971fd80bfSdanielk1977 }
60071fd80bfSdanielk1977 
6015def0843Sdrh /*
60221e8d012Sdan ** sqlite3_transaction_hook() callback.
60321e8d012Sdan */
60421e8d012Sdan static void DbTransHandler(void *clientData, int op, int iLevel){
60521e8d012Sdan   static const char *azStr[] = { "BEGIN", "COMMIT", "ROLLBACK" };
60621e8d012Sdan   SqliteDb *pDb = (SqliteDb*)clientData;
60721e8d012Sdan   Tcl_Interp *interp = pDb->interp;
60821e8d012Sdan   Tcl_Obj *pScript;
60921e8d012Sdan 
61021e8d012Sdan   assert(pDb->pTransHook);
61121e8d012Sdan   assert( SQLITE_BEGIN==1 );
61221e8d012Sdan   assert( SQLITE_COMMIT==2 );
61321e8d012Sdan   assert( SQLITE_ROLLBACK==3 );
61421e8d012Sdan 
61521e8d012Sdan   pScript = Tcl_DuplicateObj(pDb->pTransHook);
61621e8d012Sdan   Tcl_IncrRefCount(pScript);
61721e8d012Sdan   Tcl_ListObjAppendElement(interp, pScript, Tcl_NewStringObj(azStr[op-1], -1));
61821e8d012Sdan   Tcl_ListObjAppendElement(interp, pScript, Tcl_NewIntObj(iLevel));
61921e8d012Sdan   if( TCL_OK!=Tcl_EvalObjEx(interp, pScript, 0) ){
62021e8d012Sdan     Tcl_BackgroundError(interp);
62121e8d012Sdan   }
62221e8d012Sdan   Tcl_DecrRefCount(pScript);
62321e8d012Sdan }
62421e8d012Sdan 
62521e8d012Sdan /*
6265def0843Sdrh ** This procedure handles wal_hook callbacks.
6275def0843Sdrh */
6285def0843Sdrh static int DbWalHandler(
6298d22a174Sdan   void *clientData,
6308d22a174Sdan   sqlite3 *db,
6318d22a174Sdan   const char *zDb,
6328d22a174Sdan   int nEntry
6338d22a174Sdan ){
6345def0843Sdrh   int ret = SQLITE_OK;
6358d22a174Sdan   Tcl_Obj *p;
6368d22a174Sdan   SqliteDb *pDb = (SqliteDb*)clientData;
6378d22a174Sdan   Tcl_Interp *interp = pDb->interp;
6385def0843Sdrh   assert(pDb->pWalHook);
6398d22a174Sdan 
6405def0843Sdrh   p = Tcl_DuplicateObj(pDb->pWalHook);
6418d22a174Sdan   Tcl_IncrRefCount(p);
6428d22a174Sdan   Tcl_ListObjAppendElement(interp, p, Tcl_NewStringObj(zDb, -1));
6438d22a174Sdan   Tcl_ListObjAppendElement(interp, p, Tcl_NewIntObj(nEntry));
6448d22a174Sdan   if( TCL_OK!=Tcl_EvalObjEx(interp, p, 0)
6458d22a174Sdan    || TCL_OK!=Tcl_GetIntFromObj(interp, Tcl_GetObjResult(interp), &ret)
6468d22a174Sdan   ){
6478d22a174Sdan     Tcl_BackgroundError(interp);
6488d22a174Sdan   }
6498d22a174Sdan   Tcl_DecrRefCount(p);
6508d22a174Sdan 
6518d22a174Sdan   return ret;
6528d22a174Sdan }
6538d22a174Sdan 
654bcf4f484Sdrh #if defined(SQLITE_TEST) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
655404ca075Sdanielk1977 static void setTestUnlockNotifyVars(Tcl_Interp *interp, int iArg, int nArg){
656404ca075Sdanielk1977   char zBuf[64];
657404ca075Sdanielk1977   sprintf(zBuf, "%d", iArg);
658404ca075Sdanielk1977   Tcl_SetVar(interp, "sqlite_unlock_notify_arg", zBuf, TCL_GLOBAL_ONLY);
659404ca075Sdanielk1977   sprintf(zBuf, "%d", nArg);
660404ca075Sdanielk1977   Tcl_SetVar(interp, "sqlite_unlock_notify_argcount", zBuf, TCL_GLOBAL_ONLY);
661404ca075Sdanielk1977 }
662404ca075Sdanielk1977 #else
663404ca075Sdanielk1977 # define setTestUnlockNotifyVars(x,y,z)
664404ca075Sdanielk1977 #endif
665404ca075Sdanielk1977 
66669910da9Sdrh #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
667404ca075Sdanielk1977 static void DbUnlockNotify(void **apArg, int nArg){
668404ca075Sdanielk1977   int i;
669404ca075Sdanielk1977   for(i=0; i<nArg; i++){
670404ca075Sdanielk1977     const int flags = (TCL_EVAL_GLOBAL|TCL_EVAL_DIRECT);
671404ca075Sdanielk1977     SqliteDb *pDb = (SqliteDb *)apArg[i];
672404ca075Sdanielk1977     setTestUnlockNotifyVars(pDb->interp, i, nArg);
673404ca075Sdanielk1977     assert( pDb->pUnlockNotify);
674404ca075Sdanielk1977     Tcl_EvalObjEx(pDb->interp, pDb->pUnlockNotify, flags);
675404ca075Sdanielk1977     Tcl_DecrRefCount(pDb->pUnlockNotify);
676404ca075Sdanielk1977     pDb->pUnlockNotify = 0;
677404ca075Sdanielk1977   }
678404ca075Sdanielk1977 }
67969910da9Sdrh #endif
680404ca075Sdanielk1977 
68146c47d46Sdan /*
68246c47d46Sdan ** Pre-update hook callback.
68346c47d46Sdan */
68446c47d46Sdan static void DbPreUpdateHandler(
68546c47d46Sdan   void *p,
68646c47d46Sdan   sqlite3 *db,
68746c47d46Sdan   int op,
68846c47d46Sdan   const char *zDb,
68946c47d46Sdan   const char *zTbl,
69046c47d46Sdan   sqlite_int64 iKey1,
69146c47d46Sdan   sqlite_int64 iKey2
69246c47d46Sdan ){
69346c47d46Sdan   SqliteDb *pDb = (SqliteDb *)p;
69446c47d46Sdan   Tcl_Obj *pCmd;
69546c47d46Sdan   static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"};
69646c47d46Sdan 
69746c47d46Sdan   assert( (SQLITE_DELETE-1)/9 == 0 );
69846c47d46Sdan   assert( (SQLITE_INSERT-1)/9 == 1 );
69946c47d46Sdan   assert( (SQLITE_UPDATE-1)/9 == 2 );
70046c47d46Sdan   assert( pDb->pPreUpdateHook );
70146c47d46Sdan   assert( db==pDb->db );
70246c47d46Sdan   assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
70346c47d46Sdan 
70446c47d46Sdan   pCmd = Tcl_DuplicateObj(pDb->pPreUpdateHook);
70546c47d46Sdan   Tcl_IncrRefCount(pCmd);
70646c47d46Sdan   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
70746c47d46Sdan   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
70846c47d46Sdan   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
70946c47d46Sdan   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey1));
71046c47d46Sdan   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey2));
71146c47d46Sdan   Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
71246c47d46Sdan   Tcl_DecrRefCount(pCmd);
71346c47d46Sdan }
71446c47d46Sdan 
71594eb6a14Sdanielk1977 static void DbUpdateHandler(
71694eb6a14Sdanielk1977   void *p,
71794eb6a14Sdanielk1977   int op,
71894eb6a14Sdanielk1977   const char *zDb,
71994eb6a14Sdanielk1977   const char *zTbl,
72094eb6a14Sdanielk1977   sqlite_int64 rowid
72194eb6a14Sdanielk1977 ){
72294eb6a14Sdanielk1977   SqliteDb *pDb = (SqliteDb *)p;
72394eb6a14Sdanielk1977   Tcl_Obj *pCmd;
72446c47d46Sdan   static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"};
72546c47d46Sdan 
72646c47d46Sdan   assert( (SQLITE_DELETE-1)/9 == 0 );
72746c47d46Sdan   assert( (SQLITE_INSERT-1)/9 == 1 );
72846c47d46Sdan   assert( (SQLITE_UPDATE-1)/9 == 2 );
72994eb6a14Sdanielk1977 
73094eb6a14Sdanielk1977   assert( pDb->pUpdateHook );
73194eb6a14Sdanielk1977   assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
73294eb6a14Sdanielk1977 
73394eb6a14Sdanielk1977   pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
73494eb6a14Sdanielk1977   Tcl_IncrRefCount(pCmd);
73546c47d46Sdan   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
73694eb6a14Sdanielk1977   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
73794eb6a14Sdanielk1977   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
73894eb6a14Sdanielk1977   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
73994eb6a14Sdanielk1977   Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
740efdde169Sdrh   Tcl_DecrRefCount(pCmd);
74194eb6a14Sdanielk1977 }
74294eb6a14Sdanielk1977 
7437cedc8d4Sdanielk1977 static void tclCollateNeeded(
7447cedc8d4Sdanielk1977   void *pCtx,
7459bb575fdSdrh   sqlite3 *db,
7467cedc8d4Sdanielk1977   int enc,
7477cedc8d4Sdanielk1977   const char *zName
7487cedc8d4Sdanielk1977 ){
7497cedc8d4Sdanielk1977   SqliteDb *pDb = (SqliteDb *)pCtx;
7507cedc8d4Sdanielk1977   Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
7517cedc8d4Sdanielk1977   Tcl_IncrRefCount(pScript);
7527cedc8d4Sdanielk1977   Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
7537cedc8d4Sdanielk1977   Tcl_EvalObjEx(pDb->interp, pScript, 0);
7547cedc8d4Sdanielk1977   Tcl_DecrRefCount(pScript);
7557cedc8d4Sdanielk1977 }
7567cedc8d4Sdanielk1977 
757aa940eacSdrh /*
7580202b29eSdanielk1977 ** This routine is called to evaluate an SQL collation function implemented
7590202b29eSdanielk1977 ** using TCL script.
7600202b29eSdanielk1977 */
7610202b29eSdanielk1977 static int tclSqlCollate(
7620202b29eSdanielk1977   void *pCtx,
7630202b29eSdanielk1977   int nA,
7640202b29eSdanielk1977   const void *zA,
7650202b29eSdanielk1977   int nB,
7660202b29eSdanielk1977   const void *zB
7670202b29eSdanielk1977 ){
7680202b29eSdanielk1977   SqlCollate *p = (SqlCollate *)pCtx;
7690202b29eSdanielk1977   Tcl_Obj *pCmd;
7700202b29eSdanielk1977 
7710202b29eSdanielk1977   pCmd = Tcl_NewStringObj(p->zScript, -1);
7720202b29eSdanielk1977   Tcl_IncrRefCount(pCmd);
7730202b29eSdanielk1977   Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
7740202b29eSdanielk1977   Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
775d1e4733dSdrh   Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
7760202b29eSdanielk1977   Tcl_DecrRefCount(pCmd);
7770202b29eSdanielk1977   return (atoi(Tcl_GetStringResult(p->interp)));
7780202b29eSdanielk1977 }
7790202b29eSdanielk1977 
7800202b29eSdanielk1977 /*
781cabb0819Sdrh ** This routine is called to evaluate an SQL function implemented
782cabb0819Sdrh ** using TCL script.
783cabb0819Sdrh */
7840ae8b831Sdanielk1977 static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
7856f8a503dSdanielk1977   SqlFunc *p = sqlite3_user_data(context);
786d1e4733dSdrh   Tcl_Obj *pCmd;
787cabb0819Sdrh   int i;
788cabb0819Sdrh   int rc;
789cabb0819Sdrh 
790d1e4733dSdrh   if( argc==0 ){
791d1e4733dSdrh     /* If there are no arguments to the function, call Tcl_EvalObjEx on the
792d1e4733dSdrh     ** script object directly.  This allows the TCL compiler to generate
793d1e4733dSdrh     ** bytecode for the command on the first invocation and thus make
794d1e4733dSdrh     ** subsequent invocations much faster. */
795d1e4733dSdrh     pCmd = p->pScript;
796d1e4733dSdrh     Tcl_IncrRefCount(pCmd);
797d1e4733dSdrh     rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
798d1e4733dSdrh     Tcl_DecrRefCount(pCmd);
79951ad0ecdSdanielk1977   }else{
800d1e4733dSdrh     /* If there are arguments to the function, make a shallow copy of the
801d1e4733dSdrh     ** script object, lappend the arguments, then evaluate the copy.
802d1e4733dSdrh     **
803d1e4733dSdrh     ** By "shallow" copy, we mean a only the outer list Tcl_Obj is duplicated.
804d1e4733dSdrh     ** The new Tcl_Obj contains pointers to the original list elements.
805d1e4733dSdrh     ** That way, when Tcl_EvalObjv() is run and shimmers the first element
806d1e4733dSdrh     ** of the list to tclCmdNameType, that alternate representation will
807d1e4733dSdrh     ** be preserved and reused on the next invocation.
808d1e4733dSdrh     */
809d1e4733dSdrh     Tcl_Obj **aArg;
810d1e4733dSdrh     int nArg;
811d1e4733dSdrh     if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
812d1e4733dSdrh       sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
813d1e4733dSdrh       return;
814d1e4733dSdrh     }
815d1e4733dSdrh     pCmd = Tcl_NewListObj(nArg, aArg);
816d1e4733dSdrh     Tcl_IncrRefCount(pCmd);
817d1e4733dSdrh     for(i=0; i<argc; i++){
818d1e4733dSdrh       sqlite3_value *pIn = argv[i];
819d1e4733dSdrh       Tcl_Obj *pVal;
820d1e4733dSdrh 
821d1e4733dSdrh       /* Set pVal to contain the i'th column of this row. */
822d1e4733dSdrh       switch( sqlite3_value_type(pIn) ){
823d1e4733dSdrh         case SQLITE_BLOB: {
824d1e4733dSdrh           int bytes = sqlite3_value_bytes(pIn);
825d1e4733dSdrh           pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
826d1e4733dSdrh           break;
827d1e4733dSdrh         }
828d1e4733dSdrh         case SQLITE_INTEGER: {
829d1e4733dSdrh           sqlite_int64 v = sqlite3_value_int64(pIn);
830d1e4733dSdrh           if( v>=-2147483647 && v<=2147483647 ){
831d1e4733dSdrh             pVal = Tcl_NewIntObj(v);
832d1e4733dSdrh           }else{
833d1e4733dSdrh             pVal = Tcl_NewWideIntObj(v);
834d1e4733dSdrh           }
835d1e4733dSdrh           break;
836d1e4733dSdrh         }
837d1e4733dSdrh         case SQLITE_FLOAT: {
838d1e4733dSdrh           double r = sqlite3_value_double(pIn);
839d1e4733dSdrh           pVal = Tcl_NewDoubleObj(r);
840d1e4733dSdrh           break;
841d1e4733dSdrh         }
842d1e4733dSdrh         case SQLITE_NULL: {
843d1e4733dSdrh           pVal = Tcl_NewStringObj("", 0);
844d1e4733dSdrh           break;
845d1e4733dSdrh         }
846d1e4733dSdrh         default: {
847d1e4733dSdrh           int bytes = sqlite3_value_bytes(pIn);
84800fd957bSdanielk1977           pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
849d1e4733dSdrh           break;
85051ad0ecdSdanielk1977         }
851cabb0819Sdrh       }
852d1e4733dSdrh       rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
853d1e4733dSdrh       if( rc ){
854d1e4733dSdrh         Tcl_DecrRefCount(pCmd);
855d1e4733dSdrh         sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
856d1e4733dSdrh         return;
857d1e4733dSdrh       }
858d1e4733dSdrh     }
859d1e4733dSdrh     if( !p->useEvalObjv ){
860d1e4733dSdrh       /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
861d1e4733dSdrh       ** is a list without a string representation.  To prevent this from
862d1e4733dSdrh       ** happening, make sure pCmd has a valid string representation */
863d1e4733dSdrh       Tcl_GetString(pCmd);
864d1e4733dSdrh     }
865d1e4733dSdrh     rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
866d1e4733dSdrh     Tcl_DecrRefCount(pCmd);
867d1e4733dSdrh   }
868562e8d3cSdanielk1977 
869c7f269d5Sdrh   if( rc && rc!=TCL_RETURN ){
8707e18c259Sdanielk1977     sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
871cabb0819Sdrh   }else{
872c7f269d5Sdrh     Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
873c7f269d5Sdrh     int n;
874c7f269d5Sdrh     u8 *data;
8754a4c11aaSdan     const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
876c7f269d5Sdrh     char c = zType[0];
877df0bddaeSdrh     if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
878d1e4733dSdrh       /* Only return a BLOB type if the Tcl variable is a bytearray and
879df0bddaeSdrh       ** has no string representation. */
880c7f269d5Sdrh       data = Tcl_GetByteArrayFromObj(pVar, &n);
881c7f269d5Sdrh       sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
882985e0c63Sdrh     }else if( c=='b' && strcmp(zType,"boolean")==0 ){
883c7f269d5Sdrh       Tcl_GetIntFromObj(0, pVar, &n);
884c7f269d5Sdrh       sqlite3_result_int(context, n);
885c7f269d5Sdrh     }else if( c=='d' && strcmp(zType,"double")==0 ){
886c7f269d5Sdrh       double r;
887c7f269d5Sdrh       Tcl_GetDoubleFromObj(0, pVar, &r);
888c7f269d5Sdrh       sqlite3_result_double(context, r);
889985e0c63Sdrh     }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
890985e0c63Sdrh           (c=='i' && strcmp(zType,"int")==0) ){
891df0bddaeSdrh       Tcl_WideInt v;
892df0bddaeSdrh       Tcl_GetWideIntFromObj(0, pVar, &v);
893df0bddaeSdrh       sqlite3_result_int64(context, v);
894c7f269d5Sdrh     }else{
89500fd957bSdanielk1977       data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
89600fd957bSdanielk1977       sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
897c7f269d5Sdrh     }
898cabb0819Sdrh   }
899cabb0819Sdrh }
900895d7472Sdrh 
901e22a334bSdrh #ifndef SQLITE_OMIT_AUTHORIZATION
902e22a334bSdrh /*
903e22a334bSdrh ** This is the authentication function.  It appends the authentication
904e22a334bSdrh ** type code and the two arguments to zCmd[] then invokes the result
905e22a334bSdrh ** on the interpreter.  The reply is examined to determine if the
906e22a334bSdrh ** authentication fails or succeeds.
907e22a334bSdrh */
908e22a334bSdrh static int auth_callback(
909e22a334bSdrh   void *pArg,
910e22a334bSdrh   int code,
911e22a334bSdrh   const char *zArg1,
912e22a334bSdrh   const char *zArg2,
913e22a334bSdrh   const char *zArg3,
914e22a334bSdrh   const char *zArg4
915e22a334bSdrh ){
916e22a334bSdrh   char *zCode;
917e22a334bSdrh   Tcl_DString str;
918e22a334bSdrh   int rc;
919e22a334bSdrh   const char *zReply;
920e22a334bSdrh   SqliteDb *pDb = (SqliteDb*)pArg;
9211f1549f8Sdrh   if( pDb->disableAuth ) return SQLITE_OK;
922e22a334bSdrh 
923e22a334bSdrh   switch( code ){
924e22a334bSdrh     case SQLITE_COPY              : zCode="SQLITE_COPY"; break;
925e22a334bSdrh     case SQLITE_CREATE_INDEX      : zCode="SQLITE_CREATE_INDEX"; break;
926e22a334bSdrh     case SQLITE_CREATE_TABLE      : zCode="SQLITE_CREATE_TABLE"; break;
927e22a334bSdrh     case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
928e22a334bSdrh     case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
929e22a334bSdrh     case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
930e22a334bSdrh     case SQLITE_CREATE_TEMP_VIEW  : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
931e22a334bSdrh     case SQLITE_CREATE_TRIGGER    : zCode="SQLITE_CREATE_TRIGGER"; break;
932e22a334bSdrh     case SQLITE_CREATE_VIEW       : zCode="SQLITE_CREATE_VIEW"; break;
933e22a334bSdrh     case SQLITE_DELETE            : zCode="SQLITE_DELETE"; break;
934e22a334bSdrh     case SQLITE_DROP_INDEX        : zCode="SQLITE_DROP_INDEX"; break;
935e22a334bSdrh     case SQLITE_DROP_TABLE        : zCode="SQLITE_DROP_TABLE"; break;
936e22a334bSdrh     case SQLITE_DROP_TEMP_INDEX   : zCode="SQLITE_DROP_TEMP_INDEX"; break;
937e22a334bSdrh     case SQLITE_DROP_TEMP_TABLE   : zCode="SQLITE_DROP_TEMP_TABLE"; break;
938e22a334bSdrh     case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
939e22a334bSdrh     case SQLITE_DROP_TEMP_VIEW    : zCode="SQLITE_DROP_TEMP_VIEW"; break;
940e22a334bSdrh     case SQLITE_DROP_TRIGGER      : zCode="SQLITE_DROP_TRIGGER"; break;
941e22a334bSdrh     case SQLITE_DROP_VIEW         : zCode="SQLITE_DROP_VIEW"; break;
942e22a334bSdrh     case SQLITE_INSERT            : zCode="SQLITE_INSERT"; break;
943e22a334bSdrh     case SQLITE_PRAGMA            : zCode="SQLITE_PRAGMA"; break;
944e22a334bSdrh     case SQLITE_READ              : zCode="SQLITE_READ"; break;
945e22a334bSdrh     case SQLITE_SELECT            : zCode="SQLITE_SELECT"; break;
946e22a334bSdrh     case SQLITE_TRANSACTION       : zCode="SQLITE_TRANSACTION"; break;
947e22a334bSdrh     case SQLITE_UPDATE            : zCode="SQLITE_UPDATE"; break;
94881e293b4Sdrh     case SQLITE_ATTACH            : zCode="SQLITE_ATTACH"; break;
94981e293b4Sdrh     case SQLITE_DETACH            : zCode="SQLITE_DETACH"; break;
9501c8c23ccSdanielk1977     case SQLITE_ALTER_TABLE       : zCode="SQLITE_ALTER_TABLE"; break;
9511d54df88Sdanielk1977     case SQLITE_REINDEX           : zCode="SQLITE_REINDEX"; break;
952e6e04969Sdrh     case SQLITE_ANALYZE           : zCode="SQLITE_ANALYZE"; break;
953f1a381e7Sdanielk1977     case SQLITE_CREATE_VTABLE     : zCode="SQLITE_CREATE_VTABLE"; break;
954f1a381e7Sdanielk1977     case SQLITE_DROP_VTABLE       : zCode="SQLITE_DROP_VTABLE"; break;
9555169bbc6Sdrh     case SQLITE_FUNCTION          : zCode="SQLITE_FUNCTION"; break;
956ab9b703fSdanielk1977     case SQLITE_SAVEPOINT         : zCode="SQLITE_SAVEPOINT"; break;
957e22a334bSdrh     default                       : zCode="????"; break;
958e22a334bSdrh   }
959e22a334bSdrh   Tcl_DStringInit(&str);
960e22a334bSdrh   Tcl_DStringAppend(&str, pDb->zAuth, -1);
961e22a334bSdrh   Tcl_DStringAppendElement(&str, zCode);
962e22a334bSdrh   Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
963e22a334bSdrh   Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
964e22a334bSdrh   Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
965e22a334bSdrh   Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
966e22a334bSdrh   rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
967e22a334bSdrh   Tcl_DStringFree(&str);
968e22a334bSdrh   zReply = Tcl_GetStringResult(pDb->interp);
969e22a334bSdrh   if( strcmp(zReply,"SQLITE_OK")==0 ){
970e22a334bSdrh     rc = SQLITE_OK;
971e22a334bSdrh   }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
972e22a334bSdrh     rc = SQLITE_DENY;
973e22a334bSdrh   }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
974e22a334bSdrh     rc = SQLITE_IGNORE;
975e22a334bSdrh   }else{
976e22a334bSdrh     rc = 999;
977e22a334bSdrh   }
978e22a334bSdrh   return rc;
979e22a334bSdrh }
980e22a334bSdrh #endif /* SQLITE_OMIT_AUTHORIZATION */
981cabb0819Sdrh 
982cabb0819Sdrh /*
983ef2cb63eSdanielk1977 ** zText is a pointer to text obtained via an sqlite3_result_text()
984ef2cb63eSdanielk1977 ** or similar interface. This routine returns a Tcl string object,
985ef2cb63eSdanielk1977 ** reference count set to 0, containing the text. If a translation
986ef2cb63eSdanielk1977 ** between iso8859 and UTF-8 is required, it is preformed.
987ef2cb63eSdanielk1977 */
988ef2cb63eSdanielk1977 static Tcl_Obj *dbTextToObj(char const *zText){
989ef2cb63eSdanielk1977   Tcl_Obj *pVal;
990ef2cb63eSdanielk1977 #ifdef UTF_TRANSLATION_NEEDED
991ef2cb63eSdanielk1977   Tcl_DString dCol;
992ef2cb63eSdanielk1977   Tcl_DStringInit(&dCol);
993ef2cb63eSdanielk1977   Tcl_ExternalToUtfDString(NULL, zText, -1, &dCol);
994ef2cb63eSdanielk1977   pVal = Tcl_NewStringObj(Tcl_DStringValue(&dCol), -1);
995ef2cb63eSdanielk1977   Tcl_DStringFree(&dCol);
996ef2cb63eSdanielk1977 #else
997ef2cb63eSdanielk1977   pVal = Tcl_NewStringObj(zText, -1);
998ef2cb63eSdanielk1977 #endif
999ef2cb63eSdanielk1977   return pVal;
1000ef2cb63eSdanielk1977 }
1001ef2cb63eSdanielk1977 
1002ef2cb63eSdanielk1977 /*
10031067fe11Stpoindex ** This routine reads a line of text from FILE in, stores
10041067fe11Stpoindex ** the text in memory obtained from malloc() and returns a pointer
10051067fe11Stpoindex ** to the text.  NULL is returned at end of file, or if malloc()
10061067fe11Stpoindex ** fails.
10071067fe11Stpoindex **
10081067fe11Stpoindex ** The interface is like "readline" but no command-line editing
10091067fe11Stpoindex ** is done.
10101067fe11Stpoindex **
10111067fe11Stpoindex ** copied from shell.c from '.import' command
10121067fe11Stpoindex */
10131067fe11Stpoindex static char *local_getline(char *zPrompt, FILE *in){
10141067fe11Stpoindex   char *zLine;
10151067fe11Stpoindex   int nLine;
10161067fe11Stpoindex   int n;
10171067fe11Stpoindex   int eol;
10181067fe11Stpoindex 
10191067fe11Stpoindex   nLine = 100;
10201067fe11Stpoindex   zLine = malloc( nLine );
10211067fe11Stpoindex   if( zLine==0 ) return 0;
10221067fe11Stpoindex   n = 0;
10231067fe11Stpoindex   eol = 0;
10241067fe11Stpoindex   while( !eol ){
10251067fe11Stpoindex     if( n+100>nLine ){
10261067fe11Stpoindex       nLine = nLine*2 + 100;
10271067fe11Stpoindex       zLine = realloc(zLine, nLine);
10281067fe11Stpoindex       if( zLine==0 ) return 0;
10291067fe11Stpoindex     }
10301067fe11Stpoindex     if( fgets(&zLine[n], nLine - n, in)==0 ){
10311067fe11Stpoindex       if( n==0 ){
10321067fe11Stpoindex         free(zLine);
10331067fe11Stpoindex         return 0;
10341067fe11Stpoindex       }
10351067fe11Stpoindex       zLine[n] = 0;
10361067fe11Stpoindex       eol = 1;
10371067fe11Stpoindex       break;
10381067fe11Stpoindex     }
10391067fe11Stpoindex     while( zLine[n] ){ n++; }
10401067fe11Stpoindex     if( n>0 && zLine[n-1]=='\n' ){
10411067fe11Stpoindex       n--;
10421067fe11Stpoindex       zLine[n] = 0;
10431067fe11Stpoindex       eol = 1;
10441067fe11Stpoindex     }
10451067fe11Stpoindex   }
10461067fe11Stpoindex   zLine = realloc( zLine, n+1 );
10471067fe11Stpoindex   return zLine;
10481067fe11Stpoindex }
10491067fe11Stpoindex 
10508e556520Sdanielk1977 
10518e556520Sdanielk1977 /*
10524a4c11aaSdan ** This function is part of the implementation of the command:
10538e556520Sdanielk1977 **
10544a4c11aaSdan **   $db transaction [-deferred|-immediate|-exclusive] SCRIPT
10558e556520Sdanielk1977 **
10564a4c11aaSdan ** It is invoked after evaluating the script SCRIPT to commit or rollback
10574a4c11aaSdan ** the transaction or savepoint opened by the [transaction] command.
10584a4c11aaSdan */
10594a4c11aaSdan static int DbTransPostCmd(
10604a4c11aaSdan   ClientData data[],                   /* data[0] is the Sqlite3Db* for $db */
10614a4c11aaSdan   Tcl_Interp *interp,                  /* Tcl interpreter */
10624a4c11aaSdan   int result                           /* Result of evaluating SCRIPT */
10634a4c11aaSdan ){
10644a4c11aaSdan   static const char *azEnd[] = {
10654a4c11aaSdan     "RELEASE _tcl_transaction",        /* rc==TCL_ERROR, nTransaction!=0 */
10664a4c11aaSdan     "COMMIT",                          /* rc!=TCL_ERROR, nTransaction==0 */
10674a4c11aaSdan     "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction",
10684a4c11aaSdan     "ROLLBACK"                         /* rc==TCL_ERROR, nTransaction==0 */
10694a4c11aaSdan   };
10704a4c11aaSdan   SqliteDb *pDb = (SqliteDb*)data[0];
10714a4c11aaSdan   int rc = result;
10724a4c11aaSdan   const char *zEnd;
10734a4c11aaSdan 
10744a4c11aaSdan   pDb->nTransaction--;
10754a4c11aaSdan   zEnd = azEnd[(rc==TCL_ERROR)*2 + (pDb->nTransaction==0)];
10764a4c11aaSdan 
10774a4c11aaSdan   pDb->disableAuth++;
10784a4c11aaSdan   if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){
10794a4c11aaSdan       /* This is a tricky scenario to handle. The most likely cause of an
10804a4c11aaSdan       ** error is that the exec() above was an attempt to commit the
10814a4c11aaSdan       ** top-level transaction that returned SQLITE_BUSY. Or, less likely,
10824a4c11aaSdan       ** that an IO-error has occured. In either case, throw a Tcl exception
10834a4c11aaSdan       ** and try to rollback the transaction.
10844a4c11aaSdan       **
10854a4c11aaSdan       ** But it could also be that the user executed one or more BEGIN,
10864a4c11aaSdan       ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing
10874a4c11aaSdan       ** this method's logic. Not clear how this would be best handled.
10884a4c11aaSdan       */
10894a4c11aaSdan     if( rc!=TCL_ERROR ){
10904a4c11aaSdan       Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
10914a4c11aaSdan       rc = TCL_ERROR;
10924a4c11aaSdan     }
10934a4c11aaSdan     sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
10944a4c11aaSdan   }
10954a4c11aaSdan   pDb->disableAuth--;
10964a4c11aaSdan 
10974a4c11aaSdan   return rc;
10984a4c11aaSdan }
10994a4c11aaSdan 
11004a4c11aaSdan /*
11014a4c11aaSdan ** Search the cache for a prepared-statement object that implements the
11024a4c11aaSdan ** first SQL statement in the buffer pointed to by parameter zIn. If
11034a4c11aaSdan ** no such prepared-statement can be found, allocate and prepare a new
11044a4c11aaSdan ** one. In either case, bind the current values of the relevant Tcl
11054a4c11aaSdan ** variables to any $var, :var or @var variables in the statement. Before
11064a4c11aaSdan ** returning, set *ppPreStmt to point to the prepared-statement object.
11074a4c11aaSdan **
11084a4c11aaSdan ** Output parameter *pzOut is set to point to the next SQL statement in
11094a4c11aaSdan ** buffer zIn, or to the '\0' byte at the end of zIn if there is no
11104a4c11aaSdan ** next statement.
11114a4c11aaSdan **
11124a4c11aaSdan ** If successful, TCL_OK is returned. Otherwise, TCL_ERROR is returned
11134a4c11aaSdan ** and an error message loaded into interpreter pDb->interp.
11144a4c11aaSdan */
11154a4c11aaSdan static int dbPrepareAndBind(
11164a4c11aaSdan   SqliteDb *pDb,                  /* Database object */
11174a4c11aaSdan   char const *zIn,                /* SQL to compile */
11184a4c11aaSdan   char const **pzOut,             /* OUT: Pointer to next SQL statement */
11194a4c11aaSdan   SqlPreparedStmt **ppPreStmt     /* OUT: Object used to cache statement */
11204a4c11aaSdan ){
11214a4c11aaSdan   const char *zSql = zIn;         /* Pointer to first SQL statement in zIn */
11224a4c11aaSdan   sqlite3_stmt *pStmt;            /* Prepared statement object */
11234a4c11aaSdan   SqlPreparedStmt *pPreStmt;      /* Pointer to cached statement */
11244a4c11aaSdan   int nSql;                       /* Length of zSql in bytes */
11254a4c11aaSdan   int nVar;                       /* Number of variables in statement */
11264a4c11aaSdan   int iParm = 0;                  /* Next free entry in apParm */
11274a4c11aaSdan   int i;
11284a4c11aaSdan   Tcl_Interp *interp = pDb->interp;
11294a4c11aaSdan 
11304a4c11aaSdan   *ppPreStmt = 0;
11314a4c11aaSdan 
11324a4c11aaSdan   /* Trim spaces from the start of zSql and calculate the remaining length. */
11334a4c11aaSdan   while( isspace(zSql[0]) ){ zSql++; }
11344a4c11aaSdan   nSql = strlen30(zSql);
11354a4c11aaSdan 
11364a4c11aaSdan   for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pPreStmt->pNext){
11374a4c11aaSdan     int n = pPreStmt->nSql;
11384a4c11aaSdan     if( nSql>=n
11394a4c11aaSdan         && memcmp(pPreStmt->zSql, zSql, n)==0
11404a4c11aaSdan         && (zSql[n]==0 || zSql[n-1]==';')
11414a4c11aaSdan     ){
11424a4c11aaSdan       pStmt = pPreStmt->pStmt;
11434a4c11aaSdan       *pzOut = &zSql[pPreStmt->nSql];
11444a4c11aaSdan 
11454a4c11aaSdan       /* When a prepared statement is found, unlink it from the
11464a4c11aaSdan       ** cache list.  It will later be added back to the beginning
11474a4c11aaSdan       ** of the cache list in order to implement LRU replacement.
11484a4c11aaSdan       */
11494a4c11aaSdan       if( pPreStmt->pPrev ){
11504a4c11aaSdan         pPreStmt->pPrev->pNext = pPreStmt->pNext;
11514a4c11aaSdan       }else{
11524a4c11aaSdan         pDb->stmtList = pPreStmt->pNext;
11534a4c11aaSdan       }
11544a4c11aaSdan       if( pPreStmt->pNext ){
11554a4c11aaSdan         pPreStmt->pNext->pPrev = pPreStmt->pPrev;
11564a4c11aaSdan       }else{
11574a4c11aaSdan         pDb->stmtLast = pPreStmt->pPrev;
11584a4c11aaSdan       }
11594a4c11aaSdan       pDb->nStmt--;
11604a4c11aaSdan       nVar = sqlite3_bind_parameter_count(pStmt);
11614a4c11aaSdan       break;
11624a4c11aaSdan     }
11634a4c11aaSdan   }
11644a4c11aaSdan 
11654a4c11aaSdan   /* If no prepared statement was found. Compile the SQL text. Also allocate
11664a4c11aaSdan   ** a new SqlPreparedStmt structure.  */
11674a4c11aaSdan   if( pPreStmt==0 ){
11684a4c11aaSdan     int nByte;
11694a4c11aaSdan 
11704a4c11aaSdan     if( SQLITE_OK!=sqlite3_prepare_v2(pDb->db, zSql, -1, &pStmt, pzOut) ){
11714a4c11aaSdan       Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
11724a4c11aaSdan       return TCL_ERROR;
11734a4c11aaSdan     }
11744a4c11aaSdan     if( pStmt==0 ){
11754a4c11aaSdan       if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
11764a4c11aaSdan         /* A compile-time error in the statement. */
11774a4c11aaSdan         Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
11784a4c11aaSdan         return TCL_ERROR;
11794a4c11aaSdan       }else{
11804a4c11aaSdan         /* The statement was a no-op.  Continue to the next statement
11814a4c11aaSdan         ** in the SQL string.
11824a4c11aaSdan         */
11834a4c11aaSdan         return TCL_OK;
11844a4c11aaSdan       }
11854a4c11aaSdan     }
11864a4c11aaSdan 
11874a4c11aaSdan     assert( pPreStmt==0 );
11884a4c11aaSdan     nVar = sqlite3_bind_parameter_count(pStmt);
11894a4c11aaSdan     nByte = sizeof(SqlPreparedStmt) + nVar*sizeof(Tcl_Obj *);
11904a4c11aaSdan     pPreStmt = (SqlPreparedStmt*)Tcl_Alloc(nByte);
11914a4c11aaSdan     memset(pPreStmt, 0, nByte);
11924a4c11aaSdan 
11934a4c11aaSdan     pPreStmt->pStmt = pStmt;
11944a4c11aaSdan     pPreStmt->nSql = (*pzOut - zSql);
11954a4c11aaSdan     pPreStmt->zSql = sqlite3_sql(pStmt);
11964a4c11aaSdan     pPreStmt->apParm = (Tcl_Obj **)&pPreStmt[1];
11974a4c11aaSdan   }
11984a4c11aaSdan   assert( pPreStmt );
11994a4c11aaSdan   assert( strlen30(pPreStmt->zSql)==pPreStmt->nSql );
12004a4c11aaSdan   assert( 0==memcmp(pPreStmt->zSql, zSql, pPreStmt->nSql) );
12014a4c11aaSdan 
12024a4c11aaSdan   /* Bind values to parameters that begin with $ or : */
12034a4c11aaSdan   for(i=1; i<=nVar; i++){
12044a4c11aaSdan     const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
12054a4c11aaSdan     if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){
12064a4c11aaSdan       Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
12074a4c11aaSdan       if( pVar ){
12084a4c11aaSdan         int n;
12094a4c11aaSdan         u8 *data;
12104a4c11aaSdan         const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
12114a4c11aaSdan         char c = zType[0];
12124a4c11aaSdan         if( zVar[0]=='@' ||
12134a4c11aaSdan            (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){
12144a4c11aaSdan           /* Load a BLOB type if the Tcl variable is a bytearray and
12154a4c11aaSdan           ** it has no string representation or the host
12164a4c11aaSdan           ** parameter name begins with "@". */
12174a4c11aaSdan           data = Tcl_GetByteArrayFromObj(pVar, &n);
12184a4c11aaSdan           sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
12194a4c11aaSdan           Tcl_IncrRefCount(pVar);
12204a4c11aaSdan           pPreStmt->apParm[iParm++] = pVar;
12214a4c11aaSdan         }else if( c=='b' && strcmp(zType,"boolean")==0 ){
12224a4c11aaSdan           Tcl_GetIntFromObj(interp, pVar, &n);
12234a4c11aaSdan           sqlite3_bind_int(pStmt, i, n);
12244a4c11aaSdan         }else if( c=='d' && strcmp(zType,"double")==0 ){
12254a4c11aaSdan           double r;
12264a4c11aaSdan           Tcl_GetDoubleFromObj(interp, pVar, &r);
12274a4c11aaSdan           sqlite3_bind_double(pStmt, i, r);
12284a4c11aaSdan         }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
12294a4c11aaSdan               (c=='i' && strcmp(zType,"int")==0) ){
12304a4c11aaSdan           Tcl_WideInt v;
12314a4c11aaSdan           Tcl_GetWideIntFromObj(interp, pVar, &v);
12324a4c11aaSdan           sqlite3_bind_int64(pStmt, i, v);
12334a4c11aaSdan         }else{
12344a4c11aaSdan           data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
12354a4c11aaSdan           sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
12364a4c11aaSdan           Tcl_IncrRefCount(pVar);
12374a4c11aaSdan           pPreStmt->apParm[iParm++] = pVar;
12384a4c11aaSdan         }
12394a4c11aaSdan       }else{
12404a4c11aaSdan         sqlite3_bind_null(pStmt, i);
12414a4c11aaSdan       }
12424a4c11aaSdan     }
12434a4c11aaSdan   }
12444a4c11aaSdan   pPreStmt->nParm = iParm;
12454a4c11aaSdan   *ppPreStmt = pPreStmt;
1246937d0deaSdan 
12474a4c11aaSdan   return TCL_OK;
12484a4c11aaSdan }
12494a4c11aaSdan 
12504a4c11aaSdan 
12514a4c11aaSdan /*
12524a4c11aaSdan ** Release a statement reference obtained by calling dbPrepareAndBind().
12534a4c11aaSdan ** There should be exactly one call to this function for each call to
12544a4c11aaSdan ** dbPrepareAndBind().
12554a4c11aaSdan **
12564a4c11aaSdan ** If the discard parameter is non-zero, then the statement is deleted
12574a4c11aaSdan ** immediately. Otherwise it is added to the LRU list and may be returned
12584a4c11aaSdan ** by a subsequent call to dbPrepareAndBind().
12594a4c11aaSdan */
12604a4c11aaSdan static void dbReleaseStmt(
12614a4c11aaSdan   SqliteDb *pDb,                  /* Database handle */
12624a4c11aaSdan   SqlPreparedStmt *pPreStmt,      /* Prepared statement handle to release */
12634a4c11aaSdan   int discard                     /* True to delete (not cache) the pPreStmt */
12644a4c11aaSdan ){
12654a4c11aaSdan   int i;
12664a4c11aaSdan 
12674a4c11aaSdan   /* Free the bound string and blob parameters */
12684a4c11aaSdan   for(i=0; i<pPreStmt->nParm; i++){
12694a4c11aaSdan     Tcl_DecrRefCount(pPreStmt->apParm[i]);
12704a4c11aaSdan   }
12714a4c11aaSdan   pPreStmt->nParm = 0;
12724a4c11aaSdan 
12734a4c11aaSdan   if( pDb->maxStmt<=0 || discard ){
12744a4c11aaSdan     /* If the cache is turned off, deallocated the statement */
12754a4c11aaSdan     sqlite3_finalize(pPreStmt->pStmt);
12764a4c11aaSdan     Tcl_Free((char *)pPreStmt);
12774a4c11aaSdan   }else{
12784a4c11aaSdan     /* Add the prepared statement to the beginning of the cache list. */
12794a4c11aaSdan     pPreStmt->pNext = pDb->stmtList;
12804a4c11aaSdan     pPreStmt->pPrev = 0;
12814a4c11aaSdan     if( pDb->stmtList ){
12824a4c11aaSdan      pDb->stmtList->pPrev = pPreStmt;
12834a4c11aaSdan     }
12844a4c11aaSdan     pDb->stmtList = pPreStmt;
12854a4c11aaSdan     if( pDb->stmtLast==0 ){
12864a4c11aaSdan       assert( pDb->nStmt==0 );
12874a4c11aaSdan       pDb->stmtLast = pPreStmt;
12884a4c11aaSdan     }else{
12894a4c11aaSdan       assert( pDb->nStmt>0 );
12904a4c11aaSdan     }
12914a4c11aaSdan     pDb->nStmt++;
12924a4c11aaSdan 
12934a4c11aaSdan     /* If we have too many statement in cache, remove the surplus from
12944a4c11aaSdan     ** the end of the cache list.  */
12954a4c11aaSdan     while( pDb->nStmt>pDb->maxStmt ){
12964a4c11aaSdan       sqlite3_finalize(pDb->stmtLast->pStmt);
12974a4c11aaSdan       pDb->stmtLast = pDb->stmtLast->pPrev;
12984a4c11aaSdan       Tcl_Free((char*)pDb->stmtLast->pNext);
12994a4c11aaSdan       pDb->stmtLast->pNext = 0;
13004a4c11aaSdan       pDb->nStmt--;
13014a4c11aaSdan     }
13024a4c11aaSdan   }
13034a4c11aaSdan }
13044a4c11aaSdan 
13054a4c11aaSdan /*
13064a4c11aaSdan ** Structure used with dbEvalXXX() functions:
13074a4c11aaSdan **
13084a4c11aaSdan **   dbEvalInit()
13094a4c11aaSdan **   dbEvalStep()
13104a4c11aaSdan **   dbEvalFinalize()
13114a4c11aaSdan **   dbEvalRowInfo()
13124a4c11aaSdan **   dbEvalColumnValue()
13134a4c11aaSdan */
13144a4c11aaSdan typedef struct DbEvalContext DbEvalContext;
13154a4c11aaSdan struct DbEvalContext {
13164a4c11aaSdan   SqliteDb *pDb;                  /* Database handle */
13174a4c11aaSdan   Tcl_Obj *pSql;                  /* Object holding string zSql */
13184a4c11aaSdan   const char *zSql;               /* Remaining SQL to execute */
13194a4c11aaSdan   SqlPreparedStmt *pPreStmt;      /* Current statement */
13204a4c11aaSdan   int nCol;                       /* Number of columns returned by pStmt */
13214a4c11aaSdan   Tcl_Obj *pArray;                /* Name of array variable */
13224a4c11aaSdan   Tcl_Obj **apColName;            /* Array of column names */
13234a4c11aaSdan };
13244a4c11aaSdan 
13254a4c11aaSdan /*
13264a4c11aaSdan ** Release any cache of column names currently held as part of
13274a4c11aaSdan ** the DbEvalContext structure passed as the first argument.
13284a4c11aaSdan */
13294a4c11aaSdan static void dbReleaseColumnNames(DbEvalContext *p){
13304a4c11aaSdan   if( p->apColName ){
13314a4c11aaSdan     int i;
13324a4c11aaSdan     for(i=0; i<p->nCol; i++){
13334a4c11aaSdan       Tcl_DecrRefCount(p->apColName[i]);
13344a4c11aaSdan     }
13354a4c11aaSdan     Tcl_Free((char *)p->apColName);
13364a4c11aaSdan     p->apColName = 0;
13374a4c11aaSdan   }
13384a4c11aaSdan   p->nCol = 0;
13394a4c11aaSdan }
13404a4c11aaSdan 
13414a4c11aaSdan /*
13424a4c11aaSdan ** Initialize a DbEvalContext structure.
13438e556520Sdanielk1977 **
13448e556520Sdanielk1977 ** If pArray is not NULL, then it contains the name of a Tcl array
13458e556520Sdanielk1977 ** variable. The "*" member of this array is set to a list containing
13464a4c11aaSdan ** the names of the columns returned by the statement as part of each
13474a4c11aaSdan ** call to dbEvalStep(), in order from left to right. e.g. if the names
13484a4c11aaSdan ** of the returned columns are a, b and c, it does the equivalent of the
13494a4c11aaSdan ** tcl command:
13508e556520Sdanielk1977 **
13518e556520Sdanielk1977 **     set ${pArray}(*) {a b c}
13528e556520Sdanielk1977 */
13534a4c11aaSdan static void dbEvalInit(
13544a4c11aaSdan   DbEvalContext *p,               /* Pointer to structure to initialize */
13554a4c11aaSdan   SqliteDb *pDb,                  /* Database handle */
13564a4c11aaSdan   Tcl_Obj *pSql,                  /* Object containing SQL script */
13574a4c11aaSdan   Tcl_Obj *pArray                 /* Name of Tcl array to set (*) element of */
13588e556520Sdanielk1977 ){
13594a4c11aaSdan   memset(p, 0, sizeof(DbEvalContext));
13604a4c11aaSdan   p->pDb = pDb;
13614a4c11aaSdan   p->zSql = Tcl_GetString(pSql);
13624a4c11aaSdan   p->pSql = pSql;
13634a4c11aaSdan   Tcl_IncrRefCount(pSql);
13644a4c11aaSdan   if( pArray ){
13654a4c11aaSdan     p->pArray = pArray;
13664a4c11aaSdan     Tcl_IncrRefCount(pArray);
13674a4c11aaSdan   }
13684a4c11aaSdan }
13698e556520Sdanielk1977 
13704a4c11aaSdan /*
13714a4c11aaSdan ** Obtain information about the row that the DbEvalContext passed as the
13724a4c11aaSdan ** first argument currently points to.
13734a4c11aaSdan */
13744a4c11aaSdan static void dbEvalRowInfo(
13754a4c11aaSdan   DbEvalContext *p,               /* Evaluation context */
13764a4c11aaSdan   int *pnCol,                     /* OUT: Number of column names */
13774a4c11aaSdan   Tcl_Obj ***papColName           /* OUT: Array of column names */
13784a4c11aaSdan ){
13798e556520Sdanielk1977   /* Compute column names */
13804a4c11aaSdan   if( 0==p->apColName ){
13814a4c11aaSdan     sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
13824a4c11aaSdan     int i;                        /* Iterator variable */
13834a4c11aaSdan     int nCol;                     /* Number of columns returned by pStmt */
13844a4c11aaSdan     Tcl_Obj **apColName = 0;      /* Array of column names */
13854a4c11aaSdan 
13864a4c11aaSdan     p->nCol = nCol = sqlite3_column_count(pStmt);
13874a4c11aaSdan     if( nCol>0 && (papColName || p->pArray) ){
13884a4c11aaSdan       apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
13898e556520Sdanielk1977       for(i=0; i<nCol; i++){
13908e556520Sdanielk1977         apColName[i] = dbTextToObj(sqlite3_column_name(pStmt,i));
13918e556520Sdanielk1977         Tcl_IncrRefCount(apColName[i]);
13928e556520Sdanielk1977       }
13934a4c11aaSdan       p->apColName = apColName;
13944a4c11aaSdan     }
13958e556520Sdanielk1977 
13968e556520Sdanielk1977     /* If results are being stored in an array variable, then create
13978e556520Sdanielk1977     ** the array(*) entry for that array
13988e556520Sdanielk1977     */
13994a4c11aaSdan     if( p->pArray ){
14004a4c11aaSdan       Tcl_Interp *interp = p->pDb->interp;
14018e556520Sdanielk1977       Tcl_Obj *pColList = Tcl_NewObj();
14028e556520Sdanielk1977       Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
14034a4c11aaSdan 
14048e556520Sdanielk1977       for(i=0; i<nCol; i++){
14058e556520Sdanielk1977         Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
14068e556520Sdanielk1977       }
14078e556520Sdanielk1977       Tcl_IncrRefCount(pStar);
14084a4c11aaSdan       Tcl_ObjSetVar2(interp, p->pArray, pStar, pColList, 0);
14098e556520Sdanielk1977       Tcl_DecrRefCount(pStar);
14108e556520Sdanielk1977     }
14118e556520Sdanielk1977   }
14128e556520Sdanielk1977 
14134a4c11aaSdan   if( papColName ){
14144a4c11aaSdan     *papColName = p->apColName;
14154a4c11aaSdan   }
14164a4c11aaSdan   if( pnCol ){
14174a4c11aaSdan     *pnCol = p->nCol;
14184a4c11aaSdan   }
14194a4c11aaSdan }
14204a4c11aaSdan 
14214a4c11aaSdan /*
14224a4c11aaSdan ** Return one of TCL_OK, TCL_BREAK or TCL_ERROR. If TCL_ERROR is
14234a4c11aaSdan ** returned, then an error message is stored in the interpreter before
14244a4c11aaSdan ** returning.
14254a4c11aaSdan **
14264a4c11aaSdan ** A return value of TCL_OK means there is a row of data available. The
14274a4c11aaSdan ** data may be accessed using dbEvalRowInfo() and dbEvalColumnValue(). This
14284a4c11aaSdan ** is analogous to a return of SQLITE_ROW from sqlite3_step(). If TCL_BREAK
14294a4c11aaSdan ** is returned, then the SQL script has finished executing and there are
14304a4c11aaSdan ** no further rows available. This is similar to SQLITE_DONE.
14314a4c11aaSdan */
14324a4c11aaSdan static int dbEvalStep(DbEvalContext *p){
14334a4c11aaSdan   while( p->zSql[0] || p->pPreStmt ){
14344a4c11aaSdan     int rc;
14354a4c11aaSdan     if( p->pPreStmt==0 ){
14364a4c11aaSdan       rc = dbPrepareAndBind(p->pDb, p->zSql, &p->zSql, &p->pPreStmt);
14374a4c11aaSdan       if( rc!=TCL_OK ) return rc;
14384a4c11aaSdan     }else{
14394a4c11aaSdan       int rcs;
14404a4c11aaSdan       SqliteDb *pDb = p->pDb;
14414a4c11aaSdan       SqlPreparedStmt *pPreStmt = p->pPreStmt;
14424a4c11aaSdan       sqlite3_stmt *pStmt = pPreStmt->pStmt;
14434a4c11aaSdan 
14444a4c11aaSdan       rcs = sqlite3_step(pStmt);
14454a4c11aaSdan       if( rcs==SQLITE_ROW ){
14464a4c11aaSdan         return TCL_OK;
14474a4c11aaSdan       }
14484a4c11aaSdan       if( p->pArray ){
14494a4c11aaSdan         dbEvalRowInfo(p, 0, 0);
14504a4c11aaSdan       }
14514a4c11aaSdan       rcs = sqlite3_reset(pStmt);
14524a4c11aaSdan 
14534a4c11aaSdan       pDb->nStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_FULLSCAN_STEP,1);
14544a4c11aaSdan       pDb->nSort = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_SORT,1);
14553c379b01Sdrh       pDb->nIndex = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_AUTOINDEX,1);
14564a4c11aaSdan       dbReleaseColumnNames(p);
14574a4c11aaSdan       p->pPreStmt = 0;
14584a4c11aaSdan 
14594a4c11aaSdan       if( rcs!=SQLITE_OK ){
14604a4c11aaSdan         /* If a run-time error occurs, report the error and stop reading
14614a4c11aaSdan         ** the SQL.  */
14624a4c11aaSdan         Tcl_SetObjResult(pDb->interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
14634a4c11aaSdan         dbReleaseStmt(pDb, pPreStmt, 1);
14644a4c11aaSdan         return TCL_ERROR;
14654a4c11aaSdan       }else{
14664a4c11aaSdan         dbReleaseStmt(pDb, pPreStmt, 0);
14674a4c11aaSdan       }
14684a4c11aaSdan     }
14694a4c11aaSdan   }
14704a4c11aaSdan 
14714a4c11aaSdan   /* Finished */
14724a4c11aaSdan   return TCL_BREAK;
14734a4c11aaSdan }
14744a4c11aaSdan 
14754a4c11aaSdan /*
14764a4c11aaSdan ** Free all resources currently held by the DbEvalContext structure passed
14774a4c11aaSdan ** as the first argument. There should be exactly one call to this function
14784a4c11aaSdan ** for each call to dbEvalInit().
14794a4c11aaSdan */
14804a4c11aaSdan static void dbEvalFinalize(DbEvalContext *p){
14814a4c11aaSdan   if( p->pPreStmt ){
14824a4c11aaSdan     sqlite3_reset(p->pPreStmt->pStmt);
14834a4c11aaSdan     dbReleaseStmt(p->pDb, p->pPreStmt, 0);
14844a4c11aaSdan     p->pPreStmt = 0;
14854a4c11aaSdan   }
14864a4c11aaSdan   if( p->pArray ){
14874a4c11aaSdan     Tcl_DecrRefCount(p->pArray);
14884a4c11aaSdan     p->pArray = 0;
14894a4c11aaSdan   }
14904a4c11aaSdan   Tcl_DecrRefCount(p->pSql);
14914a4c11aaSdan   dbReleaseColumnNames(p);
14924a4c11aaSdan }
14934a4c11aaSdan 
14944a4c11aaSdan /*
14954a4c11aaSdan ** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains
14964a4c11aaSdan ** the value for the iCol'th column of the row currently pointed to by
14974a4c11aaSdan ** the DbEvalContext structure passed as the first argument.
14984a4c11aaSdan */
14994a4c11aaSdan static Tcl_Obj *dbEvalColumnValue(DbEvalContext *p, int iCol){
15004a4c11aaSdan   sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
15014a4c11aaSdan   switch( sqlite3_column_type(pStmt, iCol) ){
15024a4c11aaSdan     case SQLITE_BLOB: {
15034a4c11aaSdan       int bytes = sqlite3_column_bytes(pStmt, iCol);
15044a4c11aaSdan       const char *zBlob = sqlite3_column_blob(pStmt, iCol);
15054a4c11aaSdan       if( !zBlob ) bytes = 0;
15064a4c11aaSdan       return Tcl_NewByteArrayObj((u8*)zBlob, bytes);
15074a4c11aaSdan     }
15084a4c11aaSdan     case SQLITE_INTEGER: {
15094a4c11aaSdan       sqlite_int64 v = sqlite3_column_int64(pStmt, iCol);
15104a4c11aaSdan       if( v>=-2147483647 && v<=2147483647 ){
15114a4c11aaSdan         return Tcl_NewIntObj(v);
15124a4c11aaSdan       }else{
15134a4c11aaSdan         return Tcl_NewWideIntObj(v);
15144a4c11aaSdan       }
15154a4c11aaSdan     }
15164a4c11aaSdan     case SQLITE_FLOAT: {
15174a4c11aaSdan       return Tcl_NewDoubleObj(sqlite3_column_double(pStmt, iCol));
15184a4c11aaSdan     }
15194a4c11aaSdan     case SQLITE_NULL: {
15204a4c11aaSdan       return dbTextToObj(p->pDb->zNull);
15214a4c11aaSdan     }
15224a4c11aaSdan   }
15234a4c11aaSdan 
15244a4c11aaSdan   return dbTextToObj((char *)sqlite3_column_text(pStmt, iCol));
15254a4c11aaSdan }
15264a4c11aaSdan 
15274a4c11aaSdan /*
15284a4c11aaSdan ** If using Tcl version 8.6 or greater, use the NR functions to avoid
15294a4c11aaSdan ** recursive evalution of scripts by the [db eval] and [db trans]
15304a4c11aaSdan ** commands. Even if the headers used while compiling the extension
15314a4c11aaSdan ** are 8.6 or newer, the code still tests the Tcl version at runtime.
15324a4c11aaSdan ** This allows stubs-enabled builds to be used with older Tcl libraries.
15334a4c11aaSdan */
15344a4c11aaSdan #if TCL_MAJOR_VERSION>8 || (TCL_MAJOR_VERSION==8 && TCL_MINOR_VERSION>=6)
1535a2c8a95bSdrh # define SQLITE_TCL_NRE 1
15364a4c11aaSdan static int DbUseNre(void){
15374a4c11aaSdan   int major, minor;
15384a4c11aaSdan   Tcl_GetVersion(&major, &minor, 0, 0);
15394a4c11aaSdan   return( (major==8 && minor>=6) || major>8 );
15404a4c11aaSdan }
15414a4c11aaSdan #else
15424a4c11aaSdan /*
15434a4c11aaSdan ** Compiling using headers earlier than 8.6. In this case NR cannot be
15444a4c11aaSdan ** used, so DbUseNre() to always return zero. Add #defines for the other
15454a4c11aaSdan ** Tcl_NRxxx() functions to prevent them from causing compilation errors,
15464a4c11aaSdan ** even though the only invocations of them are within conditional blocks
15474a4c11aaSdan ** of the form:
15484a4c11aaSdan **
15494a4c11aaSdan **   if( DbUseNre() ) { ... }
15504a4c11aaSdan */
1551a2c8a95bSdrh # define SQLITE_TCL_NRE 0
15524a4c11aaSdan # define DbUseNre() 0
15534a4c11aaSdan # define Tcl_NRAddCallback(a,b,c,d,e,f) 0
15544a4c11aaSdan # define Tcl_NREvalObj(a,b,c) 0
15554a4c11aaSdan # define Tcl_NRCreateCommand(a,b,c,d,e,f) 0
15564a4c11aaSdan #endif
15574a4c11aaSdan 
15584a4c11aaSdan /*
15594a4c11aaSdan ** This function is part of the implementation of the command:
15604a4c11aaSdan **
15614a4c11aaSdan **   $db eval SQL ?ARRAYNAME? SCRIPT
15624a4c11aaSdan */
15634a4c11aaSdan static int DbEvalNextCmd(
15644a4c11aaSdan   ClientData data[],                   /* data[0] is the (DbEvalContext*) */
15654a4c11aaSdan   Tcl_Interp *interp,                  /* Tcl interpreter */
15664a4c11aaSdan   int result                           /* Result so far */
15674a4c11aaSdan ){
15684a4c11aaSdan   int rc = result;                     /* Return code */
15694a4c11aaSdan 
15704a4c11aaSdan   /* The first element of the data[] array is a pointer to a DbEvalContext
15714a4c11aaSdan   ** structure allocated using Tcl_Alloc(). The second element of data[]
15724a4c11aaSdan   ** is a pointer to a Tcl_Obj containing the script to run for each row
15734a4c11aaSdan   ** returned by the queries encapsulated in data[0]. */
15744a4c11aaSdan   DbEvalContext *p = (DbEvalContext *)data[0];
15754a4c11aaSdan   Tcl_Obj *pScript = (Tcl_Obj *)data[1];
15764a4c11aaSdan   Tcl_Obj *pArray = p->pArray;
15774a4c11aaSdan 
15784a4c11aaSdan   while( (rc==TCL_OK || rc==TCL_CONTINUE) && TCL_OK==(rc = dbEvalStep(p)) ){
15794a4c11aaSdan     int i;
15804a4c11aaSdan     int nCol;
15814a4c11aaSdan     Tcl_Obj **apColName;
15824a4c11aaSdan     dbEvalRowInfo(p, &nCol, &apColName);
15834a4c11aaSdan     for(i=0; i<nCol; i++){
15844a4c11aaSdan       Tcl_Obj *pVal = dbEvalColumnValue(p, i);
15854a4c11aaSdan       if( pArray==0 ){
15864a4c11aaSdan         Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
15874a4c11aaSdan       }else{
15884a4c11aaSdan         Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
15894a4c11aaSdan       }
15904a4c11aaSdan     }
15914a4c11aaSdan 
15924a4c11aaSdan     /* The required interpreter variables are now populated with the data
15934a4c11aaSdan     ** from the current row. If using NRE, schedule callbacks to evaluate
15944a4c11aaSdan     ** script pScript, then to invoke this function again to fetch the next
15954a4c11aaSdan     ** row (or clean up if there is no next row or the script throws an
15964a4c11aaSdan     ** exception). After scheduling the callbacks, return control to the
15974a4c11aaSdan     ** caller.
15984a4c11aaSdan     **
15994a4c11aaSdan     ** If not using NRE, evaluate pScript directly and continue with the
16004a4c11aaSdan     ** next iteration of this while(...) loop.  */
16014a4c11aaSdan     if( DbUseNre() ){
16024a4c11aaSdan       Tcl_NRAddCallback(interp, DbEvalNextCmd, (void*)p, (void*)pScript, 0, 0);
16034a4c11aaSdan       return Tcl_NREvalObj(interp, pScript, 0);
16044a4c11aaSdan     }else{
16054a4c11aaSdan       rc = Tcl_EvalObjEx(interp, pScript, 0);
16064a4c11aaSdan     }
16074a4c11aaSdan   }
16084a4c11aaSdan 
16094a4c11aaSdan   Tcl_DecrRefCount(pScript);
16104a4c11aaSdan   dbEvalFinalize(p);
16114a4c11aaSdan   Tcl_Free((char *)p);
16124a4c11aaSdan 
16134a4c11aaSdan   if( rc==TCL_OK || rc==TCL_BREAK ){
16144a4c11aaSdan     Tcl_ResetResult(interp);
16154a4c11aaSdan     rc = TCL_OK;
16164a4c11aaSdan   }
16174a4c11aaSdan   return rc;
16188e556520Sdanielk1977 }
16198e556520Sdanielk1977 
16201067fe11Stpoindex /*
162146c47d46Sdan ** This function is used by the implementations of the following database
162246c47d46Sdan ** handle sub-commands:
162346c47d46Sdan **
162446c47d46Sdan **   $db update_hook ?SCRIPT?
162546c47d46Sdan **   $db wal_hook ?SCRIPT?
162646c47d46Sdan **   $db commit_hook ?SCRIPT?
162746c47d46Sdan **   $db preupdate hook ?SCRIPT?
162846c47d46Sdan */
162946c47d46Sdan static void DbHookCmd(
163046c47d46Sdan   Tcl_Interp *interp,             /* Tcl interpreter */
163146c47d46Sdan   SqliteDb *pDb,                  /* Database handle */
163246c47d46Sdan   Tcl_Obj *pArg,                  /* SCRIPT argument (or NULL) */
163346c47d46Sdan   Tcl_Obj **ppHook                /* Pointer to member of SqliteDb */
163446c47d46Sdan ){
163546c47d46Sdan   sqlite3 *db = pDb->db;
163646c47d46Sdan 
163746c47d46Sdan   if( *ppHook ){
163846c47d46Sdan     Tcl_SetObjResult(interp, *ppHook);
163946c47d46Sdan     if( pArg ){
164046c47d46Sdan       Tcl_DecrRefCount(*ppHook);
164146c47d46Sdan       *ppHook = 0;
164246c47d46Sdan     }
164346c47d46Sdan   }
164446c47d46Sdan   if( pArg ){
164546c47d46Sdan     assert( !(*ppHook) );
164646c47d46Sdan     if( Tcl_GetCharLength(pArg)>0 ){
164746c47d46Sdan       *ppHook = pArg;
164846c47d46Sdan       Tcl_IncrRefCount(*ppHook);
164946c47d46Sdan     }
165046c47d46Sdan   }
165146c47d46Sdan 
165246c47d46Sdan   sqlite3_preupdate_hook(db, (pDb->pPreUpdateHook?DbPreUpdateHandler:0), pDb);
165346c47d46Sdan   sqlite3_update_hook(db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
165446c47d46Sdan   sqlite3_rollback_hook(db, (pDb->pRollbackHook?DbRollbackHandler:0), pDb);
165546c47d46Sdan   sqlite3_wal_hook(db, (pDb->pWalHook?DbWalHandler:0), pDb);
165621e8d012Sdan   sqlite3_transaction_hook(db, (pDb->pTransHook?DbTransHandler:0), pDb);
165746c47d46Sdan }
165846c47d46Sdan 
165946c47d46Sdan /*
166075897234Sdrh ** The "sqlite" command below creates a new Tcl command for each
166175897234Sdrh ** connection it opens to an SQLite database.  This routine is invoked
166275897234Sdrh ** whenever one of those connection-specific commands is executed
166375897234Sdrh ** in Tcl.  For example, if you run Tcl code like this:
166475897234Sdrh **
16659bb575fdSdrh **       sqlite3 db1  "my_database"
166675897234Sdrh **       db1 close
166775897234Sdrh **
166875897234Sdrh ** The first command opens a connection to the "my_database" database
166975897234Sdrh ** and calls that connection "db1".  The second command causes this
167075897234Sdrh ** subroutine to be invoked.
167175897234Sdrh */
16726d31316cSdrh static int DbObjCmd(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
1673bec3f402Sdrh   SqliteDb *pDb = (SqliteDb*)cd;
16746d31316cSdrh   int choice;
167522fbcb8dSdrh   int rc = TCL_OK;
16760de8c112Sdrh   static const char *DB_strs[] = {
1677dc2c4915Sdrh     "authorizer",         "backup",            "busy",
1678dc2c4915Sdrh     "cache",              "changes",           "close",
1679dc2c4915Sdrh     "collate",            "collation_needed",  "commit_hook",
1680dc2c4915Sdrh     "complete",           "copy",              "enable_load_extension",
1681dc2c4915Sdrh     "errorcode",          "eval",              "exists",
1682dc2c4915Sdrh     "function",           "incrblob",          "interrupt",
1683833bf968Sdrh     "last_insert_rowid",  "nullvalue",         "onecolumn",
168446c47d46Sdan     "preupdate",
1685833bf968Sdrh     "profile",            "progress",          "rekey",
1686833bf968Sdrh     "restore",            "rollback_hook",     "status",
1687833bf968Sdrh     "timeout",            "total_changes",     "trace",
168821e8d012Sdan     "transaction",        "transaction_hook",
168921e8d012Sdan     "unlock_notify",     "update_hook",
1690833bf968Sdrh     "version",            "wal_hook",          0
16916d31316cSdrh   };
1692411995dcSdrh   enum DB_enum {
1693dc2c4915Sdrh     DB_AUTHORIZER,        DB_BACKUP,           DB_BUSY,
1694dc2c4915Sdrh     DB_CACHE,             DB_CHANGES,          DB_CLOSE,
1695dc2c4915Sdrh     DB_COLLATE,           DB_COLLATION_NEEDED, DB_COMMIT_HOOK,
1696dc2c4915Sdrh     DB_COMPLETE,          DB_COPY,             DB_ENABLE_LOAD_EXTENSION,
1697dc2c4915Sdrh     DB_ERRORCODE,         DB_EVAL,             DB_EXISTS,
1698dc2c4915Sdrh     DB_FUNCTION,          DB_INCRBLOB,         DB_INTERRUPT,
1699833bf968Sdrh     DB_LAST_INSERT_ROWID, DB_NULLVALUE,        DB_ONECOLUMN,
170046c47d46Sdan     DB_PREUPDATE,
1701833bf968Sdrh     DB_PROFILE,           DB_PROGRESS,         DB_REKEY,
1702833bf968Sdrh     DB_RESTORE,           DB_ROLLBACK_HOOK,    DB_STATUS,
1703833bf968Sdrh     DB_TIMEOUT,           DB_TOTAL_CHANGES,    DB_TRACE,
170421e8d012Sdan     DB_TRANSACTION,       DB_TRANSACTION_HOOK,
170521e8d012Sdan     DB_UNLOCK_NOTIFY,     DB_UPDATE_HOOK,
1706833bf968Sdrh     DB_VERSION,           DB_WAL_HOOK
17076d31316cSdrh   };
17081067fe11Stpoindex   /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
17096d31316cSdrh 
17106d31316cSdrh   if( objc<2 ){
17116d31316cSdrh     Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
171275897234Sdrh     return TCL_ERROR;
171375897234Sdrh   }
1714411995dcSdrh   if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
17156d31316cSdrh     return TCL_ERROR;
17166d31316cSdrh   }
17176d31316cSdrh 
1718411995dcSdrh   switch( (enum DB_enum)choice ){
171975897234Sdrh 
1720e22a334bSdrh   /*    $db authorizer ?CALLBACK?
1721e22a334bSdrh   **
1722e22a334bSdrh   ** Invoke the given callback to authorize each SQL operation as it is
1723e22a334bSdrh   ** compiled.  5 arguments are appended to the callback before it is
1724e22a334bSdrh   ** invoked:
1725e22a334bSdrh   **
1726e22a334bSdrh   **   (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
1727e22a334bSdrh   **   (2) First descriptive name (depends on authorization type)
1728e22a334bSdrh   **   (3) Second descriptive name
1729e22a334bSdrh   **   (4) Name of the database (ex: "main", "temp")
1730e22a334bSdrh   **   (5) Name of trigger that is doing the access
1731e22a334bSdrh   **
1732e22a334bSdrh   ** The callback should return on of the following strings: SQLITE_OK,
1733e22a334bSdrh   ** SQLITE_IGNORE, or SQLITE_DENY.  Any other return value is an error.
1734e22a334bSdrh   **
1735e22a334bSdrh   ** If this method is invoked with no arguments, the current authorization
1736e22a334bSdrh   ** callback string is returned.
1737e22a334bSdrh   */
1738e22a334bSdrh   case DB_AUTHORIZER: {
17391211de37Sdrh #ifdef SQLITE_OMIT_AUTHORIZATION
17401211de37Sdrh     Tcl_AppendResult(interp, "authorization not available in this build", 0);
17411211de37Sdrh     return TCL_ERROR;
17421211de37Sdrh #else
1743e22a334bSdrh     if( objc>3 ){
1744e22a334bSdrh       Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
17450f14e2ebSdrh       return TCL_ERROR;
1746e22a334bSdrh     }else if( objc==2 ){
1747b5a20d3cSdrh       if( pDb->zAuth ){
1748e22a334bSdrh         Tcl_AppendResult(interp, pDb->zAuth, 0);
1749e22a334bSdrh       }
1750e22a334bSdrh     }else{
1751e22a334bSdrh       char *zAuth;
1752e22a334bSdrh       int len;
1753e22a334bSdrh       if( pDb->zAuth ){
1754e22a334bSdrh         Tcl_Free(pDb->zAuth);
1755e22a334bSdrh       }
1756e22a334bSdrh       zAuth = Tcl_GetStringFromObj(objv[2], &len);
1757e22a334bSdrh       if( zAuth && len>0 ){
1758e22a334bSdrh         pDb->zAuth = Tcl_Alloc( len + 1 );
17595bb3eb9bSdrh         memcpy(pDb->zAuth, zAuth, len+1);
1760e22a334bSdrh       }else{
1761e22a334bSdrh         pDb->zAuth = 0;
1762e22a334bSdrh       }
1763e22a334bSdrh       if( pDb->zAuth ){
1764e22a334bSdrh         pDb->interp = interp;
17656f8a503dSdanielk1977         sqlite3_set_authorizer(pDb->db, auth_callback, pDb);
1766e22a334bSdrh       }else{
17676f8a503dSdanielk1977         sqlite3_set_authorizer(pDb->db, 0, 0);
1768e22a334bSdrh       }
1769e22a334bSdrh     }
17701211de37Sdrh #endif
1771e22a334bSdrh     break;
1772e22a334bSdrh   }
1773e22a334bSdrh 
1774dc2c4915Sdrh   /*    $db backup ?DATABASE? FILENAME
1775dc2c4915Sdrh   **
1776dc2c4915Sdrh   ** Open or create a database file named FILENAME.  Transfer the
1777dc2c4915Sdrh   ** content of local database DATABASE (default: "main") into the
1778dc2c4915Sdrh   ** FILENAME database.
1779dc2c4915Sdrh   */
1780dc2c4915Sdrh   case DB_BACKUP: {
1781dc2c4915Sdrh     const char *zDestFile;
1782dc2c4915Sdrh     const char *zSrcDb;
1783dc2c4915Sdrh     sqlite3 *pDest;
1784dc2c4915Sdrh     sqlite3_backup *pBackup;
1785dc2c4915Sdrh 
1786dc2c4915Sdrh     if( objc==3 ){
1787dc2c4915Sdrh       zSrcDb = "main";
1788dc2c4915Sdrh       zDestFile = Tcl_GetString(objv[2]);
1789dc2c4915Sdrh     }else if( objc==4 ){
1790dc2c4915Sdrh       zSrcDb = Tcl_GetString(objv[2]);
1791dc2c4915Sdrh       zDestFile = Tcl_GetString(objv[3]);
1792dc2c4915Sdrh     }else{
1793dc2c4915Sdrh       Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
1794dc2c4915Sdrh       return TCL_ERROR;
1795dc2c4915Sdrh     }
1796dc2c4915Sdrh     rc = sqlite3_open(zDestFile, &pDest);
1797dc2c4915Sdrh     if( rc!=SQLITE_OK ){
1798dc2c4915Sdrh       Tcl_AppendResult(interp, "cannot open target database: ",
1799dc2c4915Sdrh            sqlite3_errmsg(pDest), (char*)0);
1800dc2c4915Sdrh       sqlite3_close(pDest);
1801dc2c4915Sdrh       return TCL_ERROR;
1802dc2c4915Sdrh     }
1803dc2c4915Sdrh     pBackup = sqlite3_backup_init(pDest, "main", pDb->db, zSrcDb);
1804dc2c4915Sdrh     if( pBackup==0 ){
1805dc2c4915Sdrh       Tcl_AppendResult(interp, "backup failed: ",
1806dc2c4915Sdrh            sqlite3_errmsg(pDest), (char*)0);
1807dc2c4915Sdrh       sqlite3_close(pDest);
1808dc2c4915Sdrh       return TCL_ERROR;
1809dc2c4915Sdrh     }
1810dc2c4915Sdrh     while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
1811dc2c4915Sdrh     sqlite3_backup_finish(pBackup);
1812dc2c4915Sdrh     if( rc==SQLITE_DONE ){
1813dc2c4915Sdrh       rc = TCL_OK;
1814dc2c4915Sdrh     }else{
1815dc2c4915Sdrh       Tcl_AppendResult(interp, "backup failed: ",
1816dc2c4915Sdrh            sqlite3_errmsg(pDest), (char*)0);
1817dc2c4915Sdrh       rc = TCL_ERROR;
1818dc2c4915Sdrh     }
1819dc2c4915Sdrh     sqlite3_close(pDest);
1820dc2c4915Sdrh     break;
1821dc2c4915Sdrh   }
1822dc2c4915Sdrh 
1823bec3f402Sdrh   /*    $db busy ?CALLBACK?
1824bec3f402Sdrh   **
1825bec3f402Sdrh   ** Invoke the given callback if an SQL statement attempts to open
1826bec3f402Sdrh   ** a locked database file.
1827bec3f402Sdrh   */
18286d31316cSdrh   case DB_BUSY: {
18296d31316cSdrh     if( objc>3 ){
18306d31316cSdrh       Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
1831bec3f402Sdrh       return TCL_ERROR;
18326d31316cSdrh     }else if( objc==2 ){
1833bec3f402Sdrh       if( pDb->zBusy ){
1834bec3f402Sdrh         Tcl_AppendResult(interp, pDb->zBusy, 0);
1835bec3f402Sdrh       }
1836bec3f402Sdrh     }else{
18376d31316cSdrh       char *zBusy;
18386d31316cSdrh       int len;
1839bec3f402Sdrh       if( pDb->zBusy ){
1840bec3f402Sdrh         Tcl_Free(pDb->zBusy);
18416d31316cSdrh       }
18426d31316cSdrh       zBusy = Tcl_GetStringFromObj(objv[2], &len);
18436d31316cSdrh       if( zBusy && len>0 ){
18446d31316cSdrh         pDb->zBusy = Tcl_Alloc( len + 1 );
18455bb3eb9bSdrh         memcpy(pDb->zBusy, zBusy, len+1);
18466d31316cSdrh       }else{
1847bec3f402Sdrh         pDb->zBusy = 0;
1848bec3f402Sdrh       }
1849bec3f402Sdrh       if( pDb->zBusy ){
1850bec3f402Sdrh         pDb->interp = interp;
18516f8a503dSdanielk1977         sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
18526d31316cSdrh       }else{
18536f8a503dSdanielk1977         sqlite3_busy_handler(pDb->db, 0, 0);
1854bec3f402Sdrh       }
1855bec3f402Sdrh     }
18566d31316cSdrh     break;
18576d31316cSdrh   }
1858bec3f402Sdrh 
1859fb7e7651Sdrh   /*     $db cache flush
1860fb7e7651Sdrh   **     $db cache size n
1861fb7e7651Sdrh   **
1862fb7e7651Sdrh   ** Flush the prepared statement cache, or set the maximum number of
1863fb7e7651Sdrh   ** cached statements.
1864fb7e7651Sdrh   */
1865fb7e7651Sdrh   case DB_CACHE: {
1866fb7e7651Sdrh     char *subCmd;
1867fb7e7651Sdrh     int n;
1868fb7e7651Sdrh 
1869fb7e7651Sdrh     if( objc<=2 ){
1870fb7e7651Sdrh       Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
1871fb7e7651Sdrh       return TCL_ERROR;
1872fb7e7651Sdrh     }
1873fb7e7651Sdrh     subCmd = Tcl_GetStringFromObj( objv[2], 0 );
1874fb7e7651Sdrh     if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
1875fb7e7651Sdrh       if( objc!=3 ){
1876fb7e7651Sdrh         Tcl_WrongNumArgs(interp, 2, objv, "flush");
1877fb7e7651Sdrh         return TCL_ERROR;
1878fb7e7651Sdrh       }else{
1879fb7e7651Sdrh         flushStmtCache( pDb );
1880fb7e7651Sdrh       }
1881fb7e7651Sdrh     }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
1882fb7e7651Sdrh       if( objc!=4 ){
1883fb7e7651Sdrh         Tcl_WrongNumArgs(interp, 2, objv, "size n");
1884fb7e7651Sdrh         return TCL_ERROR;
1885fb7e7651Sdrh       }else{
1886fb7e7651Sdrh         if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
1887fb7e7651Sdrh           Tcl_AppendResult( interp, "cannot convert \"",
1888fb7e7651Sdrh                Tcl_GetStringFromObj(objv[3],0), "\" to integer", 0);
1889fb7e7651Sdrh           return TCL_ERROR;
1890fb7e7651Sdrh         }else{
1891fb7e7651Sdrh           if( n<0 ){
1892fb7e7651Sdrh             flushStmtCache( pDb );
1893fb7e7651Sdrh             n = 0;
1894fb7e7651Sdrh           }else if( n>MAX_PREPARED_STMTS ){
1895fb7e7651Sdrh             n = MAX_PREPARED_STMTS;
1896fb7e7651Sdrh           }
1897fb7e7651Sdrh           pDb->maxStmt = n;
1898fb7e7651Sdrh         }
1899fb7e7651Sdrh       }
1900fb7e7651Sdrh     }else{
1901fb7e7651Sdrh       Tcl_AppendResult( interp, "bad option \"",
1902191fadcfSdanielk1977           Tcl_GetStringFromObj(objv[2],0), "\": must be flush or size", 0);
1903fb7e7651Sdrh       return TCL_ERROR;
1904fb7e7651Sdrh     }
1905fb7e7651Sdrh     break;
1906fb7e7651Sdrh   }
1907fb7e7651Sdrh 
1908b28af71aSdanielk1977   /*     $db changes
1909c8d30ac1Sdrh   **
1910c8d30ac1Sdrh   ** Return the number of rows that were modified, inserted, or deleted by
1911b28af71aSdanielk1977   ** the most recent INSERT, UPDATE or DELETE statement, not including
1912b28af71aSdanielk1977   ** any changes made by trigger programs.
1913c8d30ac1Sdrh   */
1914c8d30ac1Sdrh   case DB_CHANGES: {
1915c8d30ac1Sdrh     Tcl_Obj *pResult;
1916c8d30ac1Sdrh     if( objc!=2 ){
1917c8d30ac1Sdrh       Tcl_WrongNumArgs(interp, 2, objv, "");
1918c8d30ac1Sdrh       return TCL_ERROR;
1919c8d30ac1Sdrh     }
1920c8d30ac1Sdrh     pResult = Tcl_GetObjResult(interp);
1921b28af71aSdanielk1977     Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
1922f146a776Srdc     break;
1923f146a776Srdc   }
1924f146a776Srdc 
192575897234Sdrh   /*    $db close
192675897234Sdrh   **
192775897234Sdrh   ** Shutdown the database
192875897234Sdrh   */
19296d31316cSdrh   case DB_CLOSE: {
19306d31316cSdrh     Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
19316d31316cSdrh     break;
19326d31316cSdrh   }
193375897234Sdrh 
19340f14e2ebSdrh   /*
19350f14e2ebSdrh   **     $db collate NAME SCRIPT
19360f14e2ebSdrh   **
19370f14e2ebSdrh   ** Create a new SQL collation function called NAME.  Whenever
19380f14e2ebSdrh   ** that function is called, invoke SCRIPT to evaluate the function.
19390f14e2ebSdrh   */
19400f14e2ebSdrh   case DB_COLLATE: {
19410f14e2ebSdrh     SqlCollate *pCollate;
19420f14e2ebSdrh     char *zName;
19430f14e2ebSdrh     char *zScript;
19440f14e2ebSdrh     int nScript;
19450f14e2ebSdrh     if( objc!=4 ){
19460f14e2ebSdrh       Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
19470f14e2ebSdrh       return TCL_ERROR;
19480f14e2ebSdrh     }
19490f14e2ebSdrh     zName = Tcl_GetStringFromObj(objv[2], 0);
19500f14e2ebSdrh     zScript = Tcl_GetStringFromObj(objv[3], &nScript);
19510f14e2ebSdrh     pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
19520f14e2ebSdrh     if( pCollate==0 ) return TCL_ERROR;
19530f14e2ebSdrh     pCollate->interp = interp;
19540f14e2ebSdrh     pCollate->pNext = pDb->pCollate;
19550f14e2ebSdrh     pCollate->zScript = (char*)&pCollate[1];
19560f14e2ebSdrh     pDb->pCollate = pCollate;
19575bb3eb9bSdrh     memcpy(pCollate->zScript, zScript, nScript+1);
19580f14e2ebSdrh     if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
19590f14e2ebSdrh         pCollate, tclSqlCollate) ){
19609636c4e1Sdanielk1977       Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
19610f14e2ebSdrh       return TCL_ERROR;
19620f14e2ebSdrh     }
19630f14e2ebSdrh     break;
19640f14e2ebSdrh   }
19650f14e2ebSdrh 
19660f14e2ebSdrh   /*
19670f14e2ebSdrh   **     $db collation_needed SCRIPT
19680f14e2ebSdrh   **
19690f14e2ebSdrh   ** Create a new SQL collation function called NAME.  Whenever
19700f14e2ebSdrh   ** that function is called, invoke SCRIPT to evaluate the function.
19710f14e2ebSdrh   */
19720f14e2ebSdrh   case DB_COLLATION_NEEDED: {
19730f14e2ebSdrh     if( objc!=3 ){
19740f14e2ebSdrh       Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
19750f14e2ebSdrh       return TCL_ERROR;
19760f14e2ebSdrh     }
19770f14e2ebSdrh     if( pDb->pCollateNeeded ){
19780f14e2ebSdrh       Tcl_DecrRefCount(pDb->pCollateNeeded);
19790f14e2ebSdrh     }
19800f14e2ebSdrh     pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
19810f14e2ebSdrh     Tcl_IncrRefCount(pDb->pCollateNeeded);
19820f14e2ebSdrh     sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
19830f14e2ebSdrh     break;
19840f14e2ebSdrh   }
19850f14e2ebSdrh 
198619e2d37fSdrh   /*    $db commit_hook ?CALLBACK?
198719e2d37fSdrh   **
198819e2d37fSdrh   ** Invoke the given callback just before committing every SQL transaction.
198919e2d37fSdrh   ** If the callback throws an exception or returns non-zero, then the
199019e2d37fSdrh   ** transaction is aborted.  If CALLBACK is an empty string, the callback
199119e2d37fSdrh   ** is disabled.
199219e2d37fSdrh   */
199319e2d37fSdrh   case DB_COMMIT_HOOK: {
199419e2d37fSdrh     if( objc>3 ){
199519e2d37fSdrh       Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
199619e2d37fSdrh       return TCL_ERROR;
199719e2d37fSdrh     }else if( objc==2 ){
199819e2d37fSdrh       if( pDb->zCommit ){
199919e2d37fSdrh         Tcl_AppendResult(interp, pDb->zCommit, 0);
200019e2d37fSdrh       }
200119e2d37fSdrh     }else{
200219e2d37fSdrh       char *zCommit;
200319e2d37fSdrh       int len;
200419e2d37fSdrh       if( pDb->zCommit ){
200519e2d37fSdrh         Tcl_Free(pDb->zCommit);
200619e2d37fSdrh       }
200719e2d37fSdrh       zCommit = Tcl_GetStringFromObj(objv[2], &len);
200819e2d37fSdrh       if( zCommit && len>0 ){
200919e2d37fSdrh         pDb->zCommit = Tcl_Alloc( len + 1 );
20105bb3eb9bSdrh         memcpy(pDb->zCommit, zCommit, len+1);
201119e2d37fSdrh       }else{
201219e2d37fSdrh         pDb->zCommit = 0;
201319e2d37fSdrh       }
201419e2d37fSdrh       if( pDb->zCommit ){
201519e2d37fSdrh         pDb->interp = interp;
201619e2d37fSdrh         sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
201719e2d37fSdrh       }else{
201819e2d37fSdrh         sqlite3_commit_hook(pDb->db, 0, 0);
201919e2d37fSdrh       }
202019e2d37fSdrh     }
202119e2d37fSdrh     break;
202219e2d37fSdrh   }
202319e2d37fSdrh 
202475897234Sdrh   /*    $db complete SQL
202575897234Sdrh   **
202675897234Sdrh   ** Return TRUE if SQL is a complete SQL statement.  Return FALSE if
202775897234Sdrh   ** additional lines of input are needed.  This is similar to the
202875897234Sdrh   ** built-in "info complete" command of Tcl.
202975897234Sdrh   */
20306d31316cSdrh   case DB_COMPLETE: {
2031ccae6026Sdrh #ifndef SQLITE_OMIT_COMPLETE
20326d31316cSdrh     Tcl_Obj *pResult;
20336d31316cSdrh     int isComplete;
20346d31316cSdrh     if( objc!=3 ){
20356d31316cSdrh       Tcl_WrongNumArgs(interp, 2, objv, "SQL");
203675897234Sdrh       return TCL_ERROR;
203775897234Sdrh     }
20386f8a503dSdanielk1977     isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
20396d31316cSdrh     pResult = Tcl_GetObjResult(interp);
20406d31316cSdrh     Tcl_SetBooleanObj(pResult, isComplete);
2041ccae6026Sdrh #endif
20426d31316cSdrh     break;
20436d31316cSdrh   }
204475897234Sdrh 
204519e2d37fSdrh   /*    $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
204619e2d37fSdrh   **
204719e2d37fSdrh   ** Copy data into table from filename, optionally using SEPARATOR
204819e2d37fSdrh   ** as column separators.  If a column contains a null string, or the
204919e2d37fSdrh   ** value of NULLINDICATOR, a NULL is inserted for the column.
205019e2d37fSdrh   ** conflict-algorithm is one of the sqlite conflict algorithms:
205119e2d37fSdrh   **    rollback, abort, fail, ignore, replace
205219e2d37fSdrh   ** On success, return the number of lines processed, not necessarily same
205319e2d37fSdrh   ** as 'db changes' due to conflict-algorithm selected.
205419e2d37fSdrh   **
205519e2d37fSdrh   ** This code is basically an implementation/enhancement of
205619e2d37fSdrh   ** the sqlite3 shell.c ".import" command.
205719e2d37fSdrh   **
205819e2d37fSdrh   ** This command usage is equivalent to the sqlite2.x COPY statement,
205919e2d37fSdrh   ** which imports file data into a table using the PostgreSQL COPY file format:
206019e2d37fSdrh   **   $db copy $conflit_algo $table_name $filename \t \\N
206119e2d37fSdrh   */
206219e2d37fSdrh   case DB_COPY: {
206319e2d37fSdrh     char *zTable;               /* Insert data into this table */
206419e2d37fSdrh     char *zFile;                /* The file from which to extract data */
206519e2d37fSdrh     char *zConflict;            /* The conflict algorithm to use */
206619e2d37fSdrh     sqlite3_stmt *pStmt;        /* A statement */
206719e2d37fSdrh     int nCol;                   /* Number of columns in the table */
206819e2d37fSdrh     int nByte;                  /* Number of bytes in an SQL string */
206919e2d37fSdrh     int i, j;                   /* Loop counters */
207019e2d37fSdrh     int nSep;                   /* Number of bytes in zSep[] */
207119e2d37fSdrh     int nNull;                  /* Number of bytes in zNull[] */
207219e2d37fSdrh     char *zSql;                 /* An SQL statement */
207319e2d37fSdrh     char *zLine;                /* A single line of input from the file */
207419e2d37fSdrh     char **azCol;               /* zLine[] broken up into columns */
207519e2d37fSdrh     char *zCommit;              /* How to commit changes */
207619e2d37fSdrh     FILE *in;                   /* The input file */
207719e2d37fSdrh     int lineno = 0;             /* Line number of input file */
207819e2d37fSdrh     char zLineNum[80];          /* Line number print buffer */
207919e2d37fSdrh     Tcl_Obj *pResult;           /* interp result */
208019e2d37fSdrh 
208119e2d37fSdrh     char *zSep;
208219e2d37fSdrh     char *zNull;
208319e2d37fSdrh     if( objc<5 || objc>7 ){
208419e2d37fSdrh       Tcl_WrongNumArgs(interp, 2, objv,
208519e2d37fSdrh          "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
208619e2d37fSdrh       return TCL_ERROR;
208719e2d37fSdrh     }
208819e2d37fSdrh     if( objc>=6 ){
208919e2d37fSdrh       zSep = Tcl_GetStringFromObj(objv[5], 0);
209019e2d37fSdrh     }else{
209119e2d37fSdrh       zSep = "\t";
209219e2d37fSdrh     }
209319e2d37fSdrh     if( objc>=7 ){
209419e2d37fSdrh       zNull = Tcl_GetStringFromObj(objv[6], 0);
209519e2d37fSdrh     }else{
209619e2d37fSdrh       zNull = "";
209719e2d37fSdrh     }
209819e2d37fSdrh     zConflict = Tcl_GetStringFromObj(objv[2], 0);
209919e2d37fSdrh     zTable = Tcl_GetStringFromObj(objv[3], 0);
210019e2d37fSdrh     zFile = Tcl_GetStringFromObj(objv[4], 0);
21014f21c4afSdrh     nSep = strlen30(zSep);
21024f21c4afSdrh     nNull = strlen30(zNull);
210319e2d37fSdrh     if( nSep==0 ){
210419e2d37fSdrh       Tcl_AppendResult(interp,"Error: non-null separator required for copy",0);
210519e2d37fSdrh       return TCL_ERROR;
210619e2d37fSdrh     }
21073e59c012Sdrh     if(strcmp(zConflict, "rollback") != 0 &&
21083e59c012Sdrh        strcmp(zConflict, "abort"   ) != 0 &&
21093e59c012Sdrh        strcmp(zConflict, "fail"    ) != 0 &&
21103e59c012Sdrh        strcmp(zConflict, "ignore"  ) != 0 &&
21113e59c012Sdrh        strcmp(zConflict, "replace" ) != 0 ) {
211219e2d37fSdrh       Tcl_AppendResult(interp, "Error: \"", zConflict,
211319e2d37fSdrh             "\", conflict-algorithm must be one of: rollback, "
211419e2d37fSdrh             "abort, fail, ignore, or replace", 0);
211519e2d37fSdrh       return TCL_ERROR;
211619e2d37fSdrh     }
211719e2d37fSdrh     zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
211819e2d37fSdrh     if( zSql==0 ){
211919e2d37fSdrh       Tcl_AppendResult(interp, "Error: no such table: ", zTable, 0);
212019e2d37fSdrh       return TCL_ERROR;
212119e2d37fSdrh     }
21224f21c4afSdrh     nByte = strlen30(zSql);
21233e701a18Sdrh     rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
212419e2d37fSdrh     sqlite3_free(zSql);
212519e2d37fSdrh     if( rc ){
212619e2d37fSdrh       Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
212719e2d37fSdrh       nCol = 0;
212819e2d37fSdrh     }else{
212919e2d37fSdrh       nCol = sqlite3_column_count(pStmt);
213019e2d37fSdrh     }
213119e2d37fSdrh     sqlite3_finalize(pStmt);
213219e2d37fSdrh     if( nCol==0 ) {
213319e2d37fSdrh       return TCL_ERROR;
213419e2d37fSdrh     }
213519e2d37fSdrh     zSql = malloc( nByte + 50 + nCol*2 );
213619e2d37fSdrh     if( zSql==0 ) {
213719e2d37fSdrh       Tcl_AppendResult(interp, "Error: can't malloc()", 0);
213819e2d37fSdrh       return TCL_ERROR;
213919e2d37fSdrh     }
214019e2d37fSdrh     sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
214119e2d37fSdrh          zConflict, zTable);
21424f21c4afSdrh     j = strlen30(zSql);
214319e2d37fSdrh     for(i=1; i<nCol; i++){
214419e2d37fSdrh       zSql[j++] = ',';
214519e2d37fSdrh       zSql[j++] = '?';
214619e2d37fSdrh     }
214719e2d37fSdrh     zSql[j++] = ')';
214819e2d37fSdrh     zSql[j] = 0;
21493e701a18Sdrh     rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
215019e2d37fSdrh     free(zSql);
215119e2d37fSdrh     if( rc ){
215219e2d37fSdrh       Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
215319e2d37fSdrh       sqlite3_finalize(pStmt);
215419e2d37fSdrh       return TCL_ERROR;
215519e2d37fSdrh     }
215619e2d37fSdrh     in = fopen(zFile, "rb");
215719e2d37fSdrh     if( in==0 ){
215819e2d37fSdrh       Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL);
215919e2d37fSdrh       sqlite3_finalize(pStmt);
216019e2d37fSdrh       return TCL_ERROR;
216119e2d37fSdrh     }
216219e2d37fSdrh     azCol = malloc( sizeof(azCol[0])*(nCol+1) );
216319e2d37fSdrh     if( azCol==0 ) {
216419e2d37fSdrh       Tcl_AppendResult(interp, "Error: can't malloc()", 0);
216543617e9aSdrh       fclose(in);
216619e2d37fSdrh       return TCL_ERROR;
216719e2d37fSdrh     }
21683752785fSdrh     (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
216919e2d37fSdrh     zCommit = "COMMIT";
217019e2d37fSdrh     while( (zLine = local_getline(0, in))!=0 ){
217119e2d37fSdrh       char *z;
217219e2d37fSdrh       i = 0;
217319e2d37fSdrh       lineno++;
217419e2d37fSdrh       azCol[0] = zLine;
217519e2d37fSdrh       for(i=0, z=zLine; *z; z++){
217619e2d37fSdrh         if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
217719e2d37fSdrh           *z = 0;
217819e2d37fSdrh           i++;
217919e2d37fSdrh           if( i<nCol ){
218019e2d37fSdrh             azCol[i] = &z[nSep];
218119e2d37fSdrh             z += nSep-1;
218219e2d37fSdrh           }
218319e2d37fSdrh         }
218419e2d37fSdrh       }
218519e2d37fSdrh       if( i+1!=nCol ){
218619e2d37fSdrh         char *zErr;
21874f21c4afSdrh         int nErr = strlen30(zFile) + 200;
21885bb3eb9bSdrh         zErr = malloc(nErr);
2189c1f4494eSdrh         if( zErr ){
21905bb3eb9bSdrh           sqlite3_snprintf(nErr, zErr,
2191955de52cSdanielk1977              "Error: %s line %d: expected %d columns of data but found %d",
219219e2d37fSdrh              zFile, lineno, nCol, i+1);
219319e2d37fSdrh           Tcl_AppendResult(interp, zErr, 0);
219419e2d37fSdrh           free(zErr);
2195c1f4494eSdrh         }
219619e2d37fSdrh         zCommit = "ROLLBACK";
219719e2d37fSdrh         break;
219819e2d37fSdrh       }
219919e2d37fSdrh       for(i=0; i<nCol; i++){
220019e2d37fSdrh         /* check for null data, if so, bind as null */
2201ea678832Sdrh         if( (nNull>0 && strcmp(azCol[i], zNull)==0)
22024f21c4afSdrh           || strlen30(azCol[i])==0
2203ea678832Sdrh         ){
220419e2d37fSdrh           sqlite3_bind_null(pStmt, i+1);
220519e2d37fSdrh         }else{
220619e2d37fSdrh           sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
220719e2d37fSdrh         }
220819e2d37fSdrh       }
220919e2d37fSdrh       sqlite3_step(pStmt);
221019e2d37fSdrh       rc = sqlite3_reset(pStmt);
221119e2d37fSdrh       free(zLine);
221219e2d37fSdrh       if( rc!=SQLITE_OK ){
221319e2d37fSdrh         Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), 0);
221419e2d37fSdrh         zCommit = "ROLLBACK";
221519e2d37fSdrh         break;
221619e2d37fSdrh       }
221719e2d37fSdrh     }
221819e2d37fSdrh     free(azCol);
221919e2d37fSdrh     fclose(in);
222019e2d37fSdrh     sqlite3_finalize(pStmt);
22213752785fSdrh     (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
222219e2d37fSdrh 
222319e2d37fSdrh     if( zCommit[0] == 'C' ){
222419e2d37fSdrh       /* success, set result as number of lines processed */
222519e2d37fSdrh       pResult = Tcl_GetObjResult(interp);
222619e2d37fSdrh       Tcl_SetIntObj(pResult, lineno);
222719e2d37fSdrh       rc = TCL_OK;
222819e2d37fSdrh     }else{
222919e2d37fSdrh       /* failure, append lineno where failed */
22305bb3eb9bSdrh       sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
223119e2d37fSdrh       Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,0);
223219e2d37fSdrh       rc = TCL_ERROR;
223319e2d37fSdrh     }
223419e2d37fSdrh     break;
223519e2d37fSdrh   }
223619e2d37fSdrh 
223775897234Sdrh   /*
22384144905bSdrh   **    $db enable_load_extension BOOLEAN
22394144905bSdrh   **
22404144905bSdrh   ** Turn the extension loading feature on or off.  It if off by
22414144905bSdrh   ** default.
22424144905bSdrh   */
22434144905bSdrh   case DB_ENABLE_LOAD_EXTENSION: {
2244f533acc0Sdrh #ifndef SQLITE_OMIT_LOAD_EXTENSION
22454144905bSdrh     int onoff;
22464144905bSdrh     if( objc!=3 ){
22474144905bSdrh       Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
22484144905bSdrh       return TCL_ERROR;
22494144905bSdrh     }
22504144905bSdrh     if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
22514144905bSdrh       return TCL_ERROR;
22524144905bSdrh     }
22534144905bSdrh     sqlite3_enable_load_extension(pDb->db, onoff);
22544144905bSdrh     break;
2255f533acc0Sdrh #else
2256f533acc0Sdrh     Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
2257f533acc0Sdrh                      0);
2258f533acc0Sdrh     return TCL_ERROR;
2259f533acc0Sdrh #endif
22604144905bSdrh   }
22614144905bSdrh 
22624144905bSdrh   /*
2263dcd997eaSdrh   **    $db errorcode
2264dcd997eaSdrh   **
2265dcd997eaSdrh   ** Return the numeric error code that was returned by the most recent
22666f8a503dSdanielk1977   ** call to sqlite3_exec().
2267dcd997eaSdrh   */
2268dcd997eaSdrh   case DB_ERRORCODE: {
2269f3ce83f5Sdanielk1977     Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
2270dcd997eaSdrh     break;
2271dcd997eaSdrh   }
2272dcd997eaSdrh 
2273dcd997eaSdrh   /*
22744a4c11aaSdan   **    $db exists $sql
22751807ce37Sdrh   **    $db onecolumn $sql
227675897234Sdrh   **
22774a4c11aaSdan   ** The onecolumn method is the equivalent of:
22784a4c11aaSdan   **     lindex [$db eval $sql] 0
22794a4c11aaSdan   */
22804a4c11aaSdan   case DB_EXISTS:
22814a4c11aaSdan   case DB_ONECOLUMN: {
22824a4c11aaSdan     DbEvalContext sEval;
22834a4c11aaSdan     if( objc!=3 ){
22844a4c11aaSdan       Tcl_WrongNumArgs(interp, 2, objv, "SQL");
22854a4c11aaSdan       return TCL_ERROR;
22864a4c11aaSdan     }
22874a4c11aaSdan 
22884a4c11aaSdan     dbEvalInit(&sEval, pDb, objv[2], 0);
22894a4c11aaSdan     rc = dbEvalStep(&sEval);
22904a4c11aaSdan     if( choice==DB_ONECOLUMN ){
22914a4c11aaSdan       if( rc==TCL_OK ){
22924a4c11aaSdan         Tcl_SetObjResult(interp, dbEvalColumnValue(&sEval, 0));
22934a4c11aaSdan       }
22944a4c11aaSdan     }else if( rc==TCL_BREAK || rc==TCL_OK ){
22954a4c11aaSdan       Tcl_SetObjResult(interp, Tcl_NewBooleanObj(rc==TCL_OK));
22964a4c11aaSdan     }
22974a4c11aaSdan     dbEvalFinalize(&sEval);
22984a4c11aaSdan 
22994a4c11aaSdan     if( rc==TCL_BREAK ){
23004a4c11aaSdan       rc = TCL_OK;
23014a4c11aaSdan     }
23024a4c11aaSdan     break;
23034a4c11aaSdan   }
23044a4c11aaSdan 
23054a4c11aaSdan   /*
23064a4c11aaSdan   **    $db eval $sql ?array? ?{  ...code... }?
23074a4c11aaSdan   **
230875897234Sdrh   ** The SQL statement in $sql is evaluated.  For each row, the values are
2309bec3f402Sdrh   ** placed in elements of the array named "array" and ...code... is executed.
231075897234Sdrh   ** If "array" and "code" are omitted, then no callback is every invoked.
231175897234Sdrh   ** If "array" is an empty string, then the values are placed in variables
231275897234Sdrh   ** that have the same name as the fields extracted by the query.
231375897234Sdrh   */
23144a4c11aaSdan   case DB_EVAL: {
231592febd92Sdrh     if( objc<3 || objc>5 ){
2316895d7472Sdrh       Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
231730ccda10Sdanielk1977       return TCL_ERROR;
231830ccda10Sdanielk1977     }
23194a4c11aaSdan 
232092febd92Sdrh     if( objc==3 ){
23214a4c11aaSdan       DbEvalContext sEval;
23224a4c11aaSdan       Tcl_Obj *pRet = Tcl_NewObj();
23234a4c11aaSdan       Tcl_IncrRefCount(pRet);
23244a4c11aaSdan       dbEvalInit(&sEval, pDb, objv[2], 0);
23254a4c11aaSdan       while( TCL_OK==(rc = dbEvalStep(&sEval)) ){
23264a4c11aaSdan         int i;
23274a4c11aaSdan         int nCol;
23284a4c11aaSdan         dbEvalRowInfo(&sEval, &nCol, 0);
232992febd92Sdrh         for(i=0; i<nCol; i++){
23304a4c11aaSdan           Tcl_ListObjAppendElement(interp, pRet, dbEvalColumnValue(&sEval, i));
233192febd92Sdrh         }
233230ccda10Sdanielk1977       }
23334a4c11aaSdan       dbEvalFinalize(&sEval);
233490b6bb19Sdrh       if( rc==TCL_BREAK ){
23354a4c11aaSdan         Tcl_SetObjResult(interp, pRet);
233690b6bb19Sdrh         rc = TCL_OK;
233790b6bb19Sdrh       }
2338ef2cb63eSdanielk1977       Tcl_DecrRefCount(pRet);
23394a4c11aaSdan     }else{
23404a4c11aaSdan       ClientData cd[2];
23414a4c11aaSdan       DbEvalContext *p;
23424a4c11aaSdan       Tcl_Obj *pArray = 0;
23434a4c11aaSdan       Tcl_Obj *pScript;
23444a4c11aaSdan 
23454a4c11aaSdan       if( objc==5 && *(char *)Tcl_GetString(objv[3]) ){
23464a4c11aaSdan         pArray = objv[3];
23474a4c11aaSdan       }
23484a4c11aaSdan       pScript = objv[objc-1];
23494a4c11aaSdan       Tcl_IncrRefCount(pScript);
23504a4c11aaSdan 
23514a4c11aaSdan       p = (DbEvalContext *)Tcl_Alloc(sizeof(DbEvalContext));
23524a4c11aaSdan       dbEvalInit(p, pDb, objv[2], pArray);
23534a4c11aaSdan 
23544a4c11aaSdan       cd[0] = (void *)p;
23554a4c11aaSdan       cd[1] = (void *)pScript;
23564a4c11aaSdan       rc = DbEvalNextCmd(cd, interp, TCL_OK);
23571807ce37Sdrh     }
235830ccda10Sdanielk1977     break;
235930ccda10Sdanielk1977   }
2360bec3f402Sdrh 
2361bec3f402Sdrh   /*
2362e3602be8Sdrh   **     $db function NAME [-argcount N] SCRIPT
2363cabb0819Sdrh   **
2364cabb0819Sdrh   ** Create a new SQL function called NAME.  Whenever that function is
2365cabb0819Sdrh   ** called, invoke SCRIPT to evaluate the function.
2366cabb0819Sdrh   */
2367cabb0819Sdrh   case DB_FUNCTION: {
2368cabb0819Sdrh     SqlFunc *pFunc;
2369d1e4733dSdrh     Tcl_Obj *pScript;
2370cabb0819Sdrh     char *zName;
2371e3602be8Sdrh     int nArg = -1;
2372e3602be8Sdrh     if( objc==6 ){
2373e3602be8Sdrh       const char *z = Tcl_GetString(objv[3]);
23744f21c4afSdrh       int n = strlen30(z);
2375e3602be8Sdrh       if( n>2 && strncmp(z, "-argcount",n)==0 ){
2376e3602be8Sdrh         if( Tcl_GetIntFromObj(interp, objv[4], &nArg) ) return TCL_ERROR;
2377e3602be8Sdrh         if( nArg<0 ){
2378e3602be8Sdrh           Tcl_AppendResult(interp, "number of arguments must be non-negative",
2379e3602be8Sdrh                            (char*)0);
2380cabb0819Sdrh           return TCL_ERROR;
2381cabb0819Sdrh         }
2382e3602be8Sdrh       }
2383e3602be8Sdrh       pScript = objv[5];
2384e3602be8Sdrh     }else if( objc!=4 ){
2385e3602be8Sdrh       Tcl_WrongNumArgs(interp, 2, objv, "NAME [-argcount N] SCRIPT");
2386e3602be8Sdrh       return TCL_ERROR;
2387e3602be8Sdrh     }else{
2388d1e4733dSdrh       pScript = objv[3];
2389e3602be8Sdrh     }
2390e3602be8Sdrh     zName = Tcl_GetStringFromObj(objv[2], 0);
2391d1e4733dSdrh     pFunc = findSqlFunc(pDb, zName);
2392cabb0819Sdrh     if( pFunc==0 ) return TCL_ERROR;
2393d1e4733dSdrh     if( pFunc->pScript ){
2394d1e4733dSdrh       Tcl_DecrRefCount(pFunc->pScript);
2395d1e4733dSdrh     }
2396d1e4733dSdrh     pFunc->pScript = pScript;
2397d1e4733dSdrh     Tcl_IncrRefCount(pScript);
2398d1e4733dSdrh     pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
2399e3602be8Sdrh     rc = sqlite3_create_function(pDb->db, zName, nArg, SQLITE_UTF8,
2400d8123366Sdanielk1977         pFunc, tclSqlFunc, 0, 0);
2401fb7e7651Sdrh     if( rc!=SQLITE_OK ){
2402fb7e7651Sdrh       rc = TCL_ERROR;
24039636c4e1Sdanielk1977       Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
2404fb7e7651Sdrh     }
2405cabb0819Sdrh     break;
2406cabb0819Sdrh   }
2407cabb0819Sdrh 
2408cabb0819Sdrh   /*
24098cbadb02Sdanielk1977   **     $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
2410b4e9af9fSdanielk1977   */
2411b4e9af9fSdanielk1977   case DB_INCRBLOB: {
241232a0d8bbSdanielk1977 #ifdef SQLITE_OMIT_INCRBLOB
241332a0d8bbSdanielk1977     Tcl_AppendResult(interp, "incrblob not available in this build", 0);
241432a0d8bbSdanielk1977     return TCL_ERROR;
241532a0d8bbSdanielk1977 #else
24168cbadb02Sdanielk1977     int isReadonly = 0;
2417b4e9af9fSdanielk1977     const char *zDb = "main";
2418b4e9af9fSdanielk1977     const char *zTable;
2419b4e9af9fSdanielk1977     const char *zColumn;
2420b4e9af9fSdanielk1977     sqlite_int64 iRow;
2421b4e9af9fSdanielk1977 
24228cbadb02Sdanielk1977     /* Check for the -readonly option */
24238cbadb02Sdanielk1977     if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
24248cbadb02Sdanielk1977       isReadonly = 1;
24258cbadb02Sdanielk1977     }
24268cbadb02Sdanielk1977 
24278cbadb02Sdanielk1977     if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
24288cbadb02Sdanielk1977       Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
2429b4e9af9fSdanielk1977       return TCL_ERROR;
2430b4e9af9fSdanielk1977     }
2431b4e9af9fSdanielk1977 
24328cbadb02Sdanielk1977     if( objc==(6+isReadonly) ){
2433b4e9af9fSdanielk1977       zDb = Tcl_GetString(objv[2]);
2434b4e9af9fSdanielk1977     }
2435b4e9af9fSdanielk1977     zTable = Tcl_GetString(objv[objc-3]);
2436b4e9af9fSdanielk1977     zColumn = Tcl_GetString(objv[objc-2]);
2437b4e9af9fSdanielk1977     rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
2438b4e9af9fSdanielk1977 
2439b4e9af9fSdanielk1977     if( rc==TCL_OK ){
24408cbadb02Sdanielk1977       rc = createIncrblobChannel(
24418cbadb02Sdanielk1977           interp, pDb, zDb, zTable, zColumn, iRow, isReadonly
24428cbadb02Sdanielk1977       );
2443b4e9af9fSdanielk1977     }
244432a0d8bbSdanielk1977 #endif
2445b4e9af9fSdanielk1977     break;
2446b4e9af9fSdanielk1977   }
2447b4e9af9fSdanielk1977 
2448b4e9af9fSdanielk1977   /*
2449f11bded5Sdrh   **     $db interrupt
2450f11bded5Sdrh   **
2451f11bded5Sdrh   ** Interrupt the execution of the inner-most SQL interpreter.  This
2452f11bded5Sdrh   ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
2453f11bded5Sdrh   */
2454f11bded5Sdrh   case DB_INTERRUPT: {
2455f11bded5Sdrh     sqlite3_interrupt(pDb->db);
2456f11bded5Sdrh     break;
2457f11bded5Sdrh   }
2458f11bded5Sdrh 
2459f11bded5Sdrh   /*
246019e2d37fSdrh   **     $db nullvalue ?STRING?
246119e2d37fSdrh   **
246219e2d37fSdrh   ** Change text used when a NULL comes back from the database. If ?STRING?
246319e2d37fSdrh   ** is not present, then the current string used for NULL is returned.
246419e2d37fSdrh   ** If STRING is present, then STRING is returned.
246519e2d37fSdrh   **
246619e2d37fSdrh   */
246719e2d37fSdrh   case DB_NULLVALUE: {
246819e2d37fSdrh     if( objc!=2 && objc!=3 ){
246919e2d37fSdrh       Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
247019e2d37fSdrh       return TCL_ERROR;
247119e2d37fSdrh     }
247219e2d37fSdrh     if( objc==3 ){
247319e2d37fSdrh       int len;
247419e2d37fSdrh       char *zNull = Tcl_GetStringFromObj(objv[2], &len);
247519e2d37fSdrh       if( pDb->zNull ){
247619e2d37fSdrh         Tcl_Free(pDb->zNull);
247719e2d37fSdrh       }
247819e2d37fSdrh       if( zNull && len>0 ){
247919e2d37fSdrh         pDb->zNull = Tcl_Alloc( len + 1 );
248019e2d37fSdrh         strncpy(pDb->zNull, zNull, len);
248119e2d37fSdrh         pDb->zNull[len] = '\0';
248219e2d37fSdrh       }else{
248319e2d37fSdrh         pDb->zNull = 0;
248419e2d37fSdrh       }
248519e2d37fSdrh     }
248619e2d37fSdrh     Tcl_SetObjResult(interp, dbTextToObj(pDb->zNull));
248719e2d37fSdrh     break;
248819e2d37fSdrh   }
248919e2d37fSdrh 
249019e2d37fSdrh   /*
2491af9ff33aSdrh   **     $db last_insert_rowid
2492af9ff33aSdrh   **
2493af9ff33aSdrh   ** Return an integer which is the ROWID for the most recent insert.
2494af9ff33aSdrh   */
2495af9ff33aSdrh   case DB_LAST_INSERT_ROWID: {
2496af9ff33aSdrh     Tcl_Obj *pResult;
2497f7e678d6Sdrh     Tcl_WideInt rowid;
2498af9ff33aSdrh     if( objc!=2 ){
2499af9ff33aSdrh       Tcl_WrongNumArgs(interp, 2, objv, "");
2500af9ff33aSdrh       return TCL_ERROR;
2501af9ff33aSdrh     }
25026f8a503dSdanielk1977     rowid = sqlite3_last_insert_rowid(pDb->db);
2503af9ff33aSdrh     pResult = Tcl_GetObjResult(interp);
2504f7e678d6Sdrh     Tcl_SetWideIntObj(pResult, rowid);
2505af9ff33aSdrh     break;
2506af9ff33aSdrh   }
2507af9ff33aSdrh 
2508af9ff33aSdrh   /*
25094a4c11aaSdan   ** The DB_ONECOLUMN method is implemented together with DB_EXISTS.
25105d9d7576Sdrh   */
25111807ce37Sdrh 
25121807ce37Sdrh   /*    $db progress ?N CALLBACK?
25131807ce37Sdrh   **
25141807ce37Sdrh   ** Invoke the given callback every N virtual machine opcodes while executing
25151807ce37Sdrh   ** queries.
25161807ce37Sdrh   */
25171807ce37Sdrh   case DB_PROGRESS: {
25181807ce37Sdrh     if( objc==2 ){
25191807ce37Sdrh       if( pDb->zProgress ){
25201807ce37Sdrh         Tcl_AppendResult(interp, pDb->zProgress, 0);
25215d9d7576Sdrh       }
25221807ce37Sdrh     }else if( objc==4 ){
25231807ce37Sdrh       char *zProgress;
25241807ce37Sdrh       int len;
25251807ce37Sdrh       int N;
25261807ce37Sdrh       if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
25271807ce37Sdrh         return TCL_ERROR;
25281807ce37Sdrh       };
25291807ce37Sdrh       if( pDb->zProgress ){
25301807ce37Sdrh         Tcl_Free(pDb->zProgress);
25311807ce37Sdrh       }
25321807ce37Sdrh       zProgress = Tcl_GetStringFromObj(objv[3], &len);
25331807ce37Sdrh       if( zProgress && len>0 ){
25341807ce37Sdrh         pDb->zProgress = Tcl_Alloc( len + 1 );
25355bb3eb9bSdrh         memcpy(pDb->zProgress, zProgress, len+1);
25361807ce37Sdrh       }else{
25371807ce37Sdrh         pDb->zProgress = 0;
25381807ce37Sdrh       }
25391807ce37Sdrh #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
25401807ce37Sdrh       if( pDb->zProgress ){
25411807ce37Sdrh         pDb->interp = interp;
25421807ce37Sdrh         sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
25431807ce37Sdrh       }else{
25441807ce37Sdrh         sqlite3_progress_handler(pDb->db, 0, 0, 0);
25451807ce37Sdrh       }
25461807ce37Sdrh #endif
25471807ce37Sdrh     }else{
25481807ce37Sdrh       Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
25491807ce37Sdrh       return TCL_ERROR;
25505d9d7576Sdrh     }
25515d9d7576Sdrh     break;
25525d9d7576Sdrh   }
25535d9d7576Sdrh 
255419e2d37fSdrh   /*    $db profile ?CALLBACK?
255519e2d37fSdrh   **
255619e2d37fSdrh   ** Make arrangements to invoke the CALLBACK routine after each SQL statement
255719e2d37fSdrh   ** that has run.  The text of the SQL and the amount of elapse time are
255819e2d37fSdrh   ** appended to CALLBACK before the script is run.
255919e2d37fSdrh   */
256019e2d37fSdrh   case DB_PROFILE: {
256119e2d37fSdrh     if( objc>3 ){
256219e2d37fSdrh       Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
256319e2d37fSdrh       return TCL_ERROR;
256419e2d37fSdrh     }else if( objc==2 ){
256519e2d37fSdrh       if( pDb->zProfile ){
256619e2d37fSdrh         Tcl_AppendResult(interp, pDb->zProfile, 0);
256719e2d37fSdrh       }
256819e2d37fSdrh     }else{
256919e2d37fSdrh       char *zProfile;
257019e2d37fSdrh       int len;
257119e2d37fSdrh       if( pDb->zProfile ){
257219e2d37fSdrh         Tcl_Free(pDb->zProfile);
257319e2d37fSdrh       }
257419e2d37fSdrh       zProfile = Tcl_GetStringFromObj(objv[2], &len);
257519e2d37fSdrh       if( zProfile && len>0 ){
257619e2d37fSdrh         pDb->zProfile = Tcl_Alloc( len + 1 );
25775bb3eb9bSdrh         memcpy(pDb->zProfile, zProfile, len+1);
257819e2d37fSdrh       }else{
257919e2d37fSdrh         pDb->zProfile = 0;
258019e2d37fSdrh       }
2581bb201344Sshaneh #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
258219e2d37fSdrh       if( pDb->zProfile ){
258319e2d37fSdrh         pDb->interp = interp;
258419e2d37fSdrh         sqlite3_profile(pDb->db, DbProfileHandler, pDb);
258519e2d37fSdrh       }else{
258619e2d37fSdrh         sqlite3_profile(pDb->db, 0, 0);
258719e2d37fSdrh       }
258819e2d37fSdrh #endif
258919e2d37fSdrh     }
259019e2d37fSdrh     break;
259119e2d37fSdrh   }
259219e2d37fSdrh 
25935d9d7576Sdrh   /*
259422fbcb8dSdrh   **     $db rekey KEY
259522fbcb8dSdrh   **
259622fbcb8dSdrh   ** Change the encryption key on the currently open database.
259722fbcb8dSdrh   */
259822fbcb8dSdrh   case DB_REKEY: {
259922fbcb8dSdrh     int nKey;
260022fbcb8dSdrh     void *pKey;
260122fbcb8dSdrh     if( objc!=3 ){
260222fbcb8dSdrh       Tcl_WrongNumArgs(interp, 2, objv, "KEY");
260322fbcb8dSdrh       return TCL_ERROR;
260422fbcb8dSdrh     }
260522fbcb8dSdrh     pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
26069eb9e26bSdrh #ifdef SQLITE_HAS_CODEC
26072011d5f5Sdrh     rc = sqlite3_rekey(pDb->db, pKey, nKey);
260822fbcb8dSdrh     if( rc ){
2609f20b21c8Sdanielk1977       Tcl_AppendResult(interp, sqlite3ErrStr(rc), 0);
261022fbcb8dSdrh       rc = TCL_ERROR;
261122fbcb8dSdrh     }
261222fbcb8dSdrh #endif
261322fbcb8dSdrh     break;
261422fbcb8dSdrh   }
261522fbcb8dSdrh 
2616dc2c4915Sdrh   /*    $db restore ?DATABASE? FILENAME
2617dc2c4915Sdrh   **
2618dc2c4915Sdrh   ** Open a database file named FILENAME.  Transfer the content
2619dc2c4915Sdrh   ** of FILENAME into the local database DATABASE (default: "main").
2620dc2c4915Sdrh   */
2621dc2c4915Sdrh   case DB_RESTORE: {
2622dc2c4915Sdrh     const char *zSrcFile;
2623dc2c4915Sdrh     const char *zDestDb;
2624dc2c4915Sdrh     sqlite3 *pSrc;
2625dc2c4915Sdrh     sqlite3_backup *pBackup;
2626dc2c4915Sdrh     int nTimeout = 0;
2627dc2c4915Sdrh 
2628dc2c4915Sdrh     if( objc==3 ){
2629dc2c4915Sdrh       zDestDb = "main";
2630dc2c4915Sdrh       zSrcFile = Tcl_GetString(objv[2]);
2631dc2c4915Sdrh     }else if( objc==4 ){
2632dc2c4915Sdrh       zDestDb = Tcl_GetString(objv[2]);
2633dc2c4915Sdrh       zSrcFile = Tcl_GetString(objv[3]);
2634dc2c4915Sdrh     }else{
2635dc2c4915Sdrh       Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
2636dc2c4915Sdrh       return TCL_ERROR;
2637dc2c4915Sdrh     }
2638dc2c4915Sdrh     rc = sqlite3_open_v2(zSrcFile, &pSrc, SQLITE_OPEN_READONLY, 0);
2639dc2c4915Sdrh     if( rc!=SQLITE_OK ){
2640dc2c4915Sdrh       Tcl_AppendResult(interp, "cannot open source database: ",
2641dc2c4915Sdrh            sqlite3_errmsg(pSrc), (char*)0);
2642dc2c4915Sdrh       sqlite3_close(pSrc);
2643dc2c4915Sdrh       return TCL_ERROR;
2644dc2c4915Sdrh     }
2645dc2c4915Sdrh     pBackup = sqlite3_backup_init(pDb->db, zDestDb, pSrc, "main");
2646dc2c4915Sdrh     if( pBackup==0 ){
2647dc2c4915Sdrh       Tcl_AppendResult(interp, "restore failed: ",
2648dc2c4915Sdrh            sqlite3_errmsg(pDb->db), (char*)0);
2649dc2c4915Sdrh       sqlite3_close(pSrc);
2650dc2c4915Sdrh       return TCL_ERROR;
2651dc2c4915Sdrh     }
2652dc2c4915Sdrh     while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
2653dc2c4915Sdrh               || rc==SQLITE_BUSY ){
2654dc2c4915Sdrh       if( rc==SQLITE_BUSY ){
2655dc2c4915Sdrh         if( nTimeout++ >= 3 ) break;
2656dc2c4915Sdrh         sqlite3_sleep(100);
2657dc2c4915Sdrh       }
2658dc2c4915Sdrh     }
2659dc2c4915Sdrh     sqlite3_backup_finish(pBackup);
2660dc2c4915Sdrh     if( rc==SQLITE_DONE ){
2661dc2c4915Sdrh       rc = TCL_OK;
2662dc2c4915Sdrh     }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
2663dc2c4915Sdrh       Tcl_AppendResult(interp, "restore failed: source database busy",
2664dc2c4915Sdrh                        (char*)0);
2665dc2c4915Sdrh       rc = TCL_ERROR;
2666dc2c4915Sdrh     }else{
2667dc2c4915Sdrh       Tcl_AppendResult(interp, "restore failed: ",
2668dc2c4915Sdrh            sqlite3_errmsg(pDb->db), (char*)0);
2669dc2c4915Sdrh       rc = TCL_ERROR;
2670dc2c4915Sdrh     }
2671dc2c4915Sdrh     sqlite3_close(pSrc);
2672dc2c4915Sdrh     break;
2673dc2c4915Sdrh   }
2674dc2c4915Sdrh 
267522fbcb8dSdrh   /*
26763c379b01Sdrh   **     $db status (step|sort|autoindex)
2677d1d38488Sdrh   **
2678d1d38488Sdrh   ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or
2679d1d38488Sdrh   ** SQLITE_STMTSTATUS_SORT for the most recent eval.
2680d1d38488Sdrh   */
2681d1d38488Sdrh   case DB_STATUS: {
2682d1d38488Sdrh     int v;
2683d1d38488Sdrh     const char *zOp;
2684d1d38488Sdrh     if( objc!=3 ){
26851c320a43Sdrh       Tcl_WrongNumArgs(interp, 2, objv, "(step|sort|autoindex)");
2686d1d38488Sdrh       return TCL_ERROR;
2687d1d38488Sdrh     }
2688d1d38488Sdrh     zOp = Tcl_GetString(objv[2]);
2689d1d38488Sdrh     if( strcmp(zOp, "step")==0 ){
2690d1d38488Sdrh       v = pDb->nStep;
2691d1d38488Sdrh     }else if( strcmp(zOp, "sort")==0 ){
2692d1d38488Sdrh       v = pDb->nSort;
26933c379b01Sdrh     }else if( strcmp(zOp, "autoindex")==0 ){
26943c379b01Sdrh       v = pDb->nIndex;
2695d1d38488Sdrh     }else{
26963c379b01Sdrh       Tcl_AppendResult(interp,
26973c379b01Sdrh             "bad argument: should be autoindex, step, or sort",
2698d1d38488Sdrh             (char*)0);
2699d1d38488Sdrh       return TCL_ERROR;
2700d1d38488Sdrh     }
2701d1d38488Sdrh     Tcl_SetObjResult(interp, Tcl_NewIntObj(v));
2702d1d38488Sdrh     break;
2703d1d38488Sdrh   }
2704d1d38488Sdrh 
2705d1d38488Sdrh   /*
2706bec3f402Sdrh   **     $db timeout MILLESECONDS
2707bec3f402Sdrh   **
2708bec3f402Sdrh   ** Delay for the number of milliseconds specified when a file is locked.
2709bec3f402Sdrh   */
27106d31316cSdrh   case DB_TIMEOUT: {
2711bec3f402Sdrh     int ms;
27126d31316cSdrh     if( objc!=3 ){
27136d31316cSdrh       Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
2714bec3f402Sdrh       return TCL_ERROR;
271575897234Sdrh     }
27166d31316cSdrh     if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
27176f8a503dSdanielk1977     sqlite3_busy_timeout(pDb->db, ms);
27186d31316cSdrh     break;
271975897234Sdrh   }
2720b5a20d3cSdrh 
27210f14e2ebSdrh   /*
27220f14e2ebSdrh   **     $db total_changes
27230f14e2ebSdrh   **
27240f14e2ebSdrh   ** Return the number of rows that were modified, inserted, or deleted
27250f14e2ebSdrh   ** since the database handle was created.
27260f14e2ebSdrh   */
27270f14e2ebSdrh   case DB_TOTAL_CHANGES: {
27280f14e2ebSdrh     Tcl_Obj *pResult;
27290f14e2ebSdrh     if( objc!=2 ){
27300f14e2ebSdrh       Tcl_WrongNumArgs(interp, 2, objv, "");
27310f14e2ebSdrh       return TCL_ERROR;
27320f14e2ebSdrh     }
27330f14e2ebSdrh     pResult = Tcl_GetObjResult(interp);
27340f14e2ebSdrh     Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
27350f14e2ebSdrh     break;
27360f14e2ebSdrh   }
27370f14e2ebSdrh 
2738b5a20d3cSdrh   /*    $db trace ?CALLBACK?
2739b5a20d3cSdrh   **
2740b5a20d3cSdrh   ** Make arrangements to invoke the CALLBACK routine for each SQL statement
2741b5a20d3cSdrh   ** that is executed.  The text of the SQL is appended to CALLBACK before
2742b5a20d3cSdrh   ** it is executed.
2743b5a20d3cSdrh   */
2744b5a20d3cSdrh   case DB_TRACE: {
2745b5a20d3cSdrh     if( objc>3 ){
2746b5a20d3cSdrh       Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2747b97759edSdrh       return TCL_ERROR;
2748b5a20d3cSdrh     }else if( objc==2 ){
2749b5a20d3cSdrh       if( pDb->zTrace ){
2750b5a20d3cSdrh         Tcl_AppendResult(interp, pDb->zTrace, 0);
2751b5a20d3cSdrh       }
2752b5a20d3cSdrh     }else{
2753b5a20d3cSdrh       char *zTrace;
2754b5a20d3cSdrh       int len;
2755b5a20d3cSdrh       if( pDb->zTrace ){
2756b5a20d3cSdrh         Tcl_Free(pDb->zTrace);
2757b5a20d3cSdrh       }
2758b5a20d3cSdrh       zTrace = Tcl_GetStringFromObj(objv[2], &len);
2759b5a20d3cSdrh       if( zTrace && len>0 ){
2760b5a20d3cSdrh         pDb->zTrace = Tcl_Alloc( len + 1 );
27615bb3eb9bSdrh         memcpy(pDb->zTrace, zTrace, len+1);
2762b5a20d3cSdrh       }else{
2763b5a20d3cSdrh         pDb->zTrace = 0;
2764b5a20d3cSdrh       }
2765bb201344Sshaneh #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
2766b5a20d3cSdrh       if( pDb->zTrace ){
2767b5a20d3cSdrh         pDb->interp = interp;
27686f8a503dSdanielk1977         sqlite3_trace(pDb->db, DbTraceHandler, pDb);
2769b5a20d3cSdrh       }else{
27706f8a503dSdanielk1977         sqlite3_trace(pDb->db, 0, 0);
2771b5a20d3cSdrh       }
277219e2d37fSdrh #endif
2773b5a20d3cSdrh     }
2774b5a20d3cSdrh     break;
2775b5a20d3cSdrh   }
2776b5a20d3cSdrh 
27773d21423cSdrh   /*    $db transaction [-deferred|-immediate|-exclusive] SCRIPT
27783d21423cSdrh   **
27793d21423cSdrh   ** Start a new transaction (if we are not already in the midst of a
27803d21423cSdrh   ** transaction) and execute the TCL script SCRIPT.  After SCRIPT
27813d21423cSdrh   ** completes, either commit the transaction or roll it back if SCRIPT
27823d21423cSdrh   ** throws an exception.  Or if no new transation was started, do nothing.
27833d21423cSdrh   ** pass the exception on up the stack.
27843d21423cSdrh   **
27853d21423cSdrh   ** This command was inspired by Dave Thomas's talk on Ruby at the
27863d21423cSdrh   ** 2005 O'Reilly Open Source Convention (OSCON).
27873d21423cSdrh   */
27883d21423cSdrh   case DB_TRANSACTION: {
27893d21423cSdrh     Tcl_Obj *pScript;
2790cd38d520Sdanielk1977     const char *zBegin = "SAVEPOINT _tcl_transaction";
27913d21423cSdrh     if( objc!=3 && objc!=4 ){
27923d21423cSdrh       Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
27933d21423cSdrh       return TCL_ERROR;
27943d21423cSdrh     }
2795cd38d520Sdanielk1977 
27964a4c11aaSdan     if( pDb->nTransaction==0 && objc==4 ){
27973d21423cSdrh       static const char *TTYPE_strs[] = {
2798ce604012Sdrh         "deferred",   "exclusive",  "immediate", 0
27993d21423cSdrh       };
28003d21423cSdrh       enum TTYPE_enum {
28013d21423cSdrh         TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
28023d21423cSdrh       };
28033d21423cSdrh       int ttype;
2804b5555e7eSdrh       if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
28053d21423cSdrh                               0, &ttype) ){
28063d21423cSdrh         return TCL_ERROR;
28073d21423cSdrh       }
28083d21423cSdrh       switch( (enum TTYPE_enum)ttype ){
28093d21423cSdrh         case TTYPE_DEFERRED:    /* no-op */;                 break;
28103d21423cSdrh         case TTYPE_EXCLUSIVE:   zBegin = "BEGIN EXCLUSIVE";  break;
28113d21423cSdrh         case TTYPE_IMMEDIATE:   zBegin = "BEGIN IMMEDIATE";  break;
28123d21423cSdrh       }
28133d21423cSdrh     }
2814cd38d520Sdanielk1977     pScript = objv[objc-1];
2815cd38d520Sdanielk1977 
28164a4c11aaSdan     /* Run the SQLite BEGIN command to open a transaction or savepoint. */
28171f1549f8Sdrh     pDb->disableAuth++;
2818cd38d520Sdanielk1977     rc = sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
28191f1549f8Sdrh     pDb->disableAuth--;
2820cd38d520Sdanielk1977     if( rc!=SQLITE_OK ){
2821cd38d520Sdanielk1977       Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
2822cd38d520Sdanielk1977       return TCL_ERROR;
28233d21423cSdrh     }
2824cd38d520Sdanielk1977     pDb->nTransaction++;
2825cd38d520Sdanielk1977 
28264a4c11aaSdan     /* If using NRE, schedule a callback to invoke the script pScript, then
28274a4c11aaSdan     ** a second callback to commit (or rollback) the transaction or savepoint
28284a4c11aaSdan     ** opened above. If not using NRE, evaluate the script directly, then
28294a4c11aaSdan     ** call function DbTransPostCmd() to commit (or rollback) the transaction
28304a4c11aaSdan     ** or savepoint.  */
28314a4c11aaSdan     if( DbUseNre() ){
28324a4c11aaSdan       Tcl_NRAddCallback(interp, DbTransPostCmd, cd, 0, 0, 0);
28334a4c11aaSdan       Tcl_NREvalObj(interp, pScript, 0);
28343d21423cSdrh     }else{
28354a4c11aaSdan       rc = DbTransPostCmd(&cd, interp, Tcl_EvalObjEx(interp, pScript, 0));
28363d21423cSdrh     }
28373d21423cSdrh     break;
28383d21423cSdrh   }
28393d21423cSdrh 
284094eb6a14Sdanielk1977   /*
2841404ca075Sdanielk1977   **    $db unlock_notify ?script?
2842404ca075Sdanielk1977   */
2843404ca075Sdanielk1977   case DB_UNLOCK_NOTIFY: {
2844404ca075Sdanielk1977 #ifndef SQLITE_ENABLE_UNLOCK_NOTIFY
2845404ca075Sdanielk1977     Tcl_AppendResult(interp, "unlock_notify not available in this build", 0);
2846404ca075Sdanielk1977     rc = TCL_ERROR;
2847404ca075Sdanielk1977 #else
2848404ca075Sdanielk1977     if( objc!=2 && objc!=3 ){
2849404ca075Sdanielk1977       Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
2850404ca075Sdanielk1977       rc = TCL_ERROR;
2851404ca075Sdanielk1977     }else{
2852404ca075Sdanielk1977       void (*xNotify)(void **, int) = 0;
2853404ca075Sdanielk1977       void *pNotifyArg = 0;
2854404ca075Sdanielk1977 
2855404ca075Sdanielk1977       if( pDb->pUnlockNotify ){
2856404ca075Sdanielk1977         Tcl_DecrRefCount(pDb->pUnlockNotify);
2857404ca075Sdanielk1977         pDb->pUnlockNotify = 0;
2858404ca075Sdanielk1977       }
2859404ca075Sdanielk1977 
2860404ca075Sdanielk1977       if( objc==3 ){
2861404ca075Sdanielk1977         xNotify = DbUnlockNotify;
2862404ca075Sdanielk1977         pNotifyArg = (void *)pDb;
2863404ca075Sdanielk1977         pDb->pUnlockNotify = objv[2];
2864404ca075Sdanielk1977         Tcl_IncrRefCount(pDb->pUnlockNotify);
2865404ca075Sdanielk1977       }
2866404ca075Sdanielk1977 
2867404ca075Sdanielk1977       if( sqlite3_unlock_notify(pDb->db, xNotify, pNotifyArg) ){
2868404ca075Sdanielk1977         Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
2869404ca075Sdanielk1977         rc = TCL_ERROR;
2870404ca075Sdanielk1977       }
2871404ca075Sdanielk1977     }
2872404ca075Sdanielk1977 #endif
2873404ca075Sdanielk1977     break;
2874404ca075Sdanielk1977   }
2875404ca075Sdanielk1977 
287646c47d46Sdan   case DB_PREUPDATE: {
287746c47d46Sdan     static const char *azSub[] = {"count", "hook", "modified", "old", 0};
287846c47d46Sdan     enum DbPreupdateSubCmd {
287946c47d46Sdan       PRE_COUNT, PRE_HOOK, PRE_MODIFIED, PRE_OLD
288046c47d46Sdan     };
288146c47d46Sdan     int iSub;
288246c47d46Sdan 
288346c47d46Sdan     if( objc<3 ){
288446c47d46Sdan       Tcl_WrongNumArgs(interp, 2, objv, "SUB-COMMAND ?ARGS?");
288546c47d46Sdan     }
288646c47d46Sdan     if( Tcl_GetIndexFromObj(interp, objv[2], azSub, "sub-command", 0, &iSub) ){
288746c47d46Sdan       return TCL_ERROR;
288846c47d46Sdan     }
288946c47d46Sdan 
289046c47d46Sdan     switch( (enum DbPreupdateSubCmd)iSub ){
289146c47d46Sdan       case PRE_COUNT: {
289246c47d46Sdan         int nCol = sqlite3_preupdate_count(pDb->db);
289346c47d46Sdan         Tcl_SetObjResult(interp, Tcl_NewIntObj(nCol));
289446c47d46Sdan         break;
289546c47d46Sdan       }
289646c47d46Sdan 
289746c47d46Sdan       case PRE_HOOK: {
289846c47d46Sdan         if( objc>4 ){
289946c47d46Sdan           Tcl_WrongNumArgs(interp, 2, objv, "hook ?SCRIPT?");
290046c47d46Sdan           return TCL_ERROR;
290146c47d46Sdan         }
290246c47d46Sdan         DbHookCmd(interp, pDb, (objc==4 ? objv[3] : 0), &pDb->pPreUpdateHook);
290346c47d46Sdan         break;
290446c47d46Sdan       }
290546c47d46Sdan 
290646c47d46Sdan       case PRE_MODIFIED:
290746c47d46Sdan       case PRE_OLD: {
290846c47d46Sdan         int iIdx;
290946c47d46Sdan         if( objc!=4 ){
291046c47d46Sdan           Tcl_WrongNumArgs(interp, 3, objv, "INDEX");
291146c47d46Sdan           return TCL_ERROR;
291246c47d46Sdan         }
291346c47d46Sdan         if( Tcl_GetIntFromObj(interp, objv[3], &iIdx) ){
291446c47d46Sdan           return TCL_ERROR;
291546c47d46Sdan         }
291646c47d46Sdan 
291746c47d46Sdan         if( iSub==PRE_MODIFIED ){
291846c47d46Sdan           int iRes;
291946c47d46Sdan           rc = sqlite3_preupdate_modified(pDb->db, iIdx, &iRes);
292046c47d46Sdan           if( rc==SQLITE_OK ) Tcl_SetObjResult(interp, Tcl_NewIntObj(iRes));
292146c47d46Sdan         }else{
292246c47d46Sdan           sqlite3_value *pValue;
292346c47d46Sdan           assert( iSub==PRE_OLD );
292446c47d46Sdan           rc = sqlite3_preupdate_old(pDb->db, iIdx, &pValue);
292546c47d46Sdan           if( rc==SQLITE_OK ){
292646c47d46Sdan             Tcl_Obj *pObj = Tcl_NewStringObj(sqlite3_value_text(pValue), -1);
292746c47d46Sdan             Tcl_SetObjResult(interp, pObj);
292846c47d46Sdan           }
292946c47d46Sdan         }
293046c47d46Sdan 
293146c47d46Sdan         if( rc!=SQLITE_OK ){
293246c47d46Sdan           Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
293346c47d46Sdan           return TCL_ERROR;
293446c47d46Sdan         }
293546c47d46Sdan       }
293646c47d46Sdan     }
293746c47d46Sdan 
293846c47d46Sdan     break;
293946c47d46Sdan   }
294046c47d46Sdan 
2941404ca075Sdanielk1977   /*
2942833bf968Sdrh   **    $db wal_hook ?script?
294394eb6a14Sdanielk1977   **    $db update_hook ?script?
294471fd80bfSdanielk1977   **    $db rollback_hook ?script?
294521e8d012Sdan   **    $db transaction_hook ?script?
294694eb6a14Sdanielk1977   */
2947833bf968Sdrh   case DB_WAL_HOOK:
294871fd80bfSdanielk1977   case DB_UPDATE_HOOK:
294921e8d012Sdan   case DB_ROLLBACK_HOOK:
295021e8d012Sdan   case DB_TRANSACTION_HOOK: {
295146c47d46Sdan     sqlite3 *db = pDb->db;
295271fd80bfSdanielk1977 
295371fd80bfSdanielk1977     /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
295471fd80bfSdanielk1977     ** whether [$db update_hook] or [$db rollback_hook] was invoked.
295571fd80bfSdanielk1977     */
295671fd80bfSdanielk1977     Tcl_Obj **ppHook;
295746c47d46Sdan     if( choice==DB_WAL_HOOK ) ppHook = &pDb->pWalHook;
295846c47d46Sdan     if( choice==DB_UPDATE_HOOK ) ppHook = &pDb->pUpdateHook;
295946c47d46Sdan     if( choice==DB_ROLLBACK_HOOK ) ppHook = &pDb->pRollbackHook;
296021e8d012Sdan     if( choice==DB_TRANSACTION_HOOK ) ppHook = &pDb->pTransHook;
296146c47d46Sdan     if( objc>3 ){
296294eb6a14Sdanielk1977        Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
296394eb6a14Sdanielk1977        return TCL_ERROR;
296494eb6a14Sdanielk1977     }
296571fd80bfSdanielk1977 
296646c47d46Sdan     DbHookCmd(interp, pDb, (objc==3 ? objv[2] : 0), ppHook);
296794eb6a14Sdanielk1977     break;
296894eb6a14Sdanielk1977   }
296994eb6a14Sdanielk1977 
29704397de57Sdanielk1977   /*    $db version
29714397de57Sdanielk1977   **
29724397de57Sdanielk1977   ** Return the version string for this database.
29734397de57Sdanielk1977   */
29744397de57Sdanielk1977   case DB_VERSION: {
29754397de57Sdanielk1977     Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
29764397de57Sdanielk1977     break;
29774397de57Sdanielk1977   }
29784397de57Sdanielk1977 
29791067fe11Stpoindex 
29806d31316cSdrh   } /* End of the SWITCH statement */
298122fbcb8dSdrh   return rc;
298275897234Sdrh }
298375897234Sdrh 
2984a2c8a95bSdrh #if SQLITE_TCL_NRE
2985a2c8a95bSdrh /*
2986a2c8a95bSdrh ** Adaptor that provides an objCmd interface to the NRE-enabled
2987a2c8a95bSdrh ** interface implementation.
2988a2c8a95bSdrh */
2989a2c8a95bSdrh static int DbObjCmdAdaptor(
2990a2c8a95bSdrh   void *cd,
2991a2c8a95bSdrh   Tcl_Interp *interp,
2992a2c8a95bSdrh   int objc,
2993a2c8a95bSdrh   Tcl_Obj *const*objv
2994a2c8a95bSdrh ){
2995a2c8a95bSdrh   return Tcl_NRCallObjProc(interp, DbObjCmd, cd, objc, objv);
2996a2c8a95bSdrh }
2997a2c8a95bSdrh #endif /* SQLITE_TCL_NRE */
2998a2c8a95bSdrh 
299975897234Sdrh /*
30003570ad93Sdrh **   sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
30019a6284c1Sdanielk1977 **                           ?-create BOOLEAN? ?-nomutex BOOLEAN?
300275897234Sdrh **
300375897234Sdrh ** This is the main Tcl command.  When the "sqlite" Tcl command is
300475897234Sdrh ** invoked, this routine runs to process that command.
300575897234Sdrh **
300675897234Sdrh ** The first argument, DBNAME, is an arbitrary name for a new
300775897234Sdrh ** database connection.  This command creates a new command named
300875897234Sdrh ** DBNAME that is used to control that connection.  The database
300975897234Sdrh ** connection is deleted when the DBNAME command is deleted.
301075897234Sdrh **
30113570ad93Sdrh ** The second argument is the name of the database file.
3012fbc3eab8Sdrh **
301375897234Sdrh */
301422fbcb8dSdrh static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
3015bec3f402Sdrh   SqliteDb *p;
301622fbcb8dSdrh   void *pKey = 0;
301722fbcb8dSdrh   int nKey = 0;
301822fbcb8dSdrh   const char *zArg;
301975897234Sdrh   char *zErrMsg;
30203570ad93Sdrh   int i;
302122fbcb8dSdrh   const char *zFile;
30223570ad93Sdrh   const char *zVfs = 0;
3023d9da78a2Sdrh   int flags;
3024882e8e4dSdrh   Tcl_DString translatedFilename;
3025d9da78a2Sdrh 
3026d9da78a2Sdrh   /* In normal use, each TCL interpreter runs in a single thread.  So
3027d9da78a2Sdrh   ** by default, we can turn of mutexing on SQLite database connections.
3028d9da78a2Sdrh   ** However, for testing purposes it is useful to have mutexes turned
3029d9da78a2Sdrh   ** on.  So, by default, mutexes default off.  But if compiled with
3030d9da78a2Sdrh   ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on.
3031d9da78a2Sdrh   */
3032d9da78a2Sdrh #ifdef SQLITE_TCL_DEFAULT_FULLMUTEX
3033d9da78a2Sdrh   flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
3034d9da78a2Sdrh #else
3035d9da78a2Sdrh   flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX;
3036d9da78a2Sdrh #endif
3037d9da78a2Sdrh 
303822fbcb8dSdrh   if( objc==2 ){
303922fbcb8dSdrh     zArg = Tcl_GetStringFromObj(objv[1], 0);
304022fbcb8dSdrh     if( strcmp(zArg,"-version")==0 ){
30416f8a503dSdanielk1977       Tcl_AppendResult(interp,sqlite3_version,0);
3042647cb0e1Sdrh       return TCL_OK;
3043647cb0e1Sdrh     }
30449eb9e26bSdrh     if( strcmp(zArg,"-has-codec")==0 ){
30459eb9e26bSdrh #ifdef SQLITE_HAS_CODEC
304622fbcb8dSdrh       Tcl_AppendResult(interp,"1",0);
304722fbcb8dSdrh #else
304822fbcb8dSdrh       Tcl_AppendResult(interp,"0",0);
304922fbcb8dSdrh #endif
305022fbcb8dSdrh       return TCL_OK;
305122fbcb8dSdrh     }
3052fbc3eab8Sdrh   }
30533570ad93Sdrh   for(i=3; i+1<objc; i+=2){
30543570ad93Sdrh     zArg = Tcl_GetString(objv[i]);
305522fbcb8dSdrh     if( strcmp(zArg,"-key")==0 ){
30563570ad93Sdrh       pKey = Tcl_GetByteArrayFromObj(objv[i+1], &nKey);
30573570ad93Sdrh     }else if( strcmp(zArg, "-vfs")==0 ){
30583c3dd7b9Sdan       zVfs = Tcl_GetString(objv[i+1]);
30593570ad93Sdrh     }else if( strcmp(zArg, "-readonly")==0 ){
30603570ad93Sdrh       int b;
30613570ad93Sdrh       if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
30623570ad93Sdrh       if( b ){
306333f4e02aSdrh         flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
30643570ad93Sdrh         flags |= SQLITE_OPEN_READONLY;
30653570ad93Sdrh       }else{
30663570ad93Sdrh         flags &= ~SQLITE_OPEN_READONLY;
30673570ad93Sdrh         flags |= SQLITE_OPEN_READWRITE;
30683570ad93Sdrh       }
30693570ad93Sdrh     }else if( strcmp(zArg, "-create")==0 ){
30703570ad93Sdrh       int b;
30713570ad93Sdrh       if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
307233f4e02aSdrh       if( b && (flags & SQLITE_OPEN_READONLY)==0 ){
30733570ad93Sdrh         flags |= SQLITE_OPEN_CREATE;
30743570ad93Sdrh       }else{
30753570ad93Sdrh         flags &= ~SQLITE_OPEN_CREATE;
30763570ad93Sdrh       }
30779a6284c1Sdanielk1977     }else if( strcmp(zArg, "-nomutex")==0 ){
30789a6284c1Sdanielk1977       int b;
30799a6284c1Sdanielk1977       if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
30809a6284c1Sdanielk1977       if( b ){
30819a6284c1Sdanielk1977         flags |= SQLITE_OPEN_NOMUTEX;
3082039963adSdrh         flags &= ~SQLITE_OPEN_FULLMUTEX;
30839a6284c1Sdanielk1977       }else{
30849a6284c1Sdanielk1977         flags &= ~SQLITE_OPEN_NOMUTEX;
30859a6284c1Sdanielk1977       }
3086039963adSdrh    }else if( strcmp(zArg, "-fullmutex")==0 ){
3087039963adSdrh       int b;
3088039963adSdrh       if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3089039963adSdrh       if( b ){
3090039963adSdrh         flags |= SQLITE_OPEN_FULLMUTEX;
3091039963adSdrh         flags &= ~SQLITE_OPEN_NOMUTEX;
3092039963adSdrh       }else{
3093039963adSdrh         flags &= ~SQLITE_OPEN_FULLMUTEX;
3094039963adSdrh       }
30953570ad93Sdrh     }else{
30963570ad93Sdrh       Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
30973570ad93Sdrh       return TCL_ERROR;
309822fbcb8dSdrh     }
309922fbcb8dSdrh   }
31003570ad93Sdrh   if( objc<3 || (objc&1)!=1 ){
310122fbcb8dSdrh     Tcl_WrongNumArgs(interp, 1, objv,
31023570ad93Sdrh       "HANDLE FILENAME ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
3103039963adSdrh       " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN?"
31049eb9e26bSdrh #ifdef SQLITE_HAS_CODEC
31053570ad93Sdrh       " ?-key CODECKEY?"
310622fbcb8dSdrh #endif
310722fbcb8dSdrh     );
310875897234Sdrh     return TCL_ERROR;
310975897234Sdrh   }
311075897234Sdrh   zErrMsg = 0;
31114cdc9e84Sdrh   p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
311275897234Sdrh   if( p==0 ){
3113bec3f402Sdrh     Tcl_SetResult(interp, "malloc failed", TCL_STATIC);
3114bec3f402Sdrh     return TCL_ERROR;
3115bec3f402Sdrh   }
3116bec3f402Sdrh   memset(p, 0, sizeof(*p));
311722fbcb8dSdrh   zFile = Tcl_GetStringFromObj(objv[2], 0);
3118882e8e4dSdrh   zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
31193570ad93Sdrh   sqlite3_open_v2(zFile, &p->db, flags, zVfs);
3120882e8e4dSdrh   Tcl_DStringFree(&translatedFilename);
312180290863Sdanielk1977   if( SQLITE_OK!=sqlite3_errcode(p->db) ){
31229404d50eSdrh     zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
312380290863Sdanielk1977     sqlite3_close(p->db);
312480290863Sdanielk1977     p->db = 0;
312580290863Sdanielk1977   }
31262011d5f5Sdrh #ifdef SQLITE_HAS_CODEC
3127f3a65f7eSdrh   if( p->db ){
31282011d5f5Sdrh     sqlite3_key(p->db, pKey, nKey);
3129f3a65f7eSdrh   }
3130eb8ed70dSdrh #endif
3131bec3f402Sdrh   if( p->db==0 ){
313275897234Sdrh     Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
3133bec3f402Sdrh     Tcl_Free((char*)p);
31349404d50eSdrh     sqlite3_free(zErrMsg);
313575897234Sdrh     return TCL_ERROR;
313675897234Sdrh   }
3137fb7e7651Sdrh   p->maxStmt = NUM_PREPARED_STMTS;
31385169bbc6Sdrh   p->interp = interp;
313922fbcb8dSdrh   zArg = Tcl_GetStringFromObj(objv[1], 0);
31404a4c11aaSdan   if( DbUseNre() ){
3141a2c8a95bSdrh     Tcl_NRCreateCommand(interp, zArg, DbObjCmdAdaptor, DbObjCmd,
3142a2c8a95bSdrh                         (char*)p, DbDeleteCmd);
31434a4c11aaSdan   }else{
314422fbcb8dSdrh     Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
31454a4c11aaSdan   }
314675897234Sdrh   return TCL_OK;
314775897234Sdrh }
314875897234Sdrh 
314975897234Sdrh /*
315090ca9753Sdrh ** Provide a dummy Tcl_InitStubs if we are using this as a static
315190ca9753Sdrh ** library.
315290ca9753Sdrh */
315390ca9753Sdrh #ifndef USE_TCL_STUBS
315490ca9753Sdrh # undef  Tcl_InitStubs
315590ca9753Sdrh # define Tcl_InitStubs(a,b,c)
315690ca9753Sdrh #endif
315790ca9753Sdrh 
315890ca9753Sdrh /*
315929bc4615Sdrh ** Make sure we have a PACKAGE_VERSION macro defined.  This will be
316029bc4615Sdrh ** defined automatically by the TEA makefile.  But other makefiles
316129bc4615Sdrh ** do not define it.
316229bc4615Sdrh */
316329bc4615Sdrh #ifndef PACKAGE_VERSION
316429bc4615Sdrh # define PACKAGE_VERSION SQLITE_VERSION
316529bc4615Sdrh #endif
316629bc4615Sdrh 
316729bc4615Sdrh /*
316875897234Sdrh ** Initialize this module.
316975897234Sdrh **
317075897234Sdrh ** This Tcl module contains only a single new Tcl command named "sqlite".
317175897234Sdrh ** (Hence there is no namespace.  There is no point in using a namespace
317275897234Sdrh ** if the extension only supplies one new name!)  The "sqlite" command is
317375897234Sdrh ** used to open a new SQLite database.  See the DbMain() routine above
317475897234Sdrh ** for additional information.
3175b652f432Sdrh **
3176b652f432Sdrh ** The EXTERN macros are required by TCL in order to work on windows.
317775897234Sdrh */
3178b652f432Sdrh EXTERN int Sqlite3_Init(Tcl_Interp *interp){
317992febd92Sdrh   Tcl_InitStubs(interp, "8.4", 0);
3180ef4ac8f9Sdrh   Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
318129bc4615Sdrh   Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
31821cca0d22Sdrh 
31831cca0d22Sdrh #ifndef SQLITE_3_SUFFIX_ONLY
31841cca0d22Sdrh   /* The "sqlite" alias is undocumented.  It is here only to support
31851cca0d22Sdrh   ** legacy scripts.  All new scripts should use only the "sqlite3"
31861cca0d22Sdrh   ** command.
31871cca0d22Sdrh   */
318849766d6cSdrh   Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
31894c0f1649Sdrh #endif
31901cca0d22Sdrh 
319190ca9753Sdrh   return TCL_OK;
319290ca9753Sdrh }
3193b652f432Sdrh EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3194b652f432Sdrh EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
3195b652f432Sdrh EXTERN int Tclsqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
3196b652f432Sdrh EXTERN int Sqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3197b652f432Sdrh EXTERN int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3198b652f432Sdrh EXTERN int Sqlite3_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3199b652f432Sdrh EXTERN int Tclsqlite3_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK;}
3200e2c3a659Sdrh 
320149766d6cSdrh 
320249766d6cSdrh #ifndef SQLITE_3_SUFFIX_ONLY
3203a3e63c4aSdan int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3204a3e63c4aSdan int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3205a3e63c4aSdan int Sqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
3206a3e63c4aSdan int Tclsqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
3207a3e63c4aSdan int Sqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3208a3e63c4aSdan int Tclsqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3209a3e63c4aSdan int Sqlite_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3210a3e63c4aSdan int Tclsqlite_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK;}
321149766d6cSdrh #endif
321275897234Sdrh 
32133e27c026Sdrh #ifdef TCLSH
32143e27c026Sdrh /*****************************************************************************
321557a0227fSdrh ** All of the code that follows is used to build standalone TCL interpreters
321657a0227fSdrh ** that are statically linked with SQLite.  Enable these by compiling
321757a0227fSdrh ** with -DTCLSH=n where n can be 1 or 2.  An n of 1 generates a standard
321857a0227fSdrh ** tclsh but with SQLite built in.  An n of 2 generates the SQLite space
321957a0227fSdrh ** analysis program.
322075897234Sdrh */
3221348784efSdrh 
322257a0227fSdrh #if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
322357a0227fSdrh /*
322457a0227fSdrh  * This code implements the MD5 message-digest algorithm.
322557a0227fSdrh  * The algorithm is due to Ron Rivest.  This code was
322657a0227fSdrh  * written by Colin Plumb in 1993, no copyright is claimed.
322757a0227fSdrh  * This code is in the public domain; do with it what you wish.
322857a0227fSdrh  *
322957a0227fSdrh  * Equivalent code is available from RSA Data Security, Inc.
323057a0227fSdrh  * This code has been tested against that, and is equivalent,
323157a0227fSdrh  * except that you don't need to include two pages of legalese
323257a0227fSdrh  * with every copy.
323357a0227fSdrh  *
323457a0227fSdrh  * To compute the message digest of a chunk of bytes, declare an
323557a0227fSdrh  * MD5Context structure, pass it to MD5Init, call MD5Update as
323657a0227fSdrh  * needed on buffers full of bytes, and then call MD5Final, which
323757a0227fSdrh  * will fill a supplied 16-byte array with the digest.
323857a0227fSdrh  */
323957a0227fSdrh 
324057a0227fSdrh /*
324157a0227fSdrh  * If compiled on a machine that doesn't have a 32-bit integer,
324257a0227fSdrh  * you just set "uint32" to the appropriate datatype for an
324357a0227fSdrh  * unsigned 32-bit integer.  For example:
324457a0227fSdrh  *
324557a0227fSdrh  *       cc -Duint32='unsigned long' md5.c
324657a0227fSdrh  *
324757a0227fSdrh  */
324857a0227fSdrh #ifndef uint32
324957a0227fSdrh #  define uint32 unsigned int
325057a0227fSdrh #endif
325157a0227fSdrh 
325257a0227fSdrh struct MD5Context {
325357a0227fSdrh   int isInit;
325457a0227fSdrh   uint32 buf[4];
325557a0227fSdrh   uint32 bits[2];
325657a0227fSdrh   unsigned char in[64];
325757a0227fSdrh };
325857a0227fSdrh typedef struct MD5Context MD5Context;
325957a0227fSdrh 
326057a0227fSdrh /*
326157a0227fSdrh  * Note: this code is harmless on little-endian machines.
326257a0227fSdrh  */
326357a0227fSdrh static void byteReverse (unsigned char *buf, unsigned longs){
326457a0227fSdrh         uint32 t;
326557a0227fSdrh         do {
326657a0227fSdrh                 t = (uint32)((unsigned)buf[3]<<8 | buf[2]) << 16 |
326757a0227fSdrh                             ((unsigned)buf[1]<<8 | buf[0]);
326857a0227fSdrh                 *(uint32 *)buf = t;
326957a0227fSdrh                 buf += 4;
327057a0227fSdrh         } while (--longs);
327157a0227fSdrh }
327257a0227fSdrh /* The four core functions - F1 is optimized somewhat */
327357a0227fSdrh 
327457a0227fSdrh /* #define F1(x, y, z) (x & y | ~x & z) */
327557a0227fSdrh #define F1(x, y, z) (z ^ (x & (y ^ z)))
327657a0227fSdrh #define F2(x, y, z) F1(z, x, y)
327757a0227fSdrh #define F3(x, y, z) (x ^ y ^ z)
327857a0227fSdrh #define F4(x, y, z) (y ^ (x | ~z))
327957a0227fSdrh 
328057a0227fSdrh /* This is the central step in the MD5 algorithm. */
328157a0227fSdrh #define MD5STEP(f, w, x, y, z, data, s) \
328257a0227fSdrh         ( w += f(x, y, z) + data,  w = w<<s | w>>(32-s),  w += x )
328357a0227fSdrh 
328457a0227fSdrh /*
328557a0227fSdrh  * The core of the MD5 algorithm, this alters an existing MD5 hash to
328657a0227fSdrh  * reflect the addition of 16 longwords of new data.  MD5Update blocks
328757a0227fSdrh  * the data and converts bytes into longwords for this routine.
328857a0227fSdrh  */
328957a0227fSdrh static void MD5Transform(uint32 buf[4], const uint32 in[16]){
329057a0227fSdrh         register uint32 a, b, c, d;
329157a0227fSdrh 
329257a0227fSdrh         a = buf[0];
329357a0227fSdrh         b = buf[1];
329457a0227fSdrh         c = buf[2];
329557a0227fSdrh         d = buf[3];
329657a0227fSdrh 
329757a0227fSdrh         MD5STEP(F1, a, b, c, d, in[ 0]+0xd76aa478,  7);
329857a0227fSdrh         MD5STEP(F1, d, a, b, c, in[ 1]+0xe8c7b756, 12);
329957a0227fSdrh         MD5STEP(F1, c, d, a, b, in[ 2]+0x242070db, 17);
330057a0227fSdrh         MD5STEP(F1, b, c, d, a, in[ 3]+0xc1bdceee, 22);
330157a0227fSdrh         MD5STEP(F1, a, b, c, d, in[ 4]+0xf57c0faf,  7);
330257a0227fSdrh         MD5STEP(F1, d, a, b, c, in[ 5]+0x4787c62a, 12);
330357a0227fSdrh         MD5STEP(F1, c, d, a, b, in[ 6]+0xa8304613, 17);
330457a0227fSdrh         MD5STEP(F1, b, c, d, a, in[ 7]+0xfd469501, 22);
330557a0227fSdrh         MD5STEP(F1, a, b, c, d, in[ 8]+0x698098d8,  7);
330657a0227fSdrh         MD5STEP(F1, d, a, b, c, in[ 9]+0x8b44f7af, 12);
330757a0227fSdrh         MD5STEP(F1, c, d, a, b, in[10]+0xffff5bb1, 17);
330857a0227fSdrh         MD5STEP(F1, b, c, d, a, in[11]+0x895cd7be, 22);
330957a0227fSdrh         MD5STEP(F1, a, b, c, d, in[12]+0x6b901122,  7);
331057a0227fSdrh         MD5STEP(F1, d, a, b, c, in[13]+0xfd987193, 12);
331157a0227fSdrh         MD5STEP(F1, c, d, a, b, in[14]+0xa679438e, 17);
331257a0227fSdrh         MD5STEP(F1, b, c, d, a, in[15]+0x49b40821, 22);
331357a0227fSdrh 
331457a0227fSdrh         MD5STEP(F2, a, b, c, d, in[ 1]+0xf61e2562,  5);
331557a0227fSdrh         MD5STEP(F2, d, a, b, c, in[ 6]+0xc040b340,  9);
331657a0227fSdrh         MD5STEP(F2, c, d, a, b, in[11]+0x265e5a51, 14);
331757a0227fSdrh         MD5STEP(F2, b, c, d, a, in[ 0]+0xe9b6c7aa, 20);
331857a0227fSdrh         MD5STEP(F2, a, b, c, d, in[ 5]+0xd62f105d,  5);
331957a0227fSdrh         MD5STEP(F2, d, a, b, c, in[10]+0x02441453,  9);
332057a0227fSdrh         MD5STEP(F2, c, d, a, b, in[15]+0xd8a1e681, 14);
332157a0227fSdrh         MD5STEP(F2, b, c, d, a, in[ 4]+0xe7d3fbc8, 20);
332257a0227fSdrh         MD5STEP(F2, a, b, c, d, in[ 9]+0x21e1cde6,  5);
332357a0227fSdrh         MD5STEP(F2, d, a, b, c, in[14]+0xc33707d6,  9);
332457a0227fSdrh         MD5STEP(F2, c, d, a, b, in[ 3]+0xf4d50d87, 14);
332557a0227fSdrh         MD5STEP(F2, b, c, d, a, in[ 8]+0x455a14ed, 20);
332657a0227fSdrh         MD5STEP(F2, a, b, c, d, in[13]+0xa9e3e905,  5);
332757a0227fSdrh         MD5STEP(F2, d, a, b, c, in[ 2]+0xfcefa3f8,  9);
332857a0227fSdrh         MD5STEP(F2, c, d, a, b, in[ 7]+0x676f02d9, 14);
332957a0227fSdrh         MD5STEP(F2, b, c, d, a, in[12]+0x8d2a4c8a, 20);
333057a0227fSdrh 
333157a0227fSdrh         MD5STEP(F3, a, b, c, d, in[ 5]+0xfffa3942,  4);
333257a0227fSdrh         MD5STEP(F3, d, a, b, c, in[ 8]+0x8771f681, 11);
333357a0227fSdrh         MD5STEP(F3, c, d, a, b, in[11]+0x6d9d6122, 16);
333457a0227fSdrh         MD5STEP(F3, b, c, d, a, in[14]+0xfde5380c, 23);
333557a0227fSdrh         MD5STEP(F3, a, b, c, d, in[ 1]+0xa4beea44,  4);
333657a0227fSdrh         MD5STEP(F3, d, a, b, c, in[ 4]+0x4bdecfa9, 11);
333757a0227fSdrh         MD5STEP(F3, c, d, a, b, in[ 7]+0xf6bb4b60, 16);
333857a0227fSdrh         MD5STEP(F3, b, c, d, a, in[10]+0xbebfbc70, 23);
333957a0227fSdrh         MD5STEP(F3, a, b, c, d, in[13]+0x289b7ec6,  4);
334057a0227fSdrh         MD5STEP(F3, d, a, b, c, in[ 0]+0xeaa127fa, 11);
334157a0227fSdrh         MD5STEP(F3, c, d, a, b, in[ 3]+0xd4ef3085, 16);
334257a0227fSdrh         MD5STEP(F3, b, c, d, a, in[ 6]+0x04881d05, 23);
334357a0227fSdrh         MD5STEP(F3, a, b, c, d, in[ 9]+0xd9d4d039,  4);
334457a0227fSdrh         MD5STEP(F3, d, a, b, c, in[12]+0xe6db99e5, 11);
334557a0227fSdrh         MD5STEP(F3, c, d, a, b, in[15]+0x1fa27cf8, 16);
334657a0227fSdrh         MD5STEP(F3, b, c, d, a, in[ 2]+0xc4ac5665, 23);
334757a0227fSdrh 
334857a0227fSdrh         MD5STEP(F4, a, b, c, d, in[ 0]+0xf4292244,  6);
334957a0227fSdrh         MD5STEP(F4, d, a, b, c, in[ 7]+0x432aff97, 10);
335057a0227fSdrh         MD5STEP(F4, c, d, a, b, in[14]+0xab9423a7, 15);
335157a0227fSdrh         MD5STEP(F4, b, c, d, a, in[ 5]+0xfc93a039, 21);
335257a0227fSdrh         MD5STEP(F4, a, b, c, d, in[12]+0x655b59c3,  6);
335357a0227fSdrh         MD5STEP(F4, d, a, b, c, in[ 3]+0x8f0ccc92, 10);
335457a0227fSdrh         MD5STEP(F4, c, d, a, b, in[10]+0xffeff47d, 15);
335557a0227fSdrh         MD5STEP(F4, b, c, d, a, in[ 1]+0x85845dd1, 21);
335657a0227fSdrh         MD5STEP(F4, a, b, c, d, in[ 8]+0x6fa87e4f,  6);
335757a0227fSdrh         MD5STEP(F4, d, a, b, c, in[15]+0xfe2ce6e0, 10);
335857a0227fSdrh         MD5STEP(F4, c, d, a, b, in[ 6]+0xa3014314, 15);
335957a0227fSdrh         MD5STEP(F4, b, c, d, a, in[13]+0x4e0811a1, 21);
336057a0227fSdrh         MD5STEP(F4, a, b, c, d, in[ 4]+0xf7537e82,  6);
336157a0227fSdrh         MD5STEP(F4, d, a, b, c, in[11]+0xbd3af235, 10);
336257a0227fSdrh         MD5STEP(F4, c, d, a, b, in[ 2]+0x2ad7d2bb, 15);
336357a0227fSdrh         MD5STEP(F4, b, c, d, a, in[ 9]+0xeb86d391, 21);
336457a0227fSdrh 
336557a0227fSdrh         buf[0] += a;
336657a0227fSdrh         buf[1] += b;
336757a0227fSdrh         buf[2] += c;
336857a0227fSdrh         buf[3] += d;
336957a0227fSdrh }
337057a0227fSdrh 
337157a0227fSdrh /*
337257a0227fSdrh  * Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious
337357a0227fSdrh  * initialization constants.
337457a0227fSdrh  */
337557a0227fSdrh static void MD5Init(MD5Context *ctx){
337657a0227fSdrh         ctx->isInit = 1;
337757a0227fSdrh         ctx->buf[0] = 0x67452301;
337857a0227fSdrh         ctx->buf[1] = 0xefcdab89;
337957a0227fSdrh         ctx->buf[2] = 0x98badcfe;
338057a0227fSdrh         ctx->buf[3] = 0x10325476;
338157a0227fSdrh         ctx->bits[0] = 0;
338257a0227fSdrh         ctx->bits[1] = 0;
338357a0227fSdrh }
338457a0227fSdrh 
338557a0227fSdrh /*
338657a0227fSdrh  * Update context to reflect the concatenation of another buffer full
338757a0227fSdrh  * of bytes.
338857a0227fSdrh  */
338957a0227fSdrh static
339057a0227fSdrh void MD5Update(MD5Context *ctx, const unsigned char *buf, unsigned int len){
339157a0227fSdrh         uint32 t;
339257a0227fSdrh 
339357a0227fSdrh         /* Update bitcount */
339457a0227fSdrh 
339557a0227fSdrh         t = ctx->bits[0];
339657a0227fSdrh         if ((ctx->bits[0] = t + ((uint32)len << 3)) < t)
339757a0227fSdrh                 ctx->bits[1]++; /* Carry from low to high */
339857a0227fSdrh         ctx->bits[1] += len >> 29;
339957a0227fSdrh 
340057a0227fSdrh         t = (t >> 3) & 0x3f;    /* Bytes already in shsInfo->data */
340157a0227fSdrh 
340257a0227fSdrh         /* Handle any leading odd-sized chunks */
340357a0227fSdrh 
340457a0227fSdrh         if ( t ) {
340557a0227fSdrh                 unsigned char *p = (unsigned char *)ctx->in + t;
340657a0227fSdrh 
340757a0227fSdrh                 t = 64-t;
340857a0227fSdrh                 if (len < t) {
340957a0227fSdrh                         memcpy(p, buf, len);
341057a0227fSdrh                         return;
341157a0227fSdrh                 }
341257a0227fSdrh                 memcpy(p, buf, t);
341357a0227fSdrh                 byteReverse(ctx->in, 16);
341457a0227fSdrh                 MD5Transform(ctx->buf, (uint32 *)ctx->in);
341557a0227fSdrh                 buf += t;
341657a0227fSdrh                 len -= t;
341757a0227fSdrh         }
341857a0227fSdrh 
341957a0227fSdrh         /* Process data in 64-byte chunks */
342057a0227fSdrh 
342157a0227fSdrh         while (len >= 64) {
342257a0227fSdrh                 memcpy(ctx->in, buf, 64);
342357a0227fSdrh                 byteReverse(ctx->in, 16);
342457a0227fSdrh                 MD5Transform(ctx->buf, (uint32 *)ctx->in);
342557a0227fSdrh                 buf += 64;
342657a0227fSdrh                 len -= 64;
342757a0227fSdrh         }
342857a0227fSdrh 
342957a0227fSdrh         /* Handle any remaining bytes of data. */
343057a0227fSdrh 
343157a0227fSdrh         memcpy(ctx->in, buf, len);
343257a0227fSdrh }
343357a0227fSdrh 
343457a0227fSdrh /*
343557a0227fSdrh  * Final wrapup - pad to 64-byte boundary with the bit pattern
343657a0227fSdrh  * 1 0* (64-bit count of bits processed, MSB-first)
343757a0227fSdrh  */
343857a0227fSdrh static void MD5Final(unsigned char digest[16], MD5Context *ctx){
343957a0227fSdrh         unsigned count;
344057a0227fSdrh         unsigned char *p;
344157a0227fSdrh 
344257a0227fSdrh         /* Compute number of bytes mod 64 */
344357a0227fSdrh         count = (ctx->bits[0] >> 3) & 0x3F;
344457a0227fSdrh 
344557a0227fSdrh         /* Set the first char of padding to 0x80.  This is safe since there is
344657a0227fSdrh            always at least one byte free */
344757a0227fSdrh         p = ctx->in + count;
344857a0227fSdrh         *p++ = 0x80;
344957a0227fSdrh 
345057a0227fSdrh         /* Bytes of padding needed to make 64 bytes */
345157a0227fSdrh         count = 64 - 1 - count;
345257a0227fSdrh 
345357a0227fSdrh         /* Pad out to 56 mod 64 */
345457a0227fSdrh         if (count < 8) {
345557a0227fSdrh                 /* Two lots of padding:  Pad the first block to 64 bytes */
345657a0227fSdrh                 memset(p, 0, count);
345757a0227fSdrh                 byteReverse(ctx->in, 16);
345857a0227fSdrh                 MD5Transform(ctx->buf, (uint32 *)ctx->in);
345957a0227fSdrh 
346057a0227fSdrh                 /* Now fill the next block with 56 bytes */
346157a0227fSdrh                 memset(ctx->in, 0, 56);
346257a0227fSdrh         } else {
346357a0227fSdrh                 /* Pad block to 56 bytes */
346457a0227fSdrh                 memset(p, 0, count-8);
346557a0227fSdrh         }
346657a0227fSdrh         byteReverse(ctx->in, 14);
346757a0227fSdrh 
346857a0227fSdrh         /* Append length in bits and transform */
346957a0227fSdrh         ((uint32 *)ctx->in)[ 14 ] = ctx->bits[0];
347057a0227fSdrh         ((uint32 *)ctx->in)[ 15 ] = ctx->bits[1];
347157a0227fSdrh 
347257a0227fSdrh         MD5Transform(ctx->buf, (uint32 *)ctx->in);
347357a0227fSdrh         byteReverse((unsigned char *)ctx->buf, 4);
347457a0227fSdrh         memcpy(digest, ctx->buf, 16);
347557a0227fSdrh         memset(ctx, 0, sizeof(ctx));    /* In case it is sensitive */
347657a0227fSdrh }
347757a0227fSdrh 
347857a0227fSdrh /*
347957a0227fSdrh ** Convert a 128-bit MD5 digest into a 32-digit base-16 number.
348057a0227fSdrh */
348157a0227fSdrh static void MD5DigestToBase16(unsigned char *digest, char *zBuf){
348257a0227fSdrh   static char const zEncode[] = "0123456789abcdef";
348357a0227fSdrh   int i, j;
348457a0227fSdrh 
348557a0227fSdrh   for(j=i=0; i<16; i++){
348657a0227fSdrh     int a = digest[i];
348757a0227fSdrh     zBuf[j++] = zEncode[(a>>4)&0xf];
348857a0227fSdrh     zBuf[j++] = zEncode[a & 0xf];
348957a0227fSdrh   }
349057a0227fSdrh   zBuf[j] = 0;
349157a0227fSdrh }
349257a0227fSdrh 
349357a0227fSdrh 
349457a0227fSdrh /*
349557a0227fSdrh ** Convert a 128-bit MD5 digest into sequency of eight 5-digit integers
349657a0227fSdrh ** each representing 16 bits of the digest and separated from each
349757a0227fSdrh ** other by a "-" character.
349857a0227fSdrh */
349957a0227fSdrh static void MD5DigestToBase10x8(unsigned char digest[16], char zDigest[50]){
350057a0227fSdrh   int i, j;
350157a0227fSdrh   unsigned int x;
350257a0227fSdrh   for(i=j=0; i<16; i+=2){
350357a0227fSdrh     x = digest[i]*256 + digest[i+1];
350457a0227fSdrh     if( i>0 ) zDigest[j++] = '-';
350557a0227fSdrh     sprintf(&zDigest[j], "%05u", x);
350657a0227fSdrh     j += 5;
350757a0227fSdrh   }
350857a0227fSdrh   zDigest[j] = 0;
350957a0227fSdrh }
351057a0227fSdrh 
351157a0227fSdrh /*
351257a0227fSdrh ** A TCL command for md5.  The argument is the text to be hashed.  The
351357a0227fSdrh ** Result is the hash in base64.
351457a0227fSdrh */
351557a0227fSdrh static int md5_cmd(void*cd, Tcl_Interp *interp, int argc, const char **argv){
351657a0227fSdrh   MD5Context ctx;
351757a0227fSdrh   unsigned char digest[16];
351857a0227fSdrh   char zBuf[50];
351957a0227fSdrh   void (*converter)(unsigned char*, char*);
352057a0227fSdrh 
352157a0227fSdrh   if( argc!=2 ){
352257a0227fSdrh     Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
352357a0227fSdrh         " TEXT\"", 0);
352457a0227fSdrh     return TCL_ERROR;
352557a0227fSdrh   }
352657a0227fSdrh   MD5Init(&ctx);
352757a0227fSdrh   MD5Update(&ctx, (unsigned char*)argv[1], (unsigned)strlen(argv[1]));
352857a0227fSdrh   MD5Final(digest, &ctx);
352957a0227fSdrh   converter = (void(*)(unsigned char*,char*))cd;
353057a0227fSdrh   converter(digest, zBuf);
353157a0227fSdrh   Tcl_AppendResult(interp, zBuf, (char*)0);
353257a0227fSdrh   return TCL_OK;
353357a0227fSdrh }
353457a0227fSdrh 
353557a0227fSdrh /*
353657a0227fSdrh ** A TCL command to take the md5 hash of a file.  The argument is the
353757a0227fSdrh ** name of the file.
353857a0227fSdrh */
353957a0227fSdrh static int md5file_cmd(void*cd, Tcl_Interp*interp, int argc, const char **argv){
354057a0227fSdrh   FILE *in;
354157a0227fSdrh   MD5Context ctx;
354257a0227fSdrh   void (*converter)(unsigned char*, char*);
354357a0227fSdrh   unsigned char digest[16];
354457a0227fSdrh   char zBuf[10240];
354557a0227fSdrh 
354657a0227fSdrh   if( argc!=2 ){
354757a0227fSdrh     Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
354857a0227fSdrh         " FILENAME\"", 0);
354957a0227fSdrh     return TCL_ERROR;
355057a0227fSdrh   }
355157a0227fSdrh   in = fopen(argv[1],"rb");
355257a0227fSdrh   if( in==0 ){
355357a0227fSdrh     Tcl_AppendResult(interp,"unable to open file \"", argv[1],
355457a0227fSdrh          "\" for reading", 0);
355557a0227fSdrh     return TCL_ERROR;
355657a0227fSdrh   }
355757a0227fSdrh   MD5Init(&ctx);
355857a0227fSdrh   for(;;){
355957a0227fSdrh     int n;
356057a0227fSdrh     n = fread(zBuf, 1, sizeof(zBuf), in);
356157a0227fSdrh     if( n<=0 ) break;
356257a0227fSdrh     MD5Update(&ctx, (unsigned char*)zBuf, (unsigned)n);
356357a0227fSdrh   }
356457a0227fSdrh   fclose(in);
356557a0227fSdrh   MD5Final(digest, &ctx);
356657a0227fSdrh   converter = (void(*)(unsigned char*,char*))cd;
356757a0227fSdrh   converter(digest, zBuf);
356857a0227fSdrh   Tcl_AppendResult(interp, zBuf, (char*)0);
356957a0227fSdrh   return TCL_OK;
357057a0227fSdrh }
357157a0227fSdrh 
357257a0227fSdrh /*
357357a0227fSdrh ** Register the four new TCL commands for generating MD5 checksums
357457a0227fSdrh ** with the TCL interpreter.
357557a0227fSdrh */
357657a0227fSdrh int Md5_Init(Tcl_Interp *interp){
357757a0227fSdrh   Tcl_CreateCommand(interp, "md5", (Tcl_CmdProc*)md5_cmd,
357857a0227fSdrh                     MD5DigestToBase16, 0);
357957a0227fSdrh   Tcl_CreateCommand(interp, "md5-10x8", (Tcl_CmdProc*)md5_cmd,
358057a0227fSdrh                     MD5DigestToBase10x8, 0);
358157a0227fSdrh   Tcl_CreateCommand(interp, "md5file", (Tcl_CmdProc*)md5file_cmd,
358257a0227fSdrh                     MD5DigestToBase16, 0);
358357a0227fSdrh   Tcl_CreateCommand(interp, "md5file-10x8", (Tcl_CmdProc*)md5file_cmd,
358457a0227fSdrh                     MD5DigestToBase10x8, 0);
358557a0227fSdrh   return TCL_OK;
358657a0227fSdrh }
358757a0227fSdrh #endif /* defined(SQLITE_TEST) || defined(SQLITE_TCLMD5) */
358857a0227fSdrh 
358957a0227fSdrh #if defined(SQLITE_TEST)
359057a0227fSdrh /*
359157a0227fSdrh ** During testing, the special md5sum() aggregate function is available.
359257a0227fSdrh ** inside SQLite.  The following routines implement that function.
359357a0227fSdrh */
359457a0227fSdrh static void md5step(sqlite3_context *context, int argc, sqlite3_value **argv){
359557a0227fSdrh   MD5Context *p;
359657a0227fSdrh   int i;
359757a0227fSdrh   if( argc<1 ) return;
359857a0227fSdrh   p = sqlite3_aggregate_context(context, sizeof(*p));
359957a0227fSdrh   if( p==0 ) return;
360057a0227fSdrh   if( !p->isInit ){
360157a0227fSdrh     MD5Init(p);
360257a0227fSdrh   }
360357a0227fSdrh   for(i=0; i<argc; i++){
360457a0227fSdrh     const char *zData = (char*)sqlite3_value_text(argv[i]);
360557a0227fSdrh     if( zData ){
360657a0227fSdrh       MD5Update(p, (unsigned char*)zData, strlen(zData));
360757a0227fSdrh     }
360857a0227fSdrh   }
360957a0227fSdrh }
361057a0227fSdrh static void md5finalize(sqlite3_context *context){
361157a0227fSdrh   MD5Context *p;
361257a0227fSdrh   unsigned char digest[16];
361357a0227fSdrh   char zBuf[33];
361457a0227fSdrh   p = sqlite3_aggregate_context(context, sizeof(*p));
361557a0227fSdrh   MD5Final(digest,p);
361657a0227fSdrh   MD5DigestToBase16(digest, zBuf);
361757a0227fSdrh   sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
361857a0227fSdrh }
361957a0227fSdrh int Md5_Register(sqlite3 *db){
362057a0227fSdrh   int rc = sqlite3_create_function(db, "md5sum", -1, SQLITE_UTF8, 0, 0,
362157a0227fSdrh                                  md5step, md5finalize);
362257a0227fSdrh   sqlite3_overload_function(db, "md5sum", -1);  /* To exercise this API */
362357a0227fSdrh   return rc;
362457a0227fSdrh }
362557a0227fSdrh #endif /* defined(SQLITE_TEST) */
362657a0227fSdrh 
362757a0227fSdrh 
3628348784efSdrh /*
36293e27c026Sdrh ** If the macro TCLSH is one, then put in code this for the
36303e27c026Sdrh ** "main" routine that will initialize Tcl and take input from
36313570ad93Sdrh ** standard input, or if a file is named on the command line
36323570ad93Sdrh ** the TCL interpreter reads and evaluates that file.
3633348784efSdrh */
36343e27c026Sdrh #if TCLSH==1
3635348784efSdrh static char zMainloop[] =
3636348784efSdrh   "set line {}\n"
3637348784efSdrh   "while {![eof stdin]} {\n"
3638348784efSdrh     "if {$line!=\"\"} {\n"
3639348784efSdrh       "puts -nonewline \"> \"\n"
3640348784efSdrh     "} else {\n"
3641348784efSdrh       "puts -nonewline \"% \"\n"
3642348784efSdrh     "}\n"
3643348784efSdrh     "flush stdout\n"
3644348784efSdrh     "append line [gets stdin]\n"
3645348784efSdrh     "if {[info complete $line]} {\n"
3646348784efSdrh       "if {[catch {uplevel #0 $line} result]} {\n"
3647348784efSdrh         "puts stderr \"Error: $result\"\n"
3648348784efSdrh       "} elseif {$result!=\"\"} {\n"
3649348784efSdrh         "puts $result\n"
3650348784efSdrh       "}\n"
3651348784efSdrh       "set line {}\n"
3652348784efSdrh     "} else {\n"
3653348784efSdrh       "append line \\n\n"
3654348784efSdrh     "}\n"
3655348784efSdrh   "}\n"
3656348784efSdrh ;
36573e27c026Sdrh #endif
36583a0f13ffSdrh #if TCLSH==2
36593a0f13ffSdrh static char zMainloop[] =
36603a0f13ffSdrh #include "spaceanal_tcl.h"
36613a0f13ffSdrh ;
36623a0f13ffSdrh #endif
36633e27c026Sdrh 
3664c1a60c51Sdan #ifdef SQLITE_TEST
3665c1a60c51Sdan static void init_all(Tcl_Interp *);
3666c1a60c51Sdan static int init_all_cmd(
3667c1a60c51Sdan   ClientData cd,
3668c1a60c51Sdan   Tcl_Interp *interp,
3669c1a60c51Sdan   int objc,
3670c1a60c51Sdan   Tcl_Obj *CONST objv[]
3671c1a60c51Sdan ){
36720a549071Sdanielk1977 
3673c1a60c51Sdan   Tcl_Interp *slave;
3674c1a60c51Sdan   if( objc!=2 ){
3675c1a60c51Sdan     Tcl_WrongNumArgs(interp, 1, objv, "SLAVE");
3676c1a60c51Sdan     return TCL_ERROR;
3677c1a60c51Sdan   }
36780a549071Sdanielk1977 
3679c1a60c51Sdan   slave = Tcl_GetSlave(interp, Tcl_GetString(objv[1]));
3680c1a60c51Sdan   if( !slave ){
3681c1a60c51Sdan     return TCL_ERROR;
3682c1a60c51Sdan   }
3683c1a60c51Sdan 
3684c1a60c51Sdan   init_all(slave);
3685c1a60c51Sdan   return TCL_OK;
3686c1a60c51Sdan }
3687c1a60c51Sdan #endif
3688c1a60c51Sdan 
3689c1a60c51Sdan /*
3690c1a60c51Sdan ** Configure the interpreter passed as the first argument to have access
3691c1a60c51Sdan ** to the commands and linked variables that make up:
3692c1a60c51Sdan **
3693c1a60c51Sdan **   * the [sqlite3] extension itself,
3694c1a60c51Sdan **
3695c1a60c51Sdan **   * If SQLITE_TCLMD5 or SQLITE_TEST is defined, the Md5 commands, and
3696c1a60c51Sdan **
3697c1a60c51Sdan **   * If SQLITE_TEST is set, the various test interfaces used by the Tcl
3698c1a60c51Sdan **     test suite.
3699c1a60c51Sdan */
3700c1a60c51Sdan static void init_all(Tcl_Interp *interp){
370138f8271fSdrh   Sqlite3_Init(interp);
3702c1a60c51Sdan 
370357a0227fSdrh #if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
370457a0227fSdrh   Md5_Init(interp);
370557a0227fSdrh #endif
3706c1a60c51Sdan 
3707d9b0257aSdrh #ifdef SQLITE_TEST
3708d1bf3512Sdrh   {
37092f999a67Sdrh     extern int Sqliteconfig_Init(Tcl_Interp*);
3710d1bf3512Sdrh     extern int Sqlitetest1_Init(Tcl_Interp*);
37115c4d9703Sdrh     extern int Sqlitetest2_Init(Tcl_Interp*);
37125c4d9703Sdrh     extern int Sqlitetest3_Init(Tcl_Interp*);
3713a6064dcfSdrh     extern int Sqlitetest4_Init(Tcl_Interp*);
3714998b56c3Sdanielk1977     extern int Sqlitetest5_Init(Tcl_Interp*);
37159c06c953Sdrh     extern int Sqlitetest6_Init(Tcl_Interp*);
371629c636bcSdrh     extern int Sqlitetest7_Init(Tcl_Interp*);
3717b9bb7c18Sdrh     extern int Sqlitetest8_Init(Tcl_Interp*);
3718a713f2c3Sdanielk1977     extern int Sqlitetest9_Init(Tcl_Interp*);
37192366940dSdrh     extern int Sqlitetestasync_Init(Tcl_Interp*);
37201409be69Sdrh     extern int Sqlitetest_autoext_Init(Tcl_Interp*);
37210a7a9155Sdan     extern int Sqlitetest_demovfs_Init(Tcl_Interp *);
3722984bfaa4Sdrh     extern int Sqlitetest_func_Init(Tcl_Interp*);
372315926590Sdrh     extern int Sqlitetest_hexio_Init(Tcl_Interp*);
3724e1ab2193Sdan     extern int Sqlitetest_init_Init(Tcl_Interp*);
37252f999a67Sdrh     extern int Sqlitetest_malloc_Init(Tcl_Interp*);
37261a9ed0b2Sdanielk1977     extern int Sqlitetest_mutex_Init(Tcl_Interp*);
37272f999a67Sdrh     extern int Sqlitetestschema_Init(Tcl_Interp*);
37282f999a67Sdrh     extern int Sqlitetestsse_Init(Tcl_Interp*);
37292f999a67Sdrh     extern int Sqlitetesttclvar_Init(Tcl_Interp*);
373044918fa0Sdanielk1977     extern int SqlitetestThread_Init(Tcl_Interp*);
3731a15db353Sdanielk1977     extern int SqlitetestOnefile_Init();
37325d1f5aa6Sdanielk1977     extern int SqlitetestOsinst_Init(Tcl_Interp*);
37330410302eSdanielk1977     extern int Sqlitetestbackup_Init(Tcl_Interp*);
3734522efc62Sdrh     extern int Sqlitetestintarray_Init(Tcl_Interp*);
3735c7991bdfSdan     extern int Sqlitetestvfs_Init(Tcl_Interp *);
3736599e9d21Sdan     extern int SqlitetestStat_Init(Tcl_Interp*);
37379508daa9Sdan     extern int Sqlitetestrtree_Init(Tcl_Interp*);
37388cf35eb4Sdan     extern int Sqlitequota_Init(Tcl_Interp*);
37398a922f75Sshaneh     extern int Sqlitemultiplex_Init(Tcl_Interp*);
3740e336b001Sdan     extern int SqliteSuperlock_Init(Tcl_Interp*);
3741*4fccf43aSdan #ifdef SQLITE_ENABLE_SESSION
3742*4fccf43aSdan     extern int TestSession_Init(Tcl_Interp*);
3743*4fccf43aSdan #endif
37442e66f0b9Sdrh 
3745b29010cdSdan #ifdef SQLITE_ENABLE_ZIPVFS
3746b29010cdSdan     extern int Zipvfs_Init(Tcl_Interp*);
3747b29010cdSdan     Zipvfs_Init(interp);
3748b29010cdSdan #endif
3749b29010cdSdan 
37502f999a67Sdrh     Sqliteconfig_Init(interp);
37516490bebdSdanielk1977     Sqlitetest1_Init(interp);
37525c4d9703Sdrh     Sqlitetest2_Init(interp);
3753de647130Sdrh     Sqlitetest3_Init(interp);
3754fc57d7bfSdanielk1977     Sqlitetest4_Init(interp);
3755998b56c3Sdanielk1977     Sqlitetest5_Init(interp);
37569c06c953Sdrh     Sqlitetest6_Init(interp);
375729c636bcSdrh     Sqlitetest7_Init(interp);
3758b9bb7c18Sdrh     Sqlitetest8_Init(interp);
3759a713f2c3Sdanielk1977     Sqlitetest9_Init(interp);
37602366940dSdrh     Sqlitetestasync_Init(interp);
37611409be69Sdrh     Sqlitetest_autoext_Init(interp);
37620a7a9155Sdan     Sqlitetest_demovfs_Init(interp);
3763984bfaa4Sdrh     Sqlitetest_func_Init(interp);
376415926590Sdrh     Sqlitetest_hexio_Init(interp);
3765e1ab2193Sdan     Sqlitetest_init_Init(interp);
37662f999a67Sdrh     Sqlitetest_malloc_Init(interp);
37671a9ed0b2Sdanielk1977     Sqlitetest_mutex_Init(interp);
37682f999a67Sdrh     Sqlitetestschema_Init(interp);
37692f999a67Sdrh     Sqlitetesttclvar_Init(interp);
377044918fa0Sdanielk1977     SqlitetestThread_Init(interp);
3771a15db353Sdanielk1977     SqlitetestOnefile_Init(interp);
37725d1f5aa6Sdanielk1977     SqlitetestOsinst_Init(interp);
37730410302eSdanielk1977     Sqlitetestbackup_Init(interp);
3774522efc62Sdrh     Sqlitetestintarray_Init(interp);
3775c7991bdfSdan     Sqlitetestvfs_Init(interp);
3776599e9d21Sdan     SqlitetestStat_Init(interp);
37779508daa9Sdan     Sqlitetestrtree_Init(interp);
37788cf35eb4Sdan     Sqlitequota_Init(interp);
37798a922f75Sshaneh     Sqlitemultiplex_Init(interp);
3780e336b001Sdan     SqliteSuperlock_Init(interp);
3781*4fccf43aSdan #ifdef SQLITE_ENABLE_SESSION
3782*4fccf43aSdan     TestSession_Init(interp);
3783*4fccf43aSdan #endif
3784a15db353Sdanielk1977 
3785c1a60c51Sdan     Tcl_CreateObjCommand(interp,"load_testfixture_extensions",init_all_cmd,0,0);
3786c1a60c51Sdan 
378789dec819Sdrh #ifdef SQLITE_SSE
37882e66f0b9Sdrh     Sqlitetestsse_Init(interp);
37892e66f0b9Sdrh #endif
3790d1bf3512Sdrh   }
3791d1bf3512Sdrh #endif
3792c1a60c51Sdan }
3793c1a60c51Sdan 
3794c1a60c51Sdan #define TCLSH_MAIN main   /* Needed to fake out mktclapp */
3795c1a60c51Sdan int TCLSH_MAIN(int argc, char **argv){
3796c1a60c51Sdan   Tcl_Interp *interp;
3797c1a60c51Sdan 
3798c1a60c51Sdan   /* Call sqlite3_shutdown() once before doing anything else. This is to
3799c1a60c51Sdan   ** test that sqlite3_shutdown() can be safely called by a process before
3800c1a60c51Sdan   ** sqlite3_initialize() is. */
3801c1a60c51Sdan   sqlite3_shutdown();
3802c1a60c51Sdan 
38033a0f13ffSdrh #if TCLSH==2
38043a0f13ffSdrh   sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);
38053a0f13ffSdrh #endif
3806c1a60c51Sdan   Tcl_FindExecutable(argv[0]);
3807c1a60c51Sdan 
3808c1a60c51Sdan   interp = Tcl_CreateInterp();
3809c1a60c51Sdan   init_all(interp);
3810c7285978Sdrh   if( argc>=2 ){
3811348784efSdrh     int i;
3812ad42c3a3Sshess     char zArgc[32];
3813ad42c3a3Sshess     sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-(3-TCLSH));
3814ad42c3a3Sshess     Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
3815348784efSdrh     Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
3816348784efSdrh     Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
381761212b69Sdrh     for(i=3-TCLSH; i<argc; i++){
3818348784efSdrh       Tcl_SetVar(interp, "argv", argv[i],
3819348784efSdrh           TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
3820348784efSdrh     }
38213a0f13ffSdrh     if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
38220de8c112Sdrh       const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
3823a81c64a2Sdrh       if( zInfo==0 ) zInfo = Tcl_GetStringResult(interp);
3824c61053b7Sdrh       fprintf(stderr,"%s: %s\n", *argv, zInfo);
3825348784efSdrh       return 1;
3826348784efSdrh     }
38273e27c026Sdrh   }
38283a0f13ffSdrh   if( TCLSH==2 || argc<=1 ){
3829348784efSdrh     Tcl_GlobalEval(interp, zMainloop);
3830348784efSdrh   }
3831348784efSdrh   return 0;
3832348784efSdrh }
3833348784efSdrh #endif /* TCLSH */
3834