xref: /sqlite-3.40.0/src/tclsqlite.c (revision 2c2f392d)
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 */
2827b2f053Smistachkin 
2927b2f053Smistachkin /*
3027b2f053Smistachkin ** If requested, include the SQLite compiler options file for MSVC.
3127b2f053Smistachkin */
3227b2f053Smistachkin #if defined(INCLUDE_MSVC_H)
3327b2f053Smistachkin # include "msvc.h"
3427b2f053Smistachkin #endif
3527b2f053Smistachkin 
3652b1dbb5Smistachkin #if defined(INCLUDE_SQLITE_TCL_H)
3752b1dbb5Smistachkin # include "sqlite_tcl.h"
3852b1dbb5Smistachkin #else
39bd08af48Sdrh # include "tcl.h"
407617e4a8Smistachkin # ifndef SQLITE_TCLAPI
417617e4a8Smistachkin #  define SQLITE_TCLAPI
427617e4a8Smistachkin # endif
4352b1dbb5Smistachkin #endif
44b4e9af9fSdanielk1977 #include <errno.h>
456d31316cSdrh 
46bd08af48Sdrh /*
47bd08af48Sdrh ** Some additional include files are needed if this file is not
48bd08af48Sdrh ** appended to the amalgamation.
49bd08af48Sdrh */
50bd08af48Sdrh #ifndef SQLITE_AMALGAMATION
5165e8c82eSdrh # include "sqlite3.h"
5275897234Sdrh # include <stdlib.h>
5375897234Sdrh # include <string.h>
54ce927065Sdrh # include <assert.h>
5565e8c82eSdrh   typedef unsigned char u8;
56bd08af48Sdrh #endif
57eb206381Sdrh #include <ctype.h>
5875897234Sdrh 
591f28e070Smistachkin /* Used to get the current process ID */
601f28e070Smistachkin #if !defined(_WIN32)
611f28e070Smistachkin # include <unistd.h>
621f28e070Smistachkin # define GETPID getpid
631f28e070Smistachkin #elif !defined(_WIN32_WCE)
641f28e070Smistachkin # ifndef SQLITE_AMALGAMATION
651f28e070Smistachkin #  define WIN32_LEAN_AND_MEAN
661f28e070Smistachkin #  include <windows.h>
671f28e070Smistachkin # endif
681f28e070Smistachkin # define GETPID (int)GetCurrentProcessId
691f28e070Smistachkin #endif
701f28e070Smistachkin 
71ad6e1370Sdrh /*
72ad6e1370Sdrh  * Windows needs to know which symbols to export.  Unix does not.
73ad6e1370Sdrh  * BUILD_sqlite should be undefined for Unix.
74ad6e1370Sdrh  */
75ad6e1370Sdrh #ifdef BUILD_sqlite
76ad6e1370Sdrh #undef TCL_STORAGE_CLASS
77ad6e1370Sdrh #define TCL_STORAGE_CLASS DLLEXPORT
78ad6e1370Sdrh #endif /* BUILD_sqlite */
7929bc4615Sdrh 
80a21c6b6fSdanielk1977 #define NUM_PREPARED_STMTS 10
81fb7e7651Sdrh #define MAX_PREPARED_STMTS 100
82fb7e7651Sdrh 
83c45e6716Sdrh /* Forward declaration */
84c45e6716Sdrh typedef struct SqliteDb SqliteDb;
8598808babSdrh 
8698808babSdrh /*
87cabb0819Sdrh ** New SQL functions can be created as TCL scripts.  Each such function
88cabb0819Sdrh ** is described by an instance of the following structure.
89cabb0819Sdrh */
90cabb0819Sdrh typedef struct SqlFunc SqlFunc;
91cabb0819Sdrh struct SqlFunc {
92cabb0819Sdrh   Tcl_Interp *interp;   /* The TCL interpret to execute the function */
93d1e4733dSdrh   Tcl_Obj *pScript;     /* The Tcl_Obj representation of the script */
94c45e6716Sdrh   SqliteDb *pDb;        /* Database connection that owns this function */
95d1e4733dSdrh   int useEvalObjv;      /* True if it is safe to use Tcl_EvalObjv */
96d1e4733dSdrh   char *zName;          /* Name of this function */
97cabb0819Sdrh   SqlFunc *pNext;       /* Next function on the list of them all */
98cabb0819Sdrh };
99cabb0819Sdrh 
100cabb0819Sdrh /*
1010202b29eSdanielk1977 ** New collation sequences function can be created as TCL scripts.  Each such
1020202b29eSdanielk1977 ** function is described by an instance of the following structure.
1030202b29eSdanielk1977 */
1040202b29eSdanielk1977 typedef struct SqlCollate SqlCollate;
1050202b29eSdanielk1977 struct SqlCollate {
1060202b29eSdanielk1977   Tcl_Interp *interp;   /* The TCL interpret to execute the function */
1070202b29eSdanielk1977   char *zScript;        /* The script to be run */
1080202b29eSdanielk1977   SqlCollate *pNext;    /* Next function on the list of them all */
1090202b29eSdanielk1977 };
1100202b29eSdanielk1977 
1110202b29eSdanielk1977 /*
112fb7e7651Sdrh ** Prepared statements are cached for faster execution.  Each prepared
113fb7e7651Sdrh ** statement is described by an instance of the following structure.
114fb7e7651Sdrh */
115fb7e7651Sdrh typedef struct SqlPreparedStmt SqlPreparedStmt;
116fb7e7651Sdrh struct SqlPreparedStmt {
117fb7e7651Sdrh   SqlPreparedStmt *pNext;  /* Next in linked list */
118fb7e7651Sdrh   SqlPreparedStmt *pPrev;  /* Previous on the list */
119fb7e7651Sdrh   sqlite3_stmt *pStmt;     /* The prepared statement */
120fb7e7651Sdrh   int nSql;                /* chars in zSql[] */
121d0e2a854Sdanielk1977   const char *zSql;        /* Text of the SQL statement */
1224a4c11aaSdan   int nParm;               /* Size of apParm array */
1234a4c11aaSdan   Tcl_Obj **apParm;        /* Array of referenced object pointers */
124fb7e7651Sdrh };
125fb7e7651Sdrh 
126d0441796Sdanielk1977 typedef struct IncrblobChannel IncrblobChannel;
127d0441796Sdanielk1977 
128fb7e7651Sdrh /*
129bec3f402Sdrh ** There is one instance of this structure for each SQLite database
130bec3f402Sdrh ** that has been opened by the SQLite TCL interface.
131c431fd55Sdan **
132c431fd55Sdan ** If this module is built with SQLITE_TEST defined (to create the SQLite
133c431fd55Sdan ** testfixture executable), then it may be configured to use either
134c431fd55Sdan ** sqlite3_prepare_v2() or sqlite3_prepare() to prepare SQL statements.
135c431fd55Sdan ** If SqliteDb.bLegacyPrepare is true, sqlite3_prepare() is used.
136bec3f402Sdrh */
137bec3f402Sdrh struct SqliteDb {
138dddca286Sdrh   sqlite3 *db;               /* The "real" database structure. MUST BE FIRST */
139bec3f402Sdrh   Tcl_Interp *interp;        /* The interpreter used for this database */
1406d31316cSdrh   char *zBusy;               /* The busy callback routine */
141aa940eacSdrh   char *zCommit;             /* The commit hook callback routine */
142b5a20d3cSdrh   char *zTrace;              /* The trace callback routine */
143b56660f5Smistachkin   char *zTraceV2;            /* The trace_v2 callback routine */
14419e2d37fSdrh   char *zProfile;            /* The profile callback routine */
145348bb5d6Sdanielk1977   char *zProgress;           /* The progress callback routine */
146e22a334bSdrh   char *zAuth;               /* The authorization callback routine */
1471f1549f8Sdrh   int disableAuth;           /* Disable the authorizer if it exists */
14855c45f2eSdanielk1977   char *zNull;               /* Text to substitute for an SQL NULL value */
149cabb0819Sdrh   SqlFunc *pFunc;            /* List of SQL functions */
15094eb6a14Sdanielk1977   Tcl_Obj *pUpdateHook;      /* Update hook script (if any) */
15146c47d46Sdan   Tcl_Obj *pPreUpdateHook;   /* Pre-update hook script (if any) */
15271fd80bfSdanielk1977   Tcl_Obj *pRollbackHook;    /* Rollback hook script (if any) */
1535def0843Sdrh   Tcl_Obj *pWalHook;         /* WAL hook script (if any) */
154404ca075Sdanielk1977   Tcl_Obj *pUnlockNotify;    /* Unlock notify script (if any) */
1550202b29eSdanielk1977   SqlCollate *pCollate;      /* List of SQL collation functions */
1566f8a503dSdanielk1977   int rc;                    /* Return code of most recent sqlite3_exec() */
1577cedc8d4Sdanielk1977   Tcl_Obj *pCollateNeeded;   /* Collation needed script */
158fb7e7651Sdrh   SqlPreparedStmt *stmtList; /* List of prepared statements*/
159fb7e7651Sdrh   SqlPreparedStmt *stmtLast; /* Last statement in the list */
160fb7e7651Sdrh   int maxStmt;               /* The next maximum number of stmtList */
161fb7e7651Sdrh   int nStmt;                 /* Number of statements in stmtList */
162d0441796Sdanielk1977   IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */
1633c379b01Sdrh   int nStep, nSort, nIndex;  /* Statistics for most recent operation */
164cd38d520Sdanielk1977   int nTransaction;          /* Number of nested [transaction] methods */
165147ef394Sdrh   int openFlags;             /* Flags used to open.  (SQLITE_OPEN_URI) */
166c431fd55Sdan #ifdef SQLITE_TEST
167c431fd55Sdan   int bLegacyPrepare;        /* True to use sqlite3_prepare() */
168c431fd55Sdan #endif
16998808babSdrh };
170297ecf14Sdrh 
171b4e9af9fSdanielk1977 struct IncrblobChannel {
172d0441796Sdanielk1977   sqlite3_blob *pBlob;      /* sqlite3 blob handle */
173dcbb5d3fSdanielk1977   SqliteDb *pDb;            /* Associated database connection */
174b4e9af9fSdanielk1977   int iSeek;                /* Current seek offset */
175d0441796Sdanielk1977   Tcl_Channel channel;      /* Channel identifier */
176d0441796Sdanielk1977   IncrblobChannel *pNext;   /* Linked list of all open incrblob channels */
177d0441796Sdanielk1977   IncrblobChannel *pPrev;   /* Linked list of all open incrblob channels */
178b4e9af9fSdanielk1977 };
179b4e9af9fSdanielk1977 
180ea678832Sdrh /*
181ea678832Sdrh ** Compute a string length that is limited to what can be stored in
182ea678832Sdrh ** lower 30 bits of a 32-bit signed integer.
183ea678832Sdrh */
1844f21c4afSdrh static int strlen30(const char *z){
185ea678832Sdrh   const char *z2 = z;
186ea678832Sdrh   while( *z2 ){ z2++; }
187ea678832Sdrh   return 0x3fffffff & (int)(z2 - z);
188ea678832Sdrh }
189ea678832Sdrh 
190ea678832Sdrh 
19132a0d8bbSdanielk1977 #ifndef SQLITE_OMIT_INCRBLOB
192b4e9af9fSdanielk1977 /*
193d0441796Sdanielk1977 ** Close all incrblob channels opened using database connection pDb.
194d0441796Sdanielk1977 ** This is called when shutting down the database connection.
195d0441796Sdanielk1977 */
196d0441796Sdanielk1977 static void closeIncrblobChannels(SqliteDb *pDb){
197d0441796Sdanielk1977   IncrblobChannel *p;
198d0441796Sdanielk1977   IncrblobChannel *pNext;
199d0441796Sdanielk1977 
200d0441796Sdanielk1977   for(p=pDb->pIncrblob; p; p=pNext){
201d0441796Sdanielk1977     pNext = p->pNext;
202d0441796Sdanielk1977 
203d0441796Sdanielk1977     /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
204d0441796Sdanielk1977     ** which deletes the IncrblobChannel structure at *p. So do not
205d0441796Sdanielk1977     ** call Tcl_Free() here.
206d0441796Sdanielk1977     */
207d0441796Sdanielk1977     Tcl_UnregisterChannel(pDb->interp, p->channel);
208d0441796Sdanielk1977   }
209d0441796Sdanielk1977 }
210d0441796Sdanielk1977 
211d0441796Sdanielk1977 /*
212b4e9af9fSdanielk1977 ** Close an incremental blob channel.
213b4e9af9fSdanielk1977 */
2147617e4a8Smistachkin static int SQLITE_TCLAPI incrblobClose(
2157617e4a8Smistachkin   ClientData instanceData,
2167617e4a8Smistachkin   Tcl_Interp *interp
2177617e4a8Smistachkin ){
218b4e9af9fSdanielk1977   IncrblobChannel *p = (IncrblobChannel *)instanceData;
21992d4d7a9Sdanielk1977   int rc = sqlite3_blob_close(p->pBlob);
22092d4d7a9Sdanielk1977   sqlite3 *db = p->pDb->db;
221d0441796Sdanielk1977 
222d0441796Sdanielk1977   /* Remove the channel from the SqliteDb.pIncrblob list. */
223d0441796Sdanielk1977   if( p->pNext ){
224d0441796Sdanielk1977     p->pNext->pPrev = p->pPrev;
225d0441796Sdanielk1977   }
226d0441796Sdanielk1977   if( p->pPrev ){
227d0441796Sdanielk1977     p->pPrev->pNext = p->pNext;
228d0441796Sdanielk1977   }
229d0441796Sdanielk1977   if( p->pDb->pIncrblob==p ){
230d0441796Sdanielk1977     p->pDb->pIncrblob = p->pNext;
231d0441796Sdanielk1977   }
232d0441796Sdanielk1977 
23392d4d7a9Sdanielk1977   /* Free the IncrblobChannel structure */
234b4e9af9fSdanielk1977   Tcl_Free((char *)p);
23592d4d7a9Sdanielk1977 
23692d4d7a9Sdanielk1977   if( rc!=SQLITE_OK ){
23792d4d7a9Sdanielk1977     Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
23892d4d7a9Sdanielk1977     return TCL_ERROR;
23992d4d7a9Sdanielk1977   }
240b4e9af9fSdanielk1977   return TCL_OK;
241b4e9af9fSdanielk1977 }
242b4e9af9fSdanielk1977 
243b4e9af9fSdanielk1977 /*
244b4e9af9fSdanielk1977 ** Read data from an incremental blob channel.
245b4e9af9fSdanielk1977 */
2467617e4a8Smistachkin static int SQLITE_TCLAPI incrblobInput(
247b4e9af9fSdanielk1977   ClientData instanceData,
248b4e9af9fSdanielk1977   char *buf,
249b4e9af9fSdanielk1977   int bufSize,
250b4e9af9fSdanielk1977   int *errorCodePtr
251b4e9af9fSdanielk1977 ){
252b4e9af9fSdanielk1977   IncrblobChannel *p = (IncrblobChannel *)instanceData;
253b4e9af9fSdanielk1977   int nRead = bufSize;         /* Number of bytes to read */
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+nRead)>nBlob ){
259b4e9af9fSdanielk1977     nRead = nBlob-p->iSeek;
260b4e9af9fSdanielk1977   }
261b4e9af9fSdanielk1977   if( nRead<=0 ){
262b4e9af9fSdanielk1977     return 0;
263b4e9af9fSdanielk1977   }
264b4e9af9fSdanielk1977 
265b4e9af9fSdanielk1977   rc = sqlite3_blob_read(p->pBlob, (void *)buf, nRead, p->iSeek);
266b4e9af9fSdanielk1977   if( rc!=SQLITE_OK ){
267b4e9af9fSdanielk1977     *errorCodePtr = rc;
268b4e9af9fSdanielk1977     return -1;
269b4e9af9fSdanielk1977   }
270b4e9af9fSdanielk1977 
271b4e9af9fSdanielk1977   p->iSeek += nRead;
272b4e9af9fSdanielk1977   return nRead;
273b4e9af9fSdanielk1977 }
274b4e9af9fSdanielk1977 
275d0441796Sdanielk1977 /*
276d0441796Sdanielk1977 ** Write data to an incremental blob channel.
277d0441796Sdanielk1977 */
2787617e4a8Smistachkin static int SQLITE_TCLAPI incrblobOutput(
279b4e9af9fSdanielk1977   ClientData instanceData,
280b4e9af9fSdanielk1977   CONST char *buf,
281b4e9af9fSdanielk1977   int toWrite,
282b4e9af9fSdanielk1977   int *errorCodePtr
283b4e9af9fSdanielk1977 ){
284b4e9af9fSdanielk1977   IncrblobChannel *p = (IncrblobChannel *)instanceData;
285b4e9af9fSdanielk1977   int nWrite = toWrite;        /* Number of bytes to write */
286b4e9af9fSdanielk1977   int nBlob;                   /* Total size of the blob */
287b4e9af9fSdanielk1977   int rc;                      /* sqlite error code */
288b4e9af9fSdanielk1977 
289b4e9af9fSdanielk1977   nBlob = sqlite3_blob_bytes(p->pBlob);
290b4e9af9fSdanielk1977   if( (p->iSeek+nWrite)>nBlob ){
291b4e9af9fSdanielk1977     *errorCodePtr = EINVAL;
292b4e9af9fSdanielk1977     return -1;
293b4e9af9fSdanielk1977   }
294b4e9af9fSdanielk1977   if( nWrite<=0 ){
295b4e9af9fSdanielk1977     return 0;
296b4e9af9fSdanielk1977   }
297b4e9af9fSdanielk1977 
298b4e9af9fSdanielk1977   rc = sqlite3_blob_write(p->pBlob, (void *)buf, nWrite, p->iSeek);
299b4e9af9fSdanielk1977   if( rc!=SQLITE_OK ){
300b4e9af9fSdanielk1977     *errorCodePtr = EIO;
301b4e9af9fSdanielk1977     return -1;
302b4e9af9fSdanielk1977   }
303b4e9af9fSdanielk1977 
304b4e9af9fSdanielk1977   p->iSeek += nWrite;
305b4e9af9fSdanielk1977   return nWrite;
306b4e9af9fSdanielk1977 }
307b4e9af9fSdanielk1977 
308b4e9af9fSdanielk1977 /*
309b4e9af9fSdanielk1977 ** Seek an incremental blob channel.
310b4e9af9fSdanielk1977 */
3117617e4a8Smistachkin static int SQLITE_TCLAPI incrblobSeek(
312b4e9af9fSdanielk1977   ClientData instanceData,
313b4e9af9fSdanielk1977   long offset,
314b4e9af9fSdanielk1977   int seekMode,
315b4e9af9fSdanielk1977   int *errorCodePtr
316b4e9af9fSdanielk1977 ){
317b4e9af9fSdanielk1977   IncrblobChannel *p = (IncrblobChannel *)instanceData;
318b4e9af9fSdanielk1977 
319b4e9af9fSdanielk1977   switch( seekMode ){
320b4e9af9fSdanielk1977     case SEEK_SET:
321b4e9af9fSdanielk1977       p->iSeek = offset;
322b4e9af9fSdanielk1977       break;
323b4e9af9fSdanielk1977     case SEEK_CUR:
324b4e9af9fSdanielk1977       p->iSeek += offset;
325b4e9af9fSdanielk1977       break;
326b4e9af9fSdanielk1977     case SEEK_END:
327b4e9af9fSdanielk1977       p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset;
328b4e9af9fSdanielk1977       break;
329b4e9af9fSdanielk1977 
330b4e9af9fSdanielk1977     default: assert(!"Bad seekMode");
331b4e9af9fSdanielk1977   }
332b4e9af9fSdanielk1977 
333b4e9af9fSdanielk1977   return p->iSeek;
334b4e9af9fSdanielk1977 }
335b4e9af9fSdanielk1977 
336b4e9af9fSdanielk1977 
3377617e4a8Smistachkin static void SQLITE_TCLAPI incrblobWatch(
3387617e4a8Smistachkin   ClientData instanceData,
3397617e4a8Smistachkin   int mode
3407617e4a8Smistachkin ){
341b4e9af9fSdanielk1977   /* NO-OP */
342b4e9af9fSdanielk1977 }
3437617e4a8Smistachkin static int SQLITE_TCLAPI incrblobHandle(
3447617e4a8Smistachkin   ClientData instanceData,
3457617e4a8Smistachkin   int dir,
3467617e4a8Smistachkin   ClientData *hPtr
3477617e4a8Smistachkin ){
348b4e9af9fSdanielk1977   return TCL_ERROR;
349b4e9af9fSdanielk1977 }
350b4e9af9fSdanielk1977 
351b4e9af9fSdanielk1977 static Tcl_ChannelType IncrblobChannelType = {
352b4e9af9fSdanielk1977   "incrblob",                        /* typeName                             */
353b4e9af9fSdanielk1977   TCL_CHANNEL_VERSION_2,             /* version                              */
354b4e9af9fSdanielk1977   incrblobClose,                     /* closeProc                            */
355b4e9af9fSdanielk1977   incrblobInput,                     /* inputProc                            */
356b4e9af9fSdanielk1977   incrblobOutput,                    /* outputProc                           */
357b4e9af9fSdanielk1977   incrblobSeek,                      /* seekProc                             */
358b4e9af9fSdanielk1977   0,                                 /* setOptionProc                        */
359b4e9af9fSdanielk1977   0,                                 /* getOptionProc                        */
360b4e9af9fSdanielk1977   incrblobWatch,                     /* watchProc (this is a no-op)          */
361b4e9af9fSdanielk1977   incrblobHandle,                    /* getHandleProc (always returns error) */
362b4e9af9fSdanielk1977   0,                                 /* close2Proc                           */
363b4e9af9fSdanielk1977   0,                                 /* blockModeProc                        */
364b4e9af9fSdanielk1977   0,                                 /* flushProc                            */
365b4e9af9fSdanielk1977   0,                                 /* handlerProc                          */
366b4e9af9fSdanielk1977   0,                                 /* wideSeekProc                         */
367b4e9af9fSdanielk1977 };
368b4e9af9fSdanielk1977 
369b4e9af9fSdanielk1977 /*
370b4e9af9fSdanielk1977 ** Create a new incrblob channel.
371b4e9af9fSdanielk1977 */
372b4e9af9fSdanielk1977 static int createIncrblobChannel(
373b4e9af9fSdanielk1977   Tcl_Interp *interp,
374b4e9af9fSdanielk1977   SqliteDb *pDb,
375b4e9af9fSdanielk1977   const char *zDb,
376b4e9af9fSdanielk1977   const char *zTable,
377b4e9af9fSdanielk1977   const char *zColumn,
3788cbadb02Sdanielk1977   sqlite_int64 iRow,
3798cbadb02Sdanielk1977   int isReadonly
380b4e9af9fSdanielk1977 ){
381b4e9af9fSdanielk1977   IncrblobChannel *p;
3828cbadb02Sdanielk1977   sqlite3 *db = pDb->db;
383b4e9af9fSdanielk1977   sqlite3_blob *pBlob;
384b4e9af9fSdanielk1977   int rc;
3858cbadb02Sdanielk1977   int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE);
386b4e9af9fSdanielk1977 
387b4e9af9fSdanielk1977   /* This variable is used to name the channels: "incrblob_[incr count]" */
388b4e9af9fSdanielk1977   static int count = 0;
389b4e9af9fSdanielk1977   char zChannel[64];
390b4e9af9fSdanielk1977 
3918cbadb02Sdanielk1977   rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob);
392b4e9af9fSdanielk1977   if( rc!=SQLITE_OK ){
393b4e9af9fSdanielk1977     Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
394b4e9af9fSdanielk1977     return TCL_ERROR;
395b4e9af9fSdanielk1977   }
396b4e9af9fSdanielk1977 
397b4e9af9fSdanielk1977   p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel));
398b4e9af9fSdanielk1977   p->iSeek = 0;
399b4e9af9fSdanielk1977   p->pBlob = pBlob;
400b4e9af9fSdanielk1977 
4015bb3eb9bSdrh   sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count);
402d0441796Sdanielk1977   p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags);
403d0441796Sdanielk1977   Tcl_RegisterChannel(interp, p->channel);
404b4e9af9fSdanielk1977 
405d0441796Sdanielk1977   /* Link the new channel into the SqliteDb.pIncrblob list. */
406d0441796Sdanielk1977   p->pNext = pDb->pIncrblob;
407d0441796Sdanielk1977   p->pPrev = 0;
408d0441796Sdanielk1977   if( p->pNext ){
409d0441796Sdanielk1977     p->pNext->pPrev = p;
410d0441796Sdanielk1977   }
411d0441796Sdanielk1977   pDb->pIncrblob = p;
412d0441796Sdanielk1977   p->pDb = pDb;
413d0441796Sdanielk1977 
414d0441796Sdanielk1977   Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE);
415b4e9af9fSdanielk1977   return TCL_OK;
416b4e9af9fSdanielk1977 }
41732a0d8bbSdanielk1977 #else  /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
41832a0d8bbSdanielk1977   #define closeIncrblobChannels(pDb)
41932a0d8bbSdanielk1977 #endif
420b4e9af9fSdanielk1977 
4216d31316cSdrh /*
422d1e4733dSdrh ** Look at the script prefix in pCmd.  We will be executing this script
423d1e4733dSdrh ** after first appending one or more arguments.  This routine analyzes
424d1e4733dSdrh ** the script to see if it is safe to use Tcl_EvalObjv() on the script
425d1e4733dSdrh ** rather than the more general Tcl_EvalEx().  Tcl_EvalObjv() is much
426d1e4733dSdrh ** faster.
427d1e4733dSdrh **
428d1e4733dSdrh ** Scripts that are safe to use with Tcl_EvalObjv() consists of a
429d1e4733dSdrh ** command name followed by zero or more arguments with no [...] or $
430d1e4733dSdrh ** or {...} or ; to be seen anywhere.  Most callback scripts consist
431d1e4733dSdrh ** of just a single procedure name and they meet this requirement.
432d1e4733dSdrh */
433d1e4733dSdrh static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
434d1e4733dSdrh   /* We could try to do something with Tcl_Parse().  But we will instead
435d1e4733dSdrh   ** just do a search for forbidden characters.  If any of the forbidden
436d1e4733dSdrh   ** characters appear in pCmd, we will report the string as unsafe.
437d1e4733dSdrh   */
438d1e4733dSdrh   const char *z;
439d1e4733dSdrh   int n;
440d1e4733dSdrh   z = Tcl_GetStringFromObj(pCmd, &n);
441d1e4733dSdrh   while( n-- > 0 ){
442d1e4733dSdrh     int c = *(z++);
443d1e4733dSdrh     if( c=='$' || c=='[' || c==';' ) return 0;
444d1e4733dSdrh   }
445d1e4733dSdrh   return 1;
446d1e4733dSdrh }
447d1e4733dSdrh 
448d1e4733dSdrh /*
449d1e4733dSdrh ** Find an SqlFunc structure with the given name.  Or create a new
450d1e4733dSdrh ** one if an existing one cannot be found.  Return a pointer to the
451d1e4733dSdrh ** structure.
452d1e4733dSdrh */
453d1e4733dSdrh static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
454d1e4733dSdrh   SqlFunc *p, *pNew;
4550425f189Sdrh   int nName = strlen30(zName);
4560425f189Sdrh   pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + nName + 1 );
457d1e4733dSdrh   pNew->zName = (char*)&pNew[1];
4580425f189Sdrh   memcpy(pNew->zName, zName, nName+1);
459d1e4733dSdrh   for(p=pDb->pFunc; p; p=p->pNext){
4600425f189Sdrh     if( sqlite3_stricmp(p->zName, pNew->zName)==0 ){
461d1e4733dSdrh       Tcl_Free((char*)pNew);
462d1e4733dSdrh       return p;
463d1e4733dSdrh     }
464d1e4733dSdrh   }
465d1e4733dSdrh   pNew->interp = pDb->interp;
466c45e6716Sdrh   pNew->pDb = pDb;
467d1e4733dSdrh   pNew->pScript = 0;
468d1e4733dSdrh   pNew->pNext = pDb->pFunc;
469d1e4733dSdrh   pDb->pFunc = pNew;
470d1e4733dSdrh   return pNew;
471d1e4733dSdrh }
472d1e4733dSdrh 
473d1e4733dSdrh /*
474c431fd55Sdan ** Free a single SqlPreparedStmt object.
475c431fd55Sdan */
476c431fd55Sdan static void dbFreeStmt(SqlPreparedStmt *pStmt){
477c431fd55Sdan #ifdef SQLITE_TEST
478c431fd55Sdan   if( sqlite3_sql(pStmt->pStmt)==0 ){
479c431fd55Sdan     Tcl_Free((char *)pStmt->zSql);
480c431fd55Sdan   }
481c431fd55Sdan #endif
482c431fd55Sdan   sqlite3_finalize(pStmt->pStmt);
483c431fd55Sdan   Tcl_Free((char *)pStmt);
484c431fd55Sdan }
485c431fd55Sdan 
486c431fd55Sdan /*
487fb7e7651Sdrh ** Finalize and free a list of prepared statements
488fb7e7651Sdrh */
489fb7e7651Sdrh static void flushStmtCache(SqliteDb *pDb){
490fb7e7651Sdrh   SqlPreparedStmt *pPreStmt;
491c431fd55Sdan   SqlPreparedStmt *pNext;
492fb7e7651Sdrh 
493c431fd55Sdan   for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pNext){
494c431fd55Sdan     pNext = pPreStmt->pNext;
495c431fd55Sdan     dbFreeStmt(pPreStmt);
496fb7e7651Sdrh   }
497fb7e7651Sdrh   pDb->nStmt = 0;
498fb7e7651Sdrh   pDb->stmtLast = 0;
499c431fd55Sdan   pDb->stmtList = 0;
500fb7e7651Sdrh }
501fb7e7651Sdrh 
502fb7e7651Sdrh /*
503895d7472Sdrh ** TCL calls this procedure when an sqlite3 database command is
504895d7472Sdrh ** deleted.
50575897234Sdrh */
5067617e4a8Smistachkin static void SQLITE_TCLAPI DbDeleteCmd(void *db){
507bec3f402Sdrh   SqliteDb *pDb = (SqliteDb*)db;
508fb7e7651Sdrh   flushStmtCache(pDb);
509d0441796Sdanielk1977   closeIncrblobChannels(pDb);
5106f8a503dSdanielk1977   sqlite3_close(pDb->db);
511cabb0819Sdrh   while( pDb->pFunc ){
512cabb0819Sdrh     SqlFunc *pFunc = pDb->pFunc;
513cabb0819Sdrh     pDb->pFunc = pFunc->pNext;
514c45e6716Sdrh     assert( pFunc->pDb==pDb );
515d1e4733dSdrh     Tcl_DecrRefCount(pFunc->pScript);
516cabb0819Sdrh     Tcl_Free((char*)pFunc);
517cabb0819Sdrh   }
5180202b29eSdanielk1977   while( pDb->pCollate ){
5190202b29eSdanielk1977     SqlCollate *pCollate = pDb->pCollate;
5200202b29eSdanielk1977     pDb->pCollate = pCollate->pNext;
5210202b29eSdanielk1977     Tcl_Free((char*)pCollate);
5220202b29eSdanielk1977   }
523bec3f402Sdrh   if( pDb->zBusy ){
524bec3f402Sdrh     Tcl_Free(pDb->zBusy);
525bec3f402Sdrh   }
526b5a20d3cSdrh   if( pDb->zTrace ){
527b5a20d3cSdrh     Tcl_Free(pDb->zTrace);
5280d1a643aSdrh   }
529b56660f5Smistachkin   if( pDb->zTraceV2 ){
530b56660f5Smistachkin     Tcl_Free(pDb->zTraceV2);
531b56660f5Smistachkin   }
53219e2d37fSdrh   if( pDb->zProfile ){
53319e2d37fSdrh     Tcl_Free(pDb->zProfile);
53419e2d37fSdrh   }
535e22a334bSdrh   if( pDb->zAuth ){
536e22a334bSdrh     Tcl_Free(pDb->zAuth);
537e22a334bSdrh   }
53855c45f2eSdanielk1977   if( pDb->zNull ){
53955c45f2eSdanielk1977     Tcl_Free(pDb->zNull);
54055c45f2eSdanielk1977   }
54194eb6a14Sdanielk1977   if( pDb->pUpdateHook ){
54294eb6a14Sdanielk1977     Tcl_DecrRefCount(pDb->pUpdateHook);
54394eb6a14Sdanielk1977   }
54446c47d46Sdan   if( pDb->pPreUpdateHook ){
54546c47d46Sdan     Tcl_DecrRefCount(pDb->pPreUpdateHook);
54646c47d46Sdan   }
54771fd80bfSdanielk1977   if( pDb->pRollbackHook ){
54871fd80bfSdanielk1977     Tcl_DecrRefCount(pDb->pRollbackHook);
54971fd80bfSdanielk1977   }
5505def0843Sdrh   if( pDb->pWalHook ){
5515def0843Sdrh     Tcl_DecrRefCount(pDb->pWalHook);
5528d22a174Sdan   }
55394eb6a14Sdanielk1977   if( pDb->pCollateNeeded ){
55494eb6a14Sdanielk1977     Tcl_DecrRefCount(pDb->pCollateNeeded);
55594eb6a14Sdanielk1977   }
556bec3f402Sdrh   Tcl_Free((char*)pDb);
557bec3f402Sdrh }
558bec3f402Sdrh 
559bec3f402Sdrh /*
560bec3f402Sdrh ** This routine is called when a database file is locked while trying
561bec3f402Sdrh ** to execute SQL.
562bec3f402Sdrh */
5632a764eb0Sdanielk1977 static int DbBusyHandler(void *cd, int nTries){
564bec3f402Sdrh   SqliteDb *pDb = (SqliteDb*)cd;
565bec3f402Sdrh   int rc;
566bec3f402Sdrh   char zVal[30];
567bec3f402Sdrh 
5685bb3eb9bSdrh   sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries);
569d1e4733dSdrh   rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
570bec3f402Sdrh   if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
571bec3f402Sdrh     return 0;
572bec3f402Sdrh   }
573bec3f402Sdrh   return 1;
57475897234Sdrh }
57575897234Sdrh 
57626e4a8b1Sdrh #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
57775897234Sdrh /*
578348bb5d6Sdanielk1977 ** This routine is invoked as the 'progress callback' for the database.
579348bb5d6Sdanielk1977 */
580348bb5d6Sdanielk1977 static int DbProgressHandler(void *cd){
581348bb5d6Sdanielk1977   SqliteDb *pDb = (SqliteDb*)cd;
582348bb5d6Sdanielk1977   int rc;
583348bb5d6Sdanielk1977 
584348bb5d6Sdanielk1977   assert( pDb->zProgress );
585348bb5d6Sdanielk1977   rc = Tcl_Eval(pDb->interp, pDb->zProgress);
586348bb5d6Sdanielk1977   if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
587348bb5d6Sdanielk1977     return 1;
588348bb5d6Sdanielk1977   }
589348bb5d6Sdanielk1977   return 0;
590348bb5d6Sdanielk1977 }
59126e4a8b1Sdrh #endif
592348bb5d6Sdanielk1977 
5932eb22af0Sdrh #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
5942eb22af0Sdrh     !defined(SQLITE_OMIT_DEPRECATED)
595348bb5d6Sdanielk1977 /*
596b5a20d3cSdrh ** This routine is called by the SQLite trace handler whenever a new
597b5a20d3cSdrh ** block of SQL is executed.  The TCL script in pDb->zTrace is executed.
5980d1a643aSdrh */
599b5a20d3cSdrh static void DbTraceHandler(void *cd, const char *zSql){
6000d1a643aSdrh   SqliteDb *pDb = (SqliteDb*)cd;
601b5a20d3cSdrh   Tcl_DString str;
6020d1a643aSdrh 
603b5a20d3cSdrh   Tcl_DStringInit(&str);
604b5a20d3cSdrh   Tcl_DStringAppend(&str, pDb->zTrace, -1);
605b5a20d3cSdrh   Tcl_DStringAppendElement(&str, zSql);
606b5a20d3cSdrh   Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
607b5a20d3cSdrh   Tcl_DStringFree(&str);
608b5a20d3cSdrh   Tcl_ResetResult(pDb->interp);
6090d1a643aSdrh }
610d1167393Sdrh #endif
6110d1a643aSdrh 
612d1167393Sdrh #ifndef SQLITE_OMIT_TRACE
6130d1a643aSdrh /*
614b56660f5Smistachkin ** This routine is called by the SQLite trace_v2 handler whenever a new
615b56660f5Smistachkin ** supported event is generated.  Unsupported event types are ignored.
616b56660f5Smistachkin ** The TCL script in pDb->zTraceV2 is executed, with the arguments for
617b56660f5Smistachkin ** the event appended to it (as list elements).
618b56660f5Smistachkin */
619b56660f5Smistachkin static int DbTraceV2Handler(
620b56660f5Smistachkin   unsigned type, /* One of the SQLITE_TRACE_* event types. */
621b56660f5Smistachkin   void *cd,      /* The original context data pointer. */
622b56660f5Smistachkin   void *pd,      /* Primary event data, depends on event type. */
623b56660f5Smistachkin   void *xd       /* Extra event data, depends on event type. */
624b56660f5Smistachkin ){
625b56660f5Smistachkin   SqliteDb *pDb = (SqliteDb*)cd;
626b56660f5Smistachkin   Tcl_Obj *pCmd;
627b56660f5Smistachkin 
628b56660f5Smistachkin   switch( type ){
629b56660f5Smistachkin     case SQLITE_TRACE_STMT: {
630b56660f5Smistachkin       sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;
631b56660f5Smistachkin       char *zSql = (char *)xd;
632b56660f5Smistachkin 
633b56660f5Smistachkin       pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
634b56660f5Smistachkin       Tcl_IncrRefCount(pCmd);
635b56660f5Smistachkin       Tcl_ListObjAppendElement(pDb->interp, pCmd,
636b56660f5Smistachkin                                Tcl_NewWideIntObj((Tcl_WideInt)pStmt));
637b56660f5Smistachkin       Tcl_ListObjAppendElement(pDb->interp, pCmd,
638b56660f5Smistachkin                                Tcl_NewStringObj(zSql, -1));
639b56660f5Smistachkin       Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
640b56660f5Smistachkin       Tcl_DecrRefCount(pCmd);
641b56660f5Smistachkin       Tcl_ResetResult(pDb->interp);
642b56660f5Smistachkin       break;
643b56660f5Smistachkin     }
644b56660f5Smistachkin     case SQLITE_TRACE_PROFILE: {
645b56660f5Smistachkin       sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;
646b56660f5Smistachkin       sqlite3_int64 ns = (sqlite3_int64)xd;
647b56660f5Smistachkin 
648b56660f5Smistachkin       pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
649b56660f5Smistachkin       Tcl_IncrRefCount(pCmd);
650b56660f5Smistachkin       Tcl_ListObjAppendElement(pDb->interp, pCmd,
651b56660f5Smistachkin                                Tcl_NewWideIntObj((Tcl_WideInt)pStmt));
652b56660f5Smistachkin       Tcl_ListObjAppendElement(pDb->interp, pCmd,
653b56660f5Smistachkin                                Tcl_NewWideIntObj((Tcl_WideInt)ns));
654b56660f5Smistachkin       Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
655b56660f5Smistachkin       Tcl_DecrRefCount(pCmd);
656b56660f5Smistachkin       Tcl_ResetResult(pDb->interp);
657b56660f5Smistachkin       break;
658b56660f5Smistachkin     }
659b56660f5Smistachkin     case SQLITE_TRACE_ROW: {
660b56660f5Smistachkin       sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;
661b56660f5Smistachkin 
662b56660f5Smistachkin       pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
663b56660f5Smistachkin       Tcl_IncrRefCount(pCmd);
664b56660f5Smistachkin       Tcl_ListObjAppendElement(pDb->interp, pCmd,
665b56660f5Smistachkin                                Tcl_NewWideIntObj((Tcl_WideInt)pStmt));
666b56660f5Smistachkin       Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
667b56660f5Smistachkin       Tcl_DecrRefCount(pCmd);
668b56660f5Smistachkin       Tcl_ResetResult(pDb->interp);
669b56660f5Smistachkin       break;
670b56660f5Smistachkin     }
671b56660f5Smistachkin     case SQLITE_TRACE_CLOSE: {
672b56660f5Smistachkin       sqlite3 *db = (sqlite3 *)pd;
673b56660f5Smistachkin 
674b56660f5Smistachkin       pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
675b56660f5Smistachkin       Tcl_IncrRefCount(pCmd);
676b56660f5Smistachkin       Tcl_ListObjAppendElement(pDb->interp, pCmd,
677b56660f5Smistachkin                                Tcl_NewWideIntObj((Tcl_WideInt)db));
678b56660f5Smistachkin       Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
679b56660f5Smistachkin       Tcl_DecrRefCount(pCmd);
680b56660f5Smistachkin       Tcl_ResetResult(pDb->interp);
681b56660f5Smistachkin       break;
682b56660f5Smistachkin     }
683b56660f5Smistachkin   }
684b56660f5Smistachkin   return SQLITE_OK;
685b56660f5Smistachkin }
686b56660f5Smistachkin #endif
687b56660f5Smistachkin 
6882eb22af0Sdrh #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
6892eb22af0Sdrh     !defined(SQLITE_OMIT_DEPRECATED)
690b56660f5Smistachkin /*
69119e2d37fSdrh ** This routine is called by the SQLite profile handler after a statement
69219e2d37fSdrh ** SQL has executed.  The TCL script in pDb->zProfile is evaluated.
69319e2d37fSdrh */
69419e2d37fSdrh static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
69519e2d37fSdrh   SqliteDb *pDb = (SqliteDb*)cd;
69619e2d37fSdrh   Tcl_DString str;
69719e2d37fSdrh   char zTm[100];
69819e2d37fSdrh 
69919e2d37fSdrh   sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
70019e2d37fSdrh   Tcl_DStringInit(&str);
70119e2d37fSdrh   Tcl_DStringAppend(&str, pDb->zProfile, -1);
70219e2d37fSdrh   Tcl_DStringAppendElement(&str, zSql);
70319e2d37fSdrh   Tcl_DStringAppendElement(&str, zTm);
70419e2d37fSdrh   Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
70519e2d37fSdrh   Tcl_DStringFree(&str);
70619e2d37fSdrh   Tcl_ResetResult(pDb->interp);
70719e2d37fSdrh }
708d1167393Sdrh #endif
70919e2d37fSdrh 
71019e2d37fSdrh /*
711aa940eacSdrh ** This routine is called when a transaction is committed.  The
712aa940eacSdrh ** TCL script in pDb->zCommit is executed.  If it returns non-zero or
713aa940eacSdrh ** if it throws an exception, the transaction is rolled back instead
714aa940eacSdrh ** of being committed.
715aa940eacSdrh */
716aa940eacSdrh static int DbCommitHandler(void *cd){
717aa940eacSdrh   SqliteDb *pDb = (SqliteDb*)cd;
718aa940eacSdrh   int rc;
719aa940eacSdrh 
720aa940eacSdrh   rc = Tcl_Eval(pDb->interp, pDb->zCommit);
721aa940eacSdrh   if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
722aa940eacSdrh     return 1;
723aa940eacSdrh   }
724aa940eacSdrh   return 0;
725aa940eacSdrh }
726aa940eacSdrh 
72771fd80bfSdanielk1977 static void DbRollbackHandler(void *clientData){
72871fd80bfSdanielk1977   SqliteDb *pDb = (SqliteDb*)clientData;
72971fd80bfSdanielk1977   assert(pDb->pRollbackHook);
73071fd80bfSdanielk1977   if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
73171fd80bfSdanielk1977     Tcl_BackgroundError(pDb->interp);
73271fd80bfSdanielk1977   }
73371fd80bfSdanielk1977 }
73471fd80bfSdanielk1977 
7355def0843Sdrh /*
7365def0843Sdrh ** This procedure handles wal_hook callbacks.
7375def0843Sdrh */
7385def0843Sdrh static int DbWalHandler(
7398d22a174Sdan   void *clientData,
7408d22a174Sdan   sqlite3 *db,
7418d22a174Sdan   const char *zDb,
7428d22a174Sdan   int nEntry
7438d22a174Sdan ){
7445def0843Sdrh   int ret = SQLITE_OK;
7458d22a174Sdan   Tcl_Obj *p;
7468d22a174Sdan   SqliteDb *pDb = (SqliteDb*)clientData;
7478d22a174Sdan   Tcl_Interp *interp = pDb->interp;
7485def0843Sdrh   assert(pDb->pWalHook);
7498d22a174Sdan 
7506e45e0c8Sdan   assert( db==pDb->db );
7515def0843Sdrh   p = Tcl_DuplicateObj(pDb->pWalHook);
7528d22a174Sdan   Tcl_IncrRefCount(p);
7538d22a174Sdan   Tcl_ListObjAppendElement(interp, p, Tcl_NewStringObj(zDb, -1));
7548d22a174Sdan   Tcl_ListObjAppendElement(interp, p, Tcl_NewIntObj(nEntry));
7558d22a174Sdan   if( TCL_OK!=Tcl_EvalObjEx(interp, p, 0)
7568d22a174Sdan    || TCL_OK!=Tcl_GetIntFromObj(interp, Tcl_GetObjResult(interp), &ret)
7578d22a174Sdan   ){
7588d22a174Sdan     Tcl_BackgroundError(interp);
7598d22a174Sdan   }
7608d22a174Sdan   Tcl_DecrRefCount(p);
7618d22a174Sdan 
7628d22a174Sdan   return ret;
7638d22a174Sdan }
7648d22a174Sdan 
765bcf4f484Sdrh #if defined(SQLITE_TEST) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
766404ca075Sdanielk1977 static void setTestUnlockNotifyVars(Tcl_Interp *interp, int iArg, int nArg){
767404ca075Sdanielk1977   char zBuf[64];
76865545b59Sdrh   sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", iArg);
769404ca075Sdanielk1977   Tcl_SetVar(interp, "sqlite_unlock_notify_arg", zBuf, TCL_GLOBAL_ONLY);
77065545b59Sdrh   sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", nArg);
771404ca075Sdanielk1977   Tcl_SetVar(interp, "sqlite_unlock_notify_argcount", zBuf, TCL_GLOBAL_ONLY);
772404ca075Sdanielk1977 }
773404ca075Sdanielk1977 #else
774404ca075Sdanielk1977 # define setTestUnlockNotifyVars(x,y,z)
775404ca075Sdanielk1977 #endif
776404ca075Sdanielk1977 
77769910da9Sdrh #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
778404ca075Sdanielk1977 static void DbUnlockNotify(void **apArg, int nArg){
779404ca075Sdanielk1977   int i;
780404ca075Sdanielk1977   for(i=0; i<nArg; i++){
781404ca075Sdanielk1977     const int flags = (TCL_EVAL_GLOBAL|TCL_EVAL_DIRECT);
782404ca075Sdanielk1977     SqliteDb *pDb = (SqliteDb *)apArg[i];
783404ca075Sdanielk1977     setTestUnlockNotifyVars(pDb->interp, i, nArg);
784404ca075Sdanielk1977     assert( pDb->pUnlockNotify);
785404ca075Sdanielk1977     Tcl_EvalObjEx(pDb->interp, pDb->pUnlockNotify, flags);
786404ca075Sdanielk1977     Tcl_DecrRefCount(pDb->pUnlockNotify);
787404ca075Sdanielk1977     pDb->pUnlockNotify = 0;
788404ca075Sdanielk1977   }
789404ca075Sdanielk1977 }
79069910da9Sdrh #endif
791404ca075Sdanielk1977 
7929b1c62d4Sdrh #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
79346c47d46Sdan /*
79446c47d46Sdan ** Pre-update hook callback.
79546c47d46Sdan */
79646c47d46Sdan static void DbPreUpdateHandler(
79746c47d46Sdan   void *p,
79846c47d46Sdan   sqlite3 *db,
79946c47d46Sdan   int op,
80046c47d46Sdan   const char *zDb,
80146c47d46Sdan   const char *zTbl,
80246c47d46Sdan   sqlite_int64 iKey1,
80346c47d46Sdan   sqlite_int64 iKey2
80446c47d46Sdan ){
80546c47d46Sdan   SqliteDb *pDb = (SqliteDb *)p;
80646c47d46Sdan   Tcl_Obj *pCmd;
80746c47d46Sdan   static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"};
80846c47d46Sdan 
80946c47d46Sdan   assert( (SQLITE_DELETE-1)/9 == 0 );
81046c47d46Sdan   assert( (SQLITE_INSERT-1)/9 == 1 );
81146c47d46Sdan   assert( (SQLITE_UPDATE-1)/9 == 2 );
81246c47d46Sdan   assert( pDb->pPreUpdateHook );
81346c47d46Sdan   assert( db==pDb->db );
81446c47d46Sdan   assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
81546c47d46Sdan 
81646c47d46Sdan   pCmd = Tcl_DuplicateObj(pDb->pPreUpdateHook);
81746c47d46Sdan   Tcl_IncrRefCount(pCmd);
81846c47d46Sdan   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
81946c47d46Sdan   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
82046c47d46Sdan   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
82146c47d46Sdan   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey1));
82246c47d46Sdan   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey2));
82346c47d46Sdan   Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
82446c47d46Sdan   Tcl_DecrRefCount(pCmd);
82546c47d46Sdan }
8269b1c62d4Sdrh #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
82746c47d46Sdan 
82894eb6a14Sdanielk1977 static void DbUpdateHandler(
82994eb6a14Sdanielk1977   void *p,
83094eb6a14Sdanielk1977   int op,
83194eb6a14Sdanielk1977   const char *zDb,
83294eb6a14Sdanielk1977   const char *zTbl,
83394eb6a14Sdanielk1977   sqlite_int64 rowid
83494eb6a14Sdanielk1977 ){
83594eb6a14Sdanielk1977   SqliteDb *pDb = (SqliteDb *)p;
83694eb6a14Sdanielk1977   Tcl_Obj *pCmd;
83746c47d46Sdan   static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"};
83846c47d46Sdan 
83946c47d46Sdan   assert( (SQLITE_DELETE-1)/9 == 0 );
84046c47d46Sdan   assert( (SQLITE_INSERT-1)/9 == 1 );
84146c47d46Sdan   assert( (SQLITE_UPDATE-1)/9 == 2 );
84294eb6a14Sdanielk1977 
84394eb6a14Sdanielk1977   assert( pDb->pUpdateHook );
84494eb6a14Sdanielk1977   assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
84594eb6a14Sdanielk1977 
84694eb6a14Sdanielk1977   pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
84794eb6a14Sdanielk1977   Tcl_IncrRefCount(pCmd);
84846c47d46Sdan   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
84994eb6a14Sdanielk1977   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
85094eb6a14Sdanielk1977   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
85194eb6a14Sdanielk1977   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
85294eb6a14Sdanielk1977   Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
853efdde169Sdrh   Tcl_DecrRefCount(pCmd);
85494eb6a14Sdanielk1977 }
85594eb6a14Sdanielk1977 
8567cedc8d4Sdanielk1977 static void tclCollateNeeded(
8577cedc8d4Sdanielk1977   void *pCtx,
8589bb575fdSdrh   sqlite3 *db,
8597cedc8d4Sdanielk1977   int enc,
8607cedc8d4Sdanielk1977   const char *zName
8617cedc8d4Sdanielk1977 ){
8627cedc8d4Sdanielk1977   SqliteDb *pDb = (SqliteDb *)pCtx;
8637cedc8d4Sdanielk1977   Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
8647cedc8d4Sdanielk1977   Tcl_IncrRefCount(pScript);
8657cedc8d4Sdanielk1977   Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
8667cedc8d4Sdanielk1977   Tcl_EvalObjEx(pDb->interp, pScript, 0);
8677cedc8d4Sdanielk1977   Tcl_DecrRefCount(pScript);
8687cedc8d4Sdanielk1977 }
8697cedc8d4Sdanielk1977 
870aa940eacSdrh /*
8710202b29eSdanielk1977 ** This routine is called to evaluate an SQL collation function implemented
8720202b29eSdanielk1977 ** using TCL script.
8730202b29eSdanielk1977 */
8740202b29eSdanielk1977 static int tclSqlCollate(
8750202b29eSdanielk1977   void *pCtx,
8760202b29eSdanielk1977   int nA,
8770202b29eSdanielk1977   const void *zA,
8780202b29eSdanielk1977   int nB,
8790202b29eSdanielk1977   const void *zB
8800202b29eSdanielk1977 ){
8810202b29eSdanielk1977   SqlCollate *p = (SqlCollate *)pCtx;
8820202b29eSdanielk1977   Tcl_Obj *pCmd;
8830202b29eSdanielk1977 
8840202b29eSdanielk1977   pCmd = Tcl_NewStringObj(p->zScript, -1);
8850202b29eSdanielk1977   Tcl_IncrRefCount(pCmd);
8860202b29eSdanielk1977   Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
8870202b29eSdanielk1977   Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
888d1e4733dSdrh   Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
8890202b29eSdanielk1977   Tcl_DecrRefCount(pCmd);
8900202b29eSdanielk1977   return (atoi(Tcl_GetStringResult(p->interp)));
8910202b29eSdanielk1977 }
8920202b29eSdanielk1977 
8930202b29eSdanielk1977 /*
894cabb0819Sdrh ** This routine is called to evaluate an SQL function implemented
895cabb0819Sdrh ** using TCL script.
896cabb0819Sdrh */
8970ae8b831Sdanielk1977 static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
8986f8a503dSdanielk1977   SqlFunc *p = sqlite3_user_data(context);
899d1e4733dSdrh   Tcl_Obj *pCmd;
900cabb0819Sdrh   int i;
901cabb0819Sdrh   int rc;
902cabb0819Sdrh 
903d1e4733dSdrh   if( argc==0 ){
904d1e4733dSdrh     /* If there are no arguments to the function, call Tcl_EvalObjEx on the
905d1e4733dSdrh     ** script object directly.  This allows the TCL compiler to generate
906d1e4733dSdrh     ** bytecode for the command on the first invocation and thus make
907d1e4733dSdrh     ** subsequent invocations much faster. */
908d1e4733dSdrh     pCmd = p->pScript;
909d1e4733dSdrh     Tcl_IncrRefCount(pCmd);
910d1e4733dSdrh     rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
911d1e4733dSdrh     Tcl_DecrRefCount(pCmd);
91251ad0ecdSdanielk1977   }else{
913d1e4733dSdrh     /* If there are arguments to the function, make a shallow copy of the
914d1e4733dSdrh     ** script object, lappend the arguments, then evaluate the copy.
915d1e4733dSdrh     **
91660ec914cSpeter.d.reid     ** By "shallow" copy, we mean only the outer list Tcl_Obj is duplicated.
917d1e4733dSdrh     ** The new Tcl_Obj contains pointers to the original list elements.
918d1e4733dSdrh     ** That way, when Tcl_EvalObjv() is run and shimmers the first element
919d1e4733dSdrh     ** of the list to tclCmdNameType, that alternate representation will
920d1e4733dSdrh     ** be preserved and reused on the next invocation.
921d1e4733dSdrh     */
922d1e4733dSdrh     Tcl_Obj **aArg;
923d1e4733dSdrh     int nArg;
924d1e4733dSdrh     if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
925d1e4733dSdrh       sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
926d1e4733dSdrh       return;
927d1e4733dSdrh     }
928d1e4733dSdrh     pCmd = Tcl_NewListObj(nArg, aArg);
929d1e4733dSdrh     Tcl_IncrRefCount(pCmd);
930d1e4733dSdrh     for(i=0; i<argc; i++){
931d1e4733dSdrh       sqlite3_value *pIn = argv[i];
932d1e4733dSdrh       Tcl_Obj *pVal;
933d1e4733dSdrh 
934d1e4733dSdrh       /* Set pVal to contain the i'th column of this row. */
935d1e4733dSdrh       switch( sqlite3_value_type(pIn) ){
936d1e4733dSdrh         case SQLITE_BLOB: {
937d1e4733dSdrh           int bytes = sqlite3_value_bytes(pIn);
938d1e4733dSdrh           pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
939d1e4733dSdrh           break;
940d1e4733dSdrh         }
941d1e4733dSdrh         case SQLITE_INTEGER: {
942d1e4733dSdrh           sqlite_int64 v = sqlite3_value_int64(pIn);
943d1e4733dSdrh           if( v>=-2147483647 && v<=2147483647 ){
9447fd33929Sdrh             pVal = Tcl_NewIntObj((int)v);
945d1e4733dSdrh           }else{
946d1e4733dSdrh             pVal = Tcl_NewWideIntObj(v);
947d1e4733dSdrh           }
948d1e4733dSdrh           break;
949d1e4733dSdrh         }
950d1e4733dSdrh         case SQLITE_FLOAT: {
951d1e4733dSdrh           double r = sqlite3_value_double(pIn);
952d1e4733dSdrh           pVal = Tcl_NewDoubleObj(r);
953d1e4733dSdrh           break;
954d1e4733dSdrh         }
955d1e4733dSdrh         case SQLITE_NULL: {
956c45e6716Sdrh           pVal = Tcl_NewStringObj(p->pDb->zNull, -1);
957d1e4733dSdrh           break;
958d1e4733dSdrh         }
959d1e4733dSdrh         default: {
960d1e4733dSdrh           int bytes = sqlite3_value_bytes(pIn);
96100fd957bSdanielk1977           pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
962d1e4733dSdrh           break;
96351ad0ecdSdanielk1977         }
964cabb0819Sdrh       }
965d1e4733dSdrh       rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
966d1e4733dSdrh       if( rc ){
967d1e4733dSdrh         Tcl_DecrRefCount(pCmd);
968d1e4733dSdrh         sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
969d1e4733dSdrh         return;
970d1e4733dSdrh       }
971d1e4733dSdrh     }
972d1e4733dSdrh     if( !p->useEvalObjv ){
973d1e4733dSdrh       /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
974d1e4733dSdrh       ** is a list without a string representation.  To prevent this from
975d1e4733dSdrh       ** happening, make sure pCmd has a valid string representation */
976d1e4733dSdrh       Tcl_GetString(pCmd);
977d1e4733dSdrh     }
978d1e4733dSdrh     rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
979d1e4733dSdrh     Tcl_DecrRefCount(pCmd);
980d1e4733dSdrh   }
981562e8d3cSdanielk1977 
982c7f269d5Sdrh   if( rc && rc!=TCL_RETURN ){
9837e18c259Sdanielk1977     sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
984cabb0819Sdrh   }else{
985c7f269d5Sdrh     Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
986c7f269d5Sdrh     int n;
987c7f269d5Sdrh     u8 *data;
9884a4c11aaSdan     const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
989c7f269d5Sdrh     char c = zType[0];
990df0bddaeSdrh     if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
991d1e4733dSdrh       /* Only return a BLOB type if the Tcl variable is a bytearray and
992df0bddaeSdrh       ** has no string representation. */
993c7f269d5Sdrh       data = Tcl_GetByteArrayFromObj(pVar, &n);
994c7f269d5Sdrh       sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
995985e0c63Sdrh     }else if( c=='b' && strcmp(zType,"boolean")==0 ){
996c7f269d5Sdrh       Tcl_GetIntFromObj(0, pVar, &n);
997c7f269d5Sdrh       sqlite3_result_int(context, n);
998c7f269d5Sdrh     }else if( c=='d' && strcmp(zType,"double")==0 ){
999c7f269d5Sdrh       double r;
1000c7f269d5Sdrh       Tcl_GetDoubleFromObj(0, pVar, &r);
1001c7f269d5Sdrh       sqlite3_result_double(context, r);
1002985e0c63Sdrh     }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
1003985e0c63Sdrh           (c=='i' && strcmp(zType,"int")==0) ){
1004df0bddaeSdrh       Tcl_WideInt v;
1005df0bddaeSdrh       Tcl_GetWideIntFromObj(0, pVar, &v);
1006df0bddaeSdrh       sqlite3_result_int64(context, v);
1007c7f269d5Sdrh     }else{
100800fd957bSdanielk1977       data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
100900fd957bSdanielk1977       sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
1010c7f269d5Sdrh     }
1011cabb0819Sdrh   }
1012cabb0819Sdrh }
1013895d7472Sdrh 
1014e22a334bSdrh #ifndef SQLITE_OMIT_AUTHORIZATION
1015e22a334bSdrh /*
1016e22a334bSdrh ** This is the authentication function.  It appends the authentication
1017e22a334bSdrh ** type code and the two arguments to zCmd[] then invokes the result
1018e22a334bSdrh ** on the interpreter.  The reply is examined to determine if the
1019e22a334bSdrh ** authentication fails or succeeds.
1020e22a334bSdrh */
1021e22a334bSdrh static int auth_callback(
1022e22a334bSdrh   void *pArg,
1023e22a334bSdrh   int code,
1024e22a334bSdrh   const char *zArg1,
1025e22a334bSdrh   const char *zArg2,
1026e22a334bSdrh   const char *zArg3,
1027e22a334bSdrh   const char *zArg4
102832c6a48bSdrh #ifdef SQLITE_USER_AUTHENTICATION
102932c6a48bSdrh   ,const char *zArg5
103032c6a48bSdrh #endif
1031e22a334bSdrh ){
10326ef5e12eSmistachkin   const char *zCode;
1033e22a334bSdrh   Tcl_DString str;
1034e22a334bSdrh   int rc;
1035e22a334bSdrh   const char *zReply;
10369418921cSdrh   /* EVIDENCE-OF: R-38590-62769 The first parameter to the authorizer
10379418921cSdrh   ** callback is a copy of the third parameter to the
10389418921cSdrh   ** sqlite3_set_authorizer() interface.
10399418921cSdrh   */
1040e22a334bSdrh   SqliteDb *pDb = (SqliteDb*)pArg;
10411f1549f8Sdrh   if( pDb->disableAuth ) return SQLITE_OK;
1042e22a334bSdrh 
10439418921cSdrh   /* EVIDENCE-OF: R-56518-44310 The second parameter to the callback is an
10449418921cSdrh   ** integer action code that specifies the particular action to be
10459418921cSdrh   ** authorized. */
1046e22a334bSdrh   switch( code ){
1047e22a334bSdrh     case SQLITE_COPY              : zCode="SQLITE_COPY"; break;
1048e22a334bSdrh     case SQLITE_CREATE_INDEX      : zCode="SQLITE_CREATE_INDEX"; break;
1049e22a334bSdrh     case SQLITE_CREATE_TABLE      : zCode="SQLITE_CREATE_TABLE"; break;
1050e22a334bSdrh     case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
1051e22a334bSdrh     case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
1052e22a334bSdrh     case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
1053e22a334bSdrh     case SQLITE_CREATE_TEMP_VIEW  : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
1054e22a334bSdrh     case SQLITE_CREATE_TRIGGER    : zCode="SQLITE_CREATE_TRIGGER"; break;
1055e22a334bSdrh     case SQLITE_CREATE_VIEW       : zCode="SQLITE_CREATE_VIEW"; break;
1056e22a334bSdrh     case SQLITE_DELETE            : zCode="SQLITE_DELETE"; break;
1057e22a334bSdrh     case SQLITE_DROP_INDEX        : zCode="SQLITE_DROP_INDEX"; break;
1058e22a334bSdrh     case SQLITE_DROP_TABLE        : zCode="SQLITE_DROP_TABLE"; break;
1059e22a334bSdrh     case SQLITE_DROP_TEMP_INDEX   : zCode="SQLITE_DROP_TEMP_INDEX"; break;
1060e22a334bSdrh     case SQLITE_DROP_TEMP_TABLE   : zCode="SQLITE_DROP_TEMP_TABLE"; break;
1061e22a334bSdrh     case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
1062e22a334bSdrh     case SQLITE_DROP_TEMP_VIEW    : zCode="SQLITE_DROP_TEMP_VIEW"; break;
1063e22a334bSdrh     case SQLITE_DROP_TRIGGER      : zCode="SQLITE_DROP_TRIGGER"; break;
1064e22a334bSdrh     case SQLITE_DROP_VIEW         : zCode="SQLITE_DROP_VIEW"; break;
1065e22a334bSdrh     case SQLITE_INSERT            : zCode="SQLITE_INSERT"; break;
1066e22a334bSdrh     case SQLITE_PRAGMA            : zCode="SQLITE_PRAGMA"; break;
1067e22a334bSdrh     case SQLITE_READ              : zCode="SQLITE_READ"; break;
1068e22a334bSdrh     case SQLITE_SELECT            : zCode="SQLITE_SELECT"; break;
1069e22a334bSdrh     case SQLITE_TRANSACTION       : zCode="SQLITE_TRANSACTION"; break;
1070e22a334bSdrh     case SQLITE_UPDATE            : zCode="SQLITE_UPDATE"; break;
107181e293b4Sdrh     case SQLITE_ATTACH            : zCode="SQLITE_ATTACH"; break;
107281e293b4Sdrh     case SQLITE_DETACH            : zCode="SQLITE_DETACH"; break;
10731c8c23ccSdanielk1977     case SQLITE_ALTER_TABLE       : zCode="SQLITE_ALTER_TABLE"; break;
10741d54df88Sdanielk1977     case SQLITE_REINDEX           : zCode="SQLITE_REINDEX"; break;
1075e6e04969Sdrh     case SQLITE_ANALYZE           : zCode="SQLITE_ANALYZE"; break;
1076f1a381e7Sdanielk1977     case SQLITE_CREATE_VTABLE     : zCode="SQLITE_CREATE_VTABLE"; break;
1077f1a381e7Sdanielk1977     case SQLITE_DROP_VTABLE       : zCode="SQLITE_DROP_VTABLE"; break;
10785169bbc6Sdrh     case SQLITE_FUNCTION          : zCode="SQLITE_FUNCTION"; break;
1079ab9b703fSdanielk1977     case SQLITE_SAVEPOINT         : zCode="SQLITE_SAVEPOINT"; break;
108065a2aaa6Sdrh     case SQLITE_RECURSIVE         : zCode="SQLITE_RECURSIVE"; break;
1081e22a334bSdrh     default                       : zCode="????"; break;
1082e22a334bSdrh   }
1083e22a334bSdrh   Tcl_DStringInit(&str);
1084e22a334bSdrh   Tcl_DStringAppend(&str, pDb->zAuth, -1);
1085e22a334bSdrh   Tcl_DStringAppendElement(&str, zCode);
1086e22a334bSdrh   Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
1087e22a334bSdrh   Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
1088e22a334bSdrh   Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
1089e22a334bSdrh   Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
109032c6a48bSdrh #ifdef SQLITE_USER_AUTHENTICATION
109132c6a48bSdrh   Tcl_DStringAppendElement(&str, zArg5 ? zArg5 : "");
109232c6a48bSdrh #endif
1093e22a334bSdrh   rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
1094e22a334bSdrh   Tcl_DStringFree(&str);
1095b07028f7Sdrh   zReply = rc==TCL_OK ? Tcl_GetStringResult(pDb->interp) : "SQLITE_DENY";
1096e22a334bSdrh   if( strcmp(zReply,"SQLITE_OK")==0 ){
1097e22a334bSdrh     rc = SQLITE_OK;
1098e22a334bSdrh   }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
1099e22a334bSdrh     rc = SQLITE_DENY;
1100e22a334bSdrh   }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
1101e22a334bSdrh     rc = SQLITE_IGNORE;
1102e22a334bSdrh   }else{
1103e22a334bSdrh     rc = 999;
1104e22a334bSdrh   }
1105e22a334bSdrh   return rc;
1106e22a334bSdrh }
1107e22a334bSdrh #endif /* SQLITE_OMIT_AUTHORIZATION */
1108cabb0819Sdrh 
1109cabb0819Sdrh /*
11101067fe11Stpoindex ** This routine reads a line of text from FILE in, stores
11111067fe11Stpoindex ** the text in memory obtained from malloc() and returns a pointer
11121067fe11Stpoindex ** to the text.  NULL is returned at end of file, or if malloc()
11131067fe11Stpoindex ** fails.
11141067fe11Stpoindex **
11151067fe11Stpoindex ** The interface is like "readline" but no command-line editing
11161067fe11Stpoindex ** is done.
11171067fe11Stpoindex **
11181067fe11Stpoindex ** copied from shell.c from '.import' command
11191067fe11Stpoindex */
11201067fe11Stpoindex static char *local_getline(char *zPrompt, FILE *in){
11211067fe11Stpoindex   char *zLine;
11221067fe11Stpoindex   int nLine;
11231067fe11Stpoindex   int n;
11241067fe11Stpoindex 
11251067fe11Stpoindex   nLine = 100;
11261067fe11Stpoindex   zLine = malloc( nLine );
11271067fe11Stpoindex   if( zLine==0 ) return 0;
11281067fe11Stpoindex   n = 0;
1129b07028f7Sdrh   while( 1 ){
11301067fe11Stpoindex     if( n+100>nLine ){
11311067fe11Stpoindex       nLine = nLine*2 + 100;
11321067fe11Stpoindex       zLine = realloc(zLine, nLine);
11331067fe11Stpoindex       if( zLine==0 ) return 0;
11341067fe11Stpoindex     }
11351067fe11Stpoindex     if( fgets(&zLine[n], nLine - n, in)==0 ){
11361067fe11Stpoindex       if( n==0 ){
11371067fe11Stpoindex         free(zLine);
11381067fe11Stpoindex         return 0;
11391067fe11Stpoindex       }
11401067fe11Stpoindex       zLine[n] = 0;
11411067fe11Stpoindex       break;
11421067fe11Stpoindex     }
11431067fe11Stpoindex     while( zLine[n] ){ n++; }
11441067fe11Stpoindex     if( n>0 && zLine[n-1]=='\n' ){
11451067fe11Stpoindex       n--;
11461067fe11Stpoindex       zLine[n] = 0;
1147b07028f7Sdrh       break;
11481067fe11Stpoindex     }
11491067fe11Stpoindex   }
11501067fe11Stpoindex   zLine = realloc( zLine, n+1 );
11511067fe11Stpoindex   return zLine;
11521067fe11Stpoindex }
11531067fe11Stpoindex 
11548e556520Sdanielk1977 
11558e556520Sdanielk1977 /*
11564a4c11aaSdan ** This function is part of the implementation of the command:
11578e556520Sdanielk1977 **
11584a4c11aaSdan **   $db transaction [-deferred|-immediate|-exclusive] SCRIPT
11598e556520Sdanielk1977 **
11604a4c11aaSdan ** It is invoked after evaluating the script SCRIPT to commit or rollback
11614a4c11aaSdan ** the transaction or savepoint opened by the [transaction] command.
11624a4c11aaSdan */
1163a121cc7cSmistachkin static int SQLITE_TCLAPI DbTransPostCmd(
11644a4c11aaSdan   ClientData data[],                   /* data[0] is the Sqlite3Db* for $db */
11654a4c11aaSdan   Tcl_Interp *interp,                  /* Tcl interpreter */
11664a4c11aaSdan   int result                           /* Result of evaluating SCRIPT */
11674a4c11aaSdan ){
11686ef5e12eSmistachkin   static const char *const azEnd[] = {
11694a4c11aaSdan     "RELEASE _tcl_transaction",        /* rc==TCL_ERROR, nTransaction!=0 */
11704a4c11aaSdan     "COMMIT",                          /* rc!=TCL_ERROR, nTransaction==0 */
11714a4c11aaSdan     "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction",
11724a4c11aaSdan     "ROLLBACK"                         /* rc==TCL_ERROR, nTransaction==0 */
11734a4c11aaSdan   };
11744a4c11aaSdan   SqliteDb *pDb = (SqliteDb*)data[0];
11754a4c11aaSdan   int rc = result;
11764a4c11aaSdan   const char *zEnd;
11774a4c11aaSdan 
11784a4c11aaSdan   pDb->nTransaction--;
11794a4c11aaSdan   zEnd = azEnd[(rc==TCL_ERROR)*2 + (pDb->nTransaction==0)];
11804a4c11aaSdan 
11814a4c11aaSdan   pDb->disableAuth++;
11824a4c11aaSdan   if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){
11834a4c11aaSdan       /* This is a tricky scenario to handle. The most likely cause of an
11844a4c11aaSdan       ** error is that the exec() above was an attempt to commit the
11854a4c11aaSdan       ** top-level transaction that returned SQLITE_BUSY. Or, less likely,
118648864df9Smistachkin       ** that an IO-error has occurred. In either case, throw a Tcl exception
11874a4c11aaSdan       ** and try to rollback the transaction.
11884a4c11aaSdan       **
11894a4c11aaSdan       ** But it could also be that the user executed one or more BEGIN,
11904a4c11aaSdan       ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing
11914a4c11aaSdan       ** this method's logic. Not clear how this would be best handled.
11924a4c11aaSdan       */
11934a4c11aaSdan     if( rc!=TCL_ERROR ){
1194a198f2b5Sdrh       Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
11954a4c11aaSdan       rc = TCL_ERROR;
11964a4c11aaSdan     }
11974a4c11aaSdan     sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
11984a4c11aaSdan   }
11994a4c11aaSdan   pDb->disableAuth--;
12004a4c11aaSdan 
12014a4c11aaSdan   return rc;
12024a4c11aaSdan }
12034a4c11aaSdan 
12044a4c11aaSdan /*
1205c431fd55Sdan ** Unless SQLITE_TEST is defined, this function is a simple wrapper around
1206c431fd55Sdan ** sqlite3_prepare_v2(). If SQLITE_TEST is defined, then it uses either
1207c431fd55Sdan ** sqlite3_prepare_v2() or legacy interface sqlite3_prepare(), depending
1208c431fd55Sdan ** on whether or not the [db_use_legacy_prepare] command has been used to
1209c431fd55Sdan ** configure the connection.
1210c431fd55Sdan */
1211c431fd55Sdan static int dbPrepare(
1212c431fd55Sdan   SqliteDb *pDb,                  /* Database object */
1213c431fd55Sdan   const char *zSql,               /* SQL to compile */
1214c431fd55Sdan   sqlite3_stmt **ppStmt,          /* OUT: Prepared statement */
1215c431fd55Sdan   const char **pzOut              /* OUT: Pointer to next SQL statement */
1216c431fd55Sdan ){
1217*2c2f392dSdrh   unsigned int prepFlags = 0;
1218c431fd55Sdan #ifdef SQLITE_TEST
1219c431fd55Sdan   if( pDb->bLegacyPrepare ){
1220c431fd55Sdan     return sqlite3_prepare(pDb->db, zSql, -1, ppStmt, pzOut);
1221c431fd55Sdan   }
1222c431fd55Sdan #endif
1223*2c2f392dSdrh   /* If the statement cache is large, use the SQLITE_PREPARE_PERSISTENT
1224*2c2f392dSdrh   ** flags, which uses less lookaside memory.  But if the cache is small,
1225*2c2f392dSdrh   ** omit that flag to make full use of lookaside */
1226*2c2f392dSdrh   if( pDb->maxStmt>5 ) prepFlags = SQLITE_PREPARE_PERSISTENT;
1227*2c2f392dSdrh 
1228*2c2f392dSdrh   return sqlite3_prepare_v3(pDb->db, zSql, -1, prepFlags, ppStmt, pzOut);
1229c431fd55Sdan }
1230c431fd55Sdan 
1231c431fd55Sdan /*
12324a4c11aaSdan ** Search the cache for a prepared-statement object that implements the
12334a4c11aaSdan ** first SQL statement in the buffer pointed to by parameter zIn. If
12344a4c11aaSdan ** no such prepared-statement can be found, allocate and prepare a new
12354a4c11aaSdan ** one. In either case, bind the current values of the relevant Tcl
12364a4c11aaSdan ** variables to any $var, :var or @var variables in the statement. Before
12374a4c11aaSdan ** returning, set *ppPreStmt to point to the prepared-statement object.
12384a4c11aaSdan **
12394a4c11aaSdan ** Output parameter *pzOut is set to point to the next SQL statement in
12404a4c11aaSdan ** buffer zIn, or to the '\0' byte at the end of zIn if there is no
12414a4c11aaSdan ** next statement.
12424a4c11aaSdan **
12434a4c11aaSdan ** If successful, TCL_OK is returned. Otherwise, TCL_ERROR is returned
12444a4c11aaSdan ** and an error message loaded into interpreter pDb->interp.
12454a4c11aaSdan */
12464a4c11aaSdan static int dbPrepareAndBind(
12474a4c11aaSdan   SqliteDb *pDb,                  /* Database object */
12484a4c11aaSdan   char const *zIn,                /* SQL to compile */
12494a4c11aaSdan   char const **pzOut,             /* OUT: Pointer to next SQL statement */
12504a4c11aaSdan   SqlPreparedStmt **ppPreStmt     /* OUT: Object used to cache statement */
12514a4c11aaSdan ){
12524a4c11aaSdan   const char *zSql = zIn;         /* Pointer to first SQL statement in zIn */
12537bb22ac7Smistachkin   sqlite3_stmt *pStmt = 0;        /* Prepared statement object */
12544a4c11aaSdan   SqlPreparedStmt *pPreStmt;      /* Pointer to cached statement */
12554a4c11aaSdan   int nSql;                       /* Length of zSql in bytes */
12567bb22ac7Smistachkin   int nVar = 0;                   /* Number of variables in statement */
12574a4c11aaSdan   int iParm = 0;                  /* Next free entry in apParm */
12580425f189Sdrh   char c;
12594a4c11aaSdan   int i;
12604a4c11aaSdan   Tcl_Interp *interp = pDb->interp;
12614a4c11aaSdan 
12624a4c11aaSdan   *ppPreStmt = 0;
12634a4c11aaSdan 
12644a4c11aaSdan   /* Trim spaces from the start of zSql and calculate the remaining length. */
12650425f189Sdrh   while( (c = zSql[0])==' ' || c=='\t' || c=='\r' || c=='\n' ){ zSql++; }
12664a4c11aaSdan   nSql = strlen30(zSql);
12674a4c11aaSdan 
12684a4c11aaSdan   for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pPreStmt->pNext){
12694a4c11aaSdan     int n = pPreStmt->nSql;
12704a4c11aaSdan     if( nSql>=n
12714a4c11aaSdan         && memcmp(pPreStmt->zSql, zSql, n)==0
12724a4c11aaSdan         && (zSql[n]==0 || zSql[n-1]==';')
12734a4c11aaSdan     ){
12744a4c11aaSdan       pStmt = pPreStmt->pStmt;
12754a4c11aaSdan       *pzOut = &zSql[pPreStmt->nSql];
12764a4c11aaSdan 
12774a4c11aaSdan       /* When a prepared statement is found, unlink it from the
12784a4c11aaSdan       ** cache list.  It will later be added back to the beginning
12794a4c11aaSdan       ** of the cache list in order to implement LRU replacement.
12804a4c11aaSdan       */
12814a4c11aaSdan       if( pPreStmt->pPrev ){
12824a4c11aaSdan         pPreStmt->pPrev->pNext = pPreStmt->pNext;
12834a4c11aaSdan       }else{
12844a4c11aaSdan         pDb->stmtList = pPreStmt->pNext;
12854a4c11aaSdan       }
12864a4c11aaSdan       if( pPreStmt->pNext ){
12874a4c11aaSdan         pPreStmt->pNext->pPrev = pPreStmt->pPrev;
12884a4c11aaSdan       }else{
12894a4c11aaSdan         pDb->stmtLast = pPreStmt->pPrev;
12904a4c11aaSdan       }
12914a4c11aaSdan       pDb->nStmt--;
12924a4c11aaSdan       nVar = sqlite3_bind_parameter_count(pStmt);
12934a4c11aaSdan       break;
12944a4c11aaSdan     }
12954a4c11aaSdan   }
12964a4c11aaSdan 
12974a4c11aaSdan   /* If no prepared statement was found. Compile the SQL text. Also allocate
12984a4c11aaSdan   ** a new SqlPreparedStmt structure.  */
12994a4c11aaSdan   if( pPreStmt==0 ){
13004a4c11aaSdan     int nByte;
13014a4c11aaSdan 
1302c431fd55Sdan     if( SQLITE_OK!=dbPrepare(pDb, zSql, &pStmt, pzOut) ){
1303c45e6716Sdrh       Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
13044a4c11aaSdan       return TCL_ERROR;
13054a4c11aaSdan     }
13064a4c11aaSdan     if( pStmt==0 ){
13074a4c11aaSdan       if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
13084a4c11aaSdan         /* A compile-time error in the statement. */
1309c45e6716Sdrh         Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
13104a4c11aaSdan         return TCL_ERROR;
13114a4c11aaSdan       }else{
13124a4c11aaSdan         /* The statement was a no-op.  Continue to the next statement
13134a4c11aaSdan         ** in the SQL string.
13144a4c11aaSdan         */
13154a4c11aaSdan         return TCL_OK;
13164a4c11aaSdan       }
13174a4c11aaSdan     }
13184a4c11aaSdan 
13194a4c11aaSdan     assert( pPreStmt==0 );
13204a4c11aaSdan     nVar = sqlite3_bind_parameter_count(pStmt);
13214a4c11aaSdan     nByte = sizeof(SqlPreparedStmt) + nVar*sizeof(Tcl_Obj *);
13224a4c11aaSdan     pPreStmt = (SqlPreparedStmt*)Tcl_Alloc(nByte);
13234a4c11aaSdan     memset(pPreStmt, 0, nByte);
13244a4c11aaSdan 
13254a4c11aaSdan     pPreStmt->pStmt = pStmt;
13267ed243b7Sdrh     pPreStmt->nSql = (int)(*pzOut - zSql);
13274a4c11aaSdan     pPreStmt->zSql = sqlite3_sql(pStmt);
13284a4c11aaSdan     pPreStmt->apParm = (Tcl_Obj **)&pPreStmt[1];
1329c431fd55Sdan #ifdef SQLITE_TEST
1330c431fd55Sdan     if( pPreStmt->zSql==0 ){
1331c431fd55Sdan       char *zCopy = Tcl_Alloc(pPreStmt->nSql + 1);
1332c431fd55Sdan       memcpy(zCopy, zSql, pPreStmt->nSql);
1333c431fd55Sdan       zCopy[pPreStmt->nSql] = '\0';
1334c431fd55Sdan       pPreStmt->zSql = zCopy;
1335c431fd55Sdan     }
1336c431fd55Sdan #endif
13374a4c11aaSdan   }
13384a4c11aaSdan   assert( pPreStmt );
13394a4c11aaSdan   assert( strlen30(pPreStmt->zSql)==pPreStmt->nSql );
13404a4c11aaSdan   assert( 0==memcmp(pPreStmt->zSql, zSql, pPreStmt->nSql) );
13414a4c11aaSdan 
13424a4c11aaSdan   /* Bind values to parameters that begin with $ or : */
13434a4c11aaSdan   for(i=1; i<=nVar; i++){
13444a4c11aaSdan     const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
13454a4c11aaSdan     if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){
13464a4c11aaSdan       Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
13474a4c11aaSdan       if( pVar ){
13484a4c11aaSdan         int n;
13494a4c11aaSdan         u8 *data;
13504a4c11aaSdan         const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
13518e18922fSmistachkin         c = zType[0];
13524a4c11aaSdan         if( zVar[0]=='@' ||
13534a4c11aaSdan            (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){
13544a4c11aaSdan           /* Load a BLOB type if the Tcl variable is a bytearray and
13554a4c11aaSdan           ** it has no string representation or the host
13564a4c11aaSdan           ** parameter name begins with "@". */
13574a4c11aaSdan           data = Tcl_GetByteArrayFromObj(pVar, &n);
13584a4c11aaSdan           sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
13594a4c11aaSdan           Tcl_IncrRefCount(pVar);
13604a4c11aaSdan           pPreStmt->apParm[iParm++] = pVar;
13614a4c11aaSdan         }else if( c=='b' && strcmp(zType,"boolean")==0 ){
13624a4c11aaSdan           Tcl_GetIntFromObj(interp, pVar, &n);
13634a4c11aaSdan           sqlite3_bind_int(pStmt, i, n);
13644a4c11aaSdan         }else if( c=='d' && strcmp(zType,"double")==0 ){
13654a4c11aaSdan           double r;
13664a4c11aaSdan           Tcl_GetDoubleFromObj(interp, pVar, &r);
13674a4c11aaSdan           sqlite3_bind_double(pStmt, i, r);
13684a4c11aaSdan         }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
13694a4c11aaSdan               (c=='i' && strcmp(zType,"int")==0) ){
13704a4c11aaSdan           Tcl_WideInt v;
13714a4c11aaSdan           Tcl_GetWideIntFromObj(interp, pVar, &v);
13724a4c11aaSdan           sqlite3_bind_int64(pStmt, i, v);
13734a4c11aaSdan         }else{
13744a4c11aaSdan           data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
13754a4c11aaSdan           sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
13764a4c11aaSdan           Tcl_IncrRefCount(pVar);
13774a4c11aaSdan           pPreStmt->apParm[iParm++] = pVar;
13784a4c11aaSdan         }
13794a4c11aaSdan       }else{
13804a4c11aaSdan         sqlite3_bind_null(pStmt, i);
13814a4c11aaSdan       }
13824a4c11aaSdan     }
13834a4c11aaSdan   }
13844a4c11aaSdan   pPreStmt->nParm = iParm;
13854a4c11aaSdan   *ppPreStmt = pPreStmt;
1386937d0deaSdan 
13874a4c11aaSdan   return TCL_OK;
13884a4c11aaSdan }
13894a4c11aaSdan 
13904a4c11aaSdan /*
13914a4c11aaSdan ** Release a statement reference obtained by calling dbPrepareAndBind().
13924a4c11aaSdan ** There should be exactly one call to this function for each call to
13934a4c11aaSdan ** dbPrepareAndBind().
13944a4c11aaSdan **
13954a4c11aaSdan ** If the discard parameter is non-zero, then the statement is deleted
13964a4c11aaSdan ** immediately. Otherwise it is added to the LRU list and may be returned
13974a4c11aaSdan ** by a subsequent call to dbPrepareAndBind().
13984a4c11aaSdan */
13994a4c11aaSdan static void dbReleaseStmt(
14004a4c11aaSdan   SqliteDb *pDb,                  /* Database handle */
14014a4c11aaSdan   SqlPreparedStmt *pPreStmt,      /* Prepared statement handle to release */
14024a4c11aaSdan   int discard                     /* True to delete (not cache) the pPreStmt */
14034a4c11aaSdan ){
14044a4c11aaSdan   int i;
14054a4c11aaSdan 
14064a4c11aaSdan   /* Free the bound string and blob parameters */
14074a4c11aaSdan   for(i=0; i<pPreStmt->nParm; i++){
14084a4c11aaSdan     Tcl_DecrRefCount(pPreStmt->apParm[i]);
14094a4c11aaSdan   }
14104a4c11aaSdan   pPreStmt->nParm = 0;
14114a4c11aaSdan 
14124a4c11aaSdan   if( pDb->maxStmt<=0 || discard ){
14134a4c11aaSdan     /* If the cache is turned off, deallocated the statement */
1414c431fd55Sdan     dbFreeStmt(pPreStmt);
14154a4c11aaSdan   }else{
14164a4c11aaSdan     /* Add the prepared statement to the beginning of the cache list. */
14174a4c11aaSdan     pPreStmt->pNext = pDb->stmtList;
14184a4c11aaSdan     pPreStmt->pPrev = 0;
14194a4c11aaSdan     if( pDb->stmtList ){
14204a4c11aaSdan      pDb->stmtList->pPrev = pPreStmt;
14214a4c11aaSdan     }
14224a4c11aaSdan     pDb->stmtList = pPreStmt;
14234a4c11aaSdan     if( pDb->stmtLast==0 ){
14244a4c11aaSdan       assert( pDb->nStmt==0 );
14254a4c11aaSdan       pDb->stmtLast = pPreStmt;
14264a4c11aaSdan     }else{
14274a4c11aaSdan       assert( pDb->nStmt>0 );
14284a4c11aaSdan     }
14294a4c11aaSdan     pDb->nStmt++;
14304a4c11aaSdan 
14314a4c11aaSdan     /* If we have too many statement in cache, remove the surplus from
14324a4c11aaSdan     ** the end of the cache list.  */
14334a4c11aaSdan     while( pDb->nStmt>pDb->maxStmt ){
1434c431fd55Sdan       SqlPreparedStmt *pLast = pDb->stmtLast;
1435c431fd55Sdan       pDb->stmtLast = pLast->pPrev;
14364a4c11aaSdan       pDb->stmtLast->pNext = 0;
14374a4c11aaSdan       pDb->nStmt--;
1438c431fd55Sdan       dbFreeStmt(pLast);
14394a4c11aaSdan     }
14404a4c11aaSdan   }
14414a4c11aaSdan }
14424a4c11aaSdan 
14434a4c11aaSdan /*
14444a4c11aaSdan ** Structure used with dbEvalXXX() functions:
14454a4c11aaSdan **
14464a4c11aaSdan **   dbEvalInit()
14474a4c11aaSdan **   dbEvalStep()
14484a4c11aaSdan **   dbEvalFinalize()
14494a4c11aaSdan **   dbEvalRowInfo()
14504a4c11aaSdan **   dbEvalColumnValue()
14514a4c11aaSdan */
14524a4c11aaSdan typedef struct DbEvalContext DbEvalContext;
14534a4c11aaSdan struct DbEvalContext {
14544a4c11aaSdan   SqliteDb *pDb;                  /* Database handle */
14554a4c11aaSdan   Tcl_Obj *pSql;                  /* Object holding string zSql */
14564a4c11aaSdan   const char *zSql;               /* Remaining SQL to execute */
14574a4c11aaSdan   SqlPreparedStmt *pPreStmt;      /* Current statement */
14584a4c11aaSdan   int nCol;                       /* Number of columns returned by pStmt */
14594a4c11aaSdan   Tcl_Obj *pArray;                /* Name of array variable */
14604a4c11aaSdan   Tcl_Obj **apColName;            /* Array of column names */
14614a4c11aaSdan };
14624a4c11aaSdan 
14634a4c11aaSdan /*
14644a4c11aaSdan ** Release any cache of column names currently held as part of
14654a4c11aaSdan ** the DbEvalContext structure passed as the first argument.
14664a4c11aaSdan */
14674a4c11aaSdan static void dbReleaseColumnNames(DbEvalContext *p){
14684a4c11aaSdan   if( p->apColName ){
14694a4c11aaSdan     int i;
14704a4c11aaSdan     for(i=0; i<p->nCol; i++){
14714a4c11aaSdan       Tcl_DecrRefCount(p->apColName[i]);
14724a4c11aaSdan     }
14734a4c11aaSdan     Tcl_Free((char *)p->apColName);
14744a4c11aaSdan     p->apColName = 0;
14754a4c11aaSdan   }
14764a4c11aaSdan   p->nCol = 0;
14774a4c11aaSdan }
14784a4c11aaSdan 
14794a4c11aaSdan /*
14804a4c11aaSdan ** Initialize a DbEvalContext structure.
14818e556520Sdanielk1977 **
14828e556520Sdanielk1977 ** If pArray is not NULL, then it contains the name of a Tcl array
14838e556520Sdanielk1977 ** variable. The "*" member of this array is set to a list containing
14844a4c11aaSdan ** the names of the columns returned by the statement as part of each
14854a4c11aaSdan ** call to dbEvalStep(), in order from left to right. e.g. if the names
14864a4c11aaSdan ** of the returned columns are a, b and c, it does the equivalent of the
14874a4c11aaSdan ** tcl command:
14888e556520Sdanielk1977 **
14898e556520Sdanielk1977 **     set ${pArray}(*) {a b c}
14908e556520Sdanielk1977 */
14914a4c11aaSdan static void dbEvalInit(
14924a4c11aaSdan   DbEvalContext *p,               /* Pointer to structure to initialize */
14934a4c11aaSdan   SqliteDb *pDb,                  /* Database handle */
14944a4c11aaSdan   Tcl_Obj *pSql,                  /* Object containing SQL script */
14954a4c11aaSdan   Tcl_Obj *pArray                 /* Name of Tcl array to set (*) element of */
14968e556520Sdanielk1977 ){
14974a4c11aaSdan   memset(p, 0, sizeof(DbEvalContext));
14984a4c11aaSdan   p->pDb = pDb;
14994a4c11aaSdan   p->zSql = Tcl_GetString(pSql);
15004a4c11aaSdan   p->pSql = pSql;
15014a4c11aaSdan   Tcl_IncrRefCount(pSql);
15024a4c11aaSdan   if( pArray ){
15034a4c11aaSdan     p->pArray = pArray;
15044a4c11aaSdan     Tcl_IncrRefCount(pArray);
15054a4c11aaSdan   }
15064a4c11aaSdan }
15078e556520Sdanielk1977 
15084a4c11aaSdan /*
15094a4c11aaSdan ** Obtain information about the row that the DbEvalContext passed as the
15104a4c11aaSdan ** first argument currently points to.
15114a4c11aaSdan */
15124a4c11aaSdan static void dbEvalRowInfo(
15134a4c11aaSdan   DbEvalContext *p,               /* Evaluation context */
15144a4c11aaSdan   int *pnCol,                     /* OUT: Number of column names */
15154a4c11aaSdan   Tcl_Obj ***papColName           /* OUT: Array of column names */
15164a4c11aaSdan ){
15178e556520Sdanielk1977   /* Compute column names */
15184a4c11aaSdan   if( 0==p->apColName ){
15194a4c11aaSdan     sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
15204a4c11aaSdan     int i;                        /* Iterator variable */
15214a4c11aaSdan     int nCol;                     /* Number of columns returned by pStmt */
15224a4c11aaSdan     Tcl_Obj **apColName = 0;      /* Array of column names */
15234a4c11aaSdan 
15244a4c11aaSdan     p->nCol = nCol = sqlite3_column_count(pStmt);
15254a4c11aaSdan     if( nCol>0 && (papColName || p->pArray) ){
15264a4c11aaSdan       apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
15278e556520Sdanielk1977       for(i=0; i<nCol; i++){
1528c45e6716Sdrh         apColName[i] = Tcl_NewStringObj(sqlite3_column_name(pStmt,i), -1);
15298e556520Sdanielk1977         Tcl_IncrRefCount(apColName[i]);
15308e556520Sdanielk1977       }
15314a4c11aaSdan       p->apColName = apColName;
15324a4c11aaSdan     }
15338e556520Sdanielk1977 
15348e556520Sdanielk1977     /* If results are being stored in an array variable, then create
15358e556520Sdanielk1977     ** the array(*) entry for that array
15368e556520Sdanielk1977     */
15374a4c11aaSdan     if( p->pArray ){
15384a4c11aaSdan       Tcl_Interp *interp = p->pDb->interp;
15398e556520Sdanielk1977       Tcl_Obj *pColList = Tcl_NewObj();
15408e556520Sdanielk1977       Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
15414a4c11aaSdan 
15428e556520Sdanielk1977       for(i=0; i<nCol; i++){
15438e556520Sdanielk1977         Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
15448e556520Sdanielk1977       }
15458e556520Sdanielk1977       Tcl_IncrRefCount(pStar);
15464a4c11aaSdan       Tcl_ObjSetVar2(interp, p->pArray, pStar, pColList, 0);
15478e556520Sdanielk1977       Tcl_DecrRefCount(pStar);
15488e556520Sdanielk1977     }
15498e556520Sdanielk1977   }
15508e556520Sdanielk1977 
15514a4c11aaSdan   if( papColName ){
15524a4c11aaSdan     *papColName = p->apColName;
15534a4c11aaSdan   }
15544a4c11aaSdan   if( pnCol ){
15554a4c11aaSdan     *pnCol = p->nCol;
15564a4c11aaSdan   }
15574a4c11aaSdan }
15584a4c11aaSdan 
15594a4c11aaSdan /*
15604a4c11aaSdan ** Return one of TCL_OK, TCL_BREAK or TCL_ERROR. If TCL_ERROR is
15614a4c11aaSdan ** returned, then an error message is stored in the interpreter before
15624a4c11aaSdan ** returning.
15634a4c11aaSdan **
15644a4c11aaSdan ** A return value of TCL_OK means there is a row of data available. The
15654a4c11aaSdan ** data may be accessed using dbEvalRowInfo() and dbEvalColumnValue(). This
15664a4c11aaSdan ** is analogous to a return of SQLITE_ROW from sqlite3_step(). If TCL_BREAK
15674a4c11aaSdan ** is returned, then the SQL script has finished executing and there are
15684a4c11aaSdan ** no further rows available. This is similar to SQLITE_DONE.
15694a4c11aaSdan */
15704a4c11aaSdan static int dbEvalStep(DbEvalContext *p){
1571c431fd55Sdan   const char *zPrevSql = 0;       /* Previous value of p->zSql */
1572c431fd55Sdan 
15734a4c11aaSdan   while( p->zSql[0] || p->pPreStmt ){
15744a4c11aaSdan     int rc;
15754a4c11aaSdan     if( p->pPreStmt==0 ){
1576c431fd55Sdan       zPrevSql = (p->zSql==zPrevSql ? 0 : p->zSql);
15774a4c11aaSdan       rc = dbPrepareAndBind(p->pDb, p->zSql, &p->zSql, &p->pPreStmt);
15784a4c11aaSdan       if( rc!=TCL_OK ) return rc;
15794a4c11aaSdan     }else{
15804a4c11aaSdan       int rcs;
15814a4c11aaSdan       SqliteDb *pDb = p->pDb;
15824a4c11aaSdan       SqlPreparedStmt *pPreStmt = p->pPreStmt;
15834a4c11aaSdan       sqlite3_stmt *pStmt = pPreStmt->pStmt;
15844a4c11aaSdan 
15854a4c11aaSdan       rcs = sqlite3_step(pStmt);
15864a4c11aaSdan       if( rcs==SQLITE_ROW ){
15874a4c11aaSdan         return TCL_OK;
15884a4c11aaSdan       }
15894a4c11aaSdan       if( p->pArray ){
15904a4c11aaSdan         dbEvalRowInfo(p, 0, 0);
15914a4c11aaSdan       }
15924a4c11aaSdan       rcs = sqlite3_reset(pStmt);
15934a4c11aaSdan 
15944a4c11aaSdan       pDb->nStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_FULLSCAN_STEP,1);
15954a4c11aaSdan       pDb->nSort = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_SORT,1);
15963c379b01Sdrh       pDb->nIndex = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_AUTOINDEX,1);
15974a4c11aaSdan       dbReleaseColumnNames(p);
15984a4c11aaSdan       p->pPreStmt = 0;
15994a4c11aaSdan 
16004a4c11aaSdan       if( rcs!=SQLITE_OK ){
16014a4c11aaSdan         /* If a run-time error occurs, report the error and stop reading
16024a4c11aaSdan         ** the SQL.  */
16034a4c11aaSdan         dbReleaseStmt(pDb, pPreStmt, 1);
1604c431fd55Sdan #if SQLITE_TEST
1605c431fd55Sdan         if( p->pDb->bLegacyPrepare && rcs==SQLITE_SCHEMA && zPrevSql ){
1606c431fd55Sdan           /* If the runtime error was an SQLITE_SCHEMA, and the database
1607c431fd55Sdan           ** handle is configured to use the legacy sqlite3_prepare()
1608c431fd55Sdan           ** interface, retry prepare()/step() on the same SQL statement.
1609c431fd55Sdan           ** This only happens once. If there is a second SQLITE_SCHEMA
1610c431fd55Sdan           ** error, the error will be returned to the caller. */
1611c431fd55Sdan           p->zSql = zPrevSql;
1612c431fd55Sdan           continue;
1613c431fd55Sdan         }
1614c431fd55Sdan #endif
1615c45e6716Sdrh         Tcl_SetObjResult(pDb->interp,
1616c45e6716Sdrh                          Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
16174a4c11aaSdan         return TCL_ERROR;
16184a4c11aaSdan       }else{
16194a4c11aaSdan         dbReleaseStmt(pDb, pPreStmt, 0);
16204a4c11aaSdan       }
16214a4c11aaSdan     }
16224a4c11aaSdan   }
16234a4c11aaSdan 
16244a4c11aaSdan   /* Finished */
16254a4c11aaSdan   return TCL_BREAK;
16264a4c11aaSdan }
16274a4c11aaSdan 
16284a4c11aaSdan /*
16294a4c11aaSdan ** Free all resources currently held by the DbEvalContext structure passed
16304a4c11aaSdan ** as the first argument. There should be exactly one call to this function
16314a4c11aaSdan ** for each call to dbEvalInit().
16324a4c11aaSdan */
16334a4c11aaSdan static void dbEvalFinalize(DbEvalContext *p){
16344a4c11aaSdan   if( p->pPreStmt ){
16354a4c11aaSdan     sqlite3_reset(p->pPreStmt->pStmt);
16364a4c11aaSdan     dbReleaseStmt(p->pDb, p->pPreStmt, 0);
16374a4c11aaSdan     p->pPreStmt = 0;
16384a4c11aaSdan   }
16394a4c11aaSdan   if( p->pArray ){
16404a4c11aaSdan     Tcl_DecrRefCount(p->pArray);
16414a4c11aaSdan     p->pArray = 0;
16424a4c11aaSdan   }
16434a4c11aaSdan   Tcl_DecrRefCount(p->pSql);
16444a4c11aaSdan   dbReleaseColumnNames(p);
16454a4c11aaSdan }
16464a4c11aaSdan 
16474a4c11aaSdan /*
16484a4c11aaSdan ** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains
16494a4c11aaSdan ** the value for the iCol'th column of the row currently pointed to by
16504a4c11aaSdan ** the DbEvalContext structure passed as the first argument.
16514a4c11aaSdan */
16524a4c11aaSdan static Tcl_Obj *dbEvalColumnValue(DbEvalContext *p, int iCol){
16534a4c11aaSdan   sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
16544a4c11aaSdan   switch( sqlite3_column_type(pStmt, iCol) ){
16554a4c11aaSdan     case SQLITE_BLOB: {
16564a4c11aaSdan       int bytes = sqlite3_column_bytes(pStmt, iCol);
16574a4c11aaSdan       const char *zBlob = sqlite3_column_blob(pStmt, iCol);
16584a4c11aaSdan       if( !zBlob ) bytes = 0;
16594a4c11aaSdan       return Tcl_NewByteArrayObj((u8*)zBlob, bytes);
16604a4c11aaSdan     }
16614a4c11aaSdan     case SQLITE_INTEGER: {
16624a4c11aaSdan       sqlite_int64 v = sqlite3_column_int64(pStmt, iCol);
16634a4c11aaSdan       if( v>=-2147483647 && v<=2147483647 ){
16647fd33929Sdrh         return Tcl_NewIntObj((int)v);
16654a4c11aaSdan       }else{
16664a4c11aaSdan         return Tcl_NewWideIntObj(v);
16674a4c11aaSdan       }
16684a4c11aaSdan     }
16694a4c11aaSdan     case SQLITE_FLOAT: {
16704a4c11aaSdan       return Tcl_NewDoubleObj(sqlite3_column_double(pStmt, iCol));
16714a4c11aaSdan     }
16724a4c11aaSdan     case SQLITE_NULL: {
1673c45e6716Sdrh       return Tcl_NewStringObj(p->pDb->zNull, -1);
16744a4c11aaSdan     }
16754a4c11aaSdan   }
16764a4c11aaSdan 
1677325eff58Sdrh   return Tcl_NewStringObj((char*)sqlite3_column_text(pStmt, iCol), -1);
16784a4c11aaSdan }
16794a4c11aaSdan 
16804a4c11aaSdan /*
16814a4c11aaSdan ** If using Tcl version 8.6 or greater, use the NR functions to avoid
16824a4c11aaSdan ** recursive evalution of scripts by the [db eval] and [db trans]
16834a4c11aaSdan ** commands. Even if the headers used while compiling the extension
16844a4c11aaSdan ** are 8.6 or newer, the code still tests the Tcl version at runtime.
16854a4c11aaSdan ** This allows stubs-enabled builds to be used with older Tcl libraries.
16864a4c11aaSdan */
16874a4c11aaSdan #if TCL_MAJOR_VERSION>8 || (TCL_MAJOR_VERSION==8 && TCL_MINOR_VERSION>=6)
1688a2c8a95bSdrh # define SQLITE_TCL_NRE 1
16894a4c11aaSdan static int DbUseNre(void){
16904a4c11aaSdan   int major, minor;
16914a4c11aaSdan   Tcl_GetVersion(&major, &minor, 0, 0);
16924a4c11aaSdan   return( (major==8 && minor>=6) || major>8 );
16934a4c11aaSdan }
16944a4c11aaSdan #else
16954a4c11aaSdan /*
16964a4c11aaSdan ** Compiling using headers earlier than 8.6. In this case NR cannot be
16974a4c11aaSdan ** used, so DbUseNre() to always return zero. Add #defines for the other
16984a4c11aaSdan ** Tcl_NRxxx() functions to prevent them from causing compilation errors,
16994a4c11aaSdan ** even though the only invocations of them are within conditional blocks
17004a4c11aaSdan ** of the form:
17014a4c11aaSdan **
17024a4c11aaSdan **   if( DbUseNre() ) { ... }
17034a4c11aaSdan */
1704a2c8a95bSdrh # define SQLITE_TCL_NRE 0
17054a4c11aaSdan # define DbUseNre() 0
1706a47941feSdrh # define Tcl_NRAddCallback(a,b,c,d,e,f) (void)0
17074a4c11aaSdan # define Tcl_NREvalObj(a,b,c) 0
1708a47941feSdrh # define Tcl_NRCreateCommand(a,b,c,d,e,f) (void)0
17094a4c11aaSdan #endif
17104a4c11aaSdan 
17114a4c11aaSdan /*
17124a4c11aaSdan ** This function is part of the implementation of the command:
17134a4c11aaSdan **
17144a4c11aaSdan **   $db eval SQL ?ARRAYNAME? SCRIPT
17154a4c11aaSdan */
1716a121cc7cSmistachkin static int SQLITE_TCLAPI DbEvalNextCmd(
17174a4c11aaSdan   ClientData data[],                   /* data[0] is the (DbEvalContext*) */
17184a4c11aaSdan   Tcl_Interp *interp,                  /* Tcl interpreter */
17194a4c11aaSdan   int result                           /* Result so far */
17204a4c11aaSdan ){
17214a4c11aaSdan   int rc = result;                     /* Return code */
17224a4c11aaSdan 
17234a4c11aaSdan   /* The first element of the data[] array is a pointer to a DbEvalContext
17244a4c11aaSdan   ** structure allocated using Tcl_Alloc(). The second element of data[]
17254a4c11aaSdan   ** is a pointer to a Tcl_Obj containing the script to run for each row
17264a4c11aaSdan   ** returned by the queries encapsulated in data[0]. */
17274a4c11aaSdan   DbEvalContext *p = (DbEvalContext *)data[0];
17284a4c11aaSdan   Tcl_Obj *pScript = (Tcl_Obj *)data[1];
17294a4c11aaSdan   Tcl_Obj *pArray = p->pArray;
17304a4c11aaSdan 
17314a4c11aaSdan   while( (rc==TCL_OK || rc==TCL_CONTINUE) && TCL_OK==(rc = dbEvalStep(p)) ){
17324a4c11aaSdan     int i;
17334a4c11aaSdan     int nCol;
17344a4c11aaSdan     Tcl_Obj **apColName;
17354a4c11aaSdan     dbEvalRowInfo(p, &nCol, &apColName);
17364a4c11aaSdan     for(i=0; i<nCol; i++){
17374a4c11aaSdan       Tcl_Obj *pVal = dbEvalColumnValue(p, i);
17384a4c11aaSdan       if( pArray==0 ){
17394a4c11aaSdan         Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
17404a4c11aaSdan       }else{
17414a4c11aaSdan         Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
17424a4c11aaSdan       }
17434a4c11aaSdan     }
17444a4c11aaSdan 
17454a4c11aaSdan     /* The required interpreter variables are now populated with the data
17464a4c11aaSdan     ** from the current row. If using NRE, schedule callbacks to evaluate
17474a4c11aaSdan     ** script pScript, then to invoke this function again to fetch the next
17484a4c11aaSdan     ** row (or clean up if there is no next row or the script throws an
17494a4c11aaSdan     ** exception). After scheduling the callbacks, return control to the
17504a4c11aaSdan     ** caller.
17514a4c11aaSdan     **
17524a4c11aaSdan     ** If not using NRE, evaluate pScript directly and continue with the
17534a4c11aaSdan     ** next iteration of this while(...) loop.  */
17544a4c11aaSdan     if( DbUseNre() ){
17554a4c11aaSdan       Tcl_NRAddCallback(interp, DbEvalNextCmd, (void*)p, (void*)pScript, 0, 0);
17564a4c11aaSdan       return Tcl_NREvalObj(interp, pScript, 0);
17574a4c11aaSdan     }else{
17584a4c11aaSdan       rc = Tcl_EvalObjEx(interp, pScript, 0);
17594a4c11aaSdan     }
17604a4c11aaSdan   }
17614a4c11aaSdan 
17624a4c11aaSdan   Tcl_DecrRefCount(pScript);
17634a4c11aaSdan   dbEvalFinalize(p);
17644a4c11aaSdan   Tcl_Free((char *)p);
17654a4c11aaSdan 
17664a4c11aaSdan   if( rc==TCL_OK || rc==TCL_BREAK ){
17674a4c11aaSdan     Tcl_ResetResult(interp);
17684a4c11aaSdan     rc = TCL_OK;
17694a4c11aaSdan   }
17704a4c11aaSdan   return rc;
17718e556520Sdanielk1977 }
17728e556520Sdanielk1977 
17731067fe11Stpoindex /*
177446c47d46Sdan ** This function is used by the implementations of the following database
177546c47d46Sdan ** handle sub-commands:
177646c47d46Sdan **
177746c47d46Sdan **   $db update_hook ?SCRIPT?
177846c47d46Sdan **   $db wal_hook ?SCRIPT?
177946c47d46Sdan **   $db commit_hook ?SCRIPT?
178046c47d46Sdan **   $db preupdate hook ?SCRIPT?
178146c47d46Sdan */
178246c47d46Sdan static void DbHookCmd(
178346c47d46Sdan   Tcl_Interp *interp,             /* Tcl interpreter */
178446c47d46Sdan   SqliteDb *pDb,                  /* Database handle */
178546c47d46Sdan   Tcl_Obj *pArg,                  /* SCRIPT argument (or NULL) */
178646c47d46Sdan   Tcl_Obj **ppHook                /* Pointer to member of SqliteDb */
178746c47d46Sdan ){
178846c47d46Sdan   sqlite3 *db = pDb->db;
178946c47d46Sdan 
179046c47d46Sdan   if( *ppHook ){
179146c47d46Sdan     Tcl_SetObjResult(interp, *ppHook);
179246c47d46Sdan     if( pArg ){
179346c47d46Sdan       Tcl_DecrRefCount(*ppHook);
179446c47d46Sdan       *ppHook = 0;
179546c47d46Sdan     }
179646c47d46Sdan   }
179746c47d46Sdan   if( pArg ){
179846c47d46Sdan     assert( !(*ppHook) );
179946c47d46Sdan     if( Tcl_GetCharLength(pArg)>0 ){
180046c47d46Sdan       *ppHook = pArg;
180146c47d46Sdan       Tcl_IncrRefCount(*ppHook);
180246c47d46Sdan     }
180346c47d46Sdan   }
180446c47d46Sdan 
18059b1c62d4Sdrh #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
180646c47d46Sdan   sqlite3_preupdate_hook(db, (pDb->pPreUpdateHook?DbPreUpdateHandler:0), pDb);
18079b1c62d4Sdrh #endif
180846c47d46Sdan   sqlite3_update_hook(db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
180946c47d46Sdan   sqlite3_rollback_hook(db, (pDb->pRollbackHook?DbRollbackHandler:0), pDb);
181046c47d46Sdan   sqlite3_wal_hook(db, (pDb->pWalHook?DbWalHandler:0), pDb);
181146c47d46Sdan }
181246c47d46Sdan 
181346c47d46Sdan /*
181475897234Sdrh ** The "sqlite" command below creates a new Tcl command for each
181575897234Sdrh ** connection it opens to an SQLite database.  This routine is invoked
181675897234Sdrh ** whenever one of those connection-specific commands is executed
181775897234Sdrh ** in Tcl.  For example, if you run Tcl code like this:
181875897234Sdrh **
18199bb575fdSdrh **       sqlite3 db1  "my_database"
182075897234Sdrh **       db1 close
182175897234Sdrh **
182275897234Sdrh ** The first command opens a connection to the "my_database" database
182375897234Sdrh ** and calls that connection "db1".  The second command causes this
182475897234Sdrh ** subroutine to be invoked.
182575897234Sdrh */
18267617e4a8Smistachkin static int SQLITE_TCLAPI DbObjCmd(
18277617e4a8Smistachkin   void *cd,
18287617e4a8Smistachkin   Tcl_Interp *interp,
18297617e4a8Smistachkin   int objc,
18307617e4a8Smistachkin   Tcl_Obj *const*objv
18317617e4a8Smistachkin ){
1832bec3f402Sdrh   SqliteDb *pDb = (SqliteDb*)cd;
18336d31316cSdrh   int choice;
183422fbcb8dSdrh   int rc = TCL_OK;
18350de8c112Sdrh   static const char *DB_strs[] = {
1836dc2c4915Sdrh     "authorizer",         "backup",            "busy",
1837dc2c4915Sdrh     "cache",              "changes",           "close",
1838dc2c4915Sdrh     "collate",            "collation_needed",  "commit_hook",
1839dc2c4915Sdrh     "complete",           "copy",              "enable_load_extension",
1840dc2c4915Sdrh     "errorcode",          "eval",              "exists",
1841dc2c4915Sdrh     "function",           "incrblob",          "interrupt",
1842833bf968Sdrh     "last_insert_rowid",  "nullvalue",         "onecolumn",
1843304637c0Sdrh     "preupdate",          "profile",           "progress",
1844304637c0Sdrh     "rekey",              "restore",           "rollback_hook",
1845304637c0Sdrh     "status",             "timeout",           "total_changes",
1846b56660f5Smistachkin     "trace",              "trace_v2",          "transaction",
1847b56660f5Smistachkin     "unlock_notify",      "update_hook",       "version",
1848b56660f5Smistachkin     "wal_hook",
1849304637c0Sdrh     0
18506d31316cSdrh   };
1851411995dcSdrh   enum DB_enum {
1852dc2c4915Sdrh     DB_AUTHORIZER,        DB_BACKUP,           DB_BUSY,
1853dc2c4915Sdrh     DB_CACHE,             DB_CHANGES,          DB_CLOSE,
1854dc2c4915Sdrh     DB_COLLATE,           DB_COLLATION_NEEDED, DB_COMMIT_HOOK,
1855dc2c4915Sdrh     DB_COMPLETE,          DB_COPY,             DB_ENABLE_LOAD_EXTENSION,
1856dc2c4915Sdrh     DB_ERRORCODE,         DB_EVAL,             DB_EXISTS,
1857dc2c4915Sdrh     DB_FUNCTION,          DB_INCRBLOB,         DB_INTERRUPT,
1858833bf968Sdrh     DB_LAST_INSERT_ROWID, DB_NULLVALUE,        DB_ONECOLUMN,
1859304637c0Sdrh     DB_PREUPDATE,         DB_PROFILE,          DB_PROGRESS,
1860304637c0Sdrh     DB_REKEY,             DB_RESTORE,          DB_ROLLBACK_HOOK,
1861304637c0Sdrh     DB_STATUS,            DB_TIMEOUT,          DB_TOTAL_CHANGES,
1862b56660f5Smistachkin     DB_TRACE,             DB_TRACE_V2,         DB_TRANSACTION,
1863b56660f5Smistachkin     DB_UNLOCK_NOTIFY,     DB_UPDATE_HOOK,      DB_VERSION,
1864b56660f5Smistachkin     DB_WAL_HOOK,
18656d31316cSdrh   };
18661067fe11Stpoindex   /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
18676d31316cSdrh 
18686d31316cSdrh   if( objc<2 ){
18696d31316cSdrh     Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
187075897234Sdrh     return TCL_ERROR;
187175897234Sdrh   }
1872411995dcSdrh   if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
18736d31316cSdrh     return TCL_ERROR;
18746d31316cSdrh   }
18756d31316cSdrh 
1876411995dcSdrh   switch( (enum DB_enum)choice ){
187775897234Sdrh 
1878e22a334bSdrh   /*    $db authorizer ?CALLBACK?
1879e22a334bSdrh   **
1880e22a334bSdrh   ** Invoke the given callback to authorize each SQL operation as it is
1881e22a334bSdrh   ** compiled.  5 arguments are appended to the callback before it is
1882e22a334bSdrh   ** invoked:
1883e22a334bSdrh   **
1884e22a334bSdrh   **   (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
1885e22a334bSdrh   **   (2) First descriptive name (depends on authorization type)
1886e22a334bSdrh   **   (3) Second descriptive name
1887e22a334bSdrh   **   (4) Name of the database (ex: "main", "temp")
1888e22a334bSdrh   **   (5) Name of trigger that is doing the access
1889e22a334bSdrh   **
1890e22a334bSdrh   ** The callback should return on of the following strings: SQLITE_OK,
1891e22a334bSdrh   ** SQLITE_IGNORE, or SQLITE_DENY.  Any other return value is an error.
1892e22a334bSdrh   **
1893e22a334bSdrh   ** If this method is invoked with no arguments, the current authorization
1894e22a334bSdrh   ** callback string is returned.
1895e22a334bSdrh   */
1896e22a334bSdrh   case DB_AUTHORIZER: {
18971211de37Sdrh #ifdef SQLITE_OMIT_AUTHORIZATION
1898a198f2b5Sdrh     Tcl_AppendResult(interp, "authorization not available in this build",
1899a198f2b5Sdrh                      (char*)0);
19001211de37Sdrh     return TCL_ERROR;
19011211de37Sdrh #else
1902e22a334bSdrh     if( objc>3 ){
1903e22a334bSdrh       Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
19040f14e2ebSdrh       return TCL_ERROR;
1905e22a334bSdrh     }else if( objc==2 ){
1906b5a20d3cSdrh       if( pDb->zAuth ){
1907a198f2b5Sdrh         Tcl_AppendResult(interp, pDb->zAuth, (char*)0);
1908e22a334bSdrh       }
1909e22a334bSdrh     }else{
1910e22a334bSdrh       char *zAuth;
1911e22a334bSdrh       int len;
1912e22a334bSdrh       if( pDb->zAuth ){
1913e22a334bSdrh         Tcl_Free(pDb->zAuth);
1914e22a334bSdrh       }
1915e22a334bSdrh       zAuth = Tcl_GetStringFromObj(objv[2], &len);
1916e22a334bSdrh       if( zAuth && len>0 ){
1917e22a334bSdrh         pDb->zAuth = Tcl_Alloc( len + 1 );
19185bb3eb9bSdrh         memcpy(pDb->zAuth, zAuth, len+1);
1919e22a334bSdrh       }else{
1920e22a334bSdrh         pDb->zAuth = 0;
1921e22a334bSdrh       }
1922e22a334bSdrh       if( pDb->zAuth ){
192332c6a48bSdrh         typedef int (*sqlite3_auth_cb)(
192432c6a48bSdrh            void*,int,const char*,const char*,
192532c6a48bSdrh            const char*,const char*);
1926e22a334bSdrh         pDb->interp = interp;
192732c6a48bSdrh         sqlite3_set_authorizer(pDb->db,(sqlite3_auth_cb)auth_callback,pDb);
1928e22a334bSdrh       }else{
19296f8a503dSdanielk1977         sqlite3_set_authorizer(pDb->db, 0, 0);
1930e22a334bSdrh       }
1931e22a334bSdrh     }
19321211de37Sdrh #endif
1933e22a334bSdrh     break;
1934e22a334bSdrh   }
1935e22a334bSdrh 
1936dc2c4915Sdrh   /*    $db backup ?DATABASE? FILENAME
1937dc2c4915Sdrh   **
1938dc2c4915Sdrh   ** Open or create a database file named FILENAME.  Transfer the
1939dc2c4915Sdrh   ** content of local database DATABASE (default: "main") into the
1940dc2c4915Sdrh   ** FILENAME database.
1941dc2c4915Sdrh   */
1942dc2c4915Sdrh   case DB_BACKUP: {
1943dc2c4915Sdrh     const char *zDestFile;
1944dc2c4915Sdrh     const char *zSrcDb;
1945dc2c4915Sdrh     sqlite3 *pDest;
1946dc2c4915Sdrh     sqlite3_backup *pBackup;
1947dc2c4915Sdrh 
1948dc2c4915Sdrh     if( objc==3 ){
1949dc2c4915Sdrh       zSrcDb = "main";
1950dc2c4915Sdrh       zDestFile = Tcl_GetString(objv[2]);
1951dc2c4915Sdrh     }else if( objc==4 ){
1952dc2c4915Sdrh       zSrcDb = Tcl_GetString(objv[2]);
1953dc2c4915Sdrh       zDestFile = Tcl_GetString(objv[3]);
1954dc2c4915Sdrh     }else{
1955dc2c4915Sdrh       Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
1956dc2c4915Sdrh       return TCL_ERROR;
1957dc2c4915Sdrh     }
1958147ef394Sdrh     rc = sqlite3_open_v2(zDestFile, &pDest,
1959147ef394Sdrh                SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE| pDb->openFlags, 0);
1960dc2c4915Sdrh     if( rc!=SQLITE_OK ){
1961dc2c4915Sdrh       Tcl_AppendResult(interp, "cannot open target database: ",
1962dc2c4915Sdrh            sqlite3_errmsg(pDest), (char*)0);
1963dc2c4915Sdrh       sqlite3_close(pDest);
1964dc2c4915Sdrh       return TCL_ERROR;
1965dc2c4915Sdrh     }
1966dc2c4915Sdrh     pBackup = sqlite3_backup_init(pDest, "main", pDb->db, zSrcDb);
1967dc2c4915Sdrh     if( pBackup==0 ){
1968dc2c4915Sdrh       Tcl_AppendResult(interp, "backup failed: ",
1969dc2c4915Sdrh            sqlite3_errmsg(pDest), (char*)0);
1970dc2c4915Sdrh       sqlite3_close(pDest);
1971dc2c4915Sdrh       return TCL_ERROR;
1972dc2c4915Sdrh     }
1973dc2c4915Sdrh     while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
1974dc2c4915Sdrh     sqlite3_backup_finish(pBackup);
1975dc2c4915Sdrh     if( rc==SQLITE_DONE ){
1976dc2c4915Sdrh       rc = TCL_OK;
1977dc2c4915Sdrh     }else{
1978dc2c4915Sdrh       Tcl_AppendResult(interp, "backup failed: ",
1979dc2c4915Sdrh            sqlite3_errmsg(pDest), (char*)0);
1980dc2c4915Sdrh       rc = TCL_ERROR;
1981dc2c4915Sdrh     }
1982dc2c4915Sdrh     sqlite3_close(pDest);
1983dc2c4915Sdrh     break;
1984dc2c4915Sdrh   }
1985dc2c4915Sdrh 
1986bec3f402Sdrh   /*    $db busy ?CALLBACK?
1987bec3f402Sdrh   **
1988bec3f402Sdrh   ** Invoke the given callback if an SQL statement attempts to open
1989bec3f402Sdrh   ** a locked database file.
1990bec3f402Sdrh   */
19916d31316cSdrh   case DB_BUSY: {
19926d31316cSdrh     if( objc>3 ){
19936d31316cSdrh       Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
1994bec3f402Sdrh       return TCL_ERROR;
19956d31316cSdrh     }else if( objc==2 ){
1996bec3f402Sdrh       if( pDb->zBusy ){
1997a198f2b5Sdrh         Tcl_AppendResult(interp, pDb->zBusy, (char*)0);
1998bec3f402Sdrh       }
1999bec3f402Sdrh     }else{
20006d31316cSdrh       char *zBusy;
20016d31316cSdrh       int len;
2002bec3f402Sdrh       if( pDb->zBusy ){
2003bec3f402Sdrh         Tcl_Free(pDb->zBusy);
20046d31316cSdrh       }
20056d31316cSdrh       zBusy = Tcl_GetStringFromObj(objv[2], &len);
20066d31316cSdrh       if( zBusy && len>0 ){
20076d31316cSdrh         pDb->zBusy = Tcl_Alloc( len + 1 );
20085bb3eb9bSdrh         memcpy(pDb->zBusy, zBusy, len+1);
20096d31316cSdrh       }else{
2010bec3f402Sdrh         pDb->zBusy = 0;
2011bec3f402Sdrh       }
2012bec3f402Sdrh       if( pDb->zBusy ){
2013bec3f402Sdrh         pDb->interp = interp;
20146f8a503dSdanielk1977         sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
20156d31316cSdrh       }else{
20166f8a503dSdanielk1977         sqlite3_busy_handler(pDb->db, 0, 0);
2017bec3f402Sdrh       }
2018bec3f402Sdrh     }
20196d31316cSdrh     break;
20206d31316cSdrh   }
2021bec3f402Sdrh 
2022fb7e7651Sdrh   /*     $db cache flush
2023fb7e7651Sdrh   **     $db cache size n
2024fb7e7651Sdrh   **
2025fb7e7651Sdrh   ** Flush the prepared statement cache, or set the maximum number of
2026fb7e7651Sdrh   ** cached statements.
2027fb7e7651Sdrh   */
2028fb7e7651Sdrh   case DB_CACHE: {
2029fb7e7651Sdrh     char *subCmd;
2030fb7e7651Sdrh     int n;
2031fb7e7651Sdrh 
2032fb7e7651Sdrh     if( objc<=2 ){
2033fb7e7651Sdrh       Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
2034fb7e7651Sdrh       return TCL_ERROR;
2035fb7e7651Sdrh     }
2036fb7e7651Sdrh     subCmd = Tcl_GetStringFromObj( objv[2], 0 );
2037fb7e7651Sdrh     if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
2038fb7e7651Sdrh       if( objc!=3 ){
2039fb7e7651Sdrh         Tcl_WrongNumArgs(interp, 2, objv, "flush");
2040fb7e7651Sdrh         return TCL_ERROR;
2041fb7e7651Sdrh       }else{
2042fb7e7651Sdrh         flushStmtCache( pDb );
2043fb7e7651Sdrh       }
2044fb7e7651Sdrh     }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
2045fb7e7651Sdrh       if( objc!=4 ){
2046fb7e7651Sdrh         Tcl_WrongNumArgs(interp, 2, objv, "size n");
2047fb7e7651Sdrh         return TCL_ERROR;
2048fb7e7651Sdrh       }else{
2049fb7e7651Sdrh         if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
2050fb7e7651Sdrh           Tcl_AppendResult( interp, "cannot convert \"",
2051a198f2b5Sdrh                Tcl_GetStringFromObj(objv[3],0), "\" to integer", (char*)0);
2052fb7e7651Sdrh           return TCL_ERROR;
2053fb7e7651Sdrh         }else{
2054fb7e7651Sdrh           if( n<0 ){
2055fb7e7651Sdrh             flushStmtCache( pDb );
2056fb7e7651Sdrh             n = 0;
2057fb7e7651Sdrh           }else if( n>MAX_PREPARED_STMTS ){
2058fb7e7651Sdrh             n = MAX_PREPARED_STMTS;
2059fb7e7651Sdrh           }
2060fb7e7651Sdrh           pDb->maxStmt = n;
2061fb7e7651Sdrh         }
2062fb7e7651Sdrh       }
2063fb7e7651Sdrh     }else{
2064fb7e7651Sdrh       Tcl_AppendResult( interp, "bad option \"",
2065a198f2b5Sdrh           Tcl_GetStringFromObj(objv[2],0), "\": must be flush or size",
2066a198f2b5Sdrh           (char*)0);
2067fb7e7651Sdrh       return TCL_ERROR;
2068fb7e7651Sdrh     }
2069fb7e7651Sdrh     break;
2070fb7e7651Sdrh   }
2071fb7e7651Sdrh 
2072b28af71aSdanielk1977   /*     $db changes
2073c8d30ac1Sdrh   **
2074c8d30ac1Sdrh   ** Return the number of rows that were modified, inserted, or deleted by
2075b28af71aSdanielk1977   ** the most recent INSERT, UPDATE or DELETE statement, not including
2076b28af71aSdanielk1977   ** any changes made by trigger programs.
2077c8d30ac1Sdrh   */
2078c8d30ac1Sdrh   case DB_CHANGES: {
2079c8d30ac1Sdrh     Tcl_Obj *pResult;
2080c8d30ac1Sdrh     if( objc!=2 ){
2081c8d30ac1Sdrh       Tcl_WrongNumArgs(interp, 2, objv, "");
2082c8d30ac1Sdrh       return TCL_ERROR;
2083c8d30ac1Sdrh     }
2084c8d30ac1Sdrh     pResult = Tcl_GetObjResult(interp);
2085b28af71aSdanielk1977     Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
2086f146a776Srdc     break;
2087f146a776Srdc   }
2088f146a776Srdc 
208975897234Sdrh   /*    $db close
209075897234Sdrh   **
209175897234Sdrh   ** Shutdown the database
209275897234Sdrh   */
20936d31316cSdrh   case DB_CLOSE: {
20946d31316cSdrh     Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
20956d31316cSdrh     break;
20966d31316cSdrh   }
209775897234Sdrh 
20980f14e2ebSdrh   /*
20990f14e2ebSdrh   **     $db collate NAME SCRIPT
21000f14e2ebSdrh   **
21010f14e2ebSdrh   ** Create a new SQL collation function called NAME.  Whenever
21020f14e2ebSdrh   ** that function is called, invoke SCRIPT to evaluate the function.
21030f14e2ebSdrh   */
21040f14e2ebSdrh   case DB_COLLATE: {
21050f14e2ebSdrh     SqlCollate *pCollate;
21060f14e2ebSdrh     char *zName;
21070f14e2ebSdrh     char *zScript;
21080f14e2ebSdrh     int nScript;
21090f14e2ebSdrh     if( objc!=4 ){
21100f14e2ebSdrh       Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
21110f14e2ebSdrh       return TCL_ERROR;
21120f14e2ebSdrh     }
21130f14e2ebSdrh     zName = Tcl_GetStringFromObj(objv[2], 0);
21140f14e2ebSdrh     zScript = Tcl_GetStringFromObj(objv[3], &nScript);
21150f14e2ebSdrh     pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
21160f14e2ebSdrh     if( pCollate==0 ) return TCL_ERROR;
21170f14e2ebSdrh     pCollate->interp = interp;
21180f14e2ebSdrh     pCollate->pNext = pDb->pCollate;
21190f14e2ebSdrh     pCollate->zScript = (char*)&pCollate[1];
21200f14e2ebSdrh     pDb->pCollate = pCollate;
21215bb3eb9bSdrh     memcpy(pCollate->zScript, zScript, nScript+1);
21220f14e2ebSdrh     if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
21230f14e2ebSdrh         pCollate, tclSqlCollate) ){
21249636c4e1Sdanielk1977       Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
21250f14e2ebSdrh       return TCL_ERROR;
21260f14e2ebSdrh     }
21270f14e2ebSdrh     break;
21280f14e2ebSdrh   }
21290f14e2ebSdrh 
21300f14e2ebSdrh   /*
21310f14e2ebSdrh   **     $db collation_needed SCRIPT
21320f14e2ebSdrh   **
21330f14e2ebSdrh   ** Create a new SQL collation function called NAME.  Whenever
21340f14e2ebSdrh   ** that function is called, invoke SCRIPT to evaluate the function.
21350f14e2ebSdrh   */
21360f14e2ebSdrh   case DB_COLLATION_NEEDED: {
21370f14e2ebSdrh     if( objc!=3 ){
21380f14e2ebSdrh       Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
21390f14e2ebSdrh       return TCL_ERROR;
21400f14e2ebSdrh     }
21410f14e2ebSdrh     if( pDb->pCollateNeeded ){
21420f14e2ebSdrh       Tcl_DecrRefCount(pDb->pCollateNeeded);
21430f14e2ebSdrh     }
21440f14e2ebSdrh     pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
21450f14e2ebSdrh     Tcl_IncrRefCount(pDb->pCollateNeeded);
21460f14e2ebSdrh     sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
21470f14e2ebSdrh     break;
21480f14e2ebSdrh   }
21490f14e2ebSdrh 
215019e2d37fSdrh   /*    $db commit_hook ?CALLBACK?
215119e2d37fSdrh   **
215219e2d37fSdrh   ** Invoke the given callback just before committing every SQL transaction.
215319e2d37fSdrh   ** If the callback throws an exception or returns non-zero, then the
215419e2d37fSdrh   ** transaction is aborted.  If CALLBACK is an empty string, the callback
215519e2d37fSdrh   ** is disabled.
215619e2d37fSdrh   */
215719e2d37fSdrh   case DB_COMMIT_HOOK: {
215819e2d37fSdrh     if( objc>3 ){
215919e2d37fSdrh       Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
216019e2d37fSdrh       return TCL_ERROR;
216119e2d37fSdrh     }else if( objc==2 ){
216219e2d37fSdrh       if( pDb->zCommit ){
2163a198f2b5Sdrh         Tcl_AppendResult(interp, pDb->zCommit, (char*)0);
216419e2d37fSdrh       }
216519e2d37fSdrh     }else{
21666ef5e12eSmistachkin       const char *zCommit;
216719e2d37fSdrh       int len;
216819e2d37fSdrh       if( pDb->zCommit ){
216919e2d37fSdrh         Tcl_Free(pDb->zCommit);
217019e2d37fSdrh       }
217119e2d37fSdrh       zCommit = Tcl_GetStringFromObj(objv[2], &len);
217219e2d37fSdrh       if( zCommit && len>0 ){
217319e2d37fSdrh         pDb->zCommit = Tcl_Alloc( len + 1 );
21745bb3eb9bSdrh         memcpy(pDb->zCommit, zCommit, len+1);
217519e2d37fSdrh       }else{
217619e2d37fSdrh         pDb->zCommit = 0;
217719e2d37fSdrh       }
217819e2d37fSdrh       if( pDb->zCommit ){
217919e2d37fSdrh         pDb->interp = interp;
218019e2d37fSdrh         sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
218119e2d37fSdrh       }else{
218219e2d37fSdrh         sqlite3_commit_hook(pDb->db, 0, 0);
218319e2d37fSdrh       }
218419e2d37fSdrh     }
218519e2d37fSdrh     break;
218619e2d37fSdrh   }
218719e2d37fSdrh 
218875897234Sdrh   /*    $db complete SQL
218975897234Sdrh   **
219075897234Sdrh   ** Return TRUE if SQL is a complete SQL statement.  Return FALSE if
219175897234Sdrh   ** additional lines of input are needed.  This is similar to the
219275897234Sdrh   ** built-in "info complete" command of Tcl.
219375897234Sdrh   */
21946d31316cSdrh   case DB_COMPLETE: {
2195ccae6026Sdrh #ifndef SQLITE_OMIT_COMPLETE
21966d31316cSdrh     Tcl_Obj *pResult;
21976d31316cSdrh     int isComplete;
21986d31316cSdrh     if( objc!=3 ){
21996d31316cSdrh       Tcl_WrongNumArgs(interp, 2, objv, "SQL");
220075897234Sdrh       return TCL_ERROR;
220175897234Sdrh     }
22026f8a503dSdanielk1977     isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
22036d31316cSdrh     pResult = Tcl_GetObjResult(interp);
22046d31316cSdrh     Tcl_SetBooleanObj(pResult, isComplete);
2205ccae6026Sdrh #endif
22066d31316cSdrh     break;
22076d31316cSdrh   }
220875897234Sdrh 
220919e2d37fSdrh   /*    $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
221019e2d37fSdrh   **
221119e2d37fSdrh   ** Copy data into table from filename, optionally using SEPARATOR
221219e2d37fSdrh   ** as column separators.  If a column contains a null string, or the
221319e2d37fSdrh   ** value of NULLINDICATOR, a NULL is inserted for the column.
221419e2d37fSdrh   ** conflict-algorithm is one of the sqlite conflict algorithms:
221519e2d37fSdrh   **    rollback, abort, fail, ignore, replace
221619e2d37fSdrh   ** On success, return the number of lines processed, not necessarily same
221719e2d37fSdrh   ** as 'db changes' due to conflict-algorithm selected.
221819e2d37fSdrh   **
221919e2d37fSdrh   ** This code is basically an implementation/enhancement of
222019e2d37fSdrh   ** the sqlite3 shell.c ".import" command.
222119e2d37fSdrh   **
222219e2d37fSdrh   ** This command usage is equivalent to the sqlite2.x COPY statement,
222319e2d37fSdrh   ** which imports file data into a table using the PostgreSQL COPY file format:
222419e2d37fSdrh   **   $db copy $conflit_algo $table_name $filename \t \\N
222519e2d37fSdrh   */
222619e2d37fSdrh   case DB_COPY: {
222719e2d37fSdrh     char *zTable;               /* Insert data into this table */
222819e2d37fSdrh     char *zFile;                /* The file from which to extract data */
222919e2d37fSdrh     char *zConflict;            /* The conflict algorithm to use */
223019e2d37fSdrh     sqlite3_stmt *pStmt;        /* A statement */
223119e2d37fSdrh     int nCol;                   /* Number of columns in the table */
223219e2d37fSdrh     int nByte;                  /* Number of bytes in an SQL string */
223319e2d37fSdrh     int i, j;                   /* Loop counters */
223419e2d37fSdrh     int nSep;                   /* Number of bytes in zSep[] */
223519e2d37fSdrh     int nNull;                  /* Number of bytes in zNull[] */
223619e2d37fSdrh     char *zSql;                 /* An SQL statement */
223719e2d37fSdrh     char *zLine;                /* A single line of input from the file */
223819e2d37fSdrh     char **azCol;               /* zLine[] broken up into columns */
22396ef5e12eSmistachkin     const char *zCommit;        /* How to commit changes */
224019e2d37fSdrh     FILE *in;                   /* The input file */
224119e2d37fSdrh     int lineno = 0;             /* Line number of input file */
224219e2d37fSdrh     char zLineNum[80];          /* Line number print buffer */
224319e2d37fSdrh     Tcl_Obj *pResult;           /* interp result */
224419e2d37fSdrh 
22456ef5e12eSmistachkin     const char *zSep;
22466ef5e12eSmistachkin     const char *zNull;
224719e2d37fSdrh     if( objc<5 || objc>7 ){
224819e2d37fSdrh       Tcl_WrongNumArgs(interp, 2, objv,
224919e2d37fSdrh          "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
225019e2d37fSdrh       return TCL_ERROR;
225119e2d37fSdrh     }
225219e2d37fSdrh     if( objc>=6 ){
225319e2d37fSdrh       zSep = Tcl_GetStringFromObj(objv[5], 0);
225419e2d37fSdrh     }else{
225519e2d37fSdrh       zSep = "\t";
225619e2d37fSdrh     }
225719e2d37fSdrh     if( objc>=7 ){
225819e2d37fSdrh       zNull = Tcl_GetStringFromObj(objv[6], 0);
225919e2d37fSdrh     }else{
226019e2d37fSdrh       zNull = "";
226119e2d37fSdrh     }
226219e2d37fSdrh     zConflict = Tcl_GetStringFromObj(objv[2], 0);
226319e2d37fSdrh     zTable = Tcl_GetStringFromObj(objv[3], 0);
226419e2d37fSdrh     zFile = Tcl_GetStringFromObj(objv[4], 0);
22654f21c4afSdrh     nSep = strlen30(zSep);
22664f21c4afSdrh     nNull = strlen30(zNull);
226719e2d37fSdrh     if( nSep==0 ){
2268a198f2b5Sdrh       Tcl_AppendResult(interp,"Error: non-null separator required for copy",
2269a198f2b5Sdrh                        (char*)0);
227019e2d37fSdrh       return TCL_ERROR;
227119e2d37fSdrh     }
22723e59c012Sdrh     if(strcmp(zConflict, "rollback") != 0 &&
22733e59c012Sdrh        strcmp(zConflict, "abort"   ) != 0 &&
22743e59c012Sdrh        strcmp(zConflict, "fail"    ) != 0 &&
22753e59c012Sdrh        strcmp(zConflict, "ignore"  ) != 0 &&
22763e59c012Sdrh        strcmp(zConflict, "replace" ) != 0 ) {
227719e2d37fSdrh       Tcl_AppendResult(interp, "Error: \"", zConflict,
227819e2d37fSdrh             "\", conflict-algorithm must be one of: rollback, "
2279a198f2b5Sdrh             "abort, fail, ignore, or replace", (char*)0);
228019e2d37fSdrh       return TCL_ERROR;
228119e2d37fSdrh     }
228219e2d37fSdrh     zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
228319e2d37fSdrh     if( zSql==0 ){
2284a198f2b5Sdrh       Tcl_AppendResult(interp, "Error: no such table: ", zTable, (char*)0);
228519e2d37fSdrh       return TCL_ERROR;
228619e2d37fSdrh     }
22874f21c4afSdrh     nByte = strlen30(zSql);
22883e701a18Sdrh     rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
228919e2d37fSdrh     sqlite3_free(zSql);
229019e2d37fSdrh     if( rc ){
2291a198f2b5Sdrh       Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0);
229219e2d37fSdrh       nCol = 0;
229319e2d37fSdrh     }else{
229419e2d37fSdrh       nCol = sqlite3_column_count(pStmt);
229519e2d37fSdrh     }
229619e2d37fSdrh     sqlite3_finalize(pStmt);
229719e2d37fSdrh     if( nCol==0 ) {
229819e2d37fSdrh       return TCL_ERROR;
229919e2d37fSdrh     }
230019e2d37fSdrh     zSql = malloc( nByte + 50 + nCol*2 );
230119e2d37fSdrh     if( zSql==0 ) {
2302a198f2b5Sdrh       Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0);
230319e2d37fSdrh       return TCL_ERROR;
230419e2d37fSdrh     }
230519e2d37fSdrh     sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
230619e2d37fSdrh          zConflict, zTable);
23074f21c4afSdrh     j = strlen30(zSql);
230819e2d37fSdrh     for(i=1; i<nCol; i++){
230919e2d37fSdrh       zSql[j++] = ',';
231019e2d37fSdrh       zSql[j++] = '?';
231119e2d37fSdrh     }
231219e2d37fSdrh     zSql[j++] = ')';
231319e2d37fSdrh     zSql[j] = 0;
23143e701a18Sdrh     rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
231519e2d37fSdrh     free(zSql);
231619e2d37fSdrh     if( rc ){
2317a198f2b5Sdrh       Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0);
231819e2d37fSdrh       sqlite3_finalize(pStmt);
231919e2d37fSdrh       return TCL_ERROR;
232019e2d37fSdrh     }
232119e2d37fSdrh     in = fopen(zFile, "rb");
232219e2d37fSdrh     if( in==0 ){
2323ea8f0a15Sdrh       Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, (char*)0);
232419e2d37fSdrh       sqlite3_finalize(pStmt);
232519e2d37fSdrh       return TCL_ERROR;
232619e2d37fSdrh     }
232719e2d37fSdrh     azCol = malloc( sizeof(azCol[0])*(nCol+1) );
232819e2d37fSdrh     if( azCol==0 ) {
2329a198f2b5Sdrh       Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0);
233043617e9aSdrh       fclose(in);
233119e2d37fSdrh       return TCL_ERROR;
233219e2d37fSdrh     }
23333752785fSdrh     (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
233419e2d37fSdrh     zCommit = "COMMIT";
233519e2d37fSdrh     while( (zLine = local_getline(0, in))!=0 ){
233619e2d37fSdrh       char *z;
233719e2d37fSdrh       lineno++;
233819e2d37fSdrh       azCol[0] = zLine;
233919e2d37fSdrh       for(i=0, z=zLine; *z; z++){
234019e2d37fSdrh         if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
234119e2d37fSdrh           *z = 0;
234219e2d37fSdrh           i++;
234319e2d37fSdrh           if( i<nCol ){
234419e2d37fSdrh             azCol[i] = &z[nSep];
234519e2d37fSdrh             z += nSep-1;
234619e2d37fSdrh           }
234719e2d37fSdrh         }
234819e2d37fSdrh       }
234919e2d37fSdrh       if( i+1!=nCol ){
235019e2d37fSdrh         char *zErr;
23514f21c4afSdrh         int nErr = strlen30(zFile) + 200;
23525bb3eb9bSdrh         zErr = malloc(nErr);
2353c1f4494eSdrh         if( zErr ){
23545bb3eb9bSdrh           sqlite3_snprintf(nErr, zErr,
2355955de52cSdanielk1977              "Error: %s line %d: expected %d columns of data but found %d",
235619e2d37fSdrh              zFile, lineno, nCol, i+1);
2357a198f2b5Sdrh           Tcl_AppendResult(interp, zErr, (char*)0);
235819e2d37fSdrh           free(zErr);
2359c1f4494eSdrh         }
236019e2d37fSdrh         zCommit = "ROLLBACK";
236119e2d37fSdrh         break;
236219e2d37fSdrh       }
236319e2d37fSdrh       for(i=0; i<nCol; i++){
236419e2d37fSdrh         /* check for null data, if so, bind as null */
2365ea678832Sdrh         if( (nNull>0 && strcmp(azCol[i], zNull)==0)
23664f21c4afSdrh           || strlen30(azCol[i])==0
2367ea678832Sdrh         ){
236819e2d37fSdrh           sqlite3_bind_null(pStmt, i+1);
236919e2d37fSdrh         }else{
237019e2d37fSdrh           sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
237119e2d37fSdrh         }
237219e2d37fSdrh       }
237319e2d37fSdrh       sqlite3_step(pStmt);
237419e2d37fSdrh       rc = sqlite3_reset(pStmt);
237519e2d37fSdrh       free(zLine);
237619e2d37fSdrh       if( rc!=SQLITE_OK ){
2377a198f2b5Sdrh         Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), (char*)0);
237819e2d37fSdrh         zCommit = "ROLLBACK";
237919e2d37fSdrh         break;
238019e2d37fSdrh       }
238119e2d37fSdrh     }
238219e2d37fSdrh     free(azCol);
238319e2d37fSdrh     fclose(in);
238419e2d37fSdrh     sqlite3_finalize(pStmt);
23853752785fSdrh     (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
238619e2d37fSdrh 
238719e2d37fSdrh     if( zCommit[0] == 'C' ){
238819e2d37fSdrh       /* success, set result as number of lines processed */
238919e2d37fSdrh       pResult = Tcl_GetObjResult(interp);
239019e2d37fSdrh       Tcl_SetIntObj(pResult, lineno);
239119e2d37fSdrh       rc = TCL_OK;
239219e2d37fSdrh     }else{
239319e2d37fSdrh       /* failure, append lineno where failed */
23945bb3eb9bSdrh       sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
2395a198f2b5Sdrh       Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,
2396a198f2b5Sdrh                        (char*)0);
239719e2d37fSdrh       rc = TCL_ERROR;
239819e2d37fSdrh     }
239919e2d37fSdrh     break;
240019e2d37fSdrh   }
240119e2d37fSdrh 
240275897234Sdrh   /*
24034144905bSdrh   **    $db enable_load_extension BOOLEAN
24044144905bSdrh   **
24054144905bSdrh   ** Turn the extension loading feature on or off.  It if off by
24064144905bSdrh   ** default.
24074144905bSdrh   */
24084144905bSdrh   case DB_ENABLE_LOAD_EXTENSION: {
2409f533acc0Sdrh #ifndef SQLITE_OMIT_LOAD_EXTENSION
24104144905bSdrh     int onoff;
24114144905bSdrh     if( objc!=3 ){
24124144905bSdrh       Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
24134144905bSdrh       return TCL_ERROR;
24144144905bSdrh     }
24154144905bSdrh     if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
24164144905bSdrh       return TCL_ERROR;
24174144905bSdrh     }
24184144905bSdrh     sqlite3_enable_load_extension(pDb->db, onoff);
24194144905bSdrh     break;
2420f533acc0Sdrh #else
2421f533acc0Sdrh     Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
2422a198f2b5Sdrh                      (char*)0);
2423f533acc0Sdrh     return TCL_ERROR;
2424f533acc0Sdrh #endif
24254144905bSdrh   }
24264144905bSdrh 
24274144905bSdrh   /*
2428dcd997eaSdrh   **    $db errorcode
2429dcd997eaSdrh   **
2430dcd997eaSdrh   ** Return the numeric error code that was returned by the most recent
24316f8a503dSdanielk1977   ** call to sqlite3_exec().
2432dcd997eaSdrh   */
2433dcd997eaSdrh   case DB_ERRORCODE: {
2434f3ce83f5Sdanielk1977     Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
2435dcd997eaSdrh     break;
2436dcd997eaSdrh   }
2437dcd997eaSdrh 
2438dcd997eaSdrh   /*
24394a4c11aaSdan   **    $db exists $sql
24401807ce37Sdrh   **    $db onecolumn $sql
244175897234Sdrh   **
24424a4c11aaSdan   ** The onecolumn method is the equivalent of:
24434a4c11aaSdan   **     lindex [$db eval $sql] 0
24444a4c11aaSdan   */
24454a4c11aaSdan   case DB_EXISTS:
24464a4c11aaSdan   case DB_ONECOLUMN: {
2447edc4024bSdrh     Tcl_Obj *pResult = 0;
24484a4c11aaSdan     DbEvalContext sEval;
24494a4c11aaSdan     if( objc!=3 ){
24504a4c11aaSdan       Tcl_WrongNumArgs(interp, 2, objv, "SQL");
24514a4c11aaSdan       return TCL_ERROR;
24524a4c11aaSdan     }
24534a4c11aaSdan 
24544a4c11aaSdan     dbEvalInit(&sEval, pDb, objv[2], 0);
24554a4c11aaSdan     rc = dbEvalStep(&sEval);
24564a4c11aaSdan     if( choice==DB_ONECOLUMN ){
24574a4c11aaSdan       if( rc==TCL_OK ){
2458edc4024bSdrh         pResult = dbEvalColumnValue(&sEval, 0);
2459d5f12cd5Sdan       }else if( rc==TCL_BREAK ){
2460d5f12cd5Sdan         Tcl_ResetResult(interp);
24614a4c11aaSdan       }
24624a4c11aaSdan     }else if( rc==TCL_BREAK || rc==TCL_OK ){
2463edc4024bSdrh       pResult = Tcl_NewBooleanObj(rc==TCL_OK);
24644a4c11aaSdan     }
24654a4c11aaSdan     dbEvalFinalize(&sEval);
2466edc4024bSdrh     if( pResult ) Tcl_SetObjResult(interp, pResult);
24674a4c11aaSdan 
24684a4c11aaSdan     if( rc==TCL_BREAK ){
24694a4c11aaSdan       rc = TCL_OK;
24704a4c11aaSdan     }
24714a4c11aaSdan     break;
24724a4c11aaSdan   }
24734a4c11aaSdan 
24744a4c11aaSdan   /*
24754a4c11aaSdan   **    $db eval $sql ?array? ?{  ...code... }?
24764a4c11aaSdan   **
247775897234Sdrh   ** The SQL statement in $sql is evaluated.  For each row, the values are
2478bec3f402Sdrh   ** placed in elements of the array named "array" and ...code... is executed.
247975897234Sdrh   ** If "array" and "code" are omitted, then no callback is every invoked.
248075897234Sdrh   ** If "array" is an empty string, then the values are placed in variables
248175897234Sdrh   ** that have the same name as the fields extracted by the query.
248275897234Sdrh   */
24834a4c11aaSdan   case DB_EVAL: {
248492febd92Sdrh     if( objc<3 || objc>5 ){
2485895d7472Sdrh       Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
248630ccda10Sdanielk1977       return TCL_ERROR;
248730ccda10Sdanielk1977     }
24884a4c11aaSdan 
248992febd92Sdrh     if( objc==3 ){
24904a4c11aaSdan       DbEvalContext sEval;
24914a4c11aaSdan       Tcl_Obj *pRet = Tcl_NewObj();
24924a4c11aaSdan       Tcl_IncrRefCount(pRet);
24934a4c11aaSdan       dbEvalInit(&sEval, pDb, objv[2], 0);
24944a4c11aaSdan       while( TCL_OK==(rc = dbEvalStep(&sEval)) ){
24954a4c11aaSdan         int i;
24964a4c11aaSdan         int nCol;
24974a4c11aaSdan         dbEvalRowInfo(&sEval, &nCol, 0);
249892febd92Sdrh         for(i=0; i<nCol; i++){
24994a4c11aaSdan           Tcl_ListObjAppendElement(interp, pRet, dbEvalColumnValue(&sEval, i));
250092febd92Sdrh         }
250130ccda10Sdanielk1977       }
25024a4c11aaSdan       dbEvalFinalize(&sEval);
250390b6bb19Sdrh       if( rc==TCL_BREAK ){
25044a4c11aaSdan         Tcl_SetObjResult(interp, pRet);
250590b6bb19Sdrh         rc = TCL_OK;
250690b6bb19Sdrh       }
2507ef2cb63eSdanielk1977       Tcl_DecrRefCount(pRet);
25084a4c11aaSdan     }else{
25098e18922fSmistachkin       ClientData cd2[2];
25104a4c11aaSdan       DbEvalContext *p;
25114a4c11aaSdan       Tcl_Obj *pArray = 0;
25124a4c11aaSdan       Tcl_Obj *pScript;
25134a4c11aaSdan 
25144a4c11aaSdan       if( objc==5 && *(char *)Tcl_GetString(objv[3]) ){
25154a4c11aaSdan         pArray = objv[3];
25164a4c11aaSdan       }
25174a4c11aaSdan       pScript = objv[objc-1];
25184a4c11aaSdan       Tcl_IncrRefCount(pScript);
25194a4c11aaSdan 
25204a4c11aaSdan       p = (DbEvalContext *)Tcl_Alloc(sizeof(DbEvalContext));
25214a4c11aaSdan       dbEvalInit(p, pDb, objv[2], pArray);
25224a4c11aaSdan 
25238e18922fSmistachkin       cd2[0] = (void *)p;
25248e18922fSmistachkin       cd2[1] = (void *)pScript;
25258e18922fSmistachkin       rc = DbEvalNextCmd(cd2, interp, TCL_OK);
25261807ce37Sdrh     }
252730ccda10Sdanielk1977     break;
252830ccda10Sdanielk1977   }
2529bec3f402Sdrh 
2530bec3f402Sdrh   /*
25313df30592Sdan   **     $db function NAME [-argcount N] [-deterministic] SCRIPT
2532cabb0819Sdrh   **
2533cabb0819Sdrh   ** Create a new SQL function called NAME.  Whenever that function is
2534cabb0819Sdrh   ** called, invoke SCRIPT to evaluate the function.
2535cabb0819Sdrh   */
2536cabb0819Sdrh   case DB_FUNCTION: {
25373df30592Sdan     int flags = SQLITE_UTF8;
2538cabb0819Sdrh     SqlFunc *pFunc;
2539d1e4733dSdrh     Tcl_Obj *pScript;
2540cabb0819Sdrh     char *zName;
2541e3602be8Sdrh     int nArg = -1;
25423df30592Sdan     int i;
25433df30592Sdan     if( objc<4 ){
25443df30592Sdan       Tcl_WrongNumArgs(interp, 2, objv, "NAME ?SWITCHES? SCRIPT");
25453df30592Sdan       return TCL_ERROR;
25463df30592Sdan     }
25473df30592Sdan     for(i=3; i<(objc-1); i++){
25483df30592Sdan       const char *z = Tcl_GetString(objv[i]);
25494f21c4afSdrh       int n = strlen30(z);
2550e3602be8Sdrh       if( n>2 && strncmp(z, "-argcount",n)==0 ){
25513df30592Sdan         if( i==(objc-2) ){
2552ea8f0a15Sdrh           Tcl_AppendResult(interp, "option requires an argument: ", z,(char*)0);
25533df30592Sdan           return TCL_ERROR;
25543df30592Sdan         }
25553df30592Sdan         if( Tcl_GetIntFromObj(interp, objv[i+1], &nArg) ) return TCL_ERROR;
2556e3602be8Sdrh         if( nArg<0 ){
2557e3602be8Sdrh           Tcl_AppendResult(interp, "number of arguments must be non-negative",
2558e3602be8Sdrh                            (char*)0);
2559cabb0819Sdrh           return TCL_ERROR;
2560cabb0819Sdrh         }
25613df30592Sdan         i++;
25623df30592Sdan       }else
25633df30592Sdan       if( n>2 && strncmp(z, "-deterministic",n)==0 ){
25643df30592Sdan         flags |= SQLITE_DETERMINISTIC;
2565e3602be8Sdrh       }else{
25663df30592Sdan         Tcl_AppendResult(interp, "bad option \"", z,
2567ea8f0a15Sdrh             "\": must be -argcount or -deterministic", (char*)0
25683df30592Sdan         );
25693df30592Sdan         return TCL_ERROR;
2570e3602be8Sdrh       }
25713df30592Sdan     }
25723df30592Sdan 
25733df30592Sdan     pScript = objv[objc-1];
2574e3602be8Sdrh     zName = Tcl_GetStringFromObj(objv[2], 0);
2575d1e4733dSdrh     pFunc = findSqlFunc(pDb, zName);
2576cabb0819Sdrh     if( pFunc==0 ) return TCL_ERROR;
2577d1e4733dSdrh     if( pFunc->pScript ){
2578d1e4733dSdrh       Tcl_DecrRefCount(pFunc->pScript);
2579d1e4733dSdrh     }
2580d1e4733dSdrh     pFunc->pScript = pScript;
2581d1e4733dSdrh     Tcl_IncrRefCount(pScript);
2582d1e4733dSdrh     pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
25833df30592Sdan     rc = sqlite3_create_function(pDb->db, zName, nArg, flags,
2584d8123366Sdanielk1977         pFunc, tclSqlFunc, 0, 0);
2585fb7e7651Sdrh     if( rc!=SQLITE_OK ){
2586fb7e7651Sdrh       rc = TCL_ERROR;
25879636c4e1Sdanielk1977       Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
2588fb7e7651Sdrh     }
2589cabb0819Sdrh     break;
2590cabb0819Sdrh   }
2591cabb0819Sdrh 
2592cabb0819Sdrh   /*
25938cbadb02Sdanielk1977   **     $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
2594b4e9af9fSdanielk1977   */
2595b4e9af9fSdanielk1977   case DB_INCRBLOB: {
259632a0d8bbSdanielk1977 #ifdef SQLITE_OMIT_INCRBLOB
2597a198f2b5Sdrh     Tcl_AppendResult(interp, "incrblob not available in this build", (char*)0);
259832a0d8bbSdanielk1977     return TCL_ERROR;
259932a0d8bbSdanielk1977 #else
26008cbadb02Sdanielk1977     int isReadonly = 0;
2601b4e9af9fSdanielk1977     const char *zDb = "main";
2602b4e9af9fSdanielk1977     const char *zTable;
2603b4e9af9fSdanielk1977     const char *zColumn;
2604b3f787f4Sdrh     Tcl_WideInt iRow;
2605b4e9af9fSdanielk1977 
26068cbadb02Sdanielk1977     /* Check for the -readonly option */
26078cbadb02Sdanielk1977     if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
26088cbadb02Sdanielk1977       isReadonly = 1;
26098cbadb02Sdanielk1977     }
26108cbadb02Sdanielk1977 
26118cbadb02Sdanielk1977     if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
26128cbadb02Sdanielk1977       Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
2613b4e9af9fSdanielk1977       return TCL_ERROR;
2614b4e9af9fSdanielk1977     }
2615b4e9af9fSdanielk1977 
26168cbadb02Sdanielk1977     if( objc==(6+isReadonly) ){
2617b4e9af9fSdanielk1977       zDb = Tcl_GetString(objv[2]);
2618b4e9af9fSdanielk1977     }
2619b4e9af9fSdanielk1977     zTable = Tcl_GetString(objv[objc-3]);
2620b4e9af9fSdanielk1977     zColumn = Tcl_GetString(objv[objc-2]);
2621b4e9af9fSdanielk1977     rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
2622b4e9af9fSdanielk1977 
2623b4e9af9fSdanielk1977     if( rc==TCL_OK ){
26248cbadb02Sdanielk1977       rc = createIncrblobChannel(
2625edf5b165Sdan           interp, pDb, zDb, zTable, zColumn, (sqlite3_int64)iRow, isReadonly
26268cbadb02Sdanielk1977       );
2627b4e9af9fSdanielk1977     }
262832a0d8bbSdanielk1977 #endif
2629b4e9af9fSdanielk1977     break;
2630b4e9af9fSdanielk1977   }
2631b4e9af9fSdanielk1977 
2632b4e9af9fSdanielk1977   /*
2633f11bded5Sdrh   **     $db interrupt
2634f11bded5Sdrh   **
2635f11bded5Sdrh   ** Interrupt the execution of the inner-most SQL interpreter.  This
2636f11bded5Sdrh   ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
2637f11bded5Sdrh   */
2638f11bded5Sdrh   case DB_INTERRUPT: {
2639f11bded5Sdrh     sqlite3_interrupt(pDb->db);
2640f11bded5Sdrh     break;
2641f11bded5Sdrh   }
2642f11bded5Sdrh 
2643f11bded5Sdrh   /*
264419e2d37fSdrh   **     $db nullvalue ?STRING?
264519e2d37fSdrh   **
264619e2d37fSdrh   ** Change text used when a NULL comes back from the database. If ?STRING?
264719e2d37fSdrh   ** is not present, then the current string used for NULL is returned.
264819e2d37fSdrh   ** If STRING is present, then STRING is returned.
264919e2d37fSdrh   **
265019e2d37fSdrh   */
265119e2d37fSdrh   case DB_NULLVALUE: {
265219e2d37fSdrh     if( objc!=2 && objc!=3 ){
265319e2d37fSdrh       Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
265419e2d37fSdrh       return TCL_ERROR;
265519e2d37fSdrh     }
265619e2d37fSdrh     if( objc==3 ){
265719e2d37fSdrh       int len;
265819e2d37fSdrh       char *zNull = Tcl_GetStringFromObj(objv[2], &len);
265919e2d37fSdrh       if( pDb->zNull ){
266019e2d37fSdrh         Tcl_Free(pDb->zNull);
266119e2d37fSdrh       }
266219e2d37fSdrh       if( zNull && len>0 ){
266319e2d37fSdrh         pDb->zNull = Tcl_Alloc( len + 1 );
26647fd33929Sdrh         memcpy(pDb->zNull, zNull, len);
266519e2d37fSdrh         pDb->zNull[len] = '\0';
266619e2d37fSdrh       }else{
266719e2d37fSdrh         pDb->zNull = 0;
266819e2d37fSdrh       }
266919e2d37fSdrh     }
2670c45e6716Sdrh     Tcl_SetObjResult(interp, Tcl_NewStringObj(pDb->zNull, -1));
267119e2d37fSdrh     break;
267219e2d37fSdrh   }
267319e2d37fSdrh 
267419e2d37fSdrh   /*
2675af9ff33aSdrh   **     $db last_insert_rowid
2676af9ff33aSdrh   **
2677af9ff33aSdrh   ** Return an integer which is the ROWID for the most recent insert.
2678af9ff33aSdrh   */
2679af9ff33aSdrh   case DB_LAST_INSERT_ROWID: {
2680af9ff33aSdrh     Tcl_Obj *pResult;
2681f7e678d6Sdrh     Tcl_WideInt rowid;
2682af9ff33aSdrh     if( objc!=2 ){
2683af9ff33aSdrh       Tcl_WrongNumArgs(interp, 2, objv, "");
2684af9ff33aSdrh       return TCL_ERROR;
2685af9ff33aSdrh     }
26866f8a503dSdanielk1977     rowid = sqlite3_last_insert_rowid(pDb->db);
2687af9ff33aSdrh     pResult = Tcl_GetObjResult(interp);
2688f7e678d6Sdrh     Tcl_SetWideIntObj(pResult, rowid);
2689af9ff33aSdrh     break;
2690af9ff33aSdrh   }
2691af9ff33aSdrh 
2692af9ff33aSdrh   /*
26934a4c11aaSdan   ** The DB_ONECOLUMN method is implemented together with DB_EXISTS.
26945d9d7576Sdrh   */
26951807ce37Sdrh 
26961807ce37Sdrh   /*    $db progress ?N CALLBACK?
26971807ce37Sdrh   **
26981807ce37Sdrh   ** Invoke the given callback every N virtual machine opcodes while executing
26991807ce37Sdrh   ** queries.
27001807ce37Sdrh   */
27011807ce37Sdrh   case DB_PROGRESS: {
27021807ce37Sdrh     if( objc==2 ){
27031807ce37Sdrh       if( pDb->zProgress ){
2704a198f2b5Sdrh         Tcl_AppendResult(interp, pDb->zProgress, (char*)0);
27055d9d7576Sdrh       }
27061807ce37Sdrh     }else if( objc==4 ){
27071807ce37Sdrh       char *zProgress;
27081807ce37Sdrh       int len;
27091807ce37Sdrh       int N;
27101807ce37Sdrh       if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
27111807ce37Sdrh         return TCL_ERROR;
27121807ce37Sdrh       };
27131807ce37Sdrh       if( pDb->zProgress ){
27141807ce37Sdrh         Tcl_Free(pDb->zProgress);
27151807ce37Sdrh       }
27161807ce37Sdrh       zProgress = Tcl_GetStringFromObj(objv[3], &len);
27171807ce37Sdrh       if( zProgress && len>0 ){
27181807ce37Sdrh         pDb->zProgress = Tcl_Alloc( len + 1 );
27195bb3eb9bSdrh         memcpy(pDb->zProgress, zProgress, len+1);
27201807ce37Sdrh       }else{
27211807ce37Sdrh         pDb->zProgress = 0;
27221807ce37Sdrh       }
27231807ce37Sdrh #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
27241807ce37Sdrh       if( pDb->zProgress ){
27251807ce37Sdrh         pDb->interp = interp;
27261807ce37Sdrh         sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
27271807ce37Sdrh       }else{
27281807ce37Sdrh         sqlite3_progress_handler(pDb->db, 0, 0, 0);
27291807ce37Sdrh       }
27301807ce37Sdrh #endif
27311807ce37Sdrh     }else{
27321807ce37Sdrh       Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
27331807ce37Sdrh       return TCL_ERROR;
27345d9d7576Sdrh     }
27355d9d7576Sdrh     break;
27365d9d7576Sdrh   }
27375d9d7576Sdrh 
273819e2d37fSdrh   /*    $db profile ?CALLBACK?
273919e2d37fSdrh   **
274019e2d37fSdrh   ** Make arrangements to invoke the CALLBACK routine after each SQL statement
274119e2d37fSdrh   ** that has run.  The text of the SQL and the amount of elapse time are
274219e2d37fSdrh   ** appended to CALLBACK before the script is run.
274319e2d37fSdrh   */
274419e2d37fSdrh   case DB_PROFILE: {
274519e2d37fSdrh     if( objc>3 ){
274619e2d37fSdrh       Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
274719e2d37fSdrh       return TCL_ERROR;
274819e2d37fSdrh     }else if( objc==2 ){
274919e2d37fSdrh       if( pDb->zProfile ){
2750a198f2b5Sdrh         Tcl_AppendResult(interp, pDb->zProfile, (char*)0);
275119e2d37fSdrh       }
275219e2d37fSdrh     }else{
275319e2d37fSdrh       char *zProfile;
275419e2d37fSdrh       int len;
275519e2d37fSdrh       if( pDb->zProfile ){
275619e2d37fSdrh         Tcl_Free(pDb->zProfile);
275719e2d37fSdrh       }
275819e2d37fSdrh       zProfile = Tcl_GetStringFromObj(objv[2], &len);
275919e2d37fSdrh       if( zProfile && len>0 ){
276019e2d37fSdrh         pDb->zProfile = Tcl_Alloc( len + 1 );
27615bb3eb9bSdrh         memcpy(pDb->zProfile, zProfile, len+1);
276219e2d37fSdrh       }else{
276319e2d37fSdrh         pDb->zProfile = 0;
276419e2d37fSdrh       }
27652eb22af0Sdrh #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
27662eb22af0Sdrh     !defined(SQLITE_OMIT_DEPRECATED)
276719e2d37fSdrh       if( pDb->zProfile ){
276819e2d37fSdrh         pDb->interp = interp;
276919e2d37fSdrh         sqlite3_profile(pDb->db, DbProfileHandler, pDb);
277019e2d37fSdrh       }else{
277119e2d37fSdrh         sqlite3_profile(pDb->db, 0, 0);
277219e2d37fSdrh       }
277319e2d37fSdrh #endif
277419e2d37fSdrh     }
277519e2d37fSdrh     break;
277619e2d37fSdrh   }
277719e2d37fSdrh 
27785d9d7576Sdrh   /*
277922fbcb8dSdrh   **     $db rekey KEY
278022fbcb8dSdrh   **
278122fbcb8dSdrh   ** Change the encryption key on the currently open database.
278222fbcb8dSdrh   */
278322fbcb8dSdrh   case DB_REKEY: {
278432f57d4cSdrh #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
278522fbcb8dSdrh     int nKey;
278622fbcb8dSdrh     void *pKey;
2787b07028f7Sdrh #endif
278822fbcb8dSdrh     if( objc!=3 ){
278922fbcb8dSdrh       Tcl_WrongNumArgs(interp, 2, objv, "KEY");
279022fbcb8dSdrh       return TCL_ERROR;
279122fbcb8dSdrh     }
279232f57d4cSdrh #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
2793b07028f7Sdrh     pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
27942011d5f5Sdrh     rc = sqlite3_rekey(pDb->db, pKey, nKey);
279522fbcb8dSdrh     if( rc ){
2796a198f2b5Sdrh       Tcl_AppendResult(interp, sqlite3_errstr(rc), (char*)0);
279722fbcb8dSdrh       rc = TCL_ERROR;
279822fbcb8dSdrh     }
279922fbcb8dSdrh #endif
280022fbcb8dSdrh     break;
280122fbcb8dSdrh   }
280222fbcb8dSdrh 
2803dc2c4915Sdrh   /*    $db restore ?DATABASE? FILENAME
2804dc2c4915Sdrh   **
2805dc2c4915Sdrh   ** Open a database file named FILENAME.  Transfer the content
2806dc2c4915Sdrh   ** of FILENAME into the local database DATABASE (default: "main").
2807dc2c4915Sdrh   */
2808dc2c4915Sdrh   case DB_RESTORE: {
2809dc2c4915Sdrh     const char *zSrcFile;
2810dc2c4915Sdrh     const char *zDestDb;
2811dc2c4915Sdrh     sqlite3 *pSrc;
2812dc2c4915Sdrh     sqlite3_backup *pBackup;
2813dc2c4915Sdrh     int nTimeout = 0;
2814dc2c4915Sdrh 
2815dc2c4915Sdrh     if( objc==3 ){
2816dc2c4915Sdrh       zDestDb = "main";
2817dc2c4915Sdrh       zSrcFile = Tcl_GetString(objv[2]);
2818dc2c4915Sdrh     }else if( objc==4 ){
2819dc2c4915Sdrh       zDestDb = Tcl_GetString(objv[2]);
2820dc2c4915Sdrh       zSrcFile = Tcl_GetString(objv[3]);
2821dc2c4915Sdrh     }else{
2822dc2c4915Sdrh       Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
2823dc2c4915Sdrh       return TCL_ERROR;
2824dc2c4915Sdrh     }
2825147ef394Sdrh     rc = sqlite3_open_v2(zSrcFile, &pSrc,
2826147ef394Sdrh                          SQLITE_OPEN_READONLY | pDb->openFlags, 0);
2827dc2c4915Sdrh     if( rc!=SQLITE_OK ){
2828dc2c4915Sdrh       Tcl_AppendResult(interp, "cannot open source database: ",
2829dc2c4915Sdrh            sqlite3_errmsg(pSrc), (char*)0);
2830dc2c4915Sdrh       sqlite3_close(pSrc);
2831dc2c4915Sdrh       return TCL_ERROR;
2832dc2c4915Sdrh     }
2833dc2c4915Sdrh     pBackup = sqlite3_backup_init(pDb->db, zDestDb, pSrc, "main");
2834dc2c4915Sdrh     if( pBackup==0 ){
2835dc2c4915Sdrh       Tcl_AppendResult(interp, "restore failed: ",
2836dc2c4915Sdrh            sqlite3_errmsg(pDb->db), (char*)0);
2837dc2c4915Sdrh       sqlite3_close(pSrc);
2838dc2c4915Sdrh       return TCL_ERROR;
2839dc2c4915Sdrh     }
2840dc2c4915Sdrh     while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
2841dc2c4915Sdrh               || rc==SQLITE_BUSY ){
2842dc2c4915Sdrh       if( rc==SQLITE_BUSY ){
2843dc2c4915Sdrh         if( nTimeout++ >= 3 ) break;
2844dc2c4915Sdrh         sqlite3_sleep(100);
2845dc2c4915Sdrh       }
2846dc2c4915Sdrh     }
2847dc2c4915Sdrh     sqlite3_backup_finish(pBackup);
2848dc2c4915Sdrh     if( rc==SQLITE_DONE ){
2849dc2c4915Sdrh       rc = TCL_OK;
2850dc2c4915Sdrh     }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
2851dc2c4915Sdrh       Tcl_AppendResult(interp, "restore failed: source database busy",
2852dc2c4915Sdrh                        (char*)0);
2853dc2c4915Sdrh       rc = TCL_ERROR;
2854dc2c4915Sdrh     }else{
2855dc2c4915Sdrh       Tcl_AppendResult(interp, "restore failed: ",
2856dc2c4915Sdrh            sqlite3_errmsg(pDb->db), (char*)0);
2857dc2c4915Sdrh       rc = TCL_ERROR;
2858dc2c4915Sdrh     }
2859dc2c4915Sdrh     sqlite3_close(pSrc);
2860dc2c4915Sdrh     break;
2861dc2c4915Sdrh   }
2862dc2c4915Sdrh 
286322fbcb8dSdrh   /*
28643c379b01Sdrh   **     $db status (step|sort|autoindex)
2865d1d38488Sdrh   **
2866d1d38488Sdrh   ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or
2867d1d38488Sdrh   ** SQLITE_STMTSTATUS_SORT for the most recent eval.
2868d1d38488Sdrh   */
2869d1d38488Sdrh   case DB_STATUS: {
2870d1d38488Sdrh     int v;
2871d1d38488Sdrh     const char *zOp;
2872d1d38488Sdrh     if( objc!=3 ){
28731c320a43Sdrh       Tcl_WrongNumArgs(interp, 2, objv, "(step|sort|autoindex)");
2874d1d38488Sdrh       return TCL_ERROR;
2875d1d38488Sdrh     }
2876d1d38488Sdrh     zOp = Tcl_GetString(objv[2]);
2877d1d38488Sdrh     if( strcmp(zOp, "step")==0 ){
2878d1d38488Sdrh       v = pDb->nStep;
2879d1d38488Sdrh     }else if( strcmp(zOp, "sort")==0 ){
2880d1d38488Sdrh       v = pDb->nSort;
28813c379b01Sdrh     }else if( strcmp(zOp, "autoindex")==0 ){
28823c379b01Sdrh       v = pDb->nIndex;
2883d1d38488Sdrh     }else{
28843c379b01Sdrh       Tcl_AppendResult(interp,
28853c379b01Sdrh             "bad argument: should be autoindex, step, or sort",
2886d1d38488Sdrh             (char*)0);
2887d1d38488Sdrh       return TCL_ERROR;
2888d1d38488Sdrh     }
2889d1d38488Sdrh     Tcl_SetObjResult(interp, Tcl_NewIntObj(v));
2890d1d38488Sdrh     break;
2891d1d38488Sdrh   }
2892d1d38488Sdrh 
2893d1d38488Sdrh   /*
2894bec3f402Sdrh   **     $db timeout MILLESECONDS
2895bec3f402Sdrh   **
2896bec3f402Sdrh   ** Delay for the number of milliseconds specified when a file is locked.
2897bec3f402Sdrh   */
28986d31316cSdrh   case DB_TIMEOUT: {
2899bec3f402Sdrh     int ms;
29006d31316cSdrh     if( objc!=3 ){
29016d31316cSdrh       Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
2902bec3f402Sdrh       return TCL_ERROR;
290375897234Sdrh     }
29046d31316cSdrh     if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
29056f8a503dSdanielk1977     sqlite3_busy_timeout(pDb->db, ms);
29066d31316cSdrh     break;
290775897234Sdrh   }
2908b5a20d3cSdrh 
29090f14e2ebSdrh   /*
29100f14e2ebSdrh   **     $db total_changes
29110f14e2ebSdrh   **
29120f14e2ebSdrh   ** Return the number of rows that were modified, inserted, or deleted
29130f14e2ebSdrh   ** since the database handle was created.
29140f14e2ebSdrh   */
29150f14e2ebSdrh   case DB_TOTAL_CHANGES: {
29160f14e2ebSdrh     Tcl_Obj *pResult;
29170f14e2ebSdrh     if( objc!=2 ){
29180f14e2ebSdrh       Tcl_WrongNumArgs(interp, 2, objv, "");
29190f14e2ebSdrh       return TCL_ERROR;
29200f14e2ebSdrh     }
29210f14e2ebSdrh     pResult = Tcl_GetObjResult(interp);
29220f14e2ebSdrh     Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
29230f14e2ebSdrh     break;
29240f14e2ebSdrh   }
29250f14e2ebSdrh 
2926b5a20d3cSdrh   /*    $db trace ?CALLBACK?
2927b5a20d3cSdrh   **
2928b5a20d3cSdrh   ** Make arrangements to invoke the CALLBACK routine for each SQL statement
2929b5a20d3cSdrh   ** that is executed.  The text of the SQL is appended to CALLBACK before
2930b5a20d3cSdrh   ** it is executed.
2931b5a20d3cSdrh   */
2932b5a20d3cSdrh   case DB_TRACE: {
2933b5a20d3cSdrh     if( objc>3 ){
2934b5a20d3cSdrh       Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2935b97759edSdrh       return TCL_ERROR;
2936b5a20d3cSdrh     }else if( objc==2 ){
2937b5a20d3cSdrh       if( pDb->zTrace ){
2938a198f2b5Sdrh         Tcl_AppendResult(interp, pDb->zTrace, (char*)0);
2939b5a20d3cSdrh       }
2940b5a20d3cSdrh     }else{
2941b5a20d3cSdrh       char *zTrace;
2942b5a20d3cSdrh       int len;
2943b5a20d3cSdrh       if( pDb->zTrace ){
2944b5a20d3cSdrh         Tcl_Free(pDb->zTrace);
2945b5a20d3cSdrh       }
2946b5a20d3cSdrh       zTrace = Tcl_GetStringFromObj(objv[2], &len);
2947b5a20d3cSdrh       if( zTrace && len>0 ){
2948b5a20d3cSdrh         pDb->zTrace = Tcl_Alloc( len + 1 );
29495bb3eb9bSdrh         memcpy(pDb->zTrace, zTrace, len+1);
2950b5a20d3cSdrh       }else{
2951b5a20d3cSdrh         pDb->zTrace = 0;
2952b5a20d3cSdrh       }
29532eb22af0Sdrh #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
29542eb22af0Sdrh     !defined(SQLITE_OMIT_DEPRECATED)
2955b5a20d3cSdrh       if( pDb->zTrace ){
2956b5a20d3cSdrh         pDb->interp = interp;
29576f8a503dSdanielk1977         sqlite3_trace(pDb->db, DbTraceHandler, pDb);
2958b5a20d3cSdrh       }else{
29596f8a503dSdanielk1977         sqlite3_trace(pDb->db, 0, 0);
2960b5a20d3cSdrh       }
296119e2d37fSdrh #endif
2962b5a20d3cSdrh     }
2963b5a20d3cSdrh     break;
2964b5a20d3cSdrh   }
2965b5a20d3cSdrh 
2966b56660f5Smistachkin   /*    $db trace_v2 ?CALLBACK? ?MASK?
2967b56660f5Smistachkin   **
2968b56660f5Smistachkin   ** Make arrangements to invoke the CALLBACK routine for each trace event
2969b56660f5Smistachkin   ** matching the mask that is generated.  The parameters are appended to
2970b56660f5Smistachkin   ** CALLBACK before it is executed.
2971b56660f5Smistachkin   */
2972b56660f5Smistachkin   case DB_TRACE_V2: {
2973b56660f5Smistachkin     if( objc>4 ){
2974b56660f5Smistachkin       Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK? ?MASK?");
2975b56660f5Smistachkin       return TCL_ERROR;
2976b56660f5Smistachkin     }else if( objc==2 ){
2977b56660f5Smistachkin       if( pDb->zTraceV2 ){
2978b56660f5Smistachkin         Tcl_AppendResult(interp, pDb->zTraceV2, (char*)0);
2979b56660f5Smistachkin       }
2980b56660f5Smistachkin     }else{
2981b56660f5Smistachkin       char *zTraceV2;
2982b56660f5Smistachkin       int len;
2983b52dcd89Smistachkin       Tcl_WideInt wMask = 0;
2984b56660f5Smistachkin       if( objc==4 ){
2985b52dcd89Smistachkin         static const char *TTYPE_strs[] = {
2986b52dcd89Smistachkin           "statement", "profile", "row", "close", 0
2987b52dcd89Smistachkin         };
2988b52dcd89Smistachkin         enum TTYPE_enum {
2989b52dcd89Smistachkin           TTYPE_STMT, TTYPE_PROFILE, TTYPE_ROW, TTYPE_CLOSE
2990b52dcd89Smistachkin         };
2991b52dcd89Smistachkin         int i;
2992b52dcd89Smistachkin         if( TCL_OK!=Tcl_ListObjLength(interp, objv[3], &len) ){
2993b52dcd89Smistachkin           return TCL_ERROR;
2994b52dcd89Smistachkin         }
2995b52dcd89Smistachkin         for(i=0; i<len; i++){
2996b52dcd89Smistachkin           Tcl_Obj *pObj;
2997b52dcd89Smistachkin           int ttype;
2998b52dcd89Smistachkin           if( TCL_OK!=Tcl_ListObjIndex(interp, objv[3], i, &pObj) ){
2999b52dcd89Smistachkin             return TCL_ERROR;
3000b52dcd89Smistachkin           }
3001b52dcd89Smistachkin           if( Tcl_GetIndexFromObj(interp, pObj, TTYPE_strs, "trace type",
3002b52dcd89Smistachkin                                   0, &ttype)!=TCL_OK ){
3003b52dcd89Smistachkin             Tcl_WideInt wType;
3004b52dcd89Smistachkin             Tcl_Obj *pError = Tcl_DuplicateObj(Tcl_GetObjResult(interp));
3005b52dcd89Smistachkin             Tcl_IncrRefCount(pError);
3006b52dcd89Smistachkin             if( TCL_OK==Tcl_GetWideIntFromObj(interp, pObj, &wType) ){
3007b52dcd89Smistachkin               Tcl_DecrRefCount(pError);
3008b52dcd89Smistachkin               wMask |= wType;
3009b52dcd89Smistachkin             }else{
3010b52dcd89Smistachkin               Tcl_SetObjResult(interp, pError);
3011b52dcd89Smistachkin               Tcl_DecrRefCount(pError);
3012b56660f5Smistachkin               return TCL_ERROR;
3013b56660f5Smistachkin             }
3014b56660f5Smistachkin           }else{
3015b52dcd89Smistachkin             switch( (enum TTYPE_enum)ttype ){
3016b52dcd89Smistachkin               case TTYPE_STMT:    wMask |= SQLITE_TRACE_STMT;    break;
3017b52dcd89Smistachkin               case TTYPE_PROFILE: wMask |= SQLITE_TRACE_PROFILE; break;
3018b52dcd89Smistachkin               case TTYPE_ROW:     wMask |= SQLITE_TRACE_ROW;     break;
3019b52dcd89Smistachkin               case TTYPE_CLOSE:   wMask |= SQLITE_TRACE_CLOSE;   break;
3020b52dcd89Smistachkin             }
3021b52dcd89Smistachkin           }
3022b52dcd89Smistachkin         }
3023b52dcd89Smistachkin       }else{
3024b52dcd89Smistachkin         wMask = SQLITE_TRACE_STMT; /* use the "legacy" default */
3025b56660f5Smistachkin       }
3026b56660f5Smistachkin       if( pDb->zTraceV2 ){
3027b56660f5Smistachkin         Tcl_Free(pDb->zTraceV2);
3028b56660f5Smistachkin       }
3029b56660f5Smistachkin       zTraceV2 = Tcl_GetStringFromObj(objv[2], &len);
3030b56660f5Smistachkin       if( zTraceV2 && len>0 ){
3031b56660f5Smistachkin         pDb->zTraceV2 = Tcl_Alloc( len + 1 );
3032b56660f5Smistachkin         memcpy(pDb->zTraceV2, zTraceV2, len+1);
3033b56660f5Smistachkin       }else{
3034b56660f5Smistachkin         pDb->zTraceV2 = 0;
3035b56660f5Smistachkin       }
3036b56660f5Smistachkin #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
3037b56660f5Smistachkin       if( pDb->zTraceV2 ){
3038b56660f5Smistachkin         pDb->interp = interp;
3039b56660f5Smistachkin         sqlite3_trace_v2(pDb->db, (unsigned)wMask, DbTraceV2Handler, pDb);
3040b56660f5Smistachkin       }else{
3041b56660f5Smistachkin         sqlite3_trace_v2(pDb->db, 0, 0, 0);
3042b56660f5Smistachkin       }
3043b56660f5Smistachkin #endif
3044b56660f5Smistachkin     }
3045b56660f5Smistachkin     break;
3046b56660f5Smistachkin   }
3047b56660f5Smistachkin 
30483d21423cSdrh   /*    $db transaction [-deferred|-immediate|-exclusive] SCRIPT
30493d21423cSdrh   **
30503d21423cSdrh   ** Start a new transaction (if we are not already in the midst of a
30513d21423cSdrh   ** transaction) and execute the TCL script SCRIPT.  After SCRIPT
30523d21423cSdrh   ** completes, either commit the transaction or roll it back if SCRIPT
30533d21423cSdrh   ** throws an exception.  Or if no new transation was started, do nothing.
30543d21423cSdrh   ** pass the exception on up the stack.
30553d21423cSdrh   **
30563d21423cSdrh   ** This command was inspired by Dave Thomas's talk on Ruby at the
30573d21423cSdrh   ** 2005 O'Reilly Open Source Convention (OSCON).
30583d21423cSdrh   */
30593d21423cSdrh   case DB_TRANSACTION: {
30603d21423cSdrh     Tcl_Obj *pScript;
3061cd38d520Sdanielk1977     const char *zBegin = "SAVEPOINT _tcl_transaction";
30623d21423cSdrh     if( objc!=3 && objc!=4 ){
30633d21423cSdrh       Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
30643d21423cSdrh       return TCL_ERROR;
30653d21423cSdrh     }
3066cd38d520Sdanielk1977 
30674a4c11aaSdan     if( pDb->nTransaction==0 && objc==4 ){
30683d21423cSdrh       static const char *TTYPE_strs[] = {
3069ce604012Sdrh         "deferred",   "exclusive",  "immediate", 0
30703d21423cSdrh       };
30713d21423cSdrh       enum TTYPE_enum {
30723d21423cSdrh         TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
30733d21423cSdrh       };
30743d21423cSdrh       int ttype;
3075b5555e7eSdrh       if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
30763d21423cSdrh                               0, &ttype) ){
30773d21423cSdrh         return TCL_ERROR;
30783d21423cSdrh       }
30793d21423cSdrh       switch( (enum TTYPE_enum)ttype ){
30803d21423cSdrh         case TTYPE_DEFERRED:    /* no-op */;                 break;
30813d21423cSdrh         case TTYPE_EXCLUSIVE:   zBegin = "BEGIN EXCLUSIVE";  break;
30823d21423cSdrh         case TTYPE_IMMEDIATE:   zBegin = "BEGIN IMMEDIATE";  break;
30833d21423cSdrh       }
30843d21423cSdrh     }
3085cd38d520Sdanielk1977     pScript = objv[objc-1];
3086cd38d520Sdanielk1977 
30874a4c11aaSdan     /* Run the SQLite BEGIN command to open a transaction or savepoint. */
30881f1549f8Sdrh     pDb->disableAuth++;
3089cd38d520Sdanielk1977     rc = sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
30901f1549f8Sdrh     pDb->disableAuth--;
3091cd38d520Sdanielk1977     if( rc!=SQLITE_OK ){
3092a198f2b5Sdrh       Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
3093cd38d520Sdanielk1977       return TCL_ERROR;
30943d21423cSdrh     }
3095cd38d520Sdanielk1977     pDb->nTransaction++;
3096cd38d520Sdanielk1977 
30974a4c11aaSdan     /* If using NRE, schedule a callback to invoke the script pScript, then
30984a4c11aaSdan     ** a second callback to commit (or rollback) the transaction or savepoint
30994a4c11aaSdan     ** opened above. If not using NRE, evaluate the script directly, then
31004a4c11aaSdan     ** call function DbTransPostCmd() to commit (or rollback) the transaction
31014a4c11aaSdan     ** or savepoint.  */
31024a4c11aaSdan     if( DbUseNre() ){
31034a4c11aaSdan       Tcl_NRAddCallback(interp, DbTransPostCmd, cd, 0, 0, 0);
3104a47941feSdrh       (void)Tcl_NREvalObj(interp, pScript, 0);
31053d21423cSdrh     }else{
31064a4c11aaSdan       rc = DbTransPostCmd(&cd, interp, Tcl_EvalObjEx(interp, pScript, 0));
31073d21423cSdrh     }
31083d21423cSdrh     break;
31093d21423cSdrh   }
31103d21423cSdrh 
311194eb6a14Sdanielk1977   /*
3112404ca075Sdanielk1977   **    $db unlock_notify ?script?
3113404ca075Sdanielk1977   */
3114404ca075Sdanielk1977   case DB_UNLOCK_NOTIFY: {
3115404ca075Sdanielk1977 #ifndef SQLITE_ENABLE_UNLOCK_NOTIFY
3116a198f2b5Sdrh     Tcl_AppendResult(interp, "unlock_notify not available in this build",
3117a198f2b5Sdrh                      (char*)0);
3118404ca075Sdanielk1977     rc = TCL_ERROR;
3119404ca075Sdanielk1977 #else
3120404ca075Sdanielk1977     if( objc!=2 && objc!=3 ){
3121404ca075Sdanielk1977       Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
3122404ca075Sdanielk1977       rc = TCL_ERROR;
3123404ca075Sdanielk1977     }else{
3124404ca075Sdanielk1977       void (*xNotify)(void **, int) = 0;
3125404ca075Sdanielk1977       void *pNotifyArg = 0;
3126404ca075Sdanielk1977 
3127404ca075Sdanielk1977       if( pDb->pUnlockNotify ){
3128404ca075Sdanielk1977         Tcl_DecrRefCount(pDb->pUnlockNotify);
3129404ca075Sdanielk1977         pDb->pUnlockNotify = 0;
3130404ca075Sdanielk1977       }
3131404ca075Sdanielk1977 
3132404ca075Sdanielk1977       if( objc==3 ){
3133404ca075Sdanielk1977         xNotify = DbUnlockNotify;
3134404ca075Sdanielk1977         pNotifyArg = (void *)pDb;
3135404ca075Sdanielk1977         pDb->pUnlockNotify = objv[2];
3136404ca075Sdanielk1977         Tcl_IncrRefCount(pDb->pUnlockNotify);
3137404ca075Sdanielk1977       }
3138404ca075Sdanielk1977 
3139404ca075Sdanielk1977       if( sqlite3_unlock_notify(pDb->db, xNotify, pNotifyArg) ){
3140a198f2b5Sdrh         Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
3141404ca075Sdanielk1977         rc = TCL_ERROR;
3142404ca075Sdanielk1977       }
3143404ca075Sdanielk1977     }
3144404ca075Sdanielk1977 #endif
3145404ca075Sdanielk1977     break;
3146404ca075Sdanielk1977   }
3147404ca075Sdanielk1977 
3148304637c0Sdrh   /*
3149304637c0Sdrh   **    $db preupdate_hook count
3150304637c0Sdrh   **    $db preupdate_hook hook ?SCRIPT?
3151304637c0Sdrh   **    $db preupdate_hook new INDEX
3152304637c0Sdrh   **    $db preupdate_hook old INDEX
3153304637c0Sdrh   */
315446c47d46Sdan   case DB_PREUPDATE: {
31559b1c62d4Sdrh #ifndef SQLITE_ENABLE_PREUPDATE_HOOK
31562b519ab0Sdan     Tcl_AppendResult(interp, "preupdate_hook was omitted at compile-time",
31572b519ab0Sdan                      (char*)0);
31589b1c62d4Sdrh     rc = TCL_ERROR;
31599b1c62d4Sdrh #else
31601e7a2d43Sdan     static const char *azSub[] = {"count", "depth", "hook", "new", "old", 0};
316146c47d46Sdan     enum DbPreupdateSubCmd {
31621e7a2d43Sdan       PRE_COUNT, PRE_DEPTH, PRE_HOOK, PRE_NEW, PRE_OLD
316346c47d46Sdan     };
316446c47d46Sdan     int iSub;
316546c47d46Sdan 
316646c47d46Sdan     if( objc<3 ){
316746c47d46Sdan       Tcl_WrongNumArgs(interp, 2, objv, "SUB-COMMAND ?ARGS?");
316846c47d46Sdan     }
316946c47d46Sdan     if( Tcl_GetIndexFromObj(interp, objv[2], azSub, "sub-command", 0, &iSub) ){
317046c47d46Sdan       return TCL_ERROR;
317146c47d46Sdan     }
317246c47d46Sdan 
317346c47d46Sdan     switch( (enum DbPreupdateSubCmd)iSub ){
317446c47d46Sdan       case PRE_COUNT: {
317546c47d46Sdan         int nCol = sqlite3_preupdate_count(pDb->db);
317646c47d46Sdan         Tcl_SetObjResult(interp, Tcl_NewIntObj(nCol));
317746c47d46Sdan         break;
317846c47d46Sdan       }
317946c47d46Sdan 
318046c47d46Sdan       case PRE_HOOK: {
318146c47d46Sdan         if( objc>4 ){
318246c47d46Sdan           Tcl_WrongNumArgs(interp, 2, objv, "hook ?SCRIPT?");
318346c47d46Sdan           return TCL_ERROR;
318446c47d46Sdan         }
318546c47d46Sdan         DbHookCmd(interp, pDb, (objc==4 ? objv[3] : 0), &pDb->pPreUpdateHook);
318646c47d46Sdan         break;
318746c47d46Sdan       }
318846c47d46Sdan 
31891e7a2d43Sdan       case PRE_DEPTH: {
31901e7a2d43Sdan         Tcl_Obj *pRet;
31911e7a2d43Sdan         if( objc!=3 ){
31921e7a2d43Sdan           Tcl_WrongNumArgs(interp, 3, objv, "");
31931e7a2d43Sdan           return TCL_ERROR;
31941e7a2d43Sdan         }
31951e7a2d43Sdan         pRet = Tcl_NewIntObj(sqlite3_preupdate_depth(pDb->db));
31961e7a2d43Sdan         Tcl_SetObjResult(interp, pRet);
31971e7a2d43Sdan         break;
31981e7a2d43Sdan       }
31991e7a2d43Sdan 
320037db03bfSdan       case PRE_NEW:
320146c47d46Sdan       case PRE_OLD: {
320246c47d46Sdan         int iIdx;
320337db03bfSdan         sqlite3_value *pValue;
320446c47d46Sdan         if( objc!=4 ){
320546c47d46Sdan           Tcl_WrongNumArgs(interp, 3, objv, "INDEX");
320646c47d46Sdan           return TCL_ERROR;
320746c47d46Sdan         }
320846c47d46Sdan         if( Tcl_GetIntFromObj(interp, objv[3], &iIdx) ){
320946c47d46Sdan           return TCL_ERROR;
321046c47d46Sdan         }
321146c47d46Sdan 
321237db03bfSdan         if( iSub==PRE_OLD ){
321346c47d46Sdan           rc = sqlite3_preupdate_old(pDb->db, iIdx, &pValue);
321437db03bfSdan         }else{
321537db03bfSdan           assert( iSub==PRE_NEW );
321637db03bfSdan           rc = sqlite3_preupdate_new(pDb->db, iIdx, &pValue);
321737db03bfSdan         }
321837db03bfSdan 
321946c47d46Sdan         if( rc==SQLITE_OK ){
3220304637c0Sdrh           Tcl_Obj *pObj;
3221304637c0Sdrh           pObj = Tcl_NewStringObj((char*)sqlite3_value_text(pValue), -1);
322246c47d46Sdan           Tcl_SetObjResult(interp, pObj);
322337db03bfSdan         }else{
3224ea8f0a15Sdrh           Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
322546c47d46Sdan           return TCL_ERROR;
322646c47d46Sdan         }
322746c47d46Sdan       }
322846c47d46Sdan     }
32299b1c62d4Sdrh #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
323046c47d46Sdan     break;
323146c47d46Sdan   }
323246c47d46Sdan 
3233404ca075Sdanielk1977   /*
3234833bf968Sdrh   **    $db wal_hook ?script?
323594eb6a14Sdanielk1977   **    $db update_hook ?script?
323671fd80bfSdanielk1977   **    $db rollback_hook ?script?
323794eb6a14Sdanielk1977   */
3238833bf968Sdrh   case DB_WAL_HOOK:
323971fd80bfSdanielk1977   case DB_UPDATE_HOOK:
32406566ebe1Sdan   case DB_ROLLBACK_HOOK: {
324171fd80bfSdanielk1977     /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
324271fd80bfSdanielk1977     ** whether [$db update_hook] or [$db rollback_hook] was invoked.
324371fd80bfSdanielk1977     */
3244c5896b5cSmistachkin     Tcl_Obj **ppHook = 0;
324546c47d46Sdan     if( choice==DB_WAL_HOOK ) ppHook = &pDb->pWalHook;
324646c47d46Sdan     if( choice==DB_UPDATE_HOOK ) ppHook = &pDb->pUpdateHook;
324746c47d46Sdan     if( choice==DB_ROLLBACK_HOOK ) ppHook = &pDb->pRollbackHook;
324846c47d46Sdan     if( objc>3 ){
324994eb6a14Sdanielk1977        Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
325094eb6a14Sdanielk1977        return TCL_ERROR;
325194eb6a14Sdanielk1977     }
325271fd80bfSdanielk1977 
325346c47d46Sdan     DbHookCmd(interp, pDb, (objc==3 ? objv[2] : 0), ppHook);
325494eb6a14Sdanielk1977     break;
325594eb6a14Sdanielk1977   }
325694eb6a14Sdanielk1977 
32574397de57Sdanielk1977   /*    $db version
32584397de57Sdanielk1977   **
32594397de57Sdanielk1977   ** Return the version string for this database.
32604397de57Sdanielk1977   */
32614397de57Sdanielk1977   case DB_VERSION: {
32624397de57Sdanielk1977     Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
32634397de57Sdanielk1977     break;
32644397de57Sdanielk1977   }
32654397de57Sdanielk1977 
32661067fe11Stpoindex 
32676d31316cSdrh   } /* End of the SWITCH statement */
326822fbcb8dSdrh   return rc;
326975897234Sdrh }
327075897234Sdrh 
3271a2c8a95bSdrh #if SQLITE_TCL_NRE
3272a2c8a95bSdrh /*
3273a2c8a95bSdrh ** Adaptor that provides an objCmd interface to the NRE-enabled
3274a2c8a95bSdrh ** interface implementation.
3275a2c8a95bSdrh */
3276a121cc7cSmistachkin static int SQLITE_TCLAPI DbObjCmdAdaptor(
3277a2c8a95bSdrh   void *cd,
3278a2c8a95bSdrh   Tcl_Interp *interp,
3279a2c8a95bSdrh   int objc,
3280a2c8a95bSdrh   Tcl_Obj *const*objv
3281a2c8a95bSdrh ){
3282a2c8a95bSdrh   return Tcl_NRCallObjProc(interp, DbObjCmd, cd, objc, objv);
3283a2c8a95bSdrh }
3284a2c8a95bSdrh #endif /* SQLITE_TCL_NRE */
3285a2c8a95bSdrh 
328675897234Sdrh /*
32873570ad93Sdrh **   sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
32889a6284c1Sdanielk1977 **                           ?-create BOOLEAN? ?-nomutex BOOLEAN?
328975897234Sdrh **
329075897234Sdrh ** This is the main Tcl command.  When the "sqlite" Tcl command is
329175897234Sdrh ** invoked, this routine runs to process that command.
329275897234Sdrh **
329375897234Sdrh ** The first argument, DBNAME, is an arbitrary name for a new
329475897234Sdrh ** database connection.  This command creates a new command named
329575897234Sdrh ** DBNAME that is used to control that connection.  The database
329675897234Sdrh ** connection is deleted when the DBNAME command is deleted.
329775897234Sdrh **
32983570ad93Sdrh ** The second argument is the name of the database file.
3299fbc3eab8Sdrh **
330075897234Sdrh */
33017617e4a8Smistachkin static int SQLITE_TCLAPI DbMain(
33027617e4a8Smistachkin   void *cd,
33037617e4a8Smistachkin   Tcl_Interp *interp,
33047617e4a8Smistachkin   int objc,
33057617e4a8Smistachkin   Tcl_Obj *const*objv
33067617e4a8Smistachkin ){
3307bec3f402Sdrh   SqliteDb *p;
330822fbcb8dSdrh   const char *zArg;
330975897234Sdrh   char *zErrMsg;
33103570ad93Sdrh   int i;
331122fbcb8dSdrh   const char *zFile;
33123570ad93Sdrh   const char *zVfs = 0;
3313d9da78a2Sdrh   int flags;
3314882e8e4dSdrh   Tcl_DString translatedFilename;
331532f57d4cSdrh #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3316b07028f7Sdrh   void *pKey = 0;
3317b07028f7Sdrh   int nKey = 0;
3318b07028f7Sdrh #endif
3319540ebf82Smistachkin   int rc;
3320d9da78a2Sdrh 
3321d9da78a2Sdrh   /* In normal use, each TCL interpreter runs in a single thread.  So
3322d9da78a2Sdrh   ** by default, we can turn of mutexing on SQLite database connections.
3323d9da78a2Sdrh   ** However, for testing purposes it is useful to have mutexes turned
3324d9da78a2Sdrh   ** on.  So, by default, mutexes default off.  But if compiled with
3325d9da78a2Sdrh   ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on.
3326d9da78a2Sdrh   */
3327d9da78a2Sdrh #ifdef SQLITE_TCL_DEFAULT_FULLMUTEX
3328d9da78a2Sdrh   flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
3329d9da78a2Sdrh #else
3330d9da78a2Sdrh   flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX;
3331d9da78a2Sdrh #endif
3332d9da78a2Sdrh 
333322fbcb8dSdrh   if( objc==2 ){
333422fbcb8dSdrh     zArg = Tcl_GetStringFromObj(objv[1], 0);
333522fbcb8dSdrh     if( strcmp(zArg,"-version")==0 ){
3336a198f2b5Sdrh       Tcl_AppendResult(interp,sqlite3_libversion(), (char*)0);
3337647cb0e1Sdrh       return TCL_OK;
3338647cb0e1Sdrh     }
333972bf6a3eSdrh     if( strcmp(zArg,"-sourceid")==0 ){
334072bf6a3eSdrh       Tcl_AppendResult(interp,sqlite3_sourceid(), (char*)0);
334172bf6a3eSdrh       return TCL_OK;
334272bf6a3eSdrh     }
33439eb9e26bSdrh     if( strcmp(zArg,"-has-codec")==0 ){
334432f57d4cSdrh #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3345a198f2b5Sdrh       Tcl_AppendResult(interp,"1",(char*)0);
334622fbcb8dSdrh #else
3347a198f2b5Sdrh       Tcl_AppendResult(interp,"0",(char*)0);
334822fbcb8dSdrh #endif
334922fbcb8dSdrh       return TCL_OK;
335022fbcb8dSdrh     }
3351fbc3eab8Sdrh   }
33523570ad93Sdrh   for(i=3; i+1<objc; i+=2){
33533570ad93Sdrh     zArg = Tcl_GetString(objv[i]);
335422fbcb8dSdrh     if( strcmp(zArg,"-key")==0 ){
335532f57d4cSdrh #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
33563570ad93Sdrh       pKey = Tcl_GetByteArrayFromObj(objv[i+1], &nKey);
3357b07028f7Sdrh #endif
33583570ad93Sdrh     }else if( strcmp(zArg, "-vfs")==0 ){
33593c3dd7b9Sdan       zVfs = Tcl_GetString(objv[i+1]);
33603570ad93Sdrh     }else if( strcmp(zArg, "-readonly")==0 ){
33613570ad93Sdrh       int b;
33623570ad93Sdrh       if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
33633570ad93Sdrh       if( b ){
336433f4e02aSdrh         flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
33653570ad93Sdrh         flags |= SQLITE_OPEN_READONLY;
33663570ad93Sdrh       }else{
33673570ad93Sdrh         flags &= ~SQLITE_OPEN_READONLY;
33683570ad93Sdrh         flags |= SQLITE_OPEN_READWRITE;
33693570ad93Sdrh       }
33703570ad93Sdrh     }else if( strcmp(zArg, "-create")==0 ){
33713570ad93Sdrh       int b;
33723570ad93Sdrh       if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
337333f4e02aSdrh       if( b && (flags & SQLITE_OPEN_READONLY)==0 ){
33743570ad93Sdrh         flags |= SQLITE_OPEN_CREATE;
33753570ad93Sdrh       }else{
33763570ad93Sdrh         flags &= ~SQLITE_OPEN_CREATE;
33773570ad93Sdrh       }
33789a6284c1Sdanielk1977     }else if( strcmp(zArg, "-nomutex")==0 ){
33799a6284c1Sdanielk1977       int b;
33809a6284c1Sdanielk1977       if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
33819a6284c1Sdanielk1977       if( b ){
33829a6284c1Sdanielk1977         flags |= SQLITE_OPEN_NOMUTEX;
3383039963adSdrh         flags &= ~SQLITE_OPEN_FULLMUTEX;
33849a6284c1Sdanielk1977       }else{
33859a6284c1Sdanielk1977         flags &= ~SQLITE_OPEN_NOMUTEX;
33869a6284c1Sdanielk1977       }
3387039963adSdrh     }else if( strcmp(zArg, "-fullmutex")==0 ){
3388039963adSdrh       int b;
3389039963adSdrh       if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3390039963adSdrh       if( b ){
3391039963adSdrh         flags |= SQLITE_OPEN_FULLMUTEX;
3392039963adSdrh         flags &= ~SQLITE_OPEN_NOMUTEX;
3393039963adSdrh       }else{
3394039963adSdrh         flags &= ~SQLITE_OPEN_FULLMUTEX;
3395039963adSdrh       }
3396f12b3f60Sdrh     }else if( strcmp(zArg, "-uri")==0 ){
3397f12b3f60Sdrh       int b;
3398f12b3f60Sdrh       if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3399f12b3f60Sdrh       if( b ){
3400f12b3f60Sdrh         flags |= SQLITE_OPEN_URI;
3401f12b3f60Sdrh       }else{
3402f12b3f60Sdrh         flags &= ~SQLITE_OPEN_URI;
3403f12b3f60Sdrh       }
34043570ad93Sdrh     }else{
34053570ad93Sdrh       Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
34063570ad93Sdrh       return TCL_ERROR;
340722fbcb8dSdrh     }
340822fbcb8dSdrh   }
34093570ad93Sdrh   if( objc<3 || (objc&1)!=1 ){
341022fbcb8dSdrh     Tcl_WrongNumArgs(interp, 1, objv,
34113570ad93Sdrh       "HANDLE FILENAME ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
341268bd4aa2Sdrh       " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN? ?-uri BOOLEAN?"
341332f57d4cSdrh #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
34143570ad93Sdrh       " ?-key CODECKEY?"
341522fbcb8dSdrh #endif
341622fbcb8dSdrh     );
341775897234Sdrh     return TCL_ERROR;
341875897234Sdrh   }
341975897234Sdrh   zErrMsg = 0;
34204cdc9e84Sdrh   p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
3421bec3f402Sdrh   memset(p, 0, sizeof(*p));
342222fbcb8dSdrh   zFile = Tcl_GetStringFromObj(objv[2], 0);
3423882e8e4dSdrh   zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
3424540ebf82Smistachkin   rc = sqlite3_open_v2(zFile, &p->db, flags, zVfs);
3425882e8e4dSdrh   Tcl_DStringFree(&translatedFilename);
3426540ebf82Smistachkin   if( p->db ){
342780290863Sdanielk1977     if( SQLITE_OK!=sqlite3_errcode(p->db) ){
34289404d50eSdrh       zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
342980290863Sdanielk1977       sqlite3_close(p->db);
343080290863Sdanielk1977       p->db = 0;
343180290863Sdanielk1977     }
3432540ebf82Smistachkin   }else{
34335dac8432Smistachkin     zErrMsg = sqlite3_mprintf("%s", sqlite3_errstr(rc));
3434540ebf82Smistachkin   }
343532f57d4cSdrh #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
3436f3a65f7eSdrh   if( p->db ){
34372011d5f5Sdrh     sqlite3_key(p->db, pKey, nKey);
3438f3a65f7eSdrh   }
3439eb8ed70dSdrh #endif
3440bec3f402Sdrh   if( p->db==0 ){
344175897234Sdrh     Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
3442bec3f402Sdrh     Tcl_Free((char*)p);
34439404d50eSdrh     sqlite3_free(zErrMsg);
344475897234Sdrh     return TCL_ERROR;
344575897234Sdrh   }
3446fb7e7651Sdrh   p->maxStmt = NUM_PREPARED_STMTS;
3447147ef394Sdrh   p->openFlags = flags & SQLITE_OPEN_URI;
34485169bbc6Sdrh   p->interp = interp;
344922fbcb8dSdrh   zArg = Tcl_GetStringFromObj(objv[1], 0);
34504a4c11aaSdan   if( DbUseNre() ){
3451a2c8a95bSdrh     Tcl_NRCreateCommand(interp, zArg, DbObjCmdAdaptor, DbObjCmd,
3452a2c8a95bSdrh                         (char*)p, DbDeleteCmd);
34534a4c11aaSdan   }else{
345422fbcb8dSdrh     Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
34554a4c11aaSdan   }
345675897234Sdrh   return TCL_OK;
345775897234Sdrh }
345875897234Sdrh 
345975897234Sdrh /*
346090ca9753Sdrh ** Provide a dummy Tcl_InitStubs if we are using this as a static
346190ca9753Sdrh ** library.
346290ca9753Sdrh */
346390ca9753Sdrh #ifndef USE_TCL_STUBS
346490ca9753Sdrh # undef  Tcl_InitStubs
34650e85ccfcSdrh # define Tcl_InitStubs(a,b,c) TCL_VERSION
346690ca9753Sdrh #endif
346790ca9753Sdrh 
346890ca9753Sdrh /*
346929bc4615Sdrh ** Make sure we have a PACKAGE_VERSION macro defined.  This will be
347029bc4615Sdrh ** defined automatically by the TEA makefile.  But other makefiles
347129bc4615Sdrh ** do not define it.
347229bc4615Sdrh */
347329bc4615Sdrh #ifndef PACKAGE_VERSION
347429bc4615Sdrh # define PACKAGE_VERSION SQLITE_VERSION
347529bc4615Sdrh #endif
347629bc4615Sdrh 
347729bc4615Sdrh /*
347875897234Sdrh ** Initialize this module.
347975897234Sdrh **
348075897234Sdrh ** This Tcl module contains only a single new Tcl command named "sqlite".
348175897234Sdrh ** (Hence there is no namespace.  There is no point in using a namespace
348275897234Sdrh ** if the extension only supplies one new name!)  The "sqlite" command is
348375897234Sdrh ** used to open a new SQLite database.  See the DbMain() routine above
348475897234Sdrh ** for additional information.
3485b652f432Sdrh **
3486b652f432Sdrh ** The EXTERN macros are required by TCL in order to work on windows.
348775897234Sdrh */
3488b652f432Sdrh EXTERN int Sqlite3_Init(Tcl_Interp *interp){
348927b2f053Smistachkin   int rc = Tcl_InitStubs(interp, "8.4", 0) ? TCL_OK : TCL_ERROR;
34906dc8cbe0Sdrh   if( rc==TCL_OK ){
3491ef4ac8f9Sdrh     Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
34921cca0d22Sdrh #ifndef SQLITE_3_SUFFIX_ONLY
34931cca0d22Sdrh     /* The "sqlite" alias is undocumented.  It is here only to support
34941cca0d22Sdrh     ** legacy scripts.  All new scripts should use only the "sqlite3"
34956dc8cbe0Sdrh     ** command. */
349649766d6cSdrh     Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
34974c0f1649Sdrh #endif
34986dc8cbe0Sdrh     rc = Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
34996dc8cbe0Sdrh   }
35006dc8cbe0Sdrh   return rc;
350190ca9753Sdrh }
3502b652f432Sdrh EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3503b652f432Sdrh EXTERN int Sqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3504b652f432Sdrh EXTERN int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3505e2c3a659Sdrh 
3506d878cab5Sdrh /* Because it accesses the file-system and uses persistent state, SQLite
3507e75a9eb9Sdrh ** is not considered appropriate for safe interpreters.  Hence, we cause
3508e75a9eb9Sdrh ** the _SafeInit() interfaces return TCL_ERROR.
3509d878cab5Sdrh */
3510e75a9eb9Sdrh EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_ERROR; }
3511e75a9eb9Sdrh EXTERN int Sqlite3_SafeUnload(Tcl_Interp *interp, int flags){return TCL_ERROR;}
3512e75a9eb9Sdrh 
3513e75a9eb9Sdrh 
351449766d6cSdrh 
351549766d6cSdrh #ifndef SQLITE_3_SUFFIX_ONLY
3516a3e63c4aSdan int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3517a3e63c4aSdan int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3518a3e63c4aSdan int Sqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3519a3e63c4aSdan int Tclsqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
352049766d6cSdrh #endif
352175897234Sdrh 
35223e27c026Sdrh #ifdef TCLSH
35233e27c026Sdrh /*****************************************************************************
352457a0227fSdrh ** All of the code that follows is used to build standalone TCL interpreters
352557a0227fSdrh ** that are statically linked with SQLite.  Enable these by compiling
352657a0227fSdrh ** with -DTCLSH=n where n can be 1 or 2.  An n of 1 generates a standard
352757a0227fSdrh ** tclsh but with SQLite built in.  An n of 2 generates the SQLite space
352857a0227fSdrh ** analysis program.
352975897234Sdrh */
3530348784efSdrh 
353157a0227fSdrh #if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
353257a0227fSdrh /*
353357a0227fSdrh  * This code implements the MD5 message-digest algorithm.
353457a0227fSdrh  * The algorithm is due to Ron Rivest.  This code was
353557a0227fSdrh  * written by Colin Plumb in 1993, no copyright is claimed.
353657a0227fSdrh  * This code is in the public domain; do with it what you wish.
353757a0227fSdrh  *
353857a0227fSdrh  * Equivalent code is available from RSA Data Security, Inc.
353957a0227fSdrh  * This code has been tested against that, and is equivalent,
354057a0227fSdrh  * except that you don't need to include two pages of legalese
354157a0227fSdrh  * with every copy.
354257a0227fSdrh  *
354357a0227fSdrh  * To compute the message digest of a chunk of bytes, declare an
354457a0227fSdrh  * MD5Context structure, pass it to MD5Init, call MD5Update as
354557a0227fSdrh  * needed on buffers full of bytes, and then call MD5Final, which
354657a0227fSdrh  * will fill a supplied 16-byte array with the digest.
354757a0227fSdrh  */
354857a0227fSdrh 
354957a0227fSdrh /*
355057a0227fSdrh  * If compiled on a machine that doesn't have a 32-bit integer,
355157a0227fSdrh  * you just set "uint32" to the appropriate datatype for an
355257a0227fSdrh  * unsigned 32-bit integer.  For example:
355357a0227fSdrh  *
355457a0227fSdrh  *       cc -Duint32='unsigned long' md5.c
355557a0227fSdrh  *
355657a0227fSdrh  */
355757a0227fSdrh #ifndef uint32
355857a0227fSdrh #  define uint32 unsigned int
355957a0227fSdrh #endif
356057a0227fSdrh 
356157a0227fSdrh struct MD5Context {
356257a0227fSdrh   int isInit;
356357a0227fSdrh   uint32 buf[4];
356457a0227fSdrh   uint32 bits[2];
356557a0227fSdrh   unsigned char in[64];
356657a0227fSdrh };
356757a0227fSdrh typedef struct MD5Context MD5Context;
356857a0227fSdrh 
356957a0227fSdrh /*
357057a0227fSdrh  * Note: this code is harmless on little-endian machines.
357157a0227fSdrh  */
357257a0227fSdrh static void byteReverse (unsigned char *buf, unsigned longs){
357357a0227fSdrh         uint32 t;
357457a0227fSdrh         do {
357557a0227fSdrh                 t = (uint32)((unsigned)buf[3]<<8 | buf[2]) << 16 |
357657a0227fSdrh                             ((unsigned)buf[1]<<8 | buf[0]);
357757a0227fSdrh                 *(uint32 *)buf = t;
357857a0227fSdrh                 buf += 4;
357957a0227fSdrh         } while (--longs);
358057a0227fSdrh }
358157a0227fSdrh /* The four core functions - F1 is optimized somewhat */
358257a0227fSdrh 
358357a0227fSdrh /* #define F1(x, y, z) (x & y | ~x & z) */
358457a0227fSdrh #define F1(x, y, z) (z ^ (x & (y ^ z)))
358557a0227fSdrh #define F2(x, y, z) F1(z, x, y)
358657a0227fSdrh #define F3(x, y, z) (x ^ y ^ z)
358757a0227fSdrh #define F4(x, y, z) (y ^ (x | ~z))
358857a0227fSdrh 
358957a0227fSdrh /* This is the central step in the MD5 algorithm. */
359057a0227fSdrh #define MD5STEP(f, w, x, y, z, data, s) \
359157a0227fSdrh         ( w += f(x, y, z) + data,  w = w<<s | w>>(32-s),  w += x )
359257a0227fSdrh 
359357a0227fSdrh /*
359457a0227fSdrh  * The core of the MD5 algorithm, this alters an existing MD5 hash to
359557a0227fSdrh  * reflect the addition of 16 longwords of new data.  MD5Update blocks
359657a0227fSdrh  * the data and converts bytes into longwords for this routine.
359757a0227fSdrh  */
359857a0227fSdrh static void MD5Transform(uint32 buf[4], const uint32 in[16]){
359957a0227fSdrh         register uint32 a, b, c, d;
360057a0227fSdrh 
360157a0227fSdrh         a = buf[0];
360257a0227fSdrh         b = buf[1];
360357a0227fSdrh         c = buf[2];
360457a0227fSdrh         d = buf[3];
360557a0227fSdrh 
360657a0227fSdrh         MD5STEP(F1, a, b, c, d, in[ 0]+0xd76aa478,  7);
360757a0227fSdrh         MD5STEP(F1, d, a, b, c, in[ 1]+0xe8c7b756, 12);
360857a0227fSdrh         MD5STEP(F1, c, d, a, b, in[ 2]+0x242070db, 17);
360957a0227fSdrh         MD5STEP(F1, b, c, d, a, in[ 3]+0xc1bdceee, 22);
361057a0227fSdrh         MD5STEP(F1, a, b, c, d, in[ 4]+0xf57c0faf,  7);
361157a0227fSdrh         MD5STEP(F1, d, a, b, c, in[ 5]+0x4787c62a, 12);
361257a0227fSdrh         MD5STEP(F1, c, d, a, b, in[ 6]+0xa8304613, 17);
361357a0227fSdrh         MD5STEP(F1, b, c, d, a, in[ 7]+0xfd469501, 22);
361457a0227fSdrh         MD5STEP(F1, a, b, c, d, in[ 8]+0x698098d8,  7);
361557a0227fSdrh         MD5STEP(F1, d, a, b, c, in[ 9]+0x8b44f7af, 12);
361657a0227fSdrh         MD5STEP(F1, c, d, a, b, in[10]+0xffff5bb1, 17);
361757a0227fSdrh         MD5STEP(F1, b, c, d, a, in[11]+0x895cd7be, 22);
361857a0227fSdrh         MD5STEP(F1, a, b, c, d, in[12]+0x6b901122,  7);
361957a0227fSdrh         MD5STEP(F1, d, a, b, c, in[13]+0xfd987193, 12);
362057a0227fSdrh         MD5STEP(F1, c, d, a, b, in[14]+0xa679438e, 17);
362157a0227fSdrh         MD5STEP(F1, b, c, d, a, in[15]+0x49b40821, 22);
362257a0227fSdrh 
362357a0227fSdrh         MD5STEP(F2, a, b, c, d, in[ 1]+0xf61e2562,  5);
362457a0227fSdrh         MD5STEP(F2, d, a, b, c, in[ 6]+0xc040b340,  9);
362557a0227fSdrh         MD5STEP(F2, c, d, a, b, in[11]+0x265e5a51, 14);
362657a0227fSdrh         MD5STEP(F2, b, c, d, a, in[ 0]+0xe9b6c7aa, 20);
362757a0227fSdrh         MD5STEP(F2, a, b, c, d, in[ 5]+0xd62f105d,  5);
362857a0227fSdrh         MD5STEP(F2, d, a, b, c, in[10]+0x02441453,  9);
362957a0227fSdrh         MD5STEP(F2, c, d, a, b, in[15]+0xd8a1e681, 14);
363057a0227fSdrh         MD5STEP(F2, b, c, d, a, in[ 4]+0xe7d3fbc8, 20);
363157a0227fSdrh         MD5STEP(F2, a, b, c, d, in[ 9]+0x21e1cde6,  5);
363257a0227fSdrh         MD5STEP(F2, d, a, b, c, in[14]+0xc33707d6,  9);
363357a0227fSdrh         MD5STEP(F2, c, d, a, b, in[ 3]+0xf4d50d87, 14);
363457a0227fSdrh         MD5STEP(F2, b, c, d, a, in[ 8]+0x455a14ed, 20);
363557a0227fSdrh         MD5STEP(F2, a, b, c, d, in[13]+0xa9e3e905,  5);
363657a0227fSdrh         MD5STEP(F2, d, a, b, c, in[ 2]+0xfcefa3f8,  9);
363757a0227fSdrh         MD5STEP(F2, c, d, a, b, in[ 7]+0x676f02d9, 14);
363857a0227fSdrh         MD5STEP(F2, b, c, d, a, in[12]+0x8d2a4c8a, 20);
363957a0227fSdrh 
364057a0227fSdrh         MD5STEP(F3, a, b, c, d, in[ 5]+0xfffa3942,  4);
364157a0227fSdrh         MD5STEP(F3, d, a, b, c, in[ 8]+0x8771f681, 11);
364257a0227fSdrh         MD5STEP(F3, c, d, a, b, in[11]+0x6d9d6122, 16);
364357a0227fSdrh         MD5STEP(F3, b, c, d, a, in[14]+0xfde5380c, 23);
364457a0227fSdrh         MD5STEP(F3, a, b, c, d, in[ 1]+0xa4beea44,  4);
364557a0227fSdrh         MD5STEP(F3, d, a, b, c, in[ 4]+0x4bdecfa9, 11);
364657a0227fSdrh         MD5STEP(F3, c, d, a, b, in[ 7]+0xf6bb4b60, 16);
364757a0227fSdrh         MD5STEP(F3, b, c, d, a, in[10]+0xbebfbc70, 23);
364857a0227fSdrh         MD5STEP(F3, a, b, c, d, in[13]+0x289b7ec6,  4);
364957a0227fSdrh         MD5STEP(F3, d, a, b, c, in[ 0]+0xeaa127fa, 11);
365057a0227fSdrh         MD5STEP(F3, c, d, a, b, in[ 3]+0xd4ef3085, 16);
365157a0227fSdrh         MD5STEP(F3, b, c, d, a, in[ 6]+0x04881d05, 23);
365257a0227fSdrh         MD5STEP(F3, a, b, c, d, in[ 9]+0xd9d4d039,  4);
365357a0227fSdrh         MD5STEP(F3, d, a, b, c, in[12]+0xe6db99e5, 11);
365457a0227fSdrh         MD5STEP(F3, c, d, a, b, in[15]+0x1fa27cf8, 16);
365557a0227fSdrh         MD5STEP(F3, b, c, d, a, in[ 2]+0xc4ac5665, 23);
365657a0227fSdrh 
365757a0227fSdrh         MD5STEP(F4, a, b, c, d, in[ 0]+0xf4292244,  6);
365857a0227fSdrh         MD5STEP(F4, d, a, b, c, in[ 7]+0x432aff97, 10);
365957a0227fSdrh         MD5STEP(F4, c, d, a, b, in[14]+0xab9423a7, 15);
366057a0227fSdrh         MD5STEP(F4, b, c, d, a, in[ 5]+0xfc93a039, 21);
366157a0227fSdrh         MD5STEP(F4, a, b, c, d, in[12]+0x655b59c3,  6);
366257a0227fSdrh         MD5STEP(F4, d, a, b, c, in[ 3]+0x8f0ccc92, 10);
366357a0227fSdrh         MD5STEP(F4, c, d, a, b, in[10]+0xffeff47d, 15);
366457a0227fSdrh         MD5STEP(F4, b, c, d, a, in[ 1]+0x85845dd1, 21);
366557a0227fSdrh         MD5STEP(F4, a, b, c, d, in[ 8]+0x6fa87e4f,  6);
366657a0227fSdrh         MD5STEP(F4, d, a, b, c, in[15]+0xfe2ce6e0, 10);
366757a0227fSdrh         MD5STEP(F4, c, d, a, b, in[ 6]+0xa3014314, 15);
366857a0227fSdrh         MD5STEP(F4, b, c, d, a, in[13]+0x4e0811a1, 21);
366957a0227fSdrh         MD5STEP(F4, a, b, c, d, in[ 4]+0xf7537e82,  6);
367057a0227fSdrh         MD5STEP(F4, d, a, b, c, in[11]+0xbd3af235, 10);
367157a0227fSdrh         MD5STEP(F4, c, d, a, b, in[ 2]+0x2ad7d2bb, 15);
367257a0227fSdrh         MD5STEP(F4, b, c, d, a, in[ 9]+0xeb86d391, 21);
367357a0227fSdrh 
367457a0227fSdrh         buf[0] += a;
367557a0227fSdrh         buf[1] += b;
367657a0227fSdrh         buf[2] += c;
367757a0227fSdrh         buf[3] += d;
367857a0227fSdrh }
367957a0227fSdrh 
368057a0227fSdrh /*
368157a0227fSdrh  * Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious
368257a0227fSdrh  * initialization constants.
368357a0227fSdrh  */
368457a0227fSdrh static void MD5Init(MD5Context *ctx){
368557a0227fSdrh         ctx->isInit = 1;
368657a0227fSdrh         ctx->buf[0] = 0x67452301;
368757a0227fSdrh         ctx->buf[1] = 0xefcdab89;
368857a0227fSdrh         ctx->buf[2] = 0x98badcfe;
368957a0227fSdrh         ctx->buf[3] = 0x10325476;
369057a0227fSdrh         ctx->bits[0] = 0;
369157a0227fSdrh         ctx->bits[1] = 0;
369257a0227fSdrh }
369357a0227fSdrh 
369457a0227fSdrh /*
369557a0227fSdrh  * Update context to reflect the concatenation of another buffer full
369657a0227fSdrh  * of bytes.
369757a0227fSdrh  */
369857a0227fSdrh static
369957a0227fSdrh void MD5Update(MD5Context *ctx, const unsigned char *buf, unsigned int len){
370057a0227fSdrh         uint32 t;
370157a0227fSdrh 
370257a0227fSdrh         /* Update bitcount */
370357a0227fSdrh 
370457a0227fSdrh         t = ctx->bits[0];
370557a0227fSdrh         if ((ctx->bits[0] = t + ((uint32)len << 3)) < t)
370657a0227fSdrh                 ctx->bits[1]++; /* Carry from low to high */
370757a0227fSdrh         ctx->bits[1] += len >> 29;
370857a0227fSdrh 
370957a0227fSdrh         t = (t >> 3) & 0x3f;    /* Bytes already in shsInfo->data */
371057a0227fSdrh 
371157a0227fSdrh         /* Handle any leading odd-sized chunks */
371257a0227fSdrh 
371357a0227fSdrh         if ( t ) {
371457a0227fSdrh                 unsigned char *p = (unsigned char *)ctx->in + t;
371557a0227fSdrh 
371657a0227fSdrh                 t = 64-t;
371757a0227fSdrh                 if (len < t) {
371857a0227fSdrh                         memcpy(p, buf, len);
371957a0227fSdrh                         return;
372057a0227fSdrh                 }
372157a0227fSdrh                 memcpy(p, buf, t);
372257a0227fSdrh                 byteReverse(ctx->in, 16);
372357a0227fSdrh                 MD5Transform(ctx->buf, (uint32 *)ctx->in);
372457a0227fSdrh                 buf += t;
372557a0227fSdrh                 len -= t;
372657a0227fSdrh         }
372757a0227fSdrh 
372857a0227fSdrh         /* Process data in 64-byte chunks */
372957a0227fSdrh 
373057a0227fSdrh         while (len >= 64) {
373157a0227fSdrh                 memcpy(ctx->in, buf, 64);
373257a0227fSdrh                 byteReverse(ctx->in, 16);
373357a0227fSdrh                 MD5Transform(ctx->buf, (uint32 *)ctx->in);
373457a0227fSdrh                 buf += 64;
373557a0227fSdrh                 len -= 64;
373657a0227fSdrh         }
373757a0227fSdrh 
373857a0227fSdrh         /* Handle any remaining bytes of data. */
373957a0227fSdrh 
374057a0227fSdrh         memcpy(ctx->in, buf, len);
374157a0227fSdrh }
374257a0227fSdrh 
374357a0227fSdrh /*
374457a0227fSdrh  * Final wrapup - pad to 64-byte boundary with the bit pattern
374557a0227fSdrh  * 1 0* (64-bit count of bits processed, MSB-first)
374657a0227fSdrh  */
374757a0227fSdrh static void MD5Final(unsigned char digest[16], MD5Context *ctx){
374857a0227fSdrh         unsigned count;
374957a0227fSdrh         unsigned char *p;
375057a0227fSdrh 
375157a0227fSdrh         /* Compute number of bytes mod 64 */
375257a0227fSdrh         count = (ctx->bits[0] >> 3) & 0x3F;
375357a0227fSdrh 
375457a0227fSdrh         /* Set the first char of padding to 0x80.  This is safe since there is
375557a0227fSdrh            always at least one byte free */
375657a0227fSdrh         p = ctx->in + count;
375757a0227fSdrh         *p++ = 0x80;
375857a0227fSdrh 
375957a0227fSdrh         /* Bytes of padding needed to make 64 bytes */
376057a0227fSdrh         count = 64 - 1 - count;
376157a0227fSdrh 
376257a0227fSdrh         /* Pad out to 56 mod 64 */
376357a0227fSdrh         if (count < 8) {
376457a0227fSdrh                 /* Two lots of padding:  Pad the first block to 64 bytes */
376557a0227fSdrh                 memset(p, 0, count);
376657a0227fSdrh                 byteReverse(ctx->in, 16);
376757a0227fSdrh                 MD5Transform(ctx->buf, (uint32 *)ctx->in);
376857a0227fSdrh 
376957a0227fSdrh                 /* Now fill the next block with 56 bytes */
377057a0227fSdrh                 memset(ctx->in, 0, 56);
377157a0227fSdrh         } else {
377257a0227fSdrh                 /* Pad block to 56 bytes */
377357a0227fSdrh                 memset(p, 0, count-8);
377457a0227fSdrh         }
377557a0227fSdrh         byteReverse(ctx->in, 14);
377657a0227fSdrh 
377757a0227fSdrh         /* Append length in bits and transform */
3778a47941feSdrh         memcpy(ctx->in + 14*4, ctx->bits, 8);
377957a0227fSdrh 
378057a0227fSdrh         MD5Transform(ctx->buf, (uint32 *)ctx->in);
378157a0227fSdrh         byteReverse((unsigned char *)ctx->buf, 4);
378257a0227fSdrh         memcpy(digest, ctx->buf, 16);
378357a0227fSdrh }
378457a0227fSdrh 
378557a0227fSdrh /*
378657a0227fSdrh ** Convert a 128-bit MD5 digest into a 32-digit base-16 number.
378757a0227fSdrh */
378857a0227fSdrh static void MD5DigestToBase16(unsigned char *digest, char *zBuf){
378957a0227fSdrh   static char const zEncode[] = "0123456789abcdef";
379057a0227fSdrh   int i, j;
379157a0227fSdrh 
379257a0227fSdrh   for(j=i=0; i<16; i++){
379357a0227fSdrh     int a = digest[i];
379457a0227fSdrh     zBuf[j++] = zEncode[(a>>4)&0xf];
379557a0227fSdrh     zBuf[j++] = zEncode[a & 0xf];
379657a0227fSdrh   }
379757a0227fSdrh   zBuf[j] = 0;
379857a0227fSdrh }
379957a0227fSdrh 
380057a0227fSdrh 
380157a0227fSdrh /*
380257a0227fSdrh ** Convert a 128-bit MD5 digest into sequency of eight 5-digit integers
380357a0227fSdrh ** each representing 16 bits of the digest and separated from each
380457a0227fSdrh ** other by a "-" character.
380557a0227fSdrh */
380657a0227fSdrh static void MD5DigestToBase10x8(unsigned char digest[16], char zDigest[50]){
380757a0227fSdrh   int i, j;
380857a0227fSdrh   unsigned int x;
380957a0227fSdrh   for(i=j=0; i<16; i+=2){
381057a0227fSdrh     x = digest[i]*256 + digest[i+1];
381157a0227fSdrh     if( i>0 ) zDigest[j++] = '-';
381205f6c67cSdrh     sqlite3_snprintf(50-j, &zDigest[j], "%05u", x);
381357a0227fSdrh     j += 5;
381457a0227fSdrh   }
381557a0227fSdrh   zDigest[j] = 0;
381657a0227fSdrh }
381757a0227fSdrh 
381857a0227fSdrh /*
381957a0227fSdrh ** A TCL command for md5.  The argument is the text to be hashed.  The
382057a0227fSdrh ** Result is the hash in base64.
382157a0227fSdrh */
382244e95d4fSmistachkin static int SQLITE_TCLAPI md5_cmd(
382344e95d4fSmistachkin   void*cd,
382444e95d4fSmistachkin   Tcl_Interp *interp,
382544e95d4fSmistachkin   int argc,
382644e95d4fSmistachkin   const char **argv
382744e95d4fSmistachkin ){
382857a0227fSdrh   MD5Context ctx;
382957a0227fSdrh   unsigned char digest[16];
383057a0227fSdrh   char zBuf[50];
383157a0227fSdrh   void (*converter)(unsigned char*, char*);
383257a0227fSdrh 
383357a0227fSdrh   if( argc!=2 ){
383457a0227fSdrh     Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
3835a198f2b5Sdrh         " TEXT\"", (char*)0);
383657a0227fSdrh     return TCL_ERROR;
383757a0227fSdrh   }
383857a0227fSdrh   MD5Init(&ctx);
383957a0227fSdrh   MD5Update(&ctx, (unsigned char*)argv[1], (unsigned)strlen(argv[1]));
384057a0227fSdrh   MD5Final(digest, &ctx);
384157a0227fSdrh   converter = (void(*)(unsigned char*,char*))cd;
384257a0227fSdrh   converter(digest, zBuf);
384357a0227fSdrh   Tcl_AppendResult(interp, zBuf, (char*)0);
384457a0227fSdrh   return TCL_OK;
384557a0227fSdrh }
384657a0227fSdrh 
384757a0227fSdrh /*
384857a0227fSdrh ** A TCL command to take the md5 hash of a file.  The argument is the
384957a0227fSdrh ** name of the file.
385057a0227fSdrh */
385144e95d4fSmistachkin static int SQLITE_TCLAPI md5file_cmd(
385244e95d4fSmistachkin   void*cd,
385344e95d4fSmistachkin   Tcl_Interp *interp,
385444e95d4fSmistachkin   int argc,
385544e95d4fSmistachkin   const char **argv
385644e95d4fSmistachkin ){
385757a0227fSdrh   FILE *in;
385857a0227fSdrh   MD5Context ctx;
385957a0227fSdrh   void (*converter)(unsigned char*, char*);
386057a0227fSdrh   unsigned char digest[16];
386157a0227fSdrh   char zBuf[10240];
386257a0227fSdrh 
386357a0227fSdrh   if( argc!=2 ){
386457a0227fSdrh     Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
3865a198f2b5Sdrh         " FILENAME\"", (char*)0);
386657a0227fSdrh     return TCL_ERROR;
386757a0227fSdrh   }
386857a0227fSdrh   in = fopen(argv[1],"rb");
386957a0227fSdrh   if( in==0 ){
387057a0227fSdrh     Tcl_AppendResult(interp,"unable to open file \"", argv[1],
3871a198f2b5Sdrh          "\" for reading", (char*)0);
387257a0227fSdrh     return TCL_ERROR;
387357a0227fSdrh   }
387457a0227fSdrh   MD5Init(&ctx);
387557a0227fSdrh   for(;;){
387657a0227fSdrh     int n;
387783cc1392Sdrh     n = (int)fread(zBuf, 1, sizeof(zBuf), in);
387857a0227fSdrh     if( n<=0 ) break;
387957a0227fSdrh     MD5Update(&ctx, (unsigned char*)zBuf, (unsigned)n);
388057a0227fSdrh   }
388157a0227fSdrh   fclose(in);
388257a0227fSdrh   MD5Final(digest, &ctx);
388357a0227fSdrh   converter = (void(*)(unsigned char*,char*))cd;
388457a0227fSdrh   converter(digest, zBuf);
388557a0227fSdrh   Tcl_AppendResult(interp, zBuf, (char*)0);
388657a0227fSdrh   return TCL_OK;
388757a0227fSdrh }
388857a0227fSdrh 
388957a0227fSdrh /*
389057a0227fSdrh ** Register the four new TCL commands for generating MD5 checksums
389157a0227fSdrh ** with the TCL interpreter.
389257a0227fSdrh */
389357a0227fSdrh int Md5_Init(Tcl_Interp *interp){
389457a0227fSdrh   Tcl_CreateCommand(interp, "md5", (Tcl_CmdProc*)md5_cmd,
389557a0227fSdrh                     MD5DigestToBase16, 0);
389657a0227fSdrh   Tcl_CreateCommand(interp, "md5-10x8", (Tcl_CmdProc*)md5_cmd,
389757a0227fSdrh                     MD5DigestToBase10x8, 0);
389857a0227fSdrh   Tcl_CreateCommand(interp, "md5file", (Tcl_CmdProc*)md5file_cmd,
389957a0227fSdrh                     MD5DigestToBase16, 0);
390057a0227fSdrh   Tcl_CreateCommand(interp, "md5file-10x8", (Tcl_CmdProc*)md5file_cmd,
390157a0227fSdrh                     MD5DigestToBase10x8, 0);
390257a0227fSdrh   return TCL_OK;
390357a0227fSdrh }
390457a0227fSdrh #endif /* defined(SQLITE_TEST) || defined(SQLITE_TCLMD5) */
390557a0227fSdrh 
390657a0227fSdrh #if defined(SQLITE_TEST)
390757a0227fSdrh /*
390857a0227fSdrh ** During testing, the special md5sum() aggregate function is available.
390957a0227fSdrh ** inside SQLite.  The following routines implement that function.
391057a0227fSdrh */
391157a0227fSdrh static void md5step(sqlite3_context *context, int argc, sqlite3_value **argv){
391257a0227fSdrh   MD5Context *p;
391357a0227fSdrh   int i;
391457a0227fSdrh   if( argc<1 ) return;
391557a0227fSdrh   p = sqlite3_aggregate_context(context, sizeof(*p));
391657a0227fSdrh   if( p==0 ) return;
391757a0227fSdrh   if( !p->isInit ){
391857a0227fSdrh     MD5Init(p);
391957a0227fSdrh   }
392057a0227fSdrh   for(i=0; i<argc; i++){
392157a0227fSdrh     const char *zData = (char*)sqlite3_value_text(argv[i]);
392257a0227fSdrh     if( zData ){
392383cc1392Sdrh       MD5Update(p, (unsigned char*)zData, (int)strlen(zData));
392457a0227fSdrh     }
392557a0227fSdrh   }
392657a0227fSdrh }
392757a0227fSdrh static void md5finalize(sqlite3_context *context){
392857a0227fSdrh   MD5Context *p;
392957a0227fSdrh   unsigned char digest[16];
393057a0227fSdrh   char zBuf[33];
393157a0227fSdrh   p = sqlite3_aggregate_context(context, sizeof(*p));
393257a0227fSdrh   MD5Final(digest,p);
393357a0227fSdrh   MD5DigestToBase16(digest, zBuf);
393457a0227fSdrh   sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
393557a0227fSdrh }
393644e95d4fSmistachkin int Md5_Register(
393744e95d4fSmistachkin   sqlite3 *db,
393844e95d4fSmistachkin   char **pzErrMsg,
393985bd982bSmistachkin   const sqlite3_api_routines *pThunk
394044e95d4fSmistachkin ){
394157a0227fSdrh   int rc = sqlite3_create_function(db, "md5sum", -1, SQLITE_UTF8, 0, 0,
394257a0227fSdrh                                  md5step, md5finalize);
394357a0227fSdrh   sqlite3_overload_function(db, "md5sum", -1);  /* To exercise this API */
394457a0227fSdrh   return rc;
394557a0227fSdrh }
394657a0227fSdrh #endif /* defined(SQLITE_TEST) */
394757a0227fSdrh 
394857a0227fSdrh 
3949348784efSdrh /*
39503e27c026Sdrh ** If the macro TCLSH is one, then put in code this for the
39513e27c026Sdrh ** "main" routine that will initialize Tcl and take input from
39523570ad93Sdrh ** standard input, or if a file is named on the command line
39533570ad93Sdrh ** the TCL interpreter reads and evaluates that file.
3954348784efSdrh */
39553e27c026Sdrh #if TCLSH==1
39560ae479dfSdan static const char *tclsh_main_loop(void){
39570ae479dfSdan   static const char zMainloop[] =
3958348784efSdrh     "set line {}\n"
3959348784efSdrh     "while {![eof stdin]} {\n"
3960348784efSdrh       "if {$line!=\"\"} {\n"
3961348784efSdrh         "puts -nonewline \"> \"\n"
3962348784efSdrh       "} else {\n"
3963348784efSdrh         "puts -nonewline \"% \"\n"
3964348784efSdrh       "}\n"
3965348784efSdrh       "flush stdout\n"
3966348784efSdrh       "append line [gets stdin]\n"
3967348784efSdrh       "if {[info complete $line]} {\n"
3968348784efSdrh         "if {[catch {uplevel #0 $line} result]} {\n"
3969348784efSdrh           "puts stderr \"Error: $result\"\n"
3970348784efSdrh         "} elseif {$result!=\"\"} {\n"
3971348784efSdrh           "puts $result\n"
3972348784efSdrh         "}\n"
3973348784efSdrh         "set line {}\n"
3974348784efSdrh       "} else {\n"
3975348784efSdrh         "append line \\n\n"
3976348784efSdrh       "}\n"
3977348784efSdrh     "}\n"
3978348784efSdrh   ;
39790ae479dfSdan   return zMainloop;
39800ae479dfSdan }
39813e27c026Sdrh #endif
39823a0f13ffSdrh #if TCLSH==2
39830ae479dfSdan static const char *tclsh_main_loop(void);
39843a0f13ffSdrh #endif
39853e27c026Sdrh 
3986c1a60c51Sdan #ifdef SQLITE_TEST
3987c1a60c51Sdan static void init_all(Tcl_Interp *);
39887617e4a8Smistachkin static int SQLITE_TCLAPI init_all_cmd(
3989c1a60c51Sdan   ClientData cd,
3990c1a60c51Sdan   Tcl_Interp *interp,
3991c1a60c51Sdan   int objc,
3992c1a60c51Sdan   Tcl_Obj *CONST objv[]
3993c1a60c51Sdan ){
39940a549071Sdanielk1977 
3995c1a60c51Sdan   Tcl_Interp *slave;
3996c1a60c51Sdan   if( objc!=2 ){
3997c1a60c51Sdan     Tcl_WrongNumArgs(interp, 1, objv, "SLAVE");
3998c1a60c51Sdan     return TCL_ERROR;
3999c1a60c51Sdan   }
40000a549071Sdanielk1977 
4001c1a60c51Sdan   slave = Tcl_GetSlave(interp, Tcl_GetString(objv[1]));
4002c1a60c51Sdan   if( !slave ){
4003c1a60c51Sdan     return TCL_ERROR;
4004c1a60c51Sdan   }
4005c1a60c51Sdan 
4006c1a60c51Sdan   init_all(slave);
4007c1a60c51Sdan   return TCL_OK;
4008c1a60c51Sdan }
4009c431fd55Sdan 
4010c431fd55Sdan /*
4011c431fd55Sdan ** Tclcmd: db_use_legacy_prepare DB BOOLEAN
4012c431fd55Sdan **
4013c431fd55Sdan **   The first argument to this command must be a database command created by
4014c431fd55Sdan **   [sqlite3]. If the second argument is true, then the handle is configured
4015c431fd55Sdan **   to use the sqlite3_prepare_v2() function to prepare statements. If it
4016c431fd55Sdan **   is false, sqlite3_prepare().
4017c431fd55Sdan */
40187617e4a8Smistachkin static int SQLITE_TCLAPI db_use_legacy_prepare_cmd(
4019c431fd55Sdan   ClientData cd,
4020c431fd55Sdan   Tcl_Interp *interp,
4021c431fd55Sdan   int objc,
4022c431fd55Sdan   Tcl_Obj *CONST objv[]
4023c431fd55Sdan ){
4024c431fd55Sdan   Tcl_CmdInfo cmdInfo;
4025c431fd55Sdan   SqliteDb *pDb;
4026c431fd55Sdan   int bPrepare;
4027c431fd55Sdan 
4028c431fd55Sdan   if( objc!=3 ){
4029c431fd55Sdan     Tcl_WrongNumArgs(interp, 1, objv, "DB BOOLEAN");
4030c431fd55Sdan     return TCL_ERROR;
4031c431fd55Sdan   }
4032c431fd55Sdan 
4033c431fd55Sdan   if( !Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &cmdInfo) ){
4034c431fd55Sdan     Tcl_AppendResult(interp, "no such db: ", Tcl_GetString(objv[1]), (char*)0);
4035c431fd55Sdan     return TCL_ERROR;
4036c431fd55Sdan   }
4037c431fd55Sdan   pDb = (SqliteDb*)cmdInfo.objClientData;
4038c431fd55Sdan   if( Tcl_GetBooleanFromObj(interp, objv[2], &bPrepare) ){
4039c431fd55Sdan     return TCL_ERROR;
4040c431fd55Sdan   }
4041c431fd55Sdan 
4042c431fd55Sdan   pDb->bLegacyPrepare = bPrepare;
4043c431fd55Sdan 
4044c431fd55Sdan   Tcl_ResetResult(interp);
4045c431fd55Sdan   return TCL_OK;
4046c431fd55Sdan }
404704489b6dSdan 
404804489b6dSdan /*
404904489b6dSdan ** Tclcmd: db_last_stmt_ptr DB
405004489b6dSdan **
405104489b6dSdan **   If the statement cache associated with database DB is not empty,
405204489b6dSdan **   return the text representation of the most recently used statement
405304489b6dSdan **   handle.
405404489b6dSdan */
40557617e4a8Smistachkin static int SQLITE_TCLAPI db_last_stmt_ptr(
405604489b6dSdan   ClientData cd,
405704489b6dSdan   Tcl_Interp *interp,
405804489b6dSdan   int objc,
405904489b6dSdan   Tcl_Obj *CONST objv[]
406004489b6dSdan ){
406104489b6dSdan   extern int sqlite3TestMakePointerStr(Tcl_Interp*, char*, void*);
406204489b6dSdan   Tcl_CmdInfo cmdInfo;
406304489b6dSdan   SqliteDb *pDb;
406404489b6dSdan   sqlite3_stmt *pStmt = 0;
406504489b6dSdan   char zBuf[100];
406604489b6dSdan 
406704489b6dSdan   if( objc!=2 ){
406804489b6dSdan     Tcl_WrongNumArgs(interp, 1, objv, "DB");
406904489b6dSdan     return TCL_ERROR;
407004489b6dSdan   }
407104489b6dSdan 
407204489b6dSdan   if( !Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &cmdInfo) ){
407304489b6dSdan     Tcl_AppendResult(interp, "no such db: ", Tcl_GetString(objv[1]), (char*)0);
407404489b6dSdan     return TCL_ERROR;
407504489b6dSdan   }
407604489b6dSdan   pDb = (SqliteDb*)cmdInfo.objClientData;
407704489b6dSdan 
407804489b6dSdan   if( pDb->stmtList ) pStmt = pDb->stmtList->pStmt;
407904489b6dSdan   if( sqlite3TestMakePointerStr(interp, zBuf, pStmt) ){
408004489b6dSdan     return TCL_ERROR;
408104489b6dSdan   }
408204489b6dSdan   Tcl_SetResult(interp, zBuf, TCL_VOLATILE);
408304489b6dSdan 
408404489b6dSdan   return TCL_OK;
408504489b6dSdan }
40861a4a680aSdrh #endif /* SQLITE_TEST */
40871a4a680aSdrh 
4088c1a60c51Sdan /*
4089c1a60c51Sdan ** Configure the interpreter passed as the first argument to have access
4090c1a60c51Sdan ** to the commands and linked variables that make up:
4091c1a60c51Sdan **
4092c1a60c51Sdan **   * the [sqlite3] extension itself,
4093c1a60c51Sdan **
4094c1a60c51Sdan **   * If SQLITE_TCLMD5 or SQLITE_TEST is defined, the Md5 commands, and
4095c1a60c51Sdan **
4096c1a60c51Sdan **   * If SQLITE_TEST is set, the various test interfaces used by the Tcl
4097c1a60c51Sdan **     test suite.
4098c1a60c51Sdan */
4099c1a60c51Sdan static void init_all(Tcl_Interp *interp){
410038f8271fSdrh   Sqlite3_Init(interp);
4101c1a60c51Sdan 
410257a0227fSdrh #if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
410357a0227fSdrh   Md5_Init(interp);
410457a0227fSdrh #endif
4105c1a60c51Sdan 
4106d9b0257aSdrh #ifdef SQLITE_TEST
4107d1bf3512Sdrh   {
41082f999a67Sdrh     extern int Sqliteconfig_Init(Tcl_Interp*);
4109d1bf3512Sdrh     extern int Sqlitetest1_Init(Tcl_Interp*);
41105c4d9703Sdrh     extern int Sqlitetest2_Init(Tcl_Interp*);
41115c4d9703Sdrh     extern int Sqlitetest3_Init(Tcl_Interp*);
4112a6064dcfSdrh     extern int Sqlitetest4_Init(Tcl_Interp*);
4113998b56c3Sdanielk1977     extern int Sqlitetest5_Init(Tcl_Interp*);
41149c06c953Sdrh     extern int Sqlitetest6_Init(Tcl_Interp*);
411529c636bcSdrh     extern int Sqlitetest7_Init(Tcl_Interp*);
4116b9bb7c18Sdrh     extern int Sqlitetest8_Init(Tcl_Interp*);
4117a713f2c3Sdanielk1977     extern int Sqlitetest9_Init(Tcl_Interp*);
41182366940dSdrh     extern int Sqlitetestasync_Init(Tcl_Interp*);
41191409be69Sdrh     extern int Sqlitetest_autoext_Init(Tcl_Interp*);
4120b391b944Sdan     extern int Sqlitetest_blob_Init(Tcl_Interp*);
41210a7a9155Sdan     extern int Sqlitetest_demovfs_Init(Tcl_Interp *);
4122984bfaa4Sdrh     extern int Sqlitetest_func_Init(Tcl_Interp*);
412315926590Sdrh     extern int Sqlitetest_hexio_Init(Tcl_Interp*);
4124e1ab2193Sdan     extern int Sqlitetest_init_Init(Tcl_Interp*);
41252f999a67Sdrh     extern int Sqlitetest_malloc_Init(Tcl_Interp*);
41261a9ed0b2Sdanielk1977     extern int Sqlitetest_mutex_Init(Tcl_Interp*);
41272f999a67Sdrh     extern int Sqlitetestschema_Init(Tcl_Interp*);
41282f999a67Sdrh     extern int Sqlitetestsse_Init(Tcl_Interp*);
41292f999a67Sdrh     extern int Sqlitetesttclvar_Init(Tcl_Interp*);
41309f5ff371Sdan     extern int Sqlitetestfs_Init(Tcl_Interp*);
413144918fa0Sdanielk1977     extern int SqlitetestThread_Init(Tcl_Interp*);
4132a15db353Sdanielk1977     extern int SqlitetestOnefile_Init();
41335d1f5aa6Sdanielk1977     extern int SqlitetestOsinst_Init(Tcl_Interp*);
41340410302eSdanielk1977     extern int Sqlitetestbackup_Init(Tcl_Interp*);
4135522efc62Sdrh     extern int Sqlitetestintarray_Init(Tcl_Interp*);
4136c7991bdfSdan     extern int Sqlitetestvfs_Init(Tcl_Interp *);
41379508daa9Sdan     extern int Sqlitetestrtree_Init(Tcl_Interp*);
41388cf35eb4Sdan     extern int Sqlitequota_Init(Tcl_Interp*);
41398a922f75Sshaneh     extern int Sqlitemultiplex_Init(Tcl_Interp*);
4140e336b001Sdan     extern int SqliteSuperlock_Init(Tcl_Interp*);
4141213ca0a8Sdan     extern int SqlitetestSyscall_Init(Tcl_Interp*);
41429b1c62d4Sdrh #if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
41434fccf43aSdan     extern int TestSession_Init(Tcl_Interp*);
41444fccf43aSdan #endif
414589a89560Sdan     extern int Fts5tcl_Init(Tcl_Interp *);
4146cfb8f8d6Sdrh     extern int SqliteRbu_Init(Tcl_Interp*);
41478e4251b6Sdan     extern int Sqlitetesttcl_Init(Tcl_Interp*);
41486764a700Sdan #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
414999ebad90Sdan     extern int Sqlitetestfts3_Init(Tcl_Interp *interp);
415099ebad90Sdan #endif
415199ebad90Sdan 
4152b29010cdSdan #ifdef SQLITE_ENABLE_ZIPVFS
4153b29010cdSdan     extern int Zipvfs_Init(Tcl_Interp*);
4154b29010cdSdan     Zipvfs_Init(interp);
4155b29010cdSdan #endif
4156b29010cdSdan 
41572f999a67Sdrh     Sqliteconfig_Init(interp);
41586490bebdSdanielk1977     Sqlitetest1_Init(interp);
41595c4d9703Sdrh     Sqlitetest2_Init(interp);
4160de647130Sdrh     Sqlitetest3_Init(interp);
4161fc57d7bfSdanielk1977     Sqlitetest4_Init(interp);
4162998b56c3Sdanielk1977     Sqlitetest5_Init(interp);
41639c06c953Sdrh     Sqlitetest6_Init(interp);
416429c636bcSdrh     Sqlitetest7_Init(interp);
4165b9bb7c18Sdrh     Sqlitetest8_Init(interp);
4166a713f2c3Sdanielk1977     Sqlitetest9_Init(interp);
41672366940dSdrh     Sqlitetestasync_Init(interp);
41681409be69Sdrh     Sqlitetest_autoext_Init(interp);
4169b391b944Sdan     Sqlitetest_blob_Init(interp);
41700a7a9155Sdan     Sqlitetest_demovfs_Init(interp);
4171984bfaa4Sdrh     Sqlitetest_func_Init(interp);
417215926590Sdrh     Sqlitetest_hexio_Init(interp);
4173e1ab2193Sdan     Sqlitetest_init_Init(interp);
41742f999a67Sdrh     Sqlitetest_malloc_Init(interp);
41751a9ed0b2Sdanielk1977     Sqlitetest_mutex_Init(interp);
41762f999a67Sdrh     Sqlitetestschema_Init(interp);
41772f999a67Sdrh     Sqlitetesttclvar_Init(interp);
41789f5ff371Sdan     Sqlitetestfs_Init(interp);
417944918fa0Sdanielk1977     SqlitetestThread_Init(interp);
418052b1dbb5Smistachkin     SqlitetestOnefile_Init();
41815d1f5aa6Sdanielk1977     SqlitetestOsinst_Init(interp);
41820410302eSdanielk1977     Sqlitetestbackup_Init(interp);
4183522efc62Sdrh     Sqlitetestintarray_Init(interp);
4184c7991bdfSdan     Sqlitetestvfs_Init(interp);
41859508daa9Sdan     Sqlitetestrtree_Init(interp);
41868cf35eb4Sdan     Sqlitequota_Init(interp);
41878a922f75Sshaneh     Sqlitemultiplex_Init(interp);
4188e336b001Sdan     SqliteSuperlock_Init(interp);
4189213ca0a8Sdan     SqlitetestSyscall_Init(interp);
41909b1c62d4Sdrh #if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
41914fccf43aSdan     TestSession_Init(interp);
41924fccf43aSdan #endif
419389a89560Sdan     Fts5tcl_Init(interp);
4194cfb8f8d6Sdrh     SqliteRbu_Init(interp);
41958e4251b6Sdan     Sqlitetesttcl_Init(interp);
4196a15db353Sdanielk1977 
41976764a700Sdan #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
419899ebad90Sdan     Sqlitetestfts3_Init(interp);
419999ebad90Sdan #endif
42002e66f0b9Sdrh 
4201c431fd55Sdan     Tcl_CreateObjCommand(
4202c431fd55Sdan         interp, "load_testfixture_extensions", init_all_cmd, 0, 0
4203c431fd55Sdan     );
4204c431fd55Sdan     Tcl_CreateObjCommand(
4205c431fd55Sdan         interp, "db_use_legacy_prepare", db_use_legacy_prepare_cmd, 0, 0
4206c431fd55Sdan     );
420704489b6dSdan     Tcl_CreateObjCommand(
420804489b6dSdan         interp, "db_last_stmt_ptr", db_last_stmt_ptr, 0, 0
420904489b6dSdan     );
4210c1a60c51Sdan 
42113e27c026Sdrh #ifdef SQLITE_SSE
4212348784efSdrh     Sqlitetestsse_Init(interp);
4213348784efSdrh #endif
4214348784efSdrh   }
421561212b69Sdrh #endif
4216c1a60c51Sdan }
4217c1a60c51Sdan 
4218db6bafaeSdrh /* Needed for the setrlimit() system call on unix */
4219db6bafaeSdrh #if defined(unix)
4220db6bafaeSdrh #include <sys/resource.h>
4221db6bafaeSdrh #endif
4222db6bafaeSdrh 
4223c1a60c51Sdan #define TCLSH_MAIN main   /* Needed to fake out mktclapp */
422469def7ffSmistachkin int SQLITE_CDECL TCLSH_MAIN(int argc, char **argv){
4225c1a60c51Sdan   Tcl_Interp *interp;
4226c1a60c51Sdan 
42271f28e070Smistachkin #if !defined(_WIN32_WCE)
42281f28e070Smistachkin   if( getenv("BREAK") ){
42291f28e070Smistachkin     fprintf(stderr,
42301f28e070Smistachkin         "attach debugger to process %d and press any key to continue.\n",
42311f28e070Smistachkin         GETPID());
42321f28e070Smistachkin     fgetc(stdin);
42331f28e070Smistachkin   }
42341f28e070Smistachkin #endif
42351f28e070Smistachkin 
4236db6bafaeSdrh   /* Since the primary use case for this binary is testing of SQLite,
4237db6bafaeSdrh   ** be sure to generate core files if we crash */
4238db6bafaeSdrh #if defined(SQLITE_TEST) && defined(unix)
4239db6bafaeSdrh   { struct rlimit x;
4240db6bafaeSdrh     getrlimit(RLIMIT_CORE, &x);
4241db6bafaeSdrh     x.rlim_cur = x.rlim_max;
4242db6bafaeSdrh     setrlimit(RLIMIT_CORE, &x);
4243db6bafaeSdrh   }
4244db6bafaeSdrh #endif /* SQLITE_TEST && unix */
4245db6bafaeSdrh 
4246db6bafaeSdrh 
4247c1a60c51Sdan   /* Call sqlite3_shutdown() once before doing anything else. This is to
4248c1a60c51Sdan   ** test that sqlite3_shutdown() can be safely called by a process before
4249c1a60c51Sdan   ** sqlite3_initialize() is. */
4250c1a60c51Sdan   sqlite3_shutdown();
4251c1a60c51Sdan 
42520ae479dfSdan   Tcl_FindExecutable(argv[0]);
42532953ba9eSmistachkin   Tcl_SetSystemEncoding(NULL, "utf-8");
42540ae479dfSdan   interp = Tcl_CreateInterp();
42550ae479dfSdan 
42563a0f13ffSdrh #if TCLSH==2
42573a0f13ffSdrh   sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);
42583a0f13ffSdrh #endif
4259c1a60c51Sdan 
4260c1a60c51Sdan   init_all(interp);
4261c7285978Sdrh   if( argc>=2 ){
4262348784efSdrh     int i;
4263ad42c3a3Sshess     char zArgc[32];
4264ad42c3a3Sshess     sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-(3-TCLSH));
4265ad42c3a3Sshess     Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
4266348784efSdrh     Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
4267348784efSdrh     Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
4268348784efSdrh     for(i=3-TCLSH; i<argc; i++){
4269348784efSdrh       Tcl_SetVar(interp, "argv", argv[i],
4270348784efSdrh           TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
4271348784efSdrh     }
42723a0f13ffSdrh     if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
42730de8c112Sdrh       const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
4274a81c64a2Sdrh       if( zInfo==0 ) zInfo = Tcl_GetStringResult(interp);
4275c61053b7Sdrh       fprintf(stderr,"%s: %s\n", *argv, zInfo);
4276348784efSdrh       return 1;
4277348784efSdrh     }
42783e27c026Sdrh   }
42793a0f13ffSdrh   if( TCLSH==2 || argc<=1 ){
42800ae479dfSdan     Tcl_GlobalEval(interp, tclsh_main_loop());
4281348784efSdrh   }
4282348784efSdrh   return 0;
4283348784efSdrh }
4284348784efSdrh #endif /* TCLSH */
4285