xref: /sqlite-3.40.0/src/tclsqlite.c (revision a2c8a95b)
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.
1475897234Sdrh */
15bd08af48Sdrh #include "tcl.h"
16b4e9af9fSdanielk1977 #include <errno.h>
176d31316cSdrh 
18bd08af48Sdrh /*
19bd08af48Sdrh ** Some additional include files are needed if this file is not
20bd08af48Sdrh ** appended to the amalgamation.
21bd08af48Sdrh */
22bd08af48Sdrh #ifndef SQLITE_AMALGAMATION
2306b2718aSdrh # include "sqliteInt.h"
2475897234Sdrh # include <stdlib.h>
2575897234Sdrh # include <string.h>
26ce927065Sdrh # include <assert.h>
27d1e4733dSdrh # include <ctype.h>
28bd08af48Sdrh #endif
2975897234Sdrh 
30ad6e1370Sdrh /*
31ad6e1370Sdrh  * Windows needs to know which symbols to export.  Unix does not.
32ad6e1370Sdrh  * BUILD_sqlite should be undefined for Unix.
33ad6e1370Sdrh  */
34ad6e1370Sdrh #ifdef BUILD_sqlite
35ad6e1370Sdrh #undef TCL_STORAGE_CLASS
36ad6e1370Sdrh #define TCL_STORAGE_CLASS DLLEXPORT
37ad6e1370Sdrh #endif /* BUILD_sqlite */
3829bc4615Sdrh 
39a21c6b6fSdanielk1977 #define NUM_PREPARED_STMTS 10
40fb7e7651Sdrh #define MAX_PREPARED_STMTS 100
41fb7e7651Sdrh 
4275897234Sdrh /*
4398808babSdrh ** If TCL uses UTF-8 and SQLite is configured to use iso8859, then we
4498808babSdrh ** have to do a translation when going between the two.  Set the
4598808babSdrh ** UTF_TRANSLATION_NEEDED macro to indicate that we need to do
4698808babSdrh ** this translation.
4798808babSdrh */
4898808babSdrh #if defined(TCL_UTF_MAX) && !defined(SQLITE_UTF8)
4998808babSdrh # define UTF_TRANSLATION_NEEDED 1
5098808babSdrh #endif
5198808babSdrh 
5298808babSdrh /*
53cabb0819Sdrh ** New SQL functions can be created as TCL scripts.  Each such function
54cabb0819Sdrh ** is described by an instance of the following structure.
55cabb0819Sdrh */
56cabb0819Sdrh typedef struct SqlFunc SqlFunc;
57cabb0819Sdrh struct SqlFunc {
58cabb0819Sdrh   Tcl_Interp *interp;   /* The TCL interpret to execute the function */
59d1e4733dSdrh   Tcl_Obj *pScript;     /* The Tcl_Obj representation of the script */
60d1e4733dSdrh   int useEvalObjv;      /* True if it is safe to use Tcl_EvalObjv */
61d1e4733dSdrh   char *zName;          /* Name of this function */
62cabb0819Sdrh   SqlFunc *pNext;       /* Next function on the list of them all */
63cabb0819Sdrh };
64cabb0819Sdrh 
65cabb0819Sdrh /*
660202b29eSdanielk1977 ** New collation sequences function can be created as TCL scripts.  Each such
670202b29eSdanielk1977 ** function is described by an instance of the following structure.
680202b29eSdanielk1977 */
690202b29eSdanielk1977 typedef struct SqlCollate SqlCollate;
700202b29eSdanielk1977 struct SqlCollate {
710202b29eSdanielk1977   Tcl_Interp *interp;   /* The TCL interpret to execute the function */
720202b29eSdanielk1977   char *zScript;        /* The script to be run */
730202b29eSdanielk1977   SqlCollate *pNext;    /* Next function on the list of them all */
740202b29eSdanielk1977 };
750202b29eSdanielk1977 
760202b29eSdanielk1977 /*
77fb7e7651Sdrh ** Prepared statements are cached for faster execution.  Each prepared
78fb7e7651Sdrh ** statement is described by an instance of the following structure.
79fb7e7651Sdrh */
80fb7e7651Sdrh typedef struct SqlPreparedStmt SqlPreparedStmt;
81fb7e7651Sdrh struct SqlPreparedStmt {
82fb7e7651Sdrh   SqlPreparedStmt *pNext;  /* Next in linked list */
83fb7e7651Sdrh   SqlPreparedStmt *pPrev;  /* Previous on the list */
84fb7e7651Sdrh   sqlite3_stmt *pStmt;     /* The prepared statement */
85fb7e7651Sdrh   int nSql;                /* chars in zSql[] */
86d0e2a854Sdanielk1977   const char *zSql;        /* Text of the SQL statement */
874a4c11aaSdan   int nParm;               /* Size of apParm array */
884a4c11aaSdan   Tcl_Obj **apParm;        /* Array of referenced object pointers */
89fb7e7651Sdrh };
90fb7e7651Sdrh 
91d0441796Sdanielk1977 typedef struct IncrblobChannel IncrblobChannel;
92d0441796Sdanielk1977 
93fb7e7651Sdrh /*
94bec3f402Sdrh ** There is one instance of this structure for each SQLite database
95bec3f402Sdrh ** that has been opened by the SQLite TCL interface.
96bec3f402Sdrh */
97bec3f402Sdrh typedef struct SqliteDb SqliteDb;
98bec3f402Sdrh struct SqliteDb {
99dddca286Sdrh   sqlite3 *db;               /* The "real" database structure. MUST BE FIRST */
100bec3f402Sdrh   Tcl_Interp *interp;        /* The interpreter used for this database */
1016d31316cSdrh   char *zBusy;               /* The busy callback routine */
102aa940eacSdrh   char *zCommit;             /* The commit hook callback routine */
103b5a20d3cSdrh   char *zTrace;              /* The trace callback routine */
10419e2d37fSdrh   char *zProfile;            /* The profile callback routine */
105348bb5d6Sdanielk1977   char *zProgress;           /* The progress callback routine */
106e22a334bSdrh   char *zAuth;               /* The authorization callback routine */
1071f1549f8Sdrh   int disableAuth;           /* Disable the authorizer if it exists */
10855c45f2eSdanielk1977   char *zNull;               /* Text to substitute for an SQL NULL value */
109cabb0819Sdrh   SqlFunc *pFunc;            /* List of SQL functions */
11094eb6a14Sdanielk1977   Tcl_Obj *pUpdateHook;      /* Update hook script (if any) */
11171fd80bfSdanielk1977   Tcl_Obj *pRollbackHook;    /* Rollback hook script (if any) */
112404ca075Sdanielk1977   Tcl_Obj *pUnlockNotify;    /* Unlock notify script (if any) */
1130202b29eSdanielk1977   SqlCollate *pCollate;      /* List of SQL collation functions */
1146f8a503dSdanielk1977   int rc;                    /* Return code of most recent sqlite3_exec() */
1157cedc8d4Sdanielk1977   Tcl_Obj *pCollateNeeded;   /* Collation needed script */
116fb7e7651Sdrh   SqlPreparedStmt *stmtList; /* List of prepared statements*/
117fb7e7651Sdrh   SqlPreparedStmt *stmtLast; /* Last statement in the list */
118fb7e7651Sdrh   int maxStmt;               /* The next maximum number of stmtList */
119fb7e7651Sdrh   int nStmt;                 /* Number of statements in stmtList */
120d0441796Sdanielk1977   IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */
121d1d38488Sdrh   int nStep, nSort;          /* Statistics for most recent operation */
122cd38d520Sdanielk1977   int nTransaction;          /* Number of nested [transaction] methods */
12398808babSdrh };
124297ecf14Sdrh 
125b4e9af9fSdanielk1977 struct IncrblobChannel {
126d0441796Sdanielk1977   sqlite3_blob *pBlob;      /* sqlite3 blob handle */
127dcbb5d3fSdanielk1977   SqliteDb *pDb;            /* Associated database connection */
128b4e9af9fSdanielk1977   int iSeek;                /* Current seek offset */
129d0441796Sdanielk1977   Tcl_Channel channel;      /* Channel identifier */
130d0441796Sdanielk1977   IncrblobChannel *pNext;   /* Linked list of all open incrblob channels */
131d0441796Sdanielk1977   IncrblobChannel *pPrev;   /* Linked list of all open incrblob channels */
132b4e9af9fSdanielk1977 };
133b4e9af9fSdanielk1977 
134ea678832Sdrh /*
135ea678832Sdrh ** Compute a string length that is limited to what can be stored in
136ea678832Sdrh ** lower 30 bits of a 32-bit signed integer.
137ea678832Sdrh */
1384f21c4afSdrh static int strlen30(const char *z){
139ea678832Sdrh   const char *z2 = z;
140ea678832Sdrh   while( *z2 ){ z2++; }
141ea678832Sdrh   return 0x3fffffff & (int)(z2 - z);
142ea678832Sdrh }
143ea678832Sdrh 
144ea678832Sdrh 
14532a0d8bbSdanielk1977 #ifndef SQLITE_OMIT_INCRBLOB
146b4e9af9fSdanielk1977 /*
147d0441796Sdanielk1977 ** Close all incrblob channels opened using database connection pDb.
148d0441796Sdanielk1977 ** This is called when shutting down the database connection.
149d0441796Sdanielk1977 */
150d0441796Sdanielk1977 static void closeIncrblobChannels(SqliteDb *pDb){
151d0441796Sdanielk1977   IncrblobChannel *p;
152d0441796Sdanielk1977   IncrblobChannel *pNext;
153d0441796Sdanielk1977 
154d0441796Sdanielk1977   for(p=pDb->pIncrblob; p; p=pNext){
155d0441796Sdanielk1977     pNext = p->pNext;
156d0441796Sdanielk1977 
157d0441796Sdanielk1977     /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
158d0441796Sdanielk1977     ** which deletes the IncrblobChannel structure at *p. So do not
159d0441796Sdanielk1977     ** call Tcl_Free() here.
160d0441796Sdanielk1977     */
161d0441796Sdanielk1977     Tcl_UnregisterChannel(pDb->interp, p->channel);
162d0441796Sdanielk1977   }
163d0441796Sdanielk1977 }
164d0441796Sdanielk1977 
165d0441796Sdanielk1977 /*
166b4e9af9fSdanielk1977 ** Close an incremental blob channel.
167b4e9af9fSdanielk1977 */
168b4e9af9fSdanielk1977 static int incrblobClose(ClientData instanceData, Tcl_Interp *interp){
169b4e9af9fSdanielk1977   IncrblobChannel *p = (IncrblobChannel *)instanceData;
17092d4d7a9Sdanielk1977   int rc = sqlite3_blob_close(p->pBlob);
17192d4d7a9Sdanielk1977   sqlite3 *db = p->pDb->db;
172d0441796Sdanielk1977 
173d0441796Sdanielk1977   /* Remove the channel from the SqliteDb.pIncrblob list. */
174d0441796Sdanielk1977   if( p->pNext ){
175d0441796Sdanielk1977     p->pNext->pPrev = p->pPrev;
176d0441796Sdanielk1977   }
177d0441796Sdanielk1977   if( p->pPrev ){
178d0441796Sdanielk1977     p->pPrev->pNext = p->pNext;
179d0441796Sdanielk1977   }
180d0441796Sdanielk1977   if( p->pDb->pIncrblob==p ){
181d0441796Sdanielk1977     p->pDb->pIncrblob = p->pNext;
182d0441796Sdanielk1977   }
183d0441796Sdanielk1977 
18492d4d7a9Sdanielk1977   /* Free the IncrblobChannel structure */
185b4e9af9fSdanielk1977   Tcl_Free((char *)p);
18692d4d7a9Sdanielk1977 
18792d4d7a9Sdanielk1977   if( rc!=SQLITE_OK ){
18892d4d7a9Sdanielk1977     Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
18992d4d7a9Sdanielk1977     return TCL_ERROR;
19092d4d7a9Sdanielk1977   }
191b4e9af9fSdanielk1977   return TCL_OK;
192b4e9af9fSdanielk1977 }
193b4e9af9fSdanielk1977 
194b4e9af9fSdanielk1977 /*
195b4e9af9fSdanielk1977 ** Read data from an incremental blob channel.
196b4e9af9fSdanielk1977 */
197b4e9af9fSdanielk1977 static int incrblobInput(
198b4e9af9fSdanielk1977   ClientData instanceData,
199b4e9af9fSdanielk1977   char *buf,
200b4e9af9fSdanielk1977   int bufSize,
201b4e9af9fSdanielk1977   int *errorCodePtr
202b4e9af9fSdanielk1977 ){
203b4e9af9fSdanielk1977   IncrblobChannel *p = (IncrblobChannel *)instanceData;
204b4e9af9fSdanielk1977   int nRead = bufSize;         /* Number of bytes to read */
205b4e9af9fSdanielk1977   int nBlob;                   /* Total size of the blob */
206b4e9af9fSdanielk1977   int rc;                      /* sqlite error code */
207b4e9af9fSdanielk1977 
208b4e9af9fSdanielk1977   nBlob = sqlite3_blob_bytes(p->pBlob);
209b4e9af9fSdanielk1977   if( (p->iSeek+nRead)>nBlob ){
210b4e9af9fSdanielk1977     nRead = nBlob-p->iSeek;
211b4e9af9fSdanielk1977   }
212b4e9af9fSdanielk1977   if( nRead<=0 ){
213b4e9af9fSdanielk1977     return 0;
214b4e9af9fSdanielk1977   }
215b4e9af9fSdanielk1977 
216b4e9af9fSdanielk1977   rc = sqlite3_blob_read(p->pBlob, (void *)buf, nRead, p->iSeek);
217b4e9af9fSdanielk1977   if( rc!=SQLITE_OK ){
218b4e9af9fSdanielk1977     *errorCodePtr = rc;
219b4e9af9fSdanielk1977     return -1;
220b4e9af9fSdanielk1977   }
221b4e9af9fSdanielk1977 
222b4e9af9fSdanielk1977   p->iSeek += nRead;
223b4e9af9fSdanielk1977   return nRead;
224b4e9af9fSdanielk1977 }
225b4e9af9fSdanielk1977 
226d0441796Sdanielk1977 /*
227d0441796Sdanielk1977 ** Write data to an incremental blob channel.
228d0441796Sdanielk1977 */
229b4e9af9fSdanielk1977 static int incrblobOutput(
230b4e9af9fSdanielk1977   ClientData instanceData,
231b4e9af9fSdanielk1977   CONST char *buf,
232b4e9af9fSdanielk1977   int toWrite,
233b4e9af9fSdanielk1977   int *errorCodePtr
234b4e9af9fSdanielk1977 ){
235b4e9af9fSdanielk1977   IncrblobChannel *p = (IncrblobChannel *)instanceData;
236b4e9af9fSdanielk1977   int nWrite = toWrite;        /* Number of bytes to write */
237b4e9af9fSdanielk1977   int nBlob;                   /* Total size of the blob */
238b4e9af9fSdanielk1977   int rc;                      /* sqlite error code */
239b4e9af9fSdanielk1977 
240b4e9af9fSdanielk1977   nBlob = sqlite3_blob_bytes(p->pBlob);
241b4e9af9fSdanielk1977   if( (p->iSeek+nWrite)>nBlob ){
242b4e9af9fSdanielk1977     *errorCodePtr = EINVAL;
243b4e9af9fSdanielk1977     return -1;
244b4e9af9fSdanielk1977   }
245b4e9af9fSdanielk1977   if( nWrite<=0 ){
246b4e9af9fSdanielk1977     return 0;
247b4e9af9fSdanielk1977   }
248b4e9af9fSdanielk1977 
249b4e9af9fSdanielk1977   rc = sqlite3_blob_write(p->pBlob, (void *)buf, nWrite, p->iSeek);
250b4e9af9fSdanielk1977   if( rc!=SQLITE_OK ){
251b4e9af9fSdanielk1977     *errorCodePtr = EIO;
252b4e9af9fSdanielk1977     return -1;
253b4e9af9fSdanielk1977   }
254b4e9af9fSdanielk1977 
255b4e9af9fSdanielk1977   p->iSeek += nWrite;
256b4e9af9fSdanielk1977   return nWrite;
257b4e9af9fSdanielk1977 }
258b4e9af9fSdanielk1977 
259b4e9af9fSdanielk1977 /*
260b4e9af9fSdanielk1977 ** Seek an incremental blob channel.
261b4e9af9fSdanielk1977 */
262b4e9af9fSdanielk1977 static int incrblobSeek(
263b4e9af9fSdanielk1977   ClientData instanceData,
264b4e9af9fSdanielk1977   long offset,
265b4e9af9fSdanielk1977   int seekMode,
266b4e9af9fSdanielk1977   int *errorCodePtr
267b4e9af9fSdanielk1977 ){
268b4e9af9fSdanielk1977   IncrblobChannel *p = (IncrblobChannel *)instanceData;
269b4e9af9fSdanielk1977 
270b4e9af9fSdanielk1977   switch( seekMode ){
271b4e9af9fSdanielk1977     case SEEK_SET:
272b4e9af9fSdanielk1977       p->iSeek = offset;
273b4e9af9fSdanielk1977       break;
274b4e9af9fSdanielk1977     case SEEK_CUR:
275b4e9af9fSdanielk1977       p->iSeek += offset;
276b4e9af9fSdanielk1977       break;
277b4e9af9fSdanielk1977     case SEEK_END:
278b4e9af9fSdanielk1977       p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset;
279b4e9af9fSdanielk1977       break;
280b4e9af9fSdanielk1977 
281b4e9af9fSdanielk1977     default: assert(!"Bad seekMode");
282b4e9af9fSdanielk1977   }
283b4e9af9fSdanielk1977 
284b4e9af9fSdanielk1977   return p->iSeek;
285b4e9af9fSdanielk1977 }
286b4e9af9fSdanielk1977 
287b4e9af9fSdanielk1977 
288b4e9af9fSdanielk1977 static void incrblobWatch(ClientData instanceData, int mode){
289b4e9af9fSdanielk1977   /* NO-OP */
290b4e9af9fSdanielk1977 }
291b4e9af9fSdanielk1977 static int incrblobHandle(ClientData instanceData, int dir, ClientData *hPtr){
292b4e9af9fSdanielk1977   return TCL_ERROR;
293b4e9af9fSdanielk1977 }
294b4e9af9fSdanielk1977 
295b4e9af9fSdanielk1977 static Tcl_ChannelType IncrblobChannelType = {
296b4e9af9fSdanielk1977   "incrblob",                        /* typeName                             */
297b4e9af9fSdanielk1977   TCL_CHANNEL_VERSION_2,             /* version                              */
298b4e9af9fSdanielk1977   incrblobClose,                     /* closeProc                            */
299b4e9af9fSdanielk1977   incrblobInput,                     /* inputProc                            */
300b4e9af9fSdanielk1977   incrblobOutput,                    /* outputProc                           */
301b4e9af9fSdanielk1977   incrblobSeek,                      /* seekProc                             */
302b4e9af9fSdanielk1977   0,                                 /* setOptionProc                        */
303b4e9af9fSdanielk1977   0,                                 /* getOptionProc                        */
304b4e9af9fSdanielk1977   incrblobWatch,                     /* watchProc (this is a no-op)          */
305b4e9af9fSdanielk1977   incrblobHandle,                    /* getHandleProc (always returns error) */
306b4e9af9fSdanielk1977   0,                                 /* close2Proc                           */
307b4e9af9fSdanielk1977   0,                                 /* blockModeProc                        */
308b4e9af9fSdanielk1977   0,                                 /* flushProc                            */
309b4e9af9fSdanielk1977   0,                                 /* handlerProc                          */
310b4e9af9fSdanielk1977   0,                                 /* wideSeekProc                         */
311b4e9af9fSdanielk1977 };
312b4e9af9fSdanielk1977 
313b4e9af9fSdanielk1977 /*
314b4e9af9fSdanielk1977 ** Create a new incrblob channel.
315b4e9af9fSdanielk1977 */
316b4e9af9fSdanielk1977 static int createIncrblobChannel(
317b4e9af9fSdanielk1977   Tcl_Interp *interp,
318b4e9af9fSdanielk1977   SqliteDb *pDb,
319b4e9af9fSdanielk1977   const char *zDb,
320b4e9af9fSdanielk1977   const char *zTable,
321b4e9af9fSdanielk1977   const char *zColumn,
3228cbadb02Sdanielk1977   sqlite_int64 iRow,
3238cbadb02Sdanielk1977   int isReadonly
324b4e9af9fSdanielk1977 ){
325b4e9af9fSdanielk1977   IncrblobChannel *p;
3268cbadb02Sdanielk1977   sqlite3 *db = pDb->db;
327b4e9af9fSdanielk1977   sqlite3_blob *pBlob;
328b4e9af9fSdanielk1977   int rc;
3298cbadb02Sdanielk1977   int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE);
330b4e9af9fSdanielk1977 
331b4e9af9fSdanielk1977   /* This variable is used to name the channels: "incrblob_[incr count]" */
332b4e9af9fSdanielk1977   static int count = 0;
333b4e9af9fSdanielk1977   char zChannel[64];
334b4e9af9fSdanielk1977 
3358cbadb02Sdanielk1977   rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob);
336b4e9af9fSdanielk1977   if( rc!=SQLITE_OK ){
337b4e9af9fSdanielk1977     Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
338b4e9af9fSdanielk1977     return TCL_ERROR;
339b4e9af9fSdanielk1977   }
340b4e9af9fSdanielk1977 
341b4e9af9fSdanielk1977   p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel));
342b4e9af9fSdanielk1977   p->iSeek = 0;
343b4e9af9fSdanielk1977   p->pBlob = pBlob;
344b4e9af9fSdanielk1977 
3455bb3eb9bSdrh   sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count);
346d0441796Sdanielk1977   p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags);
347d0441796Sdanielk1977   Tcl_RegisterChannel(interp, p->channel);
348b4e9af9fSdanielk1977 
349d0441796Sdanielk1977   /* Link the new channel into the SqliteDb.pIncrblob list. */
350d0441796Sdanielk1977   p->pNext = pDb->pIncrblob;
351d0441796Sdanielk1977   p->pPrev = 0;
352d0441796Sdanielk1977   if( p->pNext ){
353d0441796Sdanielk1977     p->pNext->pPrev = p;
354d0441796Sdanielk1977   }
355d0441796Sdanielk1977   pDb->pIncrblob = p;
356d0441796Sdanielk1977   p->pDb = pDb;
357d0441796Sdanielk1977 
358d0441796Sdanielk1977   Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE);
359b4e9af9fSdanielk1977   return TCL_OK;
360b4e9af9fSdanielk1977 }
36132a0d8bbSdanielk1977 #else  /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
36232a0d8bbSdanielk1977   #define closeIncrblobChannels(pDb)
36332a0d8bbSdanielk1977 #endif
364b4e9af9fSdanielk1977 
3656d31316cSdrh /*
366d1e4733dSdrh ** Look at the script prefix in pCmd.  We will be executing this script
367d1e4733dSdrh ** after first appending one or more arguments.  This routine analyzes
368d1e4733dSdrh ** the script to see if it is safe to use Tcl_EvalObjv() on the script
369d1e4733dSdrh ** rather than the more general Tcl_EvalEx().  Tcl_EvalObjv() is much
370d1e4733dSdrh ** faster.
371d1e4733dSdrh **
372d1e4733dSdrh ** Scripts that are safe to use with Tcl_EvalObjv() consists of a
373d1e4733dSdrh ** command name followed by zero or more arguments with no [...] or $
374d1e4733dSdrh ** or {...} or ; to be seen anywhere.  Most callback scripts consist
375d1e4733dSdrh ** of just a single procedure name and they meet this requirement.
376d1e4733dSdrh */
377d1e4733dSdrh static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
378d1e4733dSdrh   /* We could try to do something with Tcl_Parse().  But we will instead
379d1e4733dSdrh   ** just do a search for forbidden characters.  If any of the forbidden
380d1e4733dSdrh   ** characters appear in pCmd, we will report the string as unsafe.
381d1e4733dSdrh   */
382d1e4733dSdrh   const char *z;
383d1e4733dSdrh   int n;
384d1e4733dSdrh   z = Tcl_GetStringFromObj(pCmd, &n);
385d1e4733dSdrh   while( n-- > 0 ){
386d1e4733dSdrh     int c = *(z++);
387d1e4733dSdrh     if( c=='$' || c=='[' || c==';' ) return 0;
388d1e4733dSdrh   }
389d1e4733dSdrh   return 1;
390d1e4733dSdrh }
391d1e4733dSdrh 
392d1e4733dSdrh /*
393d1e4733dSdrh ** Find an SqlFunc structure with the given name.  Or create a new
394d1e4733dSdrh ** one if an existing one cannot be found.  Return a pointer to the
395d1e4733dSdrh ** structure.
396d1e4733dSdrh */
397d1e4733dSdrh static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
398d1e4733dSdrh   SqlFunc *p, *pNew;
399d1e4733dSdrh   int i;
4004f21c4afSdrh   pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + strlen30(zName) + 1 );
401d1e4733dSdrh   pNew->zName = (char*)&pNew[1];
402d1e4733dSdrh   for(i=0; zName[i]; i++){ pNew->zName[i] = tolower(zName[i]); }
403d1e4733dSdrh   pNew->zName[i] = 0;
404d1e4733dSdrh   for(p=pDb->pFunc; p; p=p->pNext){
405d1e4733dSdrh     if( strcmp(p->zName, pNew->zName)==0 ){
406d1e4733dSdrh       Tcl_Free((char*)pNew);
407d1e4733dSdrh       return p;
408d1e4733dSdrh     }
409d1e4733dSdrh   }
410d1e4733dSdrh   pNew->interp = pDb->interp;
411d1e4733dSdrh   pNew->pScript = 0;
412d1e4733dSdrh   pNew->pNext = pDb->pFunc;
413d1e4733dSdrh   pDb->pFunc = pNew;
414d1e4733dSdrh   return pNew;
415d1e4733dSdrh }
416d1e4733dSdrh 
417d1e4733dSdrh /*
418fb7e7651Sdrh ** Finalize and free a list of prepared statements
419fb7e7651Sdrh */
420fb7e7651Sdrh static void flushStmtCache( SqliteDb *pDb ){
421fb7e7651Sdrh   SqlPreparedStmt *pPreStmt;
422fb7e7651Sdrh 
423fb7e7651Sdrh   while(  pDb->stmtList ){
424fb7e7651Sdrh     sqlite3_finalize( pDb->stmtList->pStmt );
425fb7e7651Sdrh     pPreStmt = pDb->stmtList;
426fb7e7651Sdrh     pDb->stmtList = pDb->stmtList->pNext;
427fb7e7651Sdrh     Tcl_Free( (char*)pPreStmt );
428fb7e7651Sdrh   }
429fb7e7651Sdrh   pDb->nStmt = 0;
430fb7e7651Sdrh   pDb->stmtLast = 0;
431fb7e7651Sdrh }
432fb7e7651Sdrh 
433fb7e7651Sdrh /*
434895d7472Sdrh ** TCL calls this procedure when an sqlite3 database command is
435895d7472Sdrh ** deleted.
43675897234Sdrh */
43775897234Sdrh static void DbDeleteCmd(void *db){
438bec3f402Sdrh   SqliteDb *pDb = (SqliteDb*)db;
439fb7e7651Sdrh   flushStmtCache(pDb);
440d0441796Sdanielk1977   closeIncrblobChannels(pDb);
4416f8a503dSdanielk1977   sqlite3_close(pDb->db);
442cabb0819Sdrh   while( pDb->pFunc ){
443cabb0819Sdrh     SqlFunc *pFunc = pDb->pFunc;
444cabb0819Sdrh     pDb->pFunc = pFunc->pNext;
445d1e4733dSdrh     Tcl_DecrRefCount(pFunc->pScript);
446cabb0819Sdrh     Tcl_Free((char*)pFunc);
447cabb0819Sdrh   }
4480202b29eSdanielk1977   while( pDb->pCollate ){
4490202b29eSdanielk1977     SqlCollate *pCollate = pDb->pCollate;
4500202b29eSdanielk1977     pDb->pCollate = pCollate->pNext;
4510202b29eSdanielk1977     Tcl_Free((char*)pCollate);
4520202b29eSdanielk1977   }
453bec3f402Sdrh   if( pDb->zBusy ){
454bec3f402Sdrh     Tcl_Free(pDb->zBusy);
455bec3f402Sdrh   }
456b5a20d3cSdrh   if( pDb->zTrace ){
457b5a20d3cSdrh     Tcl_Free(pDb->zTrace);
4580d1a643aSdrh   }
45919e2d37fSdrh   if( pDb->zProfile ){
46019e2d37fSdrh     Tcl_Free(pDb->zProfile);
46119e2d37fSdrh   }
462e22a334bSdrh   if( pDb->zAuth ){
463e22a334bSdrh     Tcl_Free(pDb->zAuth);
464e22a334bSdrh   }
46555c45f2eSdanielk1977   if( pDb->zNull ){
46655c45f2eSdanielk1977     Tcl_Free(pDb->zNull);
46755c45f2eSdanielk1977   }
46894eb6a14Sdanielk1977   if( pDb->pUpdateHook ){
46994eb6a14Sdanielk1977     Tcl_DecrRefCount(pDb->pUpdateHook);
47094eb6a14Sdanielk1977   }
47171fd80bfSdanielk1977   if( pDb->pRollbackHook ){
47271fd80bfSdanielk1977     Tcl_DecrRefCount(pDb->pRollbackHook);
47371fd80bfSdanielk1977   }
47494eb6a14Sdanielk1977   if( pDb->pCollateNeeded ){
47594eb6a14Sdanielk1977     Tcl_DecrRefCount(pDb->pCollateNeeded);
47694eb6a14Sdanielk1977   }
477bec3f402Sdrh   Tcl_Free((char*)pDb);
478bec3f402Sdrh }
479bec3f402Sdrh 
480bec3f402Sdrh /*
481bec3f402Sdrh ** This routine is called when a database file is locked while trying
482bec3f402Sdrh ** to execute SQL.
483bec3f402Sdrh */
4842a764eb0Sdanielk1977 static int DbBusyHandler(void *cd, int nTries){
485bec3f402Sdrh   SqliteDb *pDb = (SqliteDb*)cd;
486bec3f402Sdrh   int rc;
487bec3f402Sdrh   char zVal[30];
488bec3f402Sdrh 
4895bb3eb9bSdrh   sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries);
490d1e4733dSdrh   rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
491bec3f402Sdrh   if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
492bec3f402Sdrh     return 0;
493bec3f402Sdrh   }
494bec3f402Sdrh   return 1;
49575897234Sdrh }
49675897234Sdrh 
49726e4a8b1Sdrh #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
49875897234Sdrh /*
499348bb5d6Sdanielk1977 ** This routine is invoked as the 'progress callback' for the database.
500348bb5d6Sdanielk1977 */
501348bb5d6Sdanielk1977 static int DbProgressHandler(void *cd){
502348bb5d6Sdanielk1977   SqliteDb *pDb = (SqliteDb*)cd;
503348bb5d6Sdanielk1977   int rc;
504348bb5d6Sdanielk1977 
505348bb5d6Sdanielk1977   assert( pDb->zProgress );
506348bb5d6Sdanielk1977   rc = Tcl_Eval(pDb->interp, pDb->zProgress);
507348bb5d6Sdanielk1977   if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
508348bb5d6Sdanielk1977     return 1;
509348bb5d6Sdanielk1977   }
510348bb5d6Sdanielk1977   return 0;
511348bb5d6Sdanielk1977 }
51226e4a8b1Sdrh #endif
513348bb5d6Sdanielk1977 
514d1167393Sdrh #ifndef SQLITE_OMIT_TRACE
515348bb5d6Sdanielk1977 /*
516b5a20d3cSdrh ** This routine is called by the SQLite trace handler whenever a new
517b5a20d3cSdrh ** block of SQL is executed.  The TCL script in pDb->zTrace is executed.
5180d1a643aSdrh */
519b5a20d3cSdrh static void DbTraceHandler(void *cd, const char *zSql){
5200d1a643aSdrh   SqliteDb *pDb = (SqliteDb*)cd;
521b5a20d3cSdrh   Tcl_DString str;
5220d1a643aSdrh 
523b5a20d3cSdrh   Tcl_DStringInit(&str);
524b5a20d3cSdrh   Tcl_DStringAppend(&str, pDb->zTrace, -1);
525b5a20d3cSdrh   Tcl_DStringAppendElement(&str, zSql);
526b5a20d3cSdrh   Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
527b5a20d3cSdrh   Tcl_DStringFree(&str);
528b5a20d3cSdrh   Tcl_ResetResult(pDb->interp);
5290d1a643aSdrh }
530d1167393Sdrh #endif
5310d1a643aSdrh 
532d1167393Sdrh #ifndef SQLITE_OMIT_TRACE
5330d1a643aSdrh /*
53419e2d37fSdrh ** This routine is called by the SQLite profile handler after a statement
53519e2d37fSdrh ** SQL has executed.  The TCL script in pDb->zProfile is evaluated.
53619e2d37fSdrh */
53719e2d37fSdrh static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
53819e2d37fSdrh   SqliteDb *pDb = (SqliteDb*)cd;
53919e2d37fSdrh   Tcl_DString str;
54019e2d37fSdrh   char zTm[100];
54119e2d37fSdrh 
54219e2d37fSdrh   sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
54319e2d37fSdrh   Tcl_DStringInit(&str);
54419e2d37fSdrh   Tcl_DStringAppend(&str, pDb->zProfile, -1);
54519e2d37fSdrh   Tcl_DStringAppendElement(&str, zSql);
54619e2d37fSdrh   Tcl_DStringAppendElement(&str, zTm);
54719e2d37fSdrh   Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
54819e2d37fSdrh   Tcl_DStringFree(&str);
54919e2d37fSdrh   Tcl_ResetResult(pDb->interp);
55019e2d37fSdrh }
551d1167393Sdrh #endif
55219e2d37fSdrh 
55319e2d37fSdrh /*
554aa940eacSdrh ** This routine is called when a transaction is committed.  The
555aa940eacSdrh ** TCL script in pDb->zCommit is executed.  If it returns non-zero or
556aa940eacSdrh ** if it throws an exception, the transaction is rolled back instead
557aa940eacSdrh ** of being committed.
558aa940eacSdrh */
559aa940eacSdrh static int DbCommitHandler(void *cd){
560aa940eacSdrh   SqliteDb *pDb = (SqliteDb*)cd;
561aa940eacSdrh   int rc;
562aa940eacSdrh 
563aa940eacSdrh   rc = Tcl_Eval(pDb->interp, pDb->zCommit);
564aa940eacSdrh   if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
565aa940eacSdrh     return 1;
566aa940eacSdrh   }
567aa940eacSdrh   return 0;
568aa940eacSdrh }
569aa940eacSdrh 
57071fd80bfSdanielk1977 static void DbRollbackHandler(void *clientData){
57171fd80bfSdanielk1977   SqliteDb *pDb = (SqliteDb*)clientData;
57271fd80bfSdanielk1977   assert(pDb->pRollbackHook);
57371fd80bfSdanielk1977   if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
57471fd80bfSdanielk1977     Tcl_BackgroundError(pDb->interp);
57571fd80bfSdanielk1977   }
57671fd80bfSdanielk1977 }
57771fd80bfSdanielk1977 
578bcf4f484Sdrh #if defined(SQLITE_TEST) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
579404ca075Sdanielk1977 static void setTestUnlockNotifyVars(Tcl_Interp *interp, int iArg, int nArg){
580404ca075Sdanielk1977   char zBuf[64];
581404ca075Sdanielk1977   sprintf(zBuf, "%d", iArg);
582404ca075Sdanielk1977   Tcl_SetVar(interp, "sqlite_unlock_notify_arg", zBuf, TCL_GLOBAL_ONLY);
583404ca075Sdanielk1977   sprintf(zBuf, "%d", nArg);
584404ca075Sdanielk1977   Tcl_SetVar(interp, "sqlite_unlock_notify_argcount", zBuf, TCL_GLOBAL_ONLY);
585404ca075Sdanielk1977 }
586404ca075Sdanielk1977 #else
587404ca075Sdanielk1977 # define setTestUnlockNotifyVars(x,y,z)
588404ca075Sdanielk1977 #endif
589404ca075Sdanielk1977 
59069910da9Sdrh #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
591404ca075Sdanielk1977 static void DbUnlockNotify(void **apArg, int nArg){
592404ca075Sdanielk1977   int i;
593404ca075Sdanielk1977   for(i=0; i<nArg; i++){
594404ca075Sdanielk1977     const int flags = (TCL_EVAL_GLOBAL|TCL_EVAL_DIRECT);
595404ca075Sdanielk1977     SqliteDb *pDb = (SqliteDb *)apArg[i];
596404ca075Sdanielk1977     setTestUnlockNotifyVars(pDb->interp, i, nArg);
597404ca075Sdanielk1977     assert( pDb->pUnlockNotify);
598404ca075Sdanielk1977     Tcl_EvalObjEx(pDb->interp, pDb->pUnlockNotify, flags);
599404ca075Sdanielk1977     Tcl_DecrRefCount(pDb->pUnlockNotify);
600404ca075Sdanielk1977     pDb->pUnlockNotify = 0;
601404ca075Sdanielk1977   }
602404ca075Sdanielk1977 }
60369910da9Sdrh #endif
604404ca075Sdanielk1977 
60594eb6a14Sdanielk1977 static void DbUpdateHandler(
60694eb6a14Sdanielk1977   void *p,
60794eb6a14Sdanielk1977   int op,
60894eb6a14Sdanielk1977   const char *zDb,
60994eb6a14Sdanielk1977   const char *zTbl,
61094eb6a14Sdanielk1977   sqlite_int64 rowid
61194eb6a14Sdanielk1977 ){
61294eb6a14Sdanielk1977   SqliteDb *pDb = (SqliteDb *)p;
61394eb6a14Sdanielk1977   Tcl_Obj *pCmd;
61494eb6a14Sdanielk1977 
61594eb6a14Sdanielk1977   assert( pDb->pUpdateHook );
61694eb6a14Sdanielk1977   assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
61794eb6a14Sdanielk1977 
61894eb6a14Sdanielk1977   pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
61994eb6a14Sdanielk1977   Tcl_IncrRefCount(pCmd);
62094eb6a14Sdanielk1977   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(
62194eb6a14Sdanielk1977     ( (op==SQLITE_INSERT)?"INSERT":(op==SQLITE_UPDATE)?"UPDATE":"DELETE"), -1));
62294eb6a14Sdanielk1977   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
62394eb6a14Sdanielk1977   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
62494eb6a14Sdanielk1977   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
62594eb6a14Sdanielk1977   Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
62694eb6a14Sdanielk1977 }
62794eb6a14Sdanielk1977 
6287cedc8d4Sdanielk1977 static void tclCollateNeeded(
6297cedc8d4Sdanielk1977   void *pCtx,
6309bb575fdSdrh   sqlite3 *db,
6317cedc8d4Sdanielk1977   int enc,
6327cedc8d4Sdanielk1977   const char *zName
6337cedc8d4Sdanielk1977 ){
6347cedc8d4Sdanielk1977   SqliteDb *pDb = (SqliteDb *)pCtx;
6357cedc8d4Sdanielk1977   Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
6367cedc8d4Sdanielk1977   Tcl_IncrRefCount(pScript);
6377cedc8d4Sdanielk1977   Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
6387cedc8d4Sdanielk1977   Tcl_EvalObjEx(pDb->interp, pScript, 0);
6397cedc8d4Sdanielk1977   Tcl_DecrRefCount(pScript);
6407cedc8d4Sdanielk1977 }
6417cedc8d4Sdanielk1977 
642aa940eacSdrh /*
6430202b29eSdanielk1977 ** This routine is called to evaluate an SQL collation function implemented
6440202b29eSdanielk1977 ** using TCL script.
6450202b29eSdanielk1977 */
6460202b29eSdanielk1977 static int tclSqlCollate(
6470202b29eSdanielk1977   void *pCtx,
6480202b29eSdanielk1977   int nA,
6490202b29eSdanielk1977   const void *zA,
6500202b29eSdanielk1977   int nB,
6510202b29eSdanielk1977   const void *zB
6520202b29eSdanielk1977 ){
6530202b29eSdanielk1977   SqlCollate *p = (SqlCollate *)pCtx;
6540202b29eSdanielk1977   Tcl_Obj *pCmd;
6550202b29eSdanielk1977 
6560202b29eSdanielk1977   pCmd = Tcl_NewStringObj(p->zScript, -1);
6570202b29eSdanielk1977   Tcl_IncrRefCount(pCmd);
6580202b29eSdanielk1977   Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
6590202b29eSdanielk1977   Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
660d1e4733dSdrh   Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
6610202b29eSdanielk1977   Tcl_DecrRefCount(pCmd);
6620202b29eSdanielk1977   return (atoi(Tcl_GetStringResult(p->interp)));
6630202b29eSdanielk1977 }
6640202b29eSdanielk1977 
6650202b29eSdanielk1977 /*
666cabb0819Sdrh ** This routine is called to evaluate an SQL function implemented
667cabb0819Sdrh ** using TCL script.
668cabb0819Sdrh */
6690ae8b831Sdanielk1977 static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
6706f8a503dSdanielk1977   SqlFunc *p = sqlite3_user_data(context);
671d1e4733dSdrh   Tcl_Obj *pCmd;
672cabb0819Sdrh   int i;
673cabb0819Sdrh   int rc;
674cabb0819Sdrh 
675d1e4733dSdrh   if( argc==0 ){
676d1e4733dSdrh     /* If there are no arguments to the function, call Tcl_EvalObjEx on the
677d1e4733dSdrh     ** script object directly.  This allows the TCL compiler to generate
678d1e4733dSdrh     ** bytecode for the command on the first invocation and thus make
679d1e4733dSdrh     ** subsequent invocations much faster. */
680d1e4733dSdrh     pCmd = p->pScript;
681d1e4733dSdrh     Tcl_IncrRefCount(pCmd);
682d1e4733dSdrh     rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
683d1e4733dSdrh     Tcl_DecrRefCount(pCmd);
68451ad0ecdSdanielk1977   }else{
685d1e4733dSdrh     /* If there are arguments to the function, make a shallow copy of the
686d1e4733dSdrh     ** script object, lappend the arguments, then evaluate the copy.
687d1e4733dSdrh     **
688d1e4733dSdrh     ** By "shallow" copy, we mean a only the outer list Tcl_Obj is duplicated.
689d1e4733dSdrh     ** The new Tcl_Obj contains pointers to the original list elements.
690d1e4733dSdrh     ** That way, when Tcl_EvalObjv() is run and shimmers the first element
691d1e4733dSdrh     ** of the list to tclCmdNameType, that alternate representation will
692d1e4733dSdrh     ** be preserved and reused on the next invocation.
693d1e4733dSdrh     */
694d1e4733dSdrh     Tcl_Obj **aArg;
695d1e4733dSdrh     int nArg;
696d1e4733dSdrh     if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
697d1e4733dSdrh       sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
698d1e4733dSdrh       return;
699d1e4733dSdrh     }
700d1e4733dSdrh     pCmd = Tcl_NewListObj(nArg, aArg);
701d1e4733dSdrh     Tcl_IncrRefCount(pCmd);
702d1e4733dSdrh     for(i=0; i<argc; i++){
703d1e4733dSdrh       sqlite3_value *pIn = argv[i];
704d1e4733dSdrh       Tcl_Obj *pVal;
705d1e4733dSdrh 
706d1e4733dSdrh       /* Set pVal to contain the i'th column of this row. */
707d1e4733dSdrh       switch( sqlite3_value_type(pIn) ){
708d1e4733dSdrh         case SQLITE_BLOB: {
709d1e4733dSdrh           int bytes = sqlite3_value_bytes(pIn);
710d1e4733dSdrh           pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
711d1e4733dSdrh           break;
712d1e4733dSdrh         }
713d1e4733dSdrh         case SQLITE_INTEGER: {
714d1e4733dSdrh           sqlite_int64 v = sqlite3_value_int64(pIn);
715d1e4733dSdrh           if( v>=-2147483647 && v<=2147483647 ){
716d1e4733dSdrh             pVal = Tcl_NewIntObj(v);
717d1e4733dSdrh           }else{
718d1e4733dSdrh             pVal = Tcl_NewWideIntObj(v);
719d1e4733dSdrh           }
720d1e4733dSdrh           break;
721d1e4733dSdrh         }
722d1e4733dSdrh         case SQLITE_FLOAT: {
723d1e4733dSdrh           double r = sqlite3_value_double(pIn);
724d1e4733dSdrh           pVal = Tcl_NewDoubleObj(r);
725d1e4733dSdrh           break;
726d1e4733dSdrh         }
727d1e4733dSdrh         case SQLITE_NULL: {
728d1e4733dSdrh           pVal = Tcl_NewStringObj("", 0);
729d1e4733dSdrh           break;
730d1e4733dSdrh         }
731d1e4733dSdrh         default: {
732d1e4733dSdrh           int bytes = sqlite3_value_bytes(pIn);
73300fd957bSdanielk1977           pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
734d1e4733dSdrh           break;
73551ad0ecdSdanielk1977         }
736cabb0819Sdrh       }
737d1e4733dSdrh       rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
738d1e4733dSdrh       if( rc ){
739d1e4733dSdrh         Tcl_DecrRefCount(pCmd);
740d1e4733dSdrh         sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
741d1e4733dSdrh         return;
742d1e4733dSdrh       }
743d1e4733dSdrh     }
744d1e4733dSdrh     if( !p->useEvalObjv ){
745d1e4733dSdrh       /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
746d1e4733dSdrh       ** is a list without a string representation.  To prevent this from
747d1e4733dSdrh       ** happening, make sure pCmd has a valid string representation */
748d1e4733dSdrh       Tcl_GetString(pCmd);
749d1e4733dSdrh     }
750d1e4733dSdrh     rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
751d1e4733dSdrh     Tcl_DecrRefCount(pCmd);
752d1e4733dSdrh   }
753562e8d3cSdanielk1977 
754c7f269d5Sdrh   if( rc && rc!=TCL_RETURN ){
7557e18c259Sdanielk1977     sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
756cabb0819Sdrh   }else{
757c7f269d5Sdrh     Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
758c7f269d5Sdrh     int n;
759c7f269d5Sdrh     u8 *data;
7604a4c11aaSdan     const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
761c7f269d5Sdrh     char c = zType[0];
762df0bddaeSdrh     if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
763d1e4733dSdrh       /* Only return a BLOB type if the Tcl variable is a bytearray and
764df0bddaeSdrh       ** has no string representation. */
765c7f269d5Sdrh       data = Tcl_GetByteArrayFromObj(pVar, &n);
766c7f269d5Sdrh       sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
767985e0c63Sdrh     }else if( c=='b' && strcmp(zType,"boolean")==0 ){
768c7f269d5Sdrh       Tcl_GetIntFromObj(0, pVar, &n);
769c7f269d5Sdrh       sqlite3_result_int(context, n);
770c7f269d5Sdrh     }else if( c=='d' && strcmp(zType,"double")==0 ){
771c7f269d5Sdrh       double r;
772c7f269d5Sdrh       Tcl_GetDoubleFromObj(0, pVar, &r);
773c7f269d5Sdrh       sqlite3_result_double(context, r);
774985e0c63Sdrh     }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
775985e0c63Sdrh           (c=='i' && strcmp(zType,"int")==0) ){
776df0bddaeSdrh       Tcl_WideInt v;
777df0bddaeSdrh       Tcl_GetWideIntFromObj(0, pVar, &v);
778df0bddaeSdrh       sqlite3_result_int64(context, v);
779c7f269d5Sdrh     }else{
78000fd957bSdanielk1977       data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
78100fd957bSdanielk1977       sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
782c7f269d5Sdrh     }
783cabb0819Sdrh   }
784cabb0819Sdrh }
785895d7472Sdrh 
786e22a334bSdrh #ifndef SQLITE_OMIT_AUTHORIZATION
787e22a334bSdrh /*
788e22a334bSdrh ** This is the authentication function.  It appends the authentication
789e22a334bSdrh ** type code and the two arguments to zCmd[] then invokes the result
790e22a334bSdrh ** on the interpreter.  The reply is examined to determine if the
791e22a334bSdrh ** authentication fails or succeeds.
792e22a334bSdrh */
793e22a334bSdrh static int auth_callback(
794e22a334bSdrh   void *pArg,
795e22a334bSdrh   int code,
796e22a334bSdrh   const char *zArg1,
797e22a334bSdrh   const char *zArg2,
798e22a334bSdrh   const char *zArg3,
799e22a334bSdrh   const char *zArg4
800e22a334bSdrh ){
801e22a334bSdrh   char *zCode;
802e22a334bSdrh   Tcl_DString str;
803e22a334bSdrh   int rc;
804e22a334bSdrh   const char *zReply;
805e22a334bSdrh   SqliteDb *pDb = (SqliteDb*)pArg;
8061f1549f8Sdrh   if( pDb->disableAuth ) return SQLITE_OK;
807e22a334bSdrh 
808e22a334bSdrh   switch( code ){
809e22a334bSdrh     case SQLITE_COPY              : zCode="SQLITE_COPY"; break;
810e22a334bSdrh     case SQLITE_CREATE_INDEX      : zCode="SQLITE_CREATE_INDEX"; break;
811e22a334bSdrh     case SQLITE_CREATE_TABLE      : zCode="SQLITE_CREATE_TABLE"; break;
812e22a334bSdrh     case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
813e22a334bSdrh     case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
814e22a334bSdrh     case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
815e22a334bSdrh     case SQLITE_CREATE_TEMP_VIEW  : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
816e22a334bSdrh     case SQLITE_CREATE_TRIGGER    : zCode="SQLITE_CREATE_TRIGGER"; break;
817e22a334bSdrh     case SQLITE_CREATE_VIEW       : zCode="SQLITE_CREATE_VIEW"; break;
818e22a334bSdrh     case SQLITE_DELETE            : zCode="SQLITE_DELETE"; break;
819e22a334bSdrh     case SQLITE_DROP_INDEX        : zCode="SQLITE_DROP_INDEX"; break;
820e22a334bSdrh     case SQLITE_DROP_TABLE        : zCode="SQLITE_DROP_TABLE"; break;
821e22a334bSdrh     case SQLITE_DROP_TEMP_INDEX   : zCode="SQLITE_DROP_TEMP_INDEX"; break;
822e22a334bSdrh     case SQLITE_DROP_TEMP_TABLE   : zCode="SQLITE_DROP_TEMP_TABLE"; break;
823e22a334bSdrh     case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
824e22a334bSdrh     case SQLITE_DROP_TEMP_VIEW    : zCode="SQLITE_DROP_TEMP_VIEW"; break;
825e22a334bSdrh     case SQLITE_DROP_TRIGGER      : zCode="SQLITE_DROP_TRIGGER"; break;
826e22a334bSdrh     case SQLITE_DROP_VIEW         : zCode="SQLITE_DROP_VIEW"; break;
827e22a334bSdrh     case SQLITE_INSERT            : zCode="SQLITE_INSERT"; break;
828e22a334bSdrh     case SQLITE_PRAGMA            : zCode="SQLITE_PRAGMA"; break;
829e22a334bSdrh     case SQLITE_READ              : zCode="SQLITE_READ"; break;
830e22a334bSdrh     case SQLITE_SELECT            : zCode="SQLITE_SELECT"; break;
831e22a334bSdrh     case SQLITE_TRANSACTION       : zCode="SQLITE_TRANSACTION"; break;
832e22a334bSdrh     case SQLITE_UPDATE            : zCode="SQLITE_UPDATE"; break;
83381e293b4Sdrh     case SQLITE_ATTACH            : zCode="SQLITE_ATTACH"; break;
83481e293b4Sdrh     case SQLITE_DETACH            : zCode="SQLITE_DETACH"; break;
8351c8c23ccSdanielk1977     case SQLITE_ALTER_TABLE       : zCode="SQLITE_ALTER_TABLE"; break;
8361d54df88Sdanielk1977     case SQLITE_REINDEX           : zCode="SQLITE_REINDEX"; break;
837e6e04969Sdrh     case SQLITE_ANALYZE           : zCode="SQLITE_ANALYZE"; break;
838f1a381e7Sdanielk1977     case SQLITE_CREATE_VTABLE     : zCode="SQLITE_CREATE_VTABLE"; break;
839f1a381e7Sdanielk1977     case SQLITE_DROP_VTABLE       : zCode="SQLITE_DROP_VTABLE"; break;
8405169bbc6Sdrh     case SQLITE_FUNCTION          : zCode="SQLITE_FUNCTION"; break;
841ab9b703fSdanielk1977     case SQLITE_SAVEPOINT         : zCode="SQLITE_SAVEPOINT"; break;
842e22a334bSdrh     default                       : zCode="????"; break;
843e22a334bSdrh   }
844e22a334bSdrh   Tcl_DStringInit(&str);
845e22a334bSdrh   Tcl_DStringAppend(&str, pDb->zAuth, -1);
846e22a334bSdrh   Tcl_DStringAppendElement(&str, zCode);
847e22a334bSdrh   Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
848e22a334bSdrh   Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
849e22a334bSdrh   Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
850e22a334bSdrh   Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
851e22a334bSdrh   rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
852e22a334bSdrh   Tcl_DStringFree(&str);
853e22a334bSdrh   zReply = Tcl_GetStringResult(pDb->interp);
854e22a334bSdrh   if( strcmp(zReply,"SQLITE_OK")==0 ){
855e22a334bSdrh     rc = SQLITE_OK;
856e22a334bSdrh   }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
857e22a334bSdrh     rc = SQLITE_DENY;
858e22a334bSdrh   }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
859e22a334bSdrh     rc = SQLITE_IGNORE;
860e22a334bSdrh   }else{
861e22a334bSdrh     rc = 999;
862e22a334bSdrh   }
863e22a334bSdrh   return rc;
864e22a334bSdrh }
865e22a334bSdrh #endif /* SQLITE_OMIT_AUTHORIZATION */
866cabb0819Sdrh 
867cabb0819Sdrh /*
868ef2cb63eSdanielk1977 ** zText is a pointer to text obtained via an sqlite3_result_text()
869ef2cb63eSdanielk1977 ** or similar interface. This routine returns a Tcl string object,
870ef2cb63eSdanielk1977 ** reference count set to 0, containing the text. If a translation
871ef2cb63eSdanielk1977 ** between iso8859 and UTF-8 is required, it is preformed.
872ef2cb63eSdanielk1977 */
873ef2cb63eSdanielk1977 static Tcl_Obj *dbTextToObj(char const *zText){
874ef2cb63eSdanielk1977   Tcl_Obj *pVal;
875ef2cb63eSdanielk1977 #ifdef UTF_TRANSLATION_NEEDED
876ef2cb63eSdanielk1977   Tcl_DString dCol;
877ef2cb63eSdanielk1977   Tcl_DStringInit(&dCol);
878ef2cb63eSdanielk1977   Tcl_ExternalToUtfDString(NULL, zText, -1, &dCol);
879ef2cb63eSdanielk1977   pVal = Tcl_NewStringObj(Tcl_DStringValue(&dCol), -1);
880ef2cb63eSdanielk1977   Tcl_DStringFree(&dCol);
881ef2cb63eSdanielk1977 #else
882ef2cb63eSdanielk1977   pVal = Tcl_NewStringObj(zText, -1);
883ef2cb63eSdanielk1977 #endif
884ef2cb63eSdanielk1977   return pVal;
885ef2cb63eSdanielk1977 }
886ef2cb63eSdanielk1977 
887ef2cb63eSdanielk1977 /*
8881067fe11Stpoindex ** This routine reads a line of text from FILE in, stores
8891067fe11Stpoindex ** the text in memory obtained from malloc() and returns a pointer
8901067fe11Stpoindex ** to the text.  NULL is returned at end of file, or if malloc()
8911067fe11Stpoindex ** fails.
8921067fe11Stpoindex **
8931067fe11Stpoindex ** The interface is like "readline" but no command-line editing
8941067fe11Stpoindex ** is done.
8951067fe11Stpoindex **
8961067fe11Stpoindex ** copied from shell.c from '.import' command
8971067fe11Stpoindex */
8981067fe11Stpoindex static char *local_getline(char *zPrompt, FILE *in){
8991067fe11Stpoindex   char *zLine;
9001067fe11Stpoindex   int nLine;
9011067fe11Stpoindex   int n;
9021067fe11Stpoindex   int eol;
9031067fe11Stpoindex 
9041067fe11Stpoindex   nLine = 100;
9051067fe11Stpoindex   zLine = malloc( nLine );
9061067fe11Stpoindex   if( zLine==0 ) return 0;
9071067fe11Stpoindex   n = 0;
9081067fe11Stpoindex   eol = 0;
9091067fe11Stpoindex   while( !eol ){
9101067fe11Stpoindex     if( n+100>nLine ){
9111067fe11Stpoindex       nLine = nLine*2 + 100;
9121067fe11Stpoindex       zLine = realloc(zLine, nLine);
9131067fe11Stpoindex       if( zLine==0 ) return 0;
9141067fe11Stpoindex     }
9151067fe11Stpoindex     if( fgets(&zLine[n], nLine - n, in)==0 ){
9161067fe11Stpoindex       if( n==0 ){
9171067fe11Stpoindex         free(zLine);
9181067fe11Stpoindex         return 0;
9191067fe11Stpoindex       }
9201067fe11Stpoindex       zLine[n] = 0;
9211067fe11Stpoindex       eol = 1;
9221067fe11Stpoindex       break;
9231067fe11Stpoindex     }
9241067fe11Stpoindex     while( zLine[n] ){ n++; }
9251067fe11Stpoindex     if( n>0 && zLine[n-1]=='\n' ){
9261067fe11Stpoindex       n--;
9271067fe11Stpoindex       zLine[n] = 0;
9281067fe11Stpoindex       eol = 1;
9291067fe11Stpoindex     }
9301067fe11Stpoindex   }
9311067fe11Stpoindex   zLine = realloc( zLine, n+1 );
9321067fe11Stpoindex   return zLine;
9331067fe11Stpoindex }
9341067fe11Stpoindex 
9358e556520Sdanielk1977 
9368e556520Sdanielk1977 /*
9374a4c11aaSdan ** This function is part of the implementation of the command:
9388e556520Sdanielk1977 **
9394a4c11aaSdan **   $db transaction [-deferred|-immediate|-exclusive] SCRIPT
9408e556520Sdanielk1977 **
9414a4c11aaSdan ** It is invoked after evaluating the script SCRIPT to commit or rollback
9424a4c11aaSdan ** the transaction or savepoint opened by the [transaction] command.
9434a4c11aaSdan */
9444a4c11aaSdan static int DbTransPostCmd(
9454a4c11aaSdan   ClientData data[],                   /* data[0] is the Sqlite3Db* for $db */
9464a4c11aaSdan   Tcl_Interp *interp,                  /* Tcl interpreter */
9474a4c11aaSdan   int result                           /* Result of evaluating SCRIPT */
9484a4c11aaSdan ){
9494a4c11aaSdan   static const char *azEnd[] = {
9504a4c11aaSdan     "RELEASE _tcl_transaction",        /* rc==TCL_ERROR, nTransaction!=0 */
9514a4c11aaSdan     "COMMIT",                          /* rc!=TCL_ERROR, nTransaction==0 */
9524a4c11aaSdan     "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction",
9534a4c11aaSdan     "ROLLBACK"                         /* rc==TCL_ERROR, nTransaction==0 */
9544a4c11aaSdan   };
9554a4c11aaSdan   SqliteDb *pDb = (SqliteDb*)data[0];
9564a4c11aaSdan   int rc = result;
9574a4c11aaSdan   const char *zEnd;
9584a4c11aaSdan 
9594a4c11aaSdan   pDb->nTransaction--;
9604a4c11aaSdan   zEnd = azEnd[(rc==TCL_ERROR)*2 + (pDb->nTransaction==0)];
9614a4c11aaSdan 
9624a4c11aaSdan   pDb->disableAuth++;
9634a4c11aaSdan   if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){
9644a4c11aaSdan       /* This is a tricky scenario to handle. The most likely cause of an
9654a4c11aaSdan       ** error is that the exec() above was an attempt to commit the
9664a4c11aaSdan       ** top-level transaction that returned SQLITE_BUSY. Or, less likely,
9674a4c11aaSdan       ** that an IO-error has occured. In either case, throw a Tcl exception
9684a4c11aaSdan       ** and try to rollback the transaction.
9694a4c11aaSdan       **
9704a4c11aaSdan       ** But it could also be that the user executed one or more BEGIN,
9714a4c11aaSdan       ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing
9724a4c11aaSdan       ** this method's logic. Not clear how this would be best handled.
9734a4c11aaSdan       */
9744a4c11aaSdan     if( rc!=TCL_ERROR ){
9754a4c11aaSdan       Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
9764a4c11aaSdan       rc = TCL_ERROR;
9774a4c11aaSdan     }
9784a4c11aaSdan     sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
9794a4c11aaSdan   }
9804a4c11aaSdan   pDb->disableAuth--;
9814a4c11aaSdan 
9824a4c11aaSdan   return rc;
9834a4c11aaSdan }
9844a4c11aaSdan 
9854a4c11aaSdan /*
9864a4c11aaSdan ** Search the cache for a prepared-statement object that implements the
9874a4c11aaSdan ** first SQL statement in the buffer pointed to by parameter zIn. If
9884a4c11aaSdan ** no such prepared-statement can be found, allocate and prepare a new
9894a4c11aaSdan ** one. In either case, bind the current values of the relevant Tcl
9904a4c11aaSdan ** variables to any $var, :var or @var variables in the statement. Before
9914a4c11aaSdan ** returning, set *ppPreStmt to point to the prepared-statement object.
9924a4c11aaSdan **
9934a4c11aaSdan ** Output parameter *pzOut is set to point to the next SQL statement in
9944a4c11aaSdan ** buffer zIn, or to the '\0' byte at the end of zIn if there is no
9954a4c11aaSdan ** next statement.
9964a4c11aaSdan **
9974a4c11aaSdan ** If successful, TCL_OK is returned. Otherwise, TCL_ERROR is returned
9984a4c11aaSdan ** and an error message loaded into interpreter pDb->interp.
9994a4c11aaSdan */
10004a4c11aaSdan static int dbPrepareAndBind(
10014a4c11aaSdan   SqliteDb *pDb,                  /* Database object */
10024a4c11aaSdan   char const *zIn,                /* SQL to compile */
10034a4c11aaSdan   char const **pzOut,             /* OUT: Pointer to next SQL statement */
10044a4c11aaSdan   SqlPreparedStmt **ppPreStmt     /* OUT: Object used to cache statement */
10054a4c11aaSdan ){
10064a4c11aaSdan   const char *zSql = zIn;         /* Pointer to first SQL statement in zIn */
10074a4c11aaSdan   sqlite3_stmt *pStmt;            /* Prepared statement object */
10084a4c11aaSdan   SqlPreparedStmt *pPreStmt;      /* Pointer to cached statement */
10094a4c11aaSdan   int nSql;                       /* Length of zSql in bytes */
10104a4c11aaSdan   int nVar;                       /* Number of variables in statement */
10114a4c11aaSdan   int iParm = 0;                  /* Next free entry in apParm */
10124a4c11aaSdan   int i;
10134a4c11aaSdan   Tcl_Interp *interp = pDb->interp;
10144a4c11aaSdan 
10154a4c11aaSdan   *ppPreStmt = 0;
10164a4c11aaSdan 
10174a4c11aaSdan   /* Trim spaces from the start of zSql and calculate the remaining length. */
10184a4c11aaSdan   while( isspace(zSql[0]) ){ zSql++; }
10194a4c11aaSdan   nSql = strlen30(zSql);
10204a4c11aaSdan 
10214a4c11aaSdan   for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pPreStmt->pNext){
10224a4c11aaSdan     int n = pPreStmt->nSql;
10234a4c11aaSdan     if( nSql>=n
10244a4c11aaSdan         && memcmp(pPreStmt->zSql, zSql, n)==0
10254a4c11aaSdan         && (zSql[n]==0 || zSql[n-1]==';')
10264a4c11aaSdan     ){
10274a4c11aaSdan       pStmt = pPreStmt->pStmt;
10284a4c11aaSdan       *pzOut = &zSql[pPreStmt->nSql];
10294a4c11aaSdan 
10304a4c11aaSdan       /* When a prepared statement is found, unlink it from the
10314a4c11aaSdan       ** cache list.  It will later be added back to the beginning
10324a4c11aaSdan       ** of the cache list in order to implement LRU replacement.
10334a4c11aaSdan       */
10344a4c11aaSdan       if( pPreStmt->pPrev ){
10354a4c11aaSdan         pPreStmt->pPrev->pNext = pPreStmt->pNext;
10364a4c11aaSdan       }else{
10374a4c11aaSdan         pDb->stmtList = pPreStmt->pNext;
10384a4c11aaSdan       }
10394a4c11aaSdan       if( pPreStmt->pNext ){
10404a4c11aaSdan         pPreStmt->pNext->pPrev = pPreStmt->pPrev;
10414a4c11aaSdan       }else{
10424a4c11aaSdan         pDb->stmtLast = pPreStmt->pPrev;
10434a4c11aaSdan       }
10444a4c11aaSdan       pDb->nStmt--;
10454a4c11aaSdan       nVar = sqlite3_bind_parameter_count(pStmt);
10464a4c11aaSdan       break;
10474a4c11aaSdan     }
10484a4c11aaSdan   }
10494a4c11aaSdan 
10504a4c11aaSdan   /* If no prepared statement was found. Compile the SQL text. Also allocate
10514a4c11aaSdan   ** a new SqlPreparedStmt structure.  */
10524a4c11aaSdan   if( pPreStmt==0 ){
10534a4c11aaSdan     int nByte;
10544a4c11aaSdan 
10554a4c11aaSdan     if( SQLITE_OK!=sqlite3_prepare_v2(pDb->db, zSql, -1, &pStmt, pzOut) ){
10564a4c11aaSdan       Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
10574a4c11aaSdan       return TCL_ERROR;
10584a4c11aaSdan     }
10594a4c11aaSdan     if( pStmt==0 ){
10604a4c11aaSdan       if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
10614a4c11aaSdan         /* A compile-time error in the statement. */
10624a4c11aaSdan         Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
10634a4c11aaSdan         return TCL_ERROR;
10644a4c11aaSdan       }else{
10654a4c11aaSdan         /* The statement was a no-op.  Continue to the next statement
10664a4c11aaSdan         ** in the SQL string.
10674a4c11aaSdan         */
10684a4c11aaSdan         return TCL_OK;
10694a4c11aaSdan       }
10704a4c11aaSdan     }
10714a4c11aaSdan 
10724a4c11aaSdan     assert( pPreStmt==0 );
10734a4c11aaSdan     nVar = sqlite3_bind_parameter_count(pStmt);
10744a4c11aaSdan     nByte = sizeof(SqlPreparedStmt) + nVar*sizeof(Tcl_Obj *);
10754a4c11aaSdan     pPreStmt = (SqlPreparedStmt*)Tcl_Alloc(nByte);
10764a4c11aaSdan     memset(pPreStmt, 0, nByte);
10774a4c11aaSdan 
10784a4c11aaSdan     pPreStmt->pStmt = pStmt;
10794a4c11aaSdan     pPreStmt->nSql = (*pzOut - zSql);
10804a4c11aaSdan     pPreStmt->zSql = sqlite3_sql(pStmt);
10814a4c11aaSdan     pPreStmt->apParm = (Tcl_Obj **)&pPreStmt[1];
10824a4c11aaSdan   }
10834a4c11aaSdan   assert( pPreStmt );
10844a4c11aaSdan   assert( strlen30(pPreStmt->zSql)==pPreStmt->nSql );
10854a4c11aaSdan   assert( 0==memcmp(pPreStmt->zSql, zSql, pPreStmt->nSql) );
10864a4c11aaSdan 
10874a4c11aaSdan   /* Bind values to parameters that begin with $ or : */
10884a4c11aaSdan   for(i=1; i<=nVar; i++){
10894a4c11aaSdan     const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
10904a4c11aaSdan     if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){
10914a4c11aaSdan       Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
10924a4c11aaSdan       if( pVar ){
10934a4c11aaSdan         int n;
10944a4c11aaSdan         u8 *data;
10954a4c11aaSdan         const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
10964a4c11aaSdan         char c = zType[0];
10974a4c11aaSdan         if( zVar[0]=='@' ||
10984a4c11aaSdan            (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){
10994a4c11aaSdan           /* Load a BLOB type if the Tcl variable is a bytearray and
11004a4c11aaSdan           ** it has no string representation or the host
11014a4c11aaSdan           ** parameter name begins with "@". */
11024a4c11aaSdan           data = Tcl_GetByteArrayFromObj(pVar, &n);
11034a4c11aaSdan           sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
11044a4c11aaSdan           Tcl_IncrRefCount(pVar);
11054a4c11aaSdan           pPreStmt->apParm[iParm++] = pVar;
11064a4c11aaSdan         }else if( c=='b' && strcmp(zType,"boolean")==0 ){
11074a4c11aaSdan           Tcl_GetIntFromObj(interp, pVar, &n);
11084a4c11aaSdan           sqlite3_bind_int(pStmt, i, n);
11094a4c11aaSdan         }else if( c=='d' && strcmp(zType,"double")==0 ){
11104a4c11aaSdan           double r;
11114a4c11aaSdan           Tcl_GetDoubleFromObj(interp, pVar, &r);
11124a4c11aaSdan           sqlite3_bind_double(pStmt, i, r);
11134a4c11aaSdan         }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
11144a4c11aaSdan               (c=='i' && strcmp(zType,"int")==0) ){
11154a4c11aaSdan           Tcl_WideInt v;
11164a4c11aaSdan           Tcl_GetWideIntFromObj(interp, pVar, &v);
11174a4c11aaSdan           sqlite3_bind_int64(pStmt, i, v);
11184a4c11aaSdan         }else{
11194a4c11aaSdan           data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
11204a4c11aaSdan           sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
11214a4c11aaSdan           Tcl_IncrRefCount(pVar);
11224a4c11aaSdan           pPreStmt->apParm[iParm++] = pVar;
11234a4c11aaSdan         }
11244a4c11aaSdan       }else{
11254a4c11aaSdan         sqlite3_bind_null(pStmt, i);
11264a4c11aaSdan       }
11274a4c11aaSdan     }
11284a4c11aaSdan   }
11294a4c11aaSdan   pPreStmt->nParm = iParm;
11304a4c11aaSdan   *ppPreStmt = pPreStmt;
11314a4c11aaSdan   return TCL_OK;
11324a4c11aaSdan }
11334a4c11aaSdan 
11344a4c11aaSdan 
11354a4c11aaSdan /*
11364a4c11aaSdan ** Release a statement reference obtained by calling dbPrepareAndBind().
11374a4c11aaSdan ** There should be exactly one call to this function for each call to
11384a4c11aaSdan ** dbPrepareAndBind().
11394a4c11aaSdan **
11404a4c11aaSdan ** If the discard parameter is non-zero, then the statement is deleted
11414a4c11aaSdan ** immediately. Otherwise it is added to the LRU list and may be returned
11424a4c11aaSdan ** by a subsequent call to dbPrepareAndBind().
11434a4c11aaSdan */
11444a4c11aaSdan static void dbReleaseStmt(
11454a4c11aaSdan   SqliteDb *pDb,                  /* Database handle */
11464a4c11aaSdan   SqlPreparedStmt *pPreStmt,      /* Prepared statement handle to release */
11474a4c11aaSdan   int discard                     /* True to delete (not cache) the pPreStmt */
11484a4c11aaSdan ){
11494a4c11aaSdan   int i;
11504a4c11aaSdan 
11514a4c11aaSdan   /* Free the bound string and blob parameters */
11524a4c11aaSdan   for(i=0; i<pPreStmt->nParm; i++){
11534a4c11aaSdan     Tcl_DecrRefCount(pPreStmt->apParm[i]);
11544a4c11aaSdan   }
11554a4c11aaSdan   pPreStmt->nParm = 0;
11564a4c11aaSdan 
11574a4c11aaSdan   if( pDb->maxStmt<=0 || discard ){
11584a4c11aaSdan     /* If the cache is turned off, deallocated the statement */
11594a4c11aaSdan     sqlite3_finalize(pPreStmt->pStmt);
11604a4c11aaSdan     Tcl_Free((char *)pPreStmt);
11614a4c11aaSdan   }else{
11624a4c11aaSdan     /* Add the prepared statement to the beginning of the cache list. */
11634a4c11aaSdan     pPreStmt->pNext = pDb->stmtList;
11644a4c11aaSdan     pPreStmt->pPrev = 0;
11654a4c11aaSdan     if( pDb->stmtList ){
11664a4c11aaSdan      pDb->stmtList->pPrev = pPreStmt;
11674a4c11aaSdan     }
11684a4c11aaSdan     pDb->stmtList = pPreStmt;
11694a4c11aaSdan     if( pDb->stmtLast==0 ){
11704a4c11aaSdan       assert( pDb->nStmt==0 );
11714a4c11aaSdan       pDb->stmtLast = pPreStmt;
11724a4c11aaSdan     }else{
11734a4c11aaSdan       assert( pDb->nStmt>0 );
11744a4c11aaSdan     }
11754a4c11aaSdan     pDb->nStmt++;
11764a4c11aaSdan 
11774a4c11aaSdan     /* If we have too many statement in cache, remove the surplus from
11784a4c11aaSdan     ** the end of the cache list.  */
11794a4c11aaSdan     while( pDb->nStmt>pDb->maxStmt ){
11804a4c11aaSdan       sqlite3_finalize(pDb->stmtLast->pStmt);
11814a4c11aaSdan       pDb->stmtLast = pDb->stmtLast->pPrev;
11824a4c11aaSdan       Tcl_Free((char*)pDb->stmtLast->pNext);
11834a4c11aaSdan       pDb->stmtLast->pNext = 0;
11844a4c11aaSdan       pDb->nStmt--;
11854a4c11aaSdan     }
11864a4c11aaSdan   }
11874a4c11aaSdan }
11884a4c11aaSdan 
11894a4c11aaSdan /*
11904a4c11aaSdan ** Structure used with dbEvalXXX() functions:
11914a4c11aaSdan **
11924a4c11aaSdan **   dbEvalInit()
11934a4c11aaSdan **   dbEvalStep()
11944a4c11aaSdan **   dbEvalFinalize()
11954a4c11aaSdan **   dbEvalRowInfo()
11964a4c11aaSdan **   dbEvalColumnValue()
11974a4c11aaSdan */
11984a4c11aaSdan typedef struct DbEvalContext DbEvalContext;
11994a4c11aaSdan struct DbEvalContext {
12004a4c11aaSdan   SqliteDb *pDb;                  /* Database handle */
12014a4c11aaSdan   Tcl_Obj *pSql;                  /* Object holding string zSql */
12024a4c11aaSdan   const char *zSql;               /* Remaining SQL to execute */
12034a4c11aaSdan   SqlPreparedStmt *pPreStmt;      /* Current statement */
12044a4c11aaSdan   int nCol;                       /* Number of columns returned by pStmt */
12054a4c11aaSdan   Tcl_Obj *pArray;                /* Name of array variable */
12064a4c11aaSdan   Tcl_Obj **apColName;            /* Array of column names */
12074a4c11aaSdan };
12084a4c11aaSdan 
12094a4c11aaSdan /*
12104a4c11aaSdan ** Release any cache of column names currently held as part of
12114a4c11aaSdan ** the DbEvalContext structure passed as the first argument.
12124a4c11aaSdan */
12134a4c11aaSdan static void dbReleaseColumnNames(DbEvalContext *p){
12144a4c11aaSdan   if( p->apColName ){
12154a4c11aaSdan     int i;
12164a4c11aaSdan     for(i=0; i<p->nCol; i++){
12174a4c11aaSdan       Tcl_DecrRefCount(p->apColName[i]);
12184a4c11aaSdan     }
12194a4c11aaSdan     Tcl_Free((char *)p->apColName);
12204a4c11aaSdan     p->apColName = 0;
12214a4c11aaSdan   }
12224a4c11aaSdan   p->nCol = 0;
12234a4c11aaSdan }
12244a4c11aaSdan 
12254a4c11aaSdan /*
12264a4c11aaSdan ** Initialize a DbEvalContext structure.
12278e556520Sdanielk1977 **
12288e556520Sdanielk1977 ** If pArray is not NULL, then it contains the name of a Tcl array
12298e556520Sdanielk1977 ** variable. The "*" member of this array is set to a list containing
12304a4c11aaSdan ** the names of the columns returned by the statement as part of each
12314a4c11aaSdan ** call to dbEvalStep(), in order from left to right. e.g. if the names
12324a4c11aaSdan ** of the returned columns are a, b and c, it does the equivalent of the
12334a4c11aaSdan ** tcl command:
12348e556520Sdanielk1977 **
12358e556520Sdanielk1977 **     set ${pArray}(*) {a b c}
12368e556520Sdanielk1977 */
12374a4c11aaSdan static void dbEvalInit(
12384a4c11aaSdan   DbEvalContext *p,               /* Pointer to structure to initialize */
12394a4c11aaSdan   SqliteDb *pDb,                  /* Database handle */
12404a4c11aaSdan   Tcl_Obj *pSql,                  /* Object containing SQL script */
12414a4c11aaSdan   Tcl_Obj *pArray                 /* Name of Tcl array to set (*) element of */
12428e556520Sdanielk1977 ){
12434a4c11aaSdan   memset(p, 0, sizeof(DbEvalContext));
12444a4c11aaSdan   p->pDb = pDb;
12454a4c11aaSdan   p->zSql = Tcl_GetString(pSql);
12464a4c11aaSdan   p->pSql = pSql;
12474a4c11aaSdan   Tcl_IncrRefCount(pSql);
12484a4c11aaSdan   if( pArray ){
12494a4c11aaSdan     p->pArray = pArray;
12504a4c11aaSdan     Tcl_IncrRefCount(pArray);
12514a4c11aaSdan   }
12524a4c11aaSdan }
12538e556520Sdanielk1977 
12544a4c11aaSdan /*
12554a4c11aaSdan ** Obtain information about the row that the DbEvalContext passed as the
12564a4c11aaSdan ** first argument currently points to.
12574a4c11aaSdan */
12584a4c11aaSdan static void dbEvalRowInfo(
12594a4c11aaSdan   DbEvalContext *p,               /* Evaluation context */
12604a4c11aaSdan   int *pnCol,                     /* OUT: Number of column names */
12614a4c11aaSdan   Tcl_Obj ***papColName           /* OUT: Array of column names */
12624a4c11aaSdan ){
12638e556520Sdanielk1977   /* Compute column names */
12644a4c11aaSdan   if( 0==p->apColName ){
12654a4c11aaSdan     sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
12664a4c11aaSdan     int i;                        /* Iterator variable */
12674a4c11aaSdan     int nCol;                     /* Number of columns returned by pStmt */
12684a4c11aaSdan     Tcl_Obj **apColName = 0;      /* Array of column names */
12694a4c11aaSdan 
12704a4c11aaSdan     p->nCol = nCol = sqlite3_column_count(pStmt);
12714a4c11aaSdan     if( nCol>0 && (papColName || p->pArray) ){
12724a4c11aaSdan       apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
12738e556520Sdanielk1977       for(i=0; i<nCol; i++){
12748e556520Sdanielk1977         apColName[i] = dbTextToObj(sqlite3_column_name(pStmt,i));
12758e556520Sdanielk1977         Tcl_IncrRefCount(apColName[i]);
12768e556520Sdanielk1977       }
12774a4c11aaSdan       p->apColName = apColName;
12784a4c11aaSdan     }
12798e556520Sdanielk1977 
12808e556520Sdanielk1977     /* If results are being stored in an array variable, then create
12818e556520Sdanielk1977     ** the array(*) entry for that array
12828e556520Sdanielk1977     */
12834a4c11aaSdan     if( p->pArray ){
12844a4c11aaSdan       Tcl_Interp *interp = p->pDb->interp;
12858e556520Sdanielk1977       Tcl_Obj *pColList = Tcl_NewObj();
12868e556520Sdanielk1977       Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
12874a4c11aaSdan 
12888e556520Sdanielk1977       for(i=0; i<nCol; i++){
12898e556520Sdanielk1977         Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
12908e556520Sdanielk1977       }
12918e556520Sdanielk1977       Tcl_IncrRefCount(pStar);
12924a4c11aaSdan       Tcl_ObjSetVar2(interp, p->pArray, pStar, pColList, 0);
12938e556520Sdanielk1977       Tcl_DecrRefCount(pStar);
12948e556520Sdanielk1977     }
12958e556520Sdanielk1977   }
12968e556520Sdanielk1977 
12974a4c11aaSdan   if( papColName ){
12984a4c11aaSdan     *papColName = p->apColName;
12994a4c11aaSdan   }
13004a4c11aaSdan   if( pnCol ){
13014a4c11aaSdan     *pnCol = p->nCol;
13024a4c11aaSdan   }
13034a4c11aaSdan }
13044a4c11aaSdan 
13054a4c11aaSdan /*
13064a4c11aaSdan ** Return one of TCL_OK, TCL_BREAK or TCL_ERROR. If TCL_ERROR is
13074a4c11aaSdan ** returned, then an error message is stored in the interpreter before
13084a4c11aaSdan ** returning.
13094a4c11aaSdan **
13104a4c11aaSdan ** A return value of TCL_OK means there is a row of data available. The
13114a4c11aaSdan ** data may be accessed using dbEvalRowInfo() and dbEvalColumnValue(). This
13124a4c11aaSdan ** is analogous to a return of SQLITE_ROW from sqlite3_step(). If TCL_BREAK
13134a4c11aaSdan ** is returned, then the SQL script has finished executing and there are
13144a4c11aaSdan ** no further rows available. This is similar to SQLITE_DONE.
13154a4c11aaSdan */
13164a4c11aaSdan static int dbEvalStep(DbEvalContext *p){
13174a4c11aaSdan   while( p->zSql[0] || p->pPreStmt ){
13184a4c11aaSdan     int rc;
13194a4c11aaSdan     if( p->pPreStmt==0 ){
13204a4c11aaSdan       rc = dbPrepareAndBind(p->pDb, p->zSql, &p->zSql, &p->pPreStmt);
13214a4c11aaSdan       if( rc!=TCL_OK ) return rc;
13224a4c11aaSdan     }else{
13234a4c11aaSdan       int rcs;
13244a4c11aaSdan       SqliteDb *pDb = p->pDb;
13254a4c11aaSdan       SqlPreparedStmt *pPreStmt = p->pPreStmt;
13264a4c11aaSdan       sqlite3_stmt *pStmt = pPreStmt->pStmt;
13274a4c11aaSdan 
13284a4c11aaSdan       rcs = sqlite3_step(pStmt);
13294a4c11aaSdan       if( rcs==SQLITE_ROW ){
13304a4c11aaSdan         return TCL_OK;
13314a4c11aaSdan       }
13324a4c11aaSdan       if( p->pArray ){
13334a4c11aaSdan         dbEvalRowInfo(p, 0, 0);
13344a4c11aaSdan       }
13354a4c11aaSdan       rcs = sqlite3_reset(pStmt);
13364a4c11aaSdan 
13374a4c11aaSdan       pDb->nStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_FULLSCAN_STEP,1);
13384a4c11aaSdan       pDb->nSort = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_SORT,1);
13394a4c11aaSdan       dbReleaseColumnNames(p);
13404a4c11aaSdan       p->pPreStmt = 0;
13414a4c11aaSdan 
13424a4c11aaSdan       if( rcs!=SQLITE_OK ){
13434a4c11aaSdan         /* If a run-time error occurs, report the error and stop reading
13444a4c11aaSdan         ** the SQL.  */
13454a4c11aaSdan         Tcl_SetObjResult(pDb->interp, dbTextToObj(sqlite3_errmsg(pDb->db)));
13464a4c11aaSdan         dbReleaseStmt(pDb, pPreStmt, 1);
13474a4c11aaSdan         return TCL_ERROR;
13484a4c11aaSdan       }else{
13494a4c11aaSdan         dbReleaseStmt(pDb, pPreStmt, 0);
13504a4c11aaSdan       }
13514a4c11aaSdan     }
13524a4c11aaSdan   }
13534a4c11aaSdan 
13544a4c11aaSdan   /* Finished */
13554a4c11aaSdan   return TCL_BREAK;
13564a4c11aaSdan }
13574a4c11aaSdan 
13584a4c11aaSdan /*
13594a4c11aaSdan ** Free all resources currently held by the DbEvalContext structure passed
13604a4c11aaSdan ** as the first argument. There should be exactly one call to this function
13614a4c11aaSdan ** for each call to dbEvalInit().
13624a4c11aaSdan */
13634a4c11aaSdan static void dbEvalFinalize(DbEvalContext *p){
13644a4c11aaSdan   if( p->pPreStmt ){
13654a4c11aaSdan     sqlite3_reset(p->pPreStmt->pStmt);
13664a4c11aaSdan     dbReleaseStmt(p->pDb, p->pPreStmt, 0);
13674a4c11aaSdan     p->pPreStmt = 0;
13684a4c11aaSdan   }
13694a4c11aaSdan   if( p->pArray ){
13704a4c11aaSdan     Tcl_DecrRefCount(p->pArray);
13714a4c11aaSdan     p->pArray = 0;
13724a4c11aaSdan   }
13734a4c11aaSdan   Tcl_DecrRefCount(p->pSql);
13744a4c11aaSdan   dbReleaseColumnNames(p);
13754a4c11aaSdan }
13764a4c11aaSdan 
13774a4c11aaSdan /*
13784a4c11aaSdan ** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains
13794a4c11aaSdan ** the value for the iCol'th column of the row currently pointed to by
13804a4c11aaSdan ** the DbEvalContext structure passed as the first argument.
13814a4c11aaSdan */
13824a4c11aaSdan static Tcl_Obj *dbEvalColumnValue(DbEvalContext *p, int iCol){
13834a4c11aaSdan   sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
13844a4c11aaSdan   switch( sqlite3_column_type(pStmt, iCol) ){
13854a4c11aaSdan     case SQLITE_BLOB: {
13864a4c11aaSdan       int bytes = sqlite3_column_bytes(pStmt, iCol);
13874a4c11aaSdan       const char *zBlob = sqlite3_column_blob(pStmt, iCol);
13884a4c11aaSdan       if( !zBlob ) bytes = 0;
13894a4c11aaSdan       return Tcl_NewByteArrayObj((u8*)zBlob, bytes);
13904a4c11aaSdan     }
13914a4c11aaSdan     case SQLITE_INTEGER: {
13924a4c11aaSdan       sqlite_int64 v = sqlite3_column_int64(pStmt, iCol);
13934a4c11aaSdan       if( v>=-2147483647 && v<=2147483647 ){
13944a4c11aaSdan         return Tcl_NewIntObj(v);
13954a4c11aaSdan       }else{
13964a4c11aaSdan         return Tcl_NewWideIntObj(v);
13974a4c11aaSdan       }
13984a4c11aaSdan     }
13994a4c11aaSdan     case SQLITE_FLOAT: {
14004a4c11aaSdan       return Tcl_NewDoubleObj(sqlite3_column_double(pStmt, iCol));
14014a4c11aaSdan     }
14024a4c11aaSdan     case SQLITE_NULL: {
14034a4c11aaSdan       return dbTextToObj(p->pDb->zNull);
14044a4c11aaSdan     }
14054a4c11aaSdan   }
14064a4c11aaSdan 
14074a4c11aaSdan   return dbTextToObj((char *)sqlite3_column_text(pStmt, iCol));
14084a4c11aaSdan }
14094a4c11aaSdan 
14104a4c11aaSdan /*
14114a4c11aaSdan ** If using Tcl version 8.6 or greater, use the NR functions to avoid
14124a4c11aaSdan ** recursive evalution of scripts by the [db eval] and [db trans]
14134a4c11aaSdan ** commands. Even if the headers used while compiling the extension
14144a4c11aaSdan ** are 8.6 or newer, the code still tests the Tcl version at runtime.
14154a4c11aaSdan ** This allows stubs-enabled builds to be used with older Tcl libraries.
14164a4c11aaSdan */
14174a4c11aaSdan #if TCL_MAJOR_VERSION>8 || (TCL_MAJOR_VERSION==8 && TCL_MINOR_VERSION>=6)
1418*a2c8a95bSdrh # define SQLITE_TCL_NRE 1
14194a4c11aaSdan static int DbUseNre(void){
14204a4c11aaSdan   int major, minor;
14214a4c11aaSdan   Tcl_GetVersion(&major, &minor, 0, 0);
14224a4c11aaSdan   return( (major==8 && minor>=6) || major>8 );
14234a4c11aaSdan }
14244a4c11aaSdan #else
14254a4c11aaSdan /*
14264a4c11aaSdan ** Compiling using headers earlier than 8.6. In this case NR cannot be
14274a4c11aaSdan ** used, so DbUseNre() to always return zero. Add #defines for the other
14284a4c11aaSdan ** Tcl_NRxxx() functions to prevent them from causing compilation errors,
14294a4c11aaSdan ** even though the only invocations of them are within conditional blocks
14304a4c11aaSdan ** of the form:
14314a4c11aaSdan **
14324a4c11aaSdan **   if( DbUseNre() ) { ... }
14334a4c11aaSdan */
1434*a2c8a95bSdrh # define SQLITE_TCL_NRE 0
14354a4c11aaSdan # define DbUseNre() 0
14364a4c11aaSdan # define Tcl_NRAddCallback(a,b,c,d,e,f) 0
14374a4c11aaSdan # define Tcl_NREvalObj(a,b,c) 0
14384a4c11aaSdan # define Tcl_NRCreateCommand(a,b,c,d,e,f) 0
14394a4c11aaSdan #endif
14404a4c11aaSdan 
14414a4c11aaSdan /*
14424a4c11aaSdan ** This function is part of the implementation of the command:
14434a4c11aaSdan **
14444a4c11aaSdan **   $db eval SQL ?ARRAYNAME? SCRIPT
14454a4c11aaSdan */
14464a4c11aaSdan static int DbEvalNextCmd(
14474a4c11aaSdan   ClientData data[],                   /* data[0] is the (DbEvalContext*) */
14484a4c11aaSdan   Tcl_Interp *interp,                  /* Tcl interpreter */
14494a4c11aaSdan   int result                           /* Result so far */
14504a4c11aaSdan ){
14514a4c11aaSdan   int rc = result;                     /* Return code */
14524a4c11aaSdan 
14534a4c11aaSdan   /* The first element of the data[] array is a pointer to a DbEvalContext
14544a4c11aaSdan   ** structure allocated using Tcl_Alloc(). The second element of data[]
14554a4c11aaSdan   ** is a pointer to a Tcl_Obj containing the script to run for each row
14564a4c11aaSdan   ** returned by the queries encapsulated in data[0]. */
14574a4c11aaSdan   DbEvalContext *p = (DbEvalContext *)data[0];
14584a4c11aaSdan   Tcl_Obj *pScript = (Tcl_Obj *)data[1];
14594a4c11aaSdan   Tcl_Obj *pArray = p->pArray;
14604a4c11aaSdan 
14614a4c11aaSdan   while( (rc==TCL_OK || rc==TCL_CONTINUE) && TCL_OK==(rc = dbEvalStep(p)) ){
14624a4c11aaSdan     int i;
14634a4c11aaSdan     int nCol;
14644a4c11aaSdan     Tcl_Obj **apColName;
14654a4c11aaSdan     dbEvalRowInfo(p, &nCol, &apColName);
14664a4c11aaSdan     for(i=0; i<nCol; i++){
14674a4c11aaSdan       Tcl_Obj *pVal = dbEvalColumnValue(p, i);
14684a4c11aaSdan       if( pArray==0 ){
14694a4c11aaSdan         Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
14704a4c11aaSdan       }else{
14714a4c11aaSdan         Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
14724a4c11aaSdan       }
14734a4c11aaSdan     }
14744a4c11aaSdan 
14754a4c11aaSdan     /* The required interpreter variables are now populated with the data
14764a4c11aaSdan     ** from the current row. If using NRE, schedule callbacks to evaluate
14774a4c11aaSdan     ** script pScript, then to invoke this function again to fetch the next
14784a4c11aaSdan     ** row (or clean up if there is no next row or the script throws an
14794a4c11aaSdan     ** exception). After scheduling the callbacks, return control to the
14804a4c11aaSdan     ** caller.
14814a4c11aaSdan     **
14824a4c11aaSdan     ** If not using NRE, evaluate pScript directly and continue with the
14834a4c11aaSdan     ** next iteration of this while(...) loop.  */
14844a4c11aaSdan     if( DbUseNre() ){
14854a4c11aaSdan       Tcl_NRAddCallback(interp, DbEvalNextCmd, (void*)p, (void*)pScript, 0, 0);
14864a4c11aaSdan       return Tcl_NREvalObj(interp, pScript, 0);
14874a4c11aaSdan     }else{
14884a4c11aaSdan       rc = Tcl_EvalObjEx(interp, pScript, 0);
14894a4c11aaSdan     }
14904a4c11aaSdan   }
14914a4c11aaSdan 
14924a4c11aaSdan   Tcl_DecrRefCount(pScript);
14934a4c11aaSdan   dbEvalFinalize(p);
14944a4c11aaSdan   Tcl_Free((char *)p);
14954a4c11aaSdan 
14964a4c11aaSdan   if( rc==TCL_OK || rc==TCL_BREAK ){
14974a4c11aaSdan     Tcl_ResetResult(interp);
14984a4c11aaSdan     rc = TCL_OK;
14994a4c11aaSdan   }
15004a4c11aaSdan   return rc;
15018e556520Sdanielk1977 }
15028e556520Sdanielk1977 
15031067fe11Stpoindex /*
150475897234Sdrh ** The "sqlite" command below creates a new Tcl command for each
150575897234Sdrh ** connection it opens to an SQLite database.  This routine is invoked
150675897234Sdrh ** whenever one of those connection-specific commands is executed
150775897234Sdrh ** in Tcl.  For example, if you run Tcl code like this:
150875897234Sdrh **
15099bb575fdSdrh **       sqlite3 db1  "my_database"
151075897234Sdrh **       db1 close
151175897234Sdrh **
151275897234Sdrh ** The first command opens a connection to the "my_database" database
151375897234Sdrh ** and calls that connection "db1".  The second command causes this
151475897234Sdrh ** subroutine to be invoked.
151575897234Sdrh */
15166d31316cSdrh static int DbObjCmd(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
1517bec3f402Sdrh   SqliteDb *pDb = (SqliteDb*)cd;
15186d31316cSdrh   int choice;
151922fbcb8dSdrh   int rc = TCL_OK;
15200de8c112Sdrh   static const char *DB_strs[] = {
1521dc2c4915Sdrh     "authorizer",         "backup",            "busy",
1522dc2c4915Sdrh     "cache",              "changes",           "close",
1523dc2c4915Sdrh     "collate",            "collation_needed",  "commit_hook",
1524dc2c4915Sdrh     "complete",           "copy",              "enable_load_extension",
1525dc2c4915Sdrh     "errorcode",          "eval",              "exists",
1526dc2c4915Sdrh     "function",           "incrblob",          "interrupt",
1527dc2c4915Sdrh     "last_insert_rowid",  "nullvalue",         "onecolumn",
1528dc2c4915Sdrh     "profile",            "progress",          "rekey",
1529dc2c4915Sdrh     "restore",            "rollback_hook",     "status",
1530dc2c4915Sdrh     "timeout",            "total_changes",     "trace",
1531404ca075Sdanielk1977     "transaction",        "unlock_notify",     "update_hook",
1532404ca075Sdanielk1977     "version",            0
15336d31316cSdrh   };
1534411995dcSdrh   enum DB_enum {
1535dc2c4915Sdrh     DB_AUTHORIZER,        DB_BACKUP,           DB_BUSY,
1536dc2c4915Sdrh     DB_CACHE,             DB_CHANGES,          DB_CLOSE,
1537dc2c4915Sdrh     DB_COLLATE,           DB_COLLATION_NEEDED, DB_COMMIT_HOOK,
1538dc2c4915Sdrh     DB_COMPLETE,          DB_COPY,             DB_ENABLE_LOAD_EXTENSION,
1539dc2c4915Sdrh     DB_ERRORCODE,         DB_EVAL,             DB_EXISTS,
1540dc2c4915Sdrh     DB_FUNCTION,          DB_INCRBLOB,         DB_INTERRUPT,
1541dc2c4915Sdrh     DB_LAST_INSERT_ROWID, DB_NULLVALUE,        DB_ONECOLUMN,
1542dc2c4915Sdrh     DB_PROFILE,           DB_PROGRESS,         DB_REKEY,
1543dc2c4915Sdrh     DB_RESTORE,           DB_ROLLBACK_HOOK,    DB_STATUS,
1544dc2c4915Sdrh     DB_TIMEOUT,           DB_TOTAL_CHANGES,    DB_TRACE,
1545404ca075Sdanielk1977     DB_TRANSACTION,       DB_UNLOCK_NOTIFY,    DB_UPDATE_HOOK,
1546404ca075Sdanielk1977     DB_VERSION,
15476d31316cSdrh   };
15481067fe11Stpoindex   /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
15496d31316cSdrh 
15506d31316cSdrh   if( objc<2 ){
15516d31316cSdrh     Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
155275897234Sdrh     return TCL_ERROR;
155375897234Sdrh   }
1554411995dcSdrh   if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
15556d31316cSdrh     return TCL_ERROR;
15566d31316cSdrh   }
15576d31316cSdrh 
1558411995dcSdrh   switch( (enum DB_enum)choice ){
155975897234Sdrh 
1560e22a334bSdrh   /*    $db authorizer ?CALLBACK?
1561e22a334bSdrh   **
1562e22a334bSdrh   ** Invoke the given callback to authorize each SQL operation as it is
1563e22a334bSdrh   ** compiled.  5 arguments are appended to the callback before it is
1564e22a334bSdrh   ** invoked:
1565e22a334bSdrh   **
1566e22a334bSdrh   **   (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
1567e22a334bSdrh   **   (2) First descriptive name (depends on authorization type)
1568e22a334bSdrh   **   (3) Second descriptive name
1569e22a334bSdrh   **   (4) Name of the database (ex: "main", "temp")
1570e22a334bSdrh   **   (5) Name of trigger that is doing the access
1571e22a334bSdrh   **
1572e22a334bSdrh   ** The callback should return on of the following strings: SQLITE_OK,
1573e22a334bSdrh   ** SQLITE_IGNORE, or SQLITE_DENY.  Any other return value is an error.
1574e22a334bSdrh   **
1575e22a334bSdrh   ** If this method is invoked with no arguments, the current authorization
1576e22a334bSdrh   ** callback string is returned.
1577e22a334bSdrh   */
1578e22a334bSdrh   case DB_AUTHORIZER: {
15791211de37Sdrh #ifdef SQLITE_OMIT_AUTHORIZATION
15801211de37Sdrh     Tcl_AppendResult(interp, "authorization not available in this build", 0);
15811211de37Sdrh     return TCL_ERROR;
15821211de37Sdrh #else
1583e22a334bSdrh     if( objc>3 ){
1584e22a334bSdrh       Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
15850f14e2ebSdrh       return TCL_ERROR;
1586e22a334bSdrh     }else if( objc==2 ){
1587b5a20d3cSdrh       if( pDb->zAuth ){
1588e22a334bSdrh         Tcl_AppendResult(interp, pDb->zAuth, 0);
1589e22a334bSdrh       }
1590e22a334bSdrh     }else{
1591e22a334bSdrh       char *zAuth;
1592e22a334bSdrh       int len;
1593e22a334bSdrh       if( pDb->zAuth ){
1594e22a334bSdrh         Tcl_Free(pDb->zAuth);
1595e22a334bSdrh       }
1596e22a334bSdrh       zAuth = Tcl_GetStringFromObj(objv[2], &len);
1597e22a334bSdrh       if( zAuth && len>0 ){
1598e22a334bSdrh         pDb->zAuth = Tcl_Alloc( len + 1 );
15995bb3eb9bSdrh         memcpy(pDb->zAuth, zAuth, len+1);
1600e22a334bSdrh       }else{
1601e22a334bSdrh         pDb->zAuth = 0;
1602e22a334bSdrh       }
1603e22a334bSdrh       if( pDb->zAuth ){
1604e22a334bSdrh         pDb->interp = interp;
16056f8a503dSdanielk1977         sqlite3_set_authorizer(pDb->db, auth_callback, pDb);
1606e22a334bSdrh       }else{
16076f8a503dSdanielk1977         sqlite3_set_authorizer(pDb->db, 0, 0);
1608e22a334bSdrh       }
1609e22a334bSdrh     }
16101211de37Sdrh #endif
1611e22a334bSdrh     break;
1612e22a334bSdrh   }
1613e22a334bSdrh 
1614dc2c4915Sdrh   /*    $db backup ?DATABASE? FILENAME
1615dc2c4915Sdrh   **
1616dc2c4915Sdrh   ** Open or create a database file named FILENAME.  Transfer the
1617dc2c4915Sdrh   ** content of local database DATABASE (default: "main") into the
1618dc2c4915Sdrh   ** FILENAME database.
1619dc2c4915Sdrh   */
1620dc2c4915Sdrh   case DB_BACKUP: {
1621dc2c4915Sdrh     const char *zDestFile;
1622dc2c4915Sdrh     const char *zSrcDb;
1623dc2c4915Sdrh     sqlite3 *pDest;
1624dc2c4915Sdrh     sqlite3_backup *pBackup;
1625dc2c4915Sdrh 
1626dc2c4915Sdrh     if( objc==3 ){
1627dc2c4915Sdrh       zSrcDb = "main";
1628dc2c4915Sdrh       zDestFile = Tcl_GetString(objv[2]);
1629dc2c4915Sdrh     }else if( objc==4 ){
1630dc2c4915Sdrh       zSrcDb = Tcl_GetString(objv[2]);
1631dc2c4915Sdrh       zDestFile = Tcl_GetString(objv[3]);
1632dc2c4915Sdrh     }else{
1633dc2c4915Sdrh       Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
1634dc2c4915Sdrh       return TCL_ERROR;
1635dc2c4915Sdrh     }
1636dc2c4915Sdrh     rc = sqlite3_open(zDestFile, &pDest);
1637dc2c4915Sdrh     if( rc!=SQLITE_OK ){
1638dc2c4915Sdrh       Tcl_AppendResult(interp, "cannot open target database: ",
1639dc2c4915Sdrh            sqlite3_errmsg(pDest), (char*)0);
1640dc2c4915Sdrh       sqlite3_close(pDest);
1641dc2c4915Sdrh       return TCL_ERROR;
1642dc2c4915Sdrh     }
1643dc2c4915Sdrh     pBackup = sqlite3_backup_init(pDest, "main", pDb->db, zSrcDb);
1644dc2c4915Sdrh     if( pBackup==0 ){
1645dc2c4915Sdrh       Tcl_AppendResult(interp, "backup failed: ",
1646dc2c4915Sdrh            sqlite3_errmsg(pDest), (char*)0);
1647dc2c4915Sdrh       sqlite3_close(pDest);
1648dc2c4915Sdrh       return TCL_ERROR;
1649dc2c4915Sdrh     }
1650dc2c4915Sdrh     while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
1651dc2c4915Sdrh     sqlite3_backup_finish(pBackup);
1652dc2c4915Sdrh     if( rc==SQLITE_DONE ){
1653dc2c4915Sdrh       rc = TCL_OK;
1654dc2c4915Sdrh     }else{
1655dc2c4915Sdrh       Tcl_AppendResult(interp, "backup failed: ",
1656dc2c4915Sdrh            sqlite3_errmsg(pDest), (char*)0);
1657dc2c4915Sdrh       rc = TCL_ERROR;
1658dc2c4915Sdrh     }
1659dc2c4915Sdrh     sqlite3_close(pDest);
1660dc2c4915Sdrh     break;
1661dc2c4915Sdrh   }
1662dc2c4915Sdrh 
1663bec3f402Sdrh   /*    $db busy ?CALLBACK?
1664bec3f402Sdrh   **
1665bec3f402Sdrh   ** Invoke the given callback if an SQL statement attempts to open
1666bec3f402Sdrh   ** a locked database file.
1667bec3f402Sdrh   */
16686d31316cSdrh   case DB_BUSY: {
16696d31316cSdrh     if( objc>3 ){
16706d31316cSdrh       Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
1671bec3f402Sdrh       return TCL_ERROR;
16726d31316cSdrh     }else if( objc==2 ){
1673bec3f402Sdrh       if( pDb->zBusy ){
1674bec3f402Sdrh         Tcl_AppendResult(interp, pDb->zBusy, 0);
1675bec3f402Sdrh       }
1676bec3f402Sdrh     }else{
16776d31316cSdrh       char *zBusy;
16786d31316cSdrh       int len;
1679bec3f402Sdrh       if( pDb->zBusy ){
1680bec3f402Sdrh         Tcl_Free(pDb->zBusy);
16816d31316cSdrh       }
16826d31316cSdrh       zBusy = Tcl_GetStringFromObj(objv[2], &len);
16836d31316cSdrh       if( zBusy && len>0 ){
16846d31316cSdrh         pDb->zBusy = Tcl_Alloc( len + 1 );
16855bb3eb9bSdrh         memcpy(pDb->zBusy, zBusy, len+1);
16866d31316cSdrh       }else{
1687bec3f402Sdrh         pDb->zBusy = 0;
1688bec3f402Sdrh       }
1689bec3f402Sdrh       if( pDb->zBusy ){
1690bec3f402Sdrh         pDb->interp = interp;
16916f8a503dSdanielk1977         sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
16926d31316cSdrh       }else{
16936f8a503dSdanielk1977         sqlite3_busy_handler(pDb->db, 0, 0);
1694bec3f402Sdrh       }
1695bec3f402Sdrh     }
16966d31316cSdrh     break;
16976d31316cSdrh   }
1698bec3f402Sdrh 
1699fb7e7651Sdrh   /*     $db cache flush
1700fb7e7651Sdrh   **     $db cache size n
1701fb7e7651Sdrh   **
1702fb7e7651Sdrh   ** Flush the prepared statement cache, or set the maximum number of
1703fb7e7651Sdrh   ** cached statements.
1704fb7e7651Sdrh   */
1705fb7e7651Sdrh   case DB_CACHE: {
1706fb7e7651Sdrh     char *subCmd;
1707fb7e7651Sdrh     int n;
1708fb7e7651Sdrh 
1709fb7e7651Sdrh     if( objc<=2 ){
1710fb7e7651Sdrh       Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
1711fb7e7651Sdrh       return TCL_ERROR;
1712fb7e7651Sdrh     }
1713fb7e7651Sdrh     subCmd = Tcl_GetStringFromObj( objv[2], 0 );
1714fb7e7651Sdrh     if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
1715fb7e7651Sdrh       if( objc!=3 ){
1716fb7e7651Sdrh         Tcl_WrongNumArgs(interp, 2, objv, "flush");
1717fb7e7651Sdrh         return TCL_ERROR;
1718fb7e7651Sdrh       }else{
1719fb7e7651Sdrh         flushStmtCache( pDb );
1720fb7e7651Sdrh       }
1721fb7e7651Sdrh     }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
1722fb7e7651Sdrh       if( objc!=4 ){
1723fb7e7651Sdrh         Tcl_WrongNumArgs(interp, 2, objv, "size n");
1724fb7e7651Sdrh         return TCL_ERROR;
1725fb7e7651Sdrh       }else{
1726fb7e7651Sdrh         if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
1727fb7e7651Sdrh           Tcl_AppendResult( interp, "cannot convert \"",
1728fb7e7651Sdrh                Tcl_GetStringFromObj(objv[3],0), "\" to integer", 0);
1729fb7e7651Sdrh           return TCL_ERROR;
1730fb7e7651Sdrh         }else{
1731fb7e7651Sdrh           if( n<0 ){
1732fb7e7651Sdrh             flushStmtCache( pDb );
1733fb7e7651Sdrh             n = 0;
1734fb7e7651Sdrh           }else if( n>MAX_PREPARED_STMTS ){
1735fb7e7651Sdrh             n = MAX_PREPARED_STMTS;
1736fb7e7651Sdrh           }
1737fb7e7651Sdrh           pDb->maxStmt = n;
1738fb7e7651Sdrh         }
1739fb7e7651Sdrh       }
1740fb7e7651Sdrh     }else{
1741fb7e7651Sdrh       Tcl_AppendResult( interp, "bad option \"",
1742191fadcfSdanielk1977           Tcl_GetStringFromObj(objv[2],0), "\": must be flush or size", 0);
1743fb7e7651Sdrh       return TCL_ERROR;
1744fb7e7651Sdrh     }
1745fb7e7651Sdrh     break;
1746fb7e7651Sdrh   }
1747fb7e7651Sdrh 
1748b28af71aSdanielk1977   /*     $db changes
1749c8d30ac1Sdrh   **
1750c8d30ac1Sdrh   ** Return the number of rows that were modified, inserted, or deleted by
1751b28af71aSdanielk1977   ** the most recent INSERT, UPDATE or DELETE statement, not including
1752b28af71aSdanielk1977   ** any changes made by trigger programs.
1753c8d30ac1Sdrh   */
1754c8d30ac1Sdrh   case DB_CHANGES: {
1755c8d30ac1Sdrh     Tcl_Obj *pResult;
1756c8d30ac1Sdrh     if( objc!=2 ){
1757c8d30ac1Sdrh       Tcl_WrongNumArgs(interp, 2, objv, "");
1758c8d30ac1Sdrh       return TCL_ERROR;
1759c8d30ac1Sdrh     }
1760c8d30ac1Sdrh     pResult = Tcl_GetObjResult(interp);
1761b28af71aSdanielk1977     Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
1762f146a776Srdc     break;
1763f146a776Srdc   }
1764f146a776Srdc 
176575897234Sdrh   /*    $db close
176675897234Sdrh   **
176775897234Sdrh   ** Shutdown the database
176875897234Sdrh   */
17696d31316cSdrh   case DB_CLOSE: {
17706d31316cSdrh     Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
17716d31316cSdrh     break;
17726d31316cSdrh   }
177375897234Sdrh 
17740f14e2ebSdrh   /*
17750f14e2ebSdrh   **     $db collate NAME SCRIPT
17760f14e2ebSdrh   **
17770f14e2ebSdrh   ** Create a new SQL collation function called NAME.  Whenever
17780f14e2ebSdrh   ** that function is called, invoke SCRIPT to evaluate the function.
17790f14e2ebSdrh   */
17800f14e2ebSdrh   case DB_COLLATE: {
17810f14e2ebSdrh     SqlCollate *pCollate;
17820f14e2ebSdrh     char *zName;
17830f14e2ebSdrh     char *zScript;
17840f14e2ebSdrh     int nScript;
17850f14e2ebSdrh     if( objc!=4 ){
17860f14e2ebSdrh       Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
17870f14e2ebSdrh       return TCL_ERROR;
17880f14e2ebSdrh     }
17890f14e2ebSdrh     zName = Tcl_GetStringFromObj(objv[2], 0);
17900f14e2ebSdrh     zScript = Tcl_GetStringFromObj(objv[3], &nScript);
17910f14e2ebSdrh     pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
17920f14e2ebSdrh     if( pCollate==0 ) return TCL_ERROR;
17930f14e2ebSdrh     pCollate->interp = interp;
17940f14e2ebSdrh     pCollate->pNext = pDb->pCollate;
17950f14e2ebSdrh     pCollate->zScript = (char*)&pCollate[1];
17960f14e2ebSdrh     pDb->pCollate = pCollate;
17975bb3eb9bSdrh     memcpy(pCollate->zScript, zScript, nScript+1);
17980f14e2ebSdrh     if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
17990f14e2ebSdrh         pCollate, tclSqlCollate) ){
18009636c4e1Sdanielk1977       Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
18010f14e2ebSdrh       return TCL_ERROR;
18020f14e2ebSdrh     }
18030f14e2ebSdrh     break;
18040f14e2ebSdrh   }
18050f14e2ebSdrh 
18060f14e2ebSdrh   /*
18070f14e2ebSdrh   **     $db collation_needed SCRIPT
18080f14e2ebSdrh   **
18090f14e2ebSdrh   ** Create a new SQL collation function called NAME.  Whenever
18100f14e2ebSdrh   ** that function is called, invoke SCRIPT to evaluate the function.
18110f14e2ebSdrh   */
18120f14e2ebSdrh   case DB_COLLATION_NEEDED: {
18130f14e2ebSdrh     if( objc!=3 ){
18140f14e2ebSdrh       Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
18150f14e2ebSdrh       return TCL_ERROR;
18160f14e2ebSdrh     }
18170f14e2ebSdrh     if( pDb->pCollateNeeded ){
18180f14e2ebSdrh       Tcl_DecrRefCount(pDb->pCollateNeeded);
18190f14e2ebSdrh     }
18200f14e2ebSdrh     pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
18210f14e2ebSdrh     Tcl_IncrRefCount(pDb->pCollateNeeded);
18220f14e2ebSdrh     sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
18230f14e2ebSdrh     break;
18240f14e2ebSdrh   }
18250f14e2ebSdrh 
182619e2d37fSdrh   /*    $db commit_hook ?CALLBACK?
182719e2d37fSdrh   **
182819e2d37fSdrh   ** Invoke the given callback just before committing every SQL transaction.
182919e2d37fSdrh   ** If the callback throws an exception or returns non-zero, then the
183019e2d37fSdrh   ** transaction is aborted.  If CALLBACK is an empty string, the callback
183119e2d37fSdrh   ** is disabled.
183219e2d37fSdrh   */
183319e2d37fSdrh   case DB_COMMIT_HOOK: {
183419e2d37fSdrh     if( objc>3 ){
183519e2d37fSdrh       Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
183619e2d37fSdrh       return TCL_ERROR;
183719e2d37fSdrh     }else if( objc==2 ){
183819e2d37fSdrh       if( pDb->zCommit ){
183919e2d37fSdrh         Tcl_AppendResult(interp, pDb->zCommit, 0);
184019e2d37fSdrh       }
184119e2d37fSdrh     }else{
184219e2d37fSdrh       char *zCommit;
184319e2d37fSdrh       int len;
184419e2d37fSdrh       if( pDb->zCommit ){
184519e2d37fSdrh         Tcl_Free(pDb->zCommit);
184619e2d37fSdrh       }
184719e2d37fSdrh       zCommit = Tcl_GetStringFromObj(objv[2], &len);
184819e2d37fSdrh       if( zCommit && len>0 ){
184919e2d37fSdrh         pDb->zCommit = Tcl_Alloc( len + 1 );
18505bb3eb9bSdrh         memcpy(pDb->zCommit, zCommit, len+1);
185119e2d37fSdrh       }else{
185219e2d37fSdrh         pDb->zCommit = 0;
185319e2d37fSdrh       }
185419e2d37fSdrh       if( pDb->zCommit ){
185519e2d37fSdrh         pDb->interp = interp;
185619e2d37fSdrh         sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
185719e2d37fSdrh       }else{
185819e2d37fSdrh         sqlite3_commit_hook(pDb->db, 0, 0);
185919e2d37fSdrh       }
186019e2d37fSdrh     }
186119e2d37fSdrh     break;
186219e2d37fSdrh   }
186319e2d37fSdrh 
186475897234Sdrh   /*    $db complete SQL
186575897234Sdrh   **
186675897234Sdrh   ** Return TRUE if SQL is a complete SQL statement.  Return FALSE if
186775897234Sdrh   ** additional lines of input are needed.  This is similar to the
186875897234Sdrh   ** built-in "info complete" command of Tcl.
186975897234Sdrh   */
18706d31316cSdrh   case DB_COMPLETE: {
1871ccae6026Sdrh #ifndef SQLITE_OMIT_COMPLETE
18726d31316cSdrh     Tcl_Obj *pResult;
18736d31316cSdrh     int isComplete;
18746d31316cSdrh     if( objc!=3 ){
18756d31316cSdrh       Tcl_WrongNumArgs(interp, 2, objv, "SQL");
187675897234Sdrh       return TCL_ERROR;
187775897234Sdrh     }
18786f8a503dSdanielk1977     isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
18796d31316cSdrh     pResult = Tcl_GetObjResult(interp);
18806d31316cSdrh     Tcl_SetBooleanObj(pResult, isComplete);
1881ccae6026Sdrh #endif
18826d31316cSdrh     break;
18836d31316cSdrh   }
188475897234Sdrh 
188519e2d37fSdrh   /*    $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
188619e2d37fSdrh   **
188719e2d37fSdrh   ** Copy data into table from filename, optionally using SEPARATOR
188819e2d37fSdrh   ** as column separators.  If a column contains a null string, or the
188919e2d37fSdrh   ** value of NULLINDICATOR, a NULL is inserted for the column.
189019e2d37fSdrh   ** conflict-algorithm is one of the sqlite conflict algorithms:
189119e2d37fSdrh   **    rollback, abort, fail, ignore, replace
189219e2d37fSdrh   ** On success, return the number of lines processed, not necessarily same
189319e2d37fSdrh   ** as 'db changes' due to conflict-algorithm selected.
189419e2d37fSdrh   **
189519e2d37fSdrh   ** This code is basically an implementation/enhancement of
189619e2d37fSdrh   ** the sqlite3 shell.c ".import" command.
189719e2d37fSdrh   **
189819e2d37fSdrh   ** This command usage is equivalent to the sqlite2.x COPY statement,
189919e2d37fSdrh   ** which imports file data into a table using the PostgreSQL COPY file format:
190019e2d37fSdrh   **   $db copy $conflit_algo $table_name $filename \t \\N
190119e2d37fSdrh   */
190219e2d37fSdrh   case DB_COPY: {
190319e2d37fSdrh     char *zTable;               /* Insert data into this table */
190419e2d37fSdrh     char *zFile;                /* The file from which to extract data */
190519e2d37fSdrh     char *zConflict;            /* The conflict algorithm to use */
190619e2d37fSdrh     sqlite3_stmt *pStmt;        /* A statement */
190719e2d37fSdrh     int nCol;                   /* Number of columns in the table */
190819e2d37fSdrh     int nByte;                  /* Number of bytes in an SQL string */
190919e2d37fSdrh     int i, j;                   /* Loop counters */
191019e2d37fSdrh     int nSep;                   /* Number of bytes in zSep[] */
191119e2d37fSdrh     int nNull;                  /* Number of bytes in zNull[] */
191219e2d37fSdrh     char *zSql;                 /* An SQL statement */
191319e2d37fSdrh     char *zLine;                /* A single line of input from the file */
191419e2d37fSdrh     char **azCol;               /* zLine[] broken up into columns */
191519e2d37fSdrh     char *zCommit;              /* How to commit changes */
191619e2d37fSdrh     FILE *in;                   /* The input file */
191719e2d37fSdrh     int lineno = 0;             /* Line number of input file */
191819e2d37fSdrh     char zLineNum[80];          /* Line number print buffer */
191919e2d37fSdrh     Tcl_Obj *pResult;           /* interp result */
192019e2d37fSdrh 
192119e2d37fSdrh     char *zSep;
192219e2d37fSdrh     char *zNull;
192319e2d37fSdrh     if( objc<5 || objc>7 ){
192419e2d37fSdrh       Tcl_WrongNumArgs(interp, 2, objv,
192519e2d37fSdrh          "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
192619e2d37fSdrh       return TCL_ERROR;
192719e2d37fSdrh     }
192819e2d37fSdrh     if( objc>=6 ){
192919e2d37fSdrh       zSep = Tcl_GetStringFromObj(objv[5], 0);
193019e2d37fSdrh     }else{
193119e2d37fSdrh       zSep = "\t";
193219e2d37fSdrh     }
193319e2d37fSdrh     if( objc>=7 ){
193419e2d37fSdrh       zNull = Tcl_GetStringFromObj(objv[6], 0);
193519e2d37fSdrh     }else{
193619e2d37fSdrh       zNull = "";
193719e2d37fSdrh     }
193819e2d37fSdrh     zConflict = Tcl_GetStringFromObj(objv[2], 0);
193919e2d37fSdrh     zTable = Tcl_GetStringFromObj(objv[3], 0);
194019e2d37fSdrh     zFile = Tcl_GetStringFromObj(objv[4], 0);
19414f21c4afSdrh     nSep = strlen30(zSep);
19424f21c4afSdrh     nNull = strlen30(zNull);
194319e2d37fSdrh     if( nSep==0 ){
194419e2d37fSdrh       Tcl_AppendResult(interp,"Error: non-null separator required for copy",0);
194519e2d37fSdrh       return TCL_ERROR;
194619e2d37fSdrh     }
19473e59c012Sdrh     if(strcmp(zConflict, "rollback") != 0 &&
19483e59c012Sdrh        strcmp(zConflict, "abort"   ) != 0 &&
19493e59c012Sdrh        strcmp(zConflict, "fail"    ) != 0 &&
19503e59c012Sdrh        strcmp(zConflict, "ignore"  ) != 0 &&
19513e59c012Sdrh        strcmp(zConflict, "replace" ) != 0 ) {
195219e2d37fSdrh       Tcl_AppendResult(interp, "Error: \"", zConflict,
195319e2d37fSdrh             "\", conflict-algorithm must be one of: rollback, "
195419e2d37fSdrh             "abort, fail, ignore, or replace", 0);
195519e2d37fSdrh       return TCL_ERROR;
195619e2d37fSdrh     }
195719e2d37fSdrh     zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
195819e2d37fSdrh     if( zSql==0 ){
195919e2d37fSdrh       Tcl_AppendResult(interp, "Error: no such table: ", zTable, 0);
196019e2d37fSdrh       return TCL_ERROR;
196119e2d37fSdrh     }
19624f21c4afSdrh     nByte = strlen30(zSql);
19633e701a18Sdrh     rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
196419e2d37fSdrh     sqlite3_free(zSql);
196519e2d37fSdrh     if( rc ){
196619e2d37fSdrh       Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
196719e2d37fSdrh       nCol = 0;
196819e2d37fSdrh     }else{
196919e2d37fSdrh       nCol = sqlite3_column_count(pStmt);
197019e2d37fSdrh     }
197119e2d37fSdrh     sqlite3_finalize(pStmt);
197219e2d37fSdrh     if( nCol==0 ) {
197319e2d37fSdrh       return TCL_ERROR;
197419e2d37fSdrh     }
197519e2d37fSdrh     zSql = malloc( nByte + 50 + nCol*2 );
197619e2d37fSdrh     if( zSql==0 ) {
197719e2d37fSdrh       Tcl_AppendResult(interp, "Error: can't malloc()", 0);
197819e2d37fSdrh       return TCL_ERROR;
197919e2d37fSdrh     }
198019e2d37fSdrh     sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
198119e2d37fSdrh          zConflict, zTable);
19824f21c4afSdrh     j = strlen30(zSql);
198319e2d37fSdrh     for(i=1; i<nCol; i++){
198419e2d37fSdrh       zSql[j++] = ',';
198519e2d37fSdrh       zSql[j++] = '?';
198619e2d37fSdrh     }
198719e2d37fSdrh     zSql[j++] = ')';
198819e2d37fSdrh     zSql[j] = 0;
19893e701a18Sdrh     rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
199019e2d37fSdrh     free(zSql);
199119e2d37fSdrh     if( rc ){
199219e2d37fSdrh       Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0);
199319e2d37fSdrh       sqlite3_finalize(pStmt);
199419e2d37fSdrh       return TCL_ERROR;
199519e2d37fSdrh     }
199619e2d37fSdrh     in = fopen(zFile, "rb");
199719e2d37fSdrh     if( in==0 ){
199819e2d37fSdrh       Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL);
199919e2d37fSdrh       sqlite3_finalize(pStmt);
200019e2d37fSdrh       return TCL_ERROR;
200119e2d37fSdrh     }
200219e2d37fSdrh     azCol = malloc( sizeof(azCol[0])*(nCol+1) );
200319e2d37fSdrh     if( azCol==0 ) {
200419e2d37fSdrh       Tcl_AppendResult(interp, "Error: can't malloc()", 0);
200543617e9aSdrh       fclose(in);
200619e2d37fSdrh       return TCL_ERROR;
200719e2d37fSdrh     }
20083752785fSdrh     (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
200919e2d37fSdrh     zCommit = "COMMIT";
201019e2d37fSdrh     while( (zLine = local_getline(0, in))!=0 ){
201119e2d37fSdrh       char *z;
201219e2d37fSdrh       i = 0;
201319e2d37fSdrh       lineno++;
201419e2d37fSdrh       azCol[0] = zLine;
201519e2d37fSdrh       for(i=0, z=zLine; *z; z++){
201619e2d37fSdrh         if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
201719e2d37fSdrh           *z = 0;
201819e2d37fSdrh           i++;
201919e2d37fSdrh           if( i<nCol ){
202019e2d37fSdrh             azCol[i] = &z[nSep];
202119e2d37fSdrh             z += nSep-1;
202219e2d37fSdrh           }
202319e2d37fSdrh         }
202419e2d37fSdrh       }
202519e2d37fSdrh       if( i+1!=nCol ){
202619e2d37fSdrh         char *zErr;
20274f21c4afSdrh         int nErr = strlen30(zFile) + 200;
20285bb3eb9bSdrh         zErr = malloc(nErr);
2029c1f4494eSdrh         if( zErr ){
20305bb3eb9bSdrh           sqlite3_snprintf(nErr, zErr,
2031955de52cSdanielk1977              "Error: %s line %d: expected %d columns of data but found %d",
203219e2d37fSdrh              zFile, lineno, nCol, i+1);
203319e2d37fSdrh           Tcl_AppendResult(interp, zErr, 0);
203419e2d37fSdrh           free(zErr);
2035c1f4494eSdrh         }
203619e2d37fSdrh         zCommit = "ROLLBACK";
203719e2d37fSdrh         break;
203819e2d37fSdrh       }
203919e2d37fSdrh       for(i=0; i<nCol; i++){
204019e2d37fSdrh         /* check for null data, if so, bind as null */
2041ea678832Sdrh         if( (nNull>0 && strcmp(azCol[i], zNull)==0)
20424f21c4afSdrh           || strlen30(azCol[i])==0
2043ea678832Sdrh         ){
204419e2d37fSdrh           sqlite3_bind_null(pStmt, i+1);
204519e2d37fSdrh         }else{
204619e2d37fSdrh           sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
204719e2d37fSdrh         }
204819e2d37fSdrh       }
204919e2d37fSdrh       sqlite3_step(pStmt);
205019e2d37fSdrh       rc = sqlite3_reset(pStmt);
205119e2d37fSdrh       free(zLine);
205219e2d37fSdrh       if( rc!=SQLITE_OK ){
205319e2d37fSdrh         Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), 0);
205419e2d37fSdrh         zCommit = "ROLLBACK";
205519e2d37fSdrh         break;
205619e2d37fSdrh       }
205719e2d37fSdrh     }
205819e2d37fSdrh     free(azCol);
205919e2d37fSdrh     fclose(in);
206019e2d37fSdrh     sqlite3_finalize(pStmt);
20613752785fSdrh     (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
206219e2d37fSdrh 
206319e2d37fSdrh     if( zCommit[0] == 'C' ){
206419e2d37fSdrh       /* success, set result as number of lines processed */
206519e2d37fSdrh       pResult = Tcl_GetObjResult(interp);
206619e2d37fSdrh       Tcl_SetIntObj(pResult, lineno);
206719e2d37fSdrh       rc = TCL_OK;
206819e2d37fSdrh     }else{
206919e2d37fSdrh       /* failure, append lineno where failed */
20705bb3eb9bSdrh       sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
207119e2d37fSdrh       Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,0);
207219e2d37fSdrh       rc = TCL_ERROR;
207319e2d37fSdrh     }
207419e2d37fSdrh     break;
207519e2d37fSdrh   }
207619e2d37fSdrh 
207775897234Sdrh   /*
20784144905bSdrh   **    $db enable_load_extension BOOLEAN
20794144905bSdrh   **
20804144905bSdrh   ** Turn the extension loading feature on or off.  It if off by
20814144905bSdrh   ** default.
20824144905bSdrh   */
20834144905bSdrh   case DB_ENABLE_LOAD_EXTENSION: {
2084f533acc0Sdrh #ifndef SQLITE_OMIT_LOAD_EXTENSION
20854144905bSdrh     int onoff;
20864144905bSdrh     if( objc!=3 ){
20874144905bSdrh       Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
20884144905bSdrh       return TCL_ERROR;
20894144905bSdrh     }
20904144905bSdrh     if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
20914144905bSdrh       return TCL_ERROR;
20924144905bSdrh     }
20934144905bSdrh     sqlite3_enable_load_extension(pDb->db, onoff);
20944144905bSdrh     break;
2095f533acc0Sdrh #else
2096f533acc0Sdrh     Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
2097f533acc0Sdrh                      0);
2098f533acc0Sdrh     return TCL_ERROR;
2099f533acc0Sdrh #endif
21004144905bSdrh   }
21014144905bSdrh 
21024144905bSdrh   /*
2103dcd997eaSdrh   **    $db errorcode
2104dcd997eaSdrh   **
2105dcd997eaSdrh   ** Return the numeric error code that was returned by the most recent
21066f8a503dSdanielk1977   ** call to sqlite3_exec().
2107dcd997eaSdrh   */
2108dcd997eaSdrh   case DB_ERRORCODE: {
2109f3ce83f5Sdanielk1977     Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
2110dcd997eaSdrh     break;
2111dcd997eaSdrh   }
2112dcd997eaSdrh 
2113dcd997eaSdrh   /*
21144a4c11aaSdan   **    $db exists $sql
21151807ce37Sdrh   **    $db onecolumn $sql
211675897234Sdrh   **
21174a4c11aaSdan   ** The onecolumn method is the equivalent of:
21184a4c11aaSdan   **     lindex [$db eval $sql] 0
21194a4c11aaSdan   */
21204a4c11aaSdan   case DB_EXISTS:
21214a4c11aaSdan   case DB_ONECOLUMN: {
21224a4c11aaSdan     DbEvalContext sEval;
21234a4c11aaSdan     if( objc!=3 ){
21244a4c11aaSdan       Tcl_WrongNumArgs(interp, 2, objv, "SQL");
21254a4c11aaSdan       return TCL_ERROR;
21264a4c11aaSdan     }
21274a4c11aaSdan 
21284a4c11aaSdan     dbEvalInit(&sEval, pDb, objv[2], 0);
21294a4c11aaSdan     rc = dbEvalStep(&sEval);
21304a4c11aaSdan     if( choice==DB_ONECOLUMN ){
21314a4c11aaSdan       if( rc==TCL_OK ){
21324a4c11aaSdan         Tcl_SetObjResult(interp, dbEvalColumnValue(&sEval, 0));
21334a4c11aaSdan       }
21344a4c11aaSdan     }else if( rc==TCL_BREAK || rc==TCL_OK ){
21354a4c11aaSdan       Tcl_SetObjResult(interp, Tcl_NewBooleanObj(rc==TCL_OK));
21364a4c11aaSdan     }
21374a4c11aaSdan     dbEvalFinalize(&sEval);
21384a4c11aaSdan 
21394a4c11aaSdan     if( rc==TCL_BREAK ){
21404a4c11aaSdan       rc = TCL_OK;
21414a4c11aaSdan     }
21424a4c11aaSdan     break;
21434a4c11aaSdan   }
21444a4c11aaSdan 
21454a4c11aaSdan   /*
21464a4c11aaSdan   **    $db eval $sql ?array? ?{  ...code... }?
21474a4c11aaSdan   **
214875897234Sdrh   ** The SQL statement in $sql is evaluated.  For each row, the values are
2149bec3f402Sdrh   ** placed in elements of the array named "array" and ...code... is executed.
215075897234Sdrh   ** If "array" and "code" are omitted, then no callback is every invoked.
215175897234Sdrh   ** If "array" is an empty string, then the values are placed in variables
215275897234Sdrh   ** that have the same name as the fields extracted by the query.
215375897234Sdrh   */
21544a4c11aaSdan   case DB_EVAL: {
215592febd92Sdrh     if( objc<3 || objc>5 ){
2156895d7472Sdrh       Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
215730ccda10Sdanielk1977       return TCL_ERROR;
215830ccda10Sdanielk1977     }
21594a4c11aaSdan 
216092febd92Sdrh     if( objc==3 ){
21614a4c11aaSdan       DbEvalContext sEval;
21624a4c11aaSdan       Tcl_Obj *pRet = Tcl_NewObj();
21634a4c11aaSdan       Tcl_IncrRefCount(pRet);
21644a4c11aaSdan       dbEvalInit(&sEval, pDb, objv[2], 0);
21654a4c11aaSdan       while( TCL_OK==(rc = dbEvalStep(&sEval)) ){
21664a4c11aaSdan         int i;
21674a4c11aaSdan         int nCol;
21684a4c11aaSdan         dbEvalRowInfo(&sEval, &nCol, 0);
216992febd92Sdrh         for(i=0; i<nCol; i++){
21704a4c11aaSdan           Tcl_ListObjAppendElement(interp, pRet, dbEvalColumnValue(&sEval, i));
217192febd92Sdrh         }
217230ccda10Sdanielk1977       }
21734a4c11aaSdan       dbEvalFinalize(&sEval);
217490b6bb19Sdrh       if( rc==TCL_BREAK ){
21754a4c11aaSdan         Tcl_SetObjResult(interp, pRet);
217690b6bb19Sdrh         rc = TCL_OK;
217790b6bb19Sdrh       }
2178ef2cb63eSdanielk1977       Tcl_DecrRefCount(pRet);
21794a4c11aaSdan     }else{
21804a4c11aaSdan       ClientData cd[2];
21814a4c11aaSdan       DbEvalContext *p;
21824a4c11aaSdan       Tcl_Obj *pArray = 0;
21834a4c11aaSdan       Tcl_Obj *pScript;
21844a4c11aaSdan 
21854a4c11aaSdan       if( objc==5 && *(char *)Tcl_GetString(objv[3]) ){
21864a4c11aaSdan         pArray = objv[3];
21874a4c11aaSdan       }
21884a4c11aaSdan       pScript = objv[objc-1];
21894a4c11aaSdan       Tcl_IncrRefCount(pScript);
21904a4c11aaSdan 
21914a4c11aaSdan       p = (DbEvalContext *)Tcl_Alloc(sizeof(DbEvalContext));
21924a4c11aaSdan       dbEvalInit(p, pDb, objv[2], pArray);
21934a4c11aaSdan 
21944a4c11aaSdan       cd[0] = (void *)p;
21954a4c11aaSdan       cd[1] = (void *)pScript;
21964a4c11aaSdan       rc = DbEvalNextCmd(cd, interp, TCL_OK);
21971807ce37Sdrh     }
219830ccda10Sdanielk1977     break;
219930ccda10Sdanielk1977   }
2200bec3f402Sdrh 
2201bec3f402Sdrh   /*
2202e3602be8Sdrh   **     $db function NAME [-argcount N] SCRIPT
2203cabb0819Sdrh   **
2204cabb0819Sdrh   ** Create a new SQL function called NAME.  Whenever that function is
2205cabb0819Sdrh   ** called, invoke SCRIPT to evaluate the function.
2206cabb0819Sdrh   */
2207cabb0819Sdrh   case DB_FUNCTION: {
2208cabb0819Sdrh     SqlFunc *pFunc;
2209d1e4733dSdrh     Tcl_Obj *pScript;
2210cabb0819Sdrh     char *zName;
2211e3602be8Sdrh     int nArg = -1;
2212e3602be8Sdrh     if( objc==6 ){
2213e3602be8Sdrh       const char *z = Tcl_GetString(objv[3]);
22144f21c4afSdrh       int n = strlen30(z);
2215e3602be8Sdrh       if( n>2 && strncmp(z, "-argcount",n)==0 ){
2216e3602be8Sdrh         if( Tcl_GetIntFromObj(interp, objv[4], &nArg) ) return TCL_ERROR;
2217e3602be8Sdrh         if( nArg<0 ){
2218e3602be8Sdrh           Tcl_AppendResult(interp, "number of arguments must be non-negative",
2219e3602be8Sdrh                            (char*)0);
2220cabb0819Sdrh           return TCL_ERROR;
2221cabb0819Sdrh         }
2222e3602be8Sdrh       }
2223e3602be8Sdrh       pScript = objv[5];
2224e3602be8Sdrh     }else if( objc!=4 ){
2225e3602be8Sdrh       Tcl_WrongNumArgs(interp, 2, objv, "NAME [-argcount N] SCRIPT");
2226e3602be8Sdrh       return TCL_ERROR;
2227e3602be8Sdrh     }else{
2228d1e4733dSdrh       pScript = objv[3];
2229e3602be8Sdrh     }
2230e3602be8Sdrh     zName = Tcl_GetStringFromObj(objv[2], 0);
2231d1e4733dSdrh     pFunc = findSqlFunc(pDb, zName);
2232cabb0819Sdrh     if( pFunc==0 ) return TCL_ERROR;
2233d1e4733dSdrh     if( pFunc->pScript ){
2234d1e4733dSdrh       Tcl_DecrRefCount(pFunc->pScript);
2235d1e4733dSdrh     }
2236d1e4733dSdrh     pFunc->pScript = pScript;
2237d1e4733dSdrh     Tcl_IncrRefCount(pScript);
2238d1e4733dSdrh     pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
2239e3602be8Sdrh     rc = sqlite3_create_function(pDb->db, zName, nArg, SQLITE_UTF8,
2240d8123366Sdanielk1977         pFunc, tclSqlFunc, 0, 0);
2241fb7e7651Sdrh     if( rc!=SQLITE_OK ){
2242fb7e7651Sdrh       rc = TCL_ERROR;
22439636c4e1Sdanielk1977       Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
2244fb7e7651Sdrh     }
2245cabb0819Sdrh     break;
2246cabb0819Sdrh   }
2247cabb0819Sdrh 
2248cabb0819Sdrh   /*
22498cbadb02Sdanielk1977   **     $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
2250b4e9af9fSdanielk1977   */
2251b4e9af9fSdanielk1977   case DB_INCRBLOB: {
225232a0d8bbSdanielk1977 #ifdef SQLITE_OMIT_INCRBLOB
225332a0d8bbSdanielk1977     Tcl_AppendResult(interp, "incrblob not available in this build", 0);
225432a0d8bbSdanielk1977     return TCL_ERROR;
225532a0d8bbSdanielk1977 #else
22568cbadb02Sdanielk1977     int isReadonly = 0;
2257b4e9af9fSdanielk1977     const char *zDb = "main";
2258b4e9af9fSdanielk1977     const char *zTable;
2259b4e9af9fSdanielk1977     const char *zColumn;
2260b4e9af9fSdanielk1977     sqlite_int64 iRow;
2261b4e9af9fSdanielk1977 
22628cbadb02Sdanielk1977     /* Check for the -readonly option */
22638cbadb02Sdanielk1977     if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
22648cbadb02Sdanielk1977       isReadonly = 1;
22658cbadb02Sdanielk1977     }
22668cbadb02Sdanielk1977 
22678cbadb02Sdanielk1977     if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
22688cbadb02Sdanielk1977       Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
2269b4e9af9fSdanielk1977       return TCL_ERROR;
2270b4e9af9fSdanielk1977     }
2271b4e9af9fSdanielk1977 
22728cbadb02Sdanielk1977     if( objc==(6+isReadonly) ){
2273b4e9af9fSdanielk1977       zDb = Tcl_GetString(objv[2]);
2274b4e9af9fSdanielk1977     }
2275b4e9af9fSdanielk1977     zTable = Tcl_GetString(objv[objc-3]);
2276b4e9af9fSdanielk1977     zColumn = Tcl_GetString(objv[objc-2]);
2277b4e9af9fSdanielk1977     rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
2278b4e9af9fSdanielk1977 
2279b4e9af9fSdanielk1977     if( rc==TCL_OK ){
22808cbadb02Sdanielk1977       rc = createIncrblobChannel(
22818cbadb02Sdanielk1977           interp, pDb, zDb, zTable, zColumn, iRow, isReadonly
22828cbadb02Sdanielk1977       );
2283b4e9af9fSdanielk1977     }
228432a0d8bbSdanielk1977 #endif
2285b4e9af9fSdanielk1977     break;
2286b4e9af9fSdanielk1977   }
2287b4e9af9fSdanielk1977 
2288b4e9af9fSdanielk1977   /*
2289f11bded5Sdrh   **     $db interrupt
2290f11bded5Sdrh   **
2291f11bded5Sdrh   ** Interrupt the execution of the inner-most SQL interpreter.  This
2292f11bded5Sdrh   ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
2293f11bded5Sdrh   */
2294f11bded5Sdrh   case DB_INTERRUPT: {
2295f11bded5Sdrh     sqlite3_interrupt(pDb->db);
2296f11bded5Sdrh     break;
2297f11bded5Sdrh   }
2298f11bded5Sdrh 
2299f11bded5Sdrh   /*
230019e2d37fSdrh   **     $db nullvalue ?STRING?
230119e2d37fSdrh   **
230219e2d37fSdrh   ** Change text used when a NULL comes back from the database. If ?STRING?
230319e2d37fSdrh   ** is not present, then the current string used for NULL is returned.
230419e2d37fSdrh   ** If STRING is present, then STRING is returned.
230519e2d37fSdrh   **
230619e2d37fSdrh   */
230719e2d37fSdrh   case DB_NULLVALUE: {
230819e2d37fSdrh     if( objc!=2 && objc!=3 ){
230919e2d37fSdrh       Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
231019e2d37fSdrh       return TCL_ERROR;
231119e2d37fSdrh     }
231219e2d37fSdrh     if( objc==3 ){
231319e2d37fSdrh       int len;
231419e2d37fSdrh       char *zNull = Tcl_GetStringFromObj(objv[2], &len);
231519e2d37fSdrh       if( pDb->zNull ){
231619e2d37fSdrh         Tcl_Free(pDb->zNull);
231719e2d37fSdrh       }
231819e2d37fSdrh       if( zNull && len>0 ){
231919e2d37fSdrh         pDb->zNull = Tcl_Alloc( len + 1 );
232019e2d37fSdrh         strncpy(pDb->zNull, zNull, len);
232119e2d37fSdrh         pDb->zNull[len] = '\0';
232219e2d37fSdrh       }else{
232319e2d37fSdrh         pDb->zNull = 0;
232419e2d37fSdrh       }
232519e2d37fSdrh     }
232619e2d37fSdrh     Tcl_SetObjResult(interp, dbTextToObj(pDb->zNull));
232719e2d37fSdrh     break;
232819e2d37fSdrh   }
232919e2d37fSdrh 
233019e2d37fSdrh   /*
2331af9ff33aSdrh   **     $db last_insert_rowid
2332af9ff33aSdrh   **
2333af9ff33aSdrh   ** Return an integer which is the ROWID for the most recent insert.
2334af9ff33aSdrh   */
2335af9ff33aSdrh   case DB_LAST_INSERT_ROWID: {
2336af9ff33aSdrh     Tcl_Obj *pResult;
2337f7e678d6Sdrh     Tcl_WideInt rowid;
2338af9ff33aSdrh     if( objc!=2 ){
2339af9ff33aSdrh       Tcl_WrongNumArgs(interp, 2, objv, "");
2340af9ff33aSdrh       return TCL_ERROR;
2341af9ff33aSdrh     }
23426f8a503dSdanielk1977     rowid = sqlite3_last_insert_rowid(pDb->db);
2343af9ff33aSdrh     pResult = Tcl_GetObjResult(interp);
2344f7e678d6Sdrh     Tcl_SetWideIntObj(pResult, rowid);
2345af9ff33aSdrh     break;
2346af9ff33aSdrh   }
2347af9ff33aSdrh 
2348af9ff33aSdrh   /*
23494a4c11aaSdan   ** The DB_ONECOLUMN method is implemented together with DB_EXISTS.
23505d9d7576Sdrh   */
23511807ce37Sdrh 
23521807ce37Sdrh   /*    $db progress ?N CALLBACK?
23531807ce37Sdrh   **
23541807ce37Sdrh   ** Invoke the given callback every N virtual machine opcodes while executing
23551807ce37Sdrh   ** queries.
23561807ce37Sdrh   */
23571807ce37Sdrh   case DB_PROGRESS: {
23581807ce37Sdrh     if( objc==2 ){
23591807ce37Sdrh       if( pDb->zProgress ){
23601807ce37Sdrh         Tcl_AppendResult(interp, pDb->zProgress, 0);
23615d9d7576Sdrh       }
23621807ce37Sdrh     }else if( objc==4 ){
23631807ce37Sdrh       char *zProgress;
23641807ce37Sdrh       int len;
23651807ce37Sdrh       int N;
23661807ce37Sdrh       if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
23671807ce37Sdrh         return TCL_ERROR;
23681807ce37Sdrh       };
23691807ce37Sdrh       if( pDb->zProgress ){
23701807ce37Sdrh         Tcl_Free(pDb->zProgress);
23711807ce37Sdrh       }
23721807ce37Sdrh       zProgress = Tcl_GetStringFromObj(objv[3], &len);
23731807ce37Sdrh       if( zProgress && len>0 ){
23741807ce37Sdrh         pDb->zProgress = Tcl_Alloc( len + 1 );
23755bb3eb9bSdrh         memcpy(pDb->zProgress, zProgress, len+1);
23761807ce37Sdrh       }else{
23771807ce37Sdrh         pDb->zProgress = 0;
23781807ce37Sdrh       }
23791807ce37Sdrh #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
23801807ce37Sdrh       if( pDb->zProgress ){
23811807ce37Sdrh         pDb->interp = interp;
23821807ce37Sdrh         sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
23831807ce37Sdrh       }else{
23841807ce37Sdrh         sqlite3_progress_handler(pDb->db, 0, 0, 0);
23851807ce37Sdrh       }
23861807ce37Sdrh #endif
23871807ce37Sdrh     }else{
23881807ce37Sdrh       Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
23891807ce37Sdrh       return TCL_ERROR;
23905d9d7576Sdrh     }
23915d9d7576Sdrh     break;
23925d9d7576Sdrh   }
23935d9d7576Sdrh 
239419e2d37fSdrh   /*    $db profile ?CALLBACK?
239519e2d37fSdrh   **
239619e2d37fSdrh   ** Make arrangements to invoke the CALLBACK routine after each SQL statement
239719e2d37fSdrh   ** that has run.  The text of the SQL and the amount of elapse time are
239819e2d37fSdrh   ** appended to CALLBACK before the script is run.
239919e2d37fSdrh   */
240019e2d37fSdrh   case DB_PROFILE: {
240119e2d37fSdrh     if( objc>3 ){
240219e2d37fSdrh       Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
240319e2d37fSdrh       return TCL_ERROR;
240419e2d37fSdrh     }else if( objc==2 ){
240519e2d37fSdrh       if( pDb->zProfile ){
240619e2d37fSdrh         Tcl_AppendResult(interp, pDb->zProfile, 0);
240719e2d37fSdrh       }
240819e2d37fSdrh     }else{
240919e2d37fSdrh       char *zProfile;
241019e2d37fSdrh       int len;
241119e2d37fSdrh       if( pDb->zProfile ){
241219e2d37fSdrh         Tcl_Free(pDb->zProfile);
241319e2d37fSdrh       }
241419e2d37fSdrh       zProfile = Tcl_GetStringFromObj(objv[2], &len);
241519e2d37fSdrh       if( zProfile && len>0 ){
241619e2d37fSdrh         pDb->zProfile = Tcl_Alloc( len + 1 );
24175bb3eb9bSdrh         memcpy(pDb->zProfile, zProfile, len+1);
241819e2d37fSdrh       }else{
241919e2d37fSdrh         pDb->zProfile = 0;
242019e2d37fSdrh       }
242119e2d37fSdrh #ifndef SQLITE_OMIT_TRACE
242219e2d37fSdrh       if( pDb->zProfile ){
242319e2d37fSdrh         pDb->interp = interp;
242419e2d37fSdrh         sqlite3_profile(pDb->db, DbProfileHandler, pDb);
242519e2d37fSdrh       }else{
242619e2d37fSdrh         sqlite3_profile(pDb->db, 0, 0);
242719e2d37fSdrh       }
242819e2d37fSdrh #endif
242919e2d37fSdrh     }
243019e2d37fSdrh     break;
243119e2d37fSdrh   }
243219e2d37fSdrh 
24335d9d7576Sdrh   /*
243422fbcb8dSdrh   **     $db rekey KEY
243522fbcb8dSdrh   **
243622fbcb8dSdrh   ** Change the encryption key on the currently open database.
243722fbcb8dSdrh   */
243822fbcb8dSdrh   case DB_REKEY: {
243922fbcb8dSdrh     int nKey;
244022fbcb8dSdrh     void *pKey;
244122fbcb8dSdrh     if( objc!=3 ){
244222fbcb8dSdrh       Tcl_WrongNumArgs(interp, 2, objv, "KEY");
244322fbcb8dSdrh       return TCL_ERROR;
244422fbcb8dSdrh     }
244522fbcb8dSdrh     pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
24469eb9e26bSdrh #ifdef SQLITE_HAS_CODEC
24472011d5f5Sdrh     rc = sqlite3_rekey(pDb->db, pKey, nKey);
244822fbcb8dSdrh     if( rc ){
2449f20b21c8Sdanielk1977       Tcl_AppendResult(interp, sqlite3ErrStr(rc), 0);
245022fbcb8dSdrh       rc = TCL_ERROR;
245122fbcb8dSdrh     }
245222fbcb8dSdrh #endif
245322fbcb8dSdrh     break;
245422fbcb8dSdrh   }
245522fbcb8dSdrh 
2456dc2c4915Sdrh   /*    $db restore ?DATABASE? FILENAME
2457dc2c4915Sdrh   **
2458dc2c4915Sdrh   ** Open a database file named FILENAME.  Transfer the content
2459dc2c4915Sdrh   ** of FILENAME into the local database DATABASE (default: "main").
2460dc2c4915Sdrh   */
2461dc2c4915Sdrh   case DB_RESTORE: {
2462dc2c4915Sdrh     const char *zSrcFile;
2463dc2c4915Sdrh     const char *zDestDb;
2464dc2c4915Sdrh     sqlite3 *pSrc;
2465dc2c4915Sdrh     sqlite3_backup *pBackup;
2466dc2c4915Sdrh     int nTimeout = 0;
2467dc2c4915Sdrh 
2468dc2c4915Sdrh     if( objc==3 ){
2469dc2c4915Sdrh       zDestDb = "main";
2470dc2c4915Sdrh       zSrcFile = Tcl_GetString(objv[2]);
2471dc2c4915Sdrh     }else if( objc==4 ){
2472dc2c4915Sdrh       zDestDb = Tcl_GetString(objv[2]);
2473dc2c4915Sdrh       zSrcFile = Tcl_GetString(objv[3]);
2474dc2c4915Sdrh     }else{
2475dc2c4915Sdrh       Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
2476dc2c4915Sdrh       return TCL_ERROR;
2477dc2c4915Sdrh     }
2478dc2c4915Sdrh     rc = sqlite3_open_v2(zSrcFile, &pSrc, SQLITE_OPEN_READONLY, 0);
2479dc2c4915Sdrh     if( rc!=SQLITE_OK ){
2480dc2c4915Sdrh       Tcl_AppendResult(interp, "cannot open source database: ",
2481dc2c4915Sdrh            sqlite3_errmsg(pSrc), (char*)0);
2482dc2c4915Sdrh       sqlite3_close(pSrc);
2483dc2c4915Sdrh       return TCL_ERROR;
2484dc2c4915Sdrh     }
2485dc2c4915Sdrh     pBackup = sqlite3_backup_init(pDb->db, zDestDb, pSrc, "main");
2486dc2c4915Sdrh     if( pBackup==0 ){
2487dc2c4915Sdrh       Tcl_AppendResult(interp, "restore failed: ",
2488dc2c4915Sdrh            sqlite3_errmsg(pDb->db), (char*)0);
2489dc2c4915Sdrh       sqlite3_close(pSrc);
2490dc2c4915Sdrh       return TCL_ERROR;
2491dc2c4915Sdrh     }
2492dc2c4915Sdrh     while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
2493dc2c4915Sdrh               || rc==SQLITE_BUSY ){
2494dc2c4915Sdrh       if( rc==SQLITE_BUSY ){
2495dc2c4915Sdrh         if( nTimeout++ >= 3 ) break;
2496dc2c4915Sdrh         sqlite3_sleep(100);
2497dc2c4915Sdrh       }
2498dc2c4915Sdrh     }
2499dc2c4915Sdrh     sqlite3_backup_finish(pBackup);
2500dc2c4915Sdrh     if( rc==SQLITE_DONE ){
2501dc2c4915Sdrh       rc = TCL_OK;
2502dc2c4915Sdrh     }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
2503dc2c4915Sdrh       Tcl_AppendResult(interp, "restore failed: source database busy",
2504dc2c4915Sdrh                        (char*)0);
2505dc2c4915Sdrh       rc = TCL_ERROR;
2506dc2c4915Sdrh     }else{
2507dc2c4915Sdrh       Tcl_AppendResult(interp, "restore failed: ",
2508dc2c4915Sdrh            sqlite3_errmsg(pDb->db), (char*)0);
2509dc2c4915Sdrh       rc = TCL_ERROR;
2510dc2c4915Sdrh     }
2511dc2c4915Sdrh     sqlite3_close(pSrc);
2512dc2c4915Sdrh     break;
2513dc2c4915Sdrh   }
2514dc2c4915Sdrh 
251522fbcb8dSdrh   /*
2516d1d38488Sdrh   **     $db status (step|sort)
2517d1d38488Sdrh   **
2518d1d38488Sdrh   ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or
2519d1d38488Sdrh   ** SQLITE_STMTSTATUS_SORT for the most recent eval.
2520d1d38488Sdrh   */
2521d1d38488Sdrh   case DB_STATUS: {
2522d1d38488Sdrh     int v;
2523d1d38488Sdrh     const char *zOp;
2524d1d38488Sdrh     if( objc!=3 ){
2525d1d38488Sdrh       Tcl_WrongNumArgs(interp, 2, objv, "(step|sort)");
2526d1d38488Sdrh       return TCL_ERROR;
2527d1d38488Sdrh     }
2528d1d38488Sdrh     zOp = Tcl_GetString(objv[2]);
2529d1d38488Sdrh     if( strcmp(zOp, "step")==0 ){
2530d1d38488Sdrh       v = pDb->nStep;
2531d1d38488Sdrh     }else if( strcmp(zOp, "sort")==0 ){
2532d1d38488Sdrh       v = pDb->nSort;
2533d1d38488Sdrh     }else{
2534d1d38488Sdrh       Tcl_AppendResult(interp, "bad argument: should be step or sort",
2535d1d38488Sdrh             (char*)0);
2536d1d38488Sdrh       return TCL_ERROR;
2537d1d38488Sdrh     }
2538d1d38488Sdrh     Tcl_SetObjResult(interp, Tcl_NewIntObj(v));
2539d1d38488Sdrh     break;
2540d1d38488Sdrh   }
2541d1d38488Sdrh 
2542d1d38488Sdrh   /*
2543bec3f402Sdrh   **     $db timeout MILLESECONDS
2544bec3f402Sdrh   **
2545bec3f402Sdrh   ** Delay for the number of milliseconds specified when a file is locked.
2546bec3f402Sdrh   */
25476d31316cSdrh   case DB_TIMEOUT: {
2548bec3f402Sdrh     int ms;
25496d31316cSdrh     if( objc!=3 ){
25506d31316cSdrh       Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
2551bec3f402Sdrh       return TCL_ERROR;
255275897234Sdrh     }
25536d31316cSdrh     if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
25546f8a503dSdanielk1977     sqlite3_busy_timeout(pDb->db, ms);
25556d31316cSdrh     break;
255675897234Sdrh   }
2557b5a20d3cSdrh 
25580f14e2ebSdrh   /*
25590f14e2ebSdrh   **     $db total_changes
25600f14e2ebSdrh   **
25610f14e2ebSdrh   ** Return the number of rows that were modified, inserted, or deleted
25620f14e2ebSdrh   ** since the database handle was created.
25630f14e2ebSdrh   */
25640f14e2ebSdrh   case DB_TOTAL_CHANGES: {
25650f14e2ebSdrh     Tcl_Obj *pResult;
25660f14e2ebSdrh     if( objc!=2 ){
25670f14e2ebSdrh       Tcl_WrongNumArgs(interp, 2, objv, "");
25680f14e2ebSdrh       return TCL_ERROR;
25690f14e2ebSdrh     }
25700f14e2ebSdrh     pResult = Tcl_GetObjResult(interp);
25710f14e2ebSdrh     Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
25720f14e2ebSdrh     break;
25730f14e2ebSdrh   }
25740f14e2ebSdrh 
2575b5a20d3cSdrh   /*    $db trace ?CALLBACK?
2576b5a20d3cSdrh   **
2577b5a20d3cSdrh   ** Make arrangements to invoke the CALLBACK routine for each SQL statement
2578b5a20d3cSdrh   ** that is executed.  The text of the SQL is appended to CALLBACK before
2579b5a20d3cSdrh   ** it is executed.
2580b5a20d3cSdrh   */
2581b5a20d3cSdrh   case DB_TRACE: {
2582b5a20d3cSdrh     if( objc>3 ){
2583b5a20d3cSdrh       Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2584b97759edSdrh       return TCL_ERROR;
2585b5a20d3cSdrh     }else if( objc==2 ){
2586b5a20d3cSdrh       if( pDb->zTrace ){
2587b5a20d3cSdrh         Tcl_AppendResult(interp, pDb->zTrace, 0);
2588b5a20d3cSdrh       }
2589b5a20d3cSdrh     }else{
2590b5a20d3cSdrh       char *zTrace;
2591b5a20d3cSdrh       int len;
2592b5a20d3cSdrh       if( pDb->zTrace ){
2593b5a20d3cSdrh         Tcl_Free(pDb->zTrace);
2594b5a20d3cSdrh       }
2595b5a20d3cSdrh       zTrace = Tcl_GetStringFromObj(objv[2], &len);
2596b5a20d3cSdrh       if( zTrace && len>0 ){
2597b5a20d3cSdrh         pDb->zTrace = Tcl_Alloc( len + 1 );
25985bb3eb9bSdrh         memcpy(pDb->zTrace, zTrace, len+1);
2599b5a20d3cSdrh       }else{
2600b5a20d3cSdrh         pDb->zTrace = 0;
2601b5a20d3cSdrh       }
260219e2d37fSdrh #ifndef SQLITE_OMIT_TRACE
2603b5a20d3cSdrh       if( pDb->zTrace ){
2604b5a20d3cSdrh         pDb->interp = interp;
26056f8a503dSdanielk1977         sqlite3_trace(pDb->db, DbTraceHandler, pDb);
2606b5a20d3cSdrh       }else{
26076f8a503dSdanielk1977         sqlite3_trace(pDb->db, 0, 0);
2608b5a20d3cSdrh       }
260919e2d37fSdrh #endif
2610b5a20d3cSdrh     }
2611b5a20d3cSdrh     break;
2612b5a20d3cSdrh   }
2613b5a20d3cSdrh 
26143d21423cSdrh   /*    $db transaction [-deferred|-immediate|-exclusive] SCRIPT
26153d21423cSdrh   **
26163d21423cSdrh   ** Start a new transaction (if we are not already in the midst of a
26173d21423cSdrh   ** transaction) and execute the TCL script SCRIPT.  After SCRIPT
26183d21423cSdrh   ** completes, either commit the transaction or roll it back if SCRIPT
26193d21423cSdrh   ** throws an exception.  Or if no new transation was started, do nothing.
26203d21423cSdrh   ** pass the exception on up the stack.
26213d21423cSdrh   **
26223d21423cSdrh   ** This command was inspired by Dave Thomas's talk on Ruby at the
26233d21423cSdrh   ** 2005 O'Reilly Open Source Convention (OSCON).
26243d21423cSdrh   */
26253d21423cSdrh   case DB_TRANSACTION: {
26263d21423cSdrh     Tcl_Obj *pScript;
2627cd38d520Sdanielk1977     const char *zBegin = "SAVEPOINT _tcl_transaction";
26283d21423cSdrh     if( objc!=3 && objc!=4 ){
26293d21423cSdrh       Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
26303d21423cSdrh       return TCL_ERROR;
26313d21423cSdrh     }
2632cd38d520Sdanielk1977 
26334a4c11aaSdan     if( pDb->nTransaction==0 && objc==4 ){
26343d21423cSdrh       static const char *TTYPE_strs[] = {
2635ce604012Sdrh         "deferred",   "exclusive",  "immediate", 0
26363d21423cSdrh       };
26373d21423cSdrh       enum TTYPE_enum {
26383d21423cSdrh         TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
26393d21423cSdrh       };
26403d21423cSdrh       int ttype;
2641b5555e7eSdrh       if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
26423d21423cSdrh                               0, &ttype) ){
26433d21423cSdrh         return TCL_ERROR;
26443d21423cSdrh       }
26453d21423cSdrh       switch( (enum TTYPE_enum)ttype ){
26463d21423cSdrh         case TTYPE_DEFERRED:    /* no-op */;                 break;
26473d21423cSdrh         case TTYPE_EXCLUSIVE:   zBegin = "BEGIN EXCLUSIVE";  break;
26483d21423cSdrh         case TTYPE_IMMEDIATE:   zBegin = "BEGIN IMMEDIATE";  break;
26493d21423cSdrh       }
26503d21423cSdrh     }
2651cd38d520Sdanielk1977     pScript = objv[objc-1];
2652cd38d520Sdanielk1977 
26534a4c11aaSdan     /* Run the SQLite BEGIN command to open a transaction or savepoint. */
26541f1549f8Sdrh     pDb->disableAuth++;
2655cd38d520Sdanielk1977     rc = sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
26561f1549f8Sdrh     pDb->disableAuth--;
2657cd38d520Sdanielk1977     if( rc!=SQLITE_OK ){
2658cd38d520Sdanielk1977       Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
2659cd38d520Sdanielk1977       return TCL_ERROR;
26603d21423cSdrh     }
2661cd38d520Sdanielk1977     pDb->nTransaction++;
2662cd38d520Sdanielk1977 
26634a4c11aaSdan     /* If using NRE, schedule a callback to invoke the script pScript, then
26644a4c11aaSdan     ** a second callback to commit (or rollback) the transaction or savepoint
26654a4c11aaSdan     ** opened above. If not using NRE, evaluate the script directly, then
26664a4c11aaSdan     ** call function DbTransPostCmd() to commit (or rollback) the transaction
26674a4c11aaSdan     ** or savepoint.  */
26684a4c11aaSdan     if( DbUseNre() ){
26694a4c11aaSdan       Tcl_NRAddCallback(interp, DbTransPostCmd, cd, 0, 0, 0);
26704a4c11aaSdan       Tcl_NREvalObj(interp, pScript, 0);
26713d21423cSdrh     }else{
26724a4c11aaSdan       rc = DbTransPostCmd(&cd, interp, Tcl_EvalObjEx(interp, pScript, 0));
26733d21423cSdrh     }
26743d21423cSdrh     break;
26753d21423cSdrh   }
26763d21423cSdrh 
267794eb6a14Sdanielk1977   /*
2678404ca075Sdanielk1977   **    $db unlock_notify ?script?
2679404ca075Sdanielk1977   */
2680404ca075Sdanielk1977   case DB_UNLOCK_NOTIFY: {
2681404ca075Sdanielk1977 #ifndef SQLITE_ENABLE_UNLOCK_NOTIFY
2682404ca075Sdanielk1977     Tcl_AppendResult(interp, "unlock_notify not available in this build", 0);
2683404ca075Sdanielk1977     rc = TCL_ERROR;
2684404ca075Sdanielk1977 #else
2685404ca075Sdanielk1977     if( objc!=2 && objc!=3 ){
2686404ca075Sdanielk1977       Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
2687404ca075Sdanielk1977       rc = TCL_ERROR;
2688404ca075Sdanielk1977     }else{
2689404ca075Sdanielk1977       void (*xNotify)(void **, int) = 0;
2690404ca075Sdanielk1977       void *pNotifyArg = 0;
2691404ca075Sdanielk1977 
2692404ca075Sdanielk1977       if( pDb->pUnlockNotify ){
2693404ca075Sdanielk1977         Tcl_DecrRefCount(pDb->pUnlockNotify);
2694404ca075Sdanielk1977         pDb->pUnlockNotify = 0;
2695404ca075Sdanielk1977       }
2696404ca075Sdanielk1977 
2697404ca075Sdanielk1977       if( objc==3 ){
2698404ca075Sdanielk1977         xNotify = DbUnlockNotify;
2699404ca075Sdanielk1977         pNotifyArg = (void *)pDb;
2700404ca075Sdanielk1977         pDb->pUnlockNotify = objv[2];
2701404ca075Sdanielk1977         Tcl_IncrRefCount(pDb->pUnlockNotify);
2702404ca075Sdanielk1977       }
2703404ca075Sdanielk1977 
2704404ca075Sdanielk1977       if( sqlite3_unlock_notify(pDb->db, xNotify, pNotifyArg) ){
2705404ca075Sdanielk1977         Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0);
2706404ca075Sdanielk1977         rc = TCL_ERROR;
2707404ca075Sdanielk1977       }
2708404ca075Sdanielk1977     }
2709404ca075Sdanielk1977 #endif
2710404ca075Sdanielk1977     break;
2711404ca075Sdanielk1977   }
2712404ca075Sdanielk1977 
2713404ca075Sdanielk1977   /*
271494eb6a14Sdanielk1977   **    $db update_hook ?script?
271571fd80bfSdanielk1977   **    $db rollback_hook ?script?
271694eb6a14Sdanielk1977   */
271771fd80bfSdanielk1977   case DB_UPDATE_HOOK:
271871fd80bfSdanielk1977   case DB_ROLLBACK_HOOK: {
271971fd80bfSdanielk1977 
272071fd80bfSdanielk1977     /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
272171fd80bfSdanielk1977     ** whether [$db update_hook] or [$db rollback_hook] was invoked.
272271fd80bfSdanielk1977     */
272371fd80bfSdanielk1977     Tcl_Obj **ppHook;
272471fd80bfSdanielk1977     if( choice==DB_UPDATE_HOOK ){
272571fd80bfSdanielk1977       ppHook = &pDb->pUpdateHook;
272671fd80bfSdanielk1977     }else{
272771fd80bfSdanielk1977       ppHook = &pDb->pRollbackHook;
272871fd80bfSdanielk1977     }
272971fd80bfSdanielk1977 
273094eb6a14Sdanielk1977     if( objc!=2 && objc!=3 ){
273194eb6a14Sdanielk1977        Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
273294eb6a14Sdanielk1977        return TCL_ERROR;
273394eb6a14Sdanielk1977     }
273471fd80bfSdanielk1977     if( *ppHook ){
273571fd80bfSdanielk1977       Tcl_SetObjResult(interp, *ppHook);
273694eb6a14Sdanielk1977       if( objc==3 ){
273771fd80bfSdanielk1977         Tcl_DecrRefCount(*ppHook);
273871fd80bfSdanielk1977         *ppHook = 0;
273994eb6a14Sdanielk1977       }
274094eb6a14Sdanielk1977     }
274194eb6a14Sdanielk1977     if( objc==3 ){
274271fd80bfSdanielk1977       assert( !(*ppHook) );
274394eb6a14Sdanielk1977       if( Tcl_GetCharLength(objv[2])>0 ){
274471fd80bfSdanielk1977         *ppHook = objv[2];
274571fd80bfSdanielk1977         Tcl_IncrRefCount(*ppHook);
274694eb6a14Sdanielk1977       }
274794eb6a14Sdanielk1977     }
274871fd80bfSdanielk1977 
274971fd80bfSdanielk1977     sqlite3_update_hook(pDb->db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
275071fd80bfSdanielk1977     sqlite3_rollback_hook(pDb->db,(pDb->pRollbackHook?DbRollbackHandler:0),pDb);
275171fd80bfSdanielk1977 
275294eb6a14Sdanielk1977     break;
275394eb6a14Sdanielk1977   }
275494eb6a14Sdanielk1977 
27554397de57Sdanielk1977   /*    $db version
27564397de57Sdanielk1977   **
27574397de57Sdanielk1977   ** Return the version string for this database.
27584397de57Sdanielk1977   */
27594397de57Sdanielk1977   case DB_VERSION: {
27604397de57Sdanielk1977     Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
27614397de57Sdanielk1977     break;
27624397de57Sdanielk1977   }
27634397de57Sdanielk1977 
27641067fe11Stpoindex 
27656d31316cSdrh   } /* End of the SWITCH statement */
276622fbcb8dSdrh   return rc;
276775897234Sdrh }
276875897234Sdrh 
2769*a2c8a95bSdrh #if SQLITE_TCL_NRE
2770*a2c8a95bSdrh /*
2771*a2c8a95bSdrh ** Adaptor that provides an objCmd interface to the NRE-enabled
2772*a2c8a95bSdrh ** interface implementation.
2773*a2c8a95bSdrh */
2774*a2c8a95bSdrh static int DbObjCmdAdaptor(
2775*a2c8a95bSdrh   void *cd,
2776*a2c8a95bSdrh   Tcl_Interp *interp,
2777*a2c8a95bSdrh   int objc,
2778*a2c8a95bSdrh   Tcl_Obj *const*objv
2779*a2c8a95bSdrh ){
2780*a2c8a95bSdrh   return Tcl_NRCallObjProc(interp, DbObjCmd, cd, objc, objv);
2781*a2c8a95bSdrh }
2782*a2c8a95bSdrh #endif /* SQLITE_TCL_NRE */
2783*a2c8a95bSdrh 
278475897234Sdrh /*
27853570ad93Sdrh **   sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
27869a6284c1Sdanielk1977 **                           ?-create BOOLEAN? ?-nomutex BOOLEAN?
278775897234Sdrh **
278875897234Sdrh ** This is the main Tcl command.  When the "sqlite" Tcl command is
278975897234Sdrh ** invoked, this routine runs to process that command.
279075897234Sdrh **
279175897234Sdrh ** The first argument, DBNAME, is an arbitrary name for a new
279275897234Sdrh ** database connection.  This command creates a new command named
279375897234Sdrh ** DBNAME that is used to control that connection.  The database
279475897234Sdrh ** connection is deleted when the DBNAME command is deleted.
279575897234Sdrh **
27963570ad93Sdrh ** The second argument is the name of the database file.
2797fbc3eab8Sdrh **
279875897234Sdrh */
279922fbcb8dSdrh static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
2800bec3f402Sdrh   SqliteDb *p;
280122fbcb8dSdrh   void *pKey = 0;
280222fbcb8dSdrh   int nKey = 0;
280322fbcb8dSdrh   const char *zArg;
280475897234Sdrh   char *zErrMsg;
28053570ad93Sdrh   int i;
280622fbcb8dSdrh   const char *zFile;
28073570ad93Sdrh   const char *zVfs = 0;
2808d9da78a2Sdrh   int flags;
2809882e8e4dSdrh   Tcl_DString translatedFilename;
2810d9da78a2Sdrh 
2811d9da78a2Sdrh   /* In normal use, each TCL interpreter runs in a single thread.  So
2812d9da78a2Sdrh   ** by default, we can turn of mutexing on SQLite database connections.
2813d9da78a2Sdrh   ** However, for testing purposes it is useful to have mutexes turned
2814d9da78a2Sdrh   ** on.  So, by default, mutexes default off.  But if compiled with
2815d9da78a2Sdrh   ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on.
2816d9da78a2Sdrh   */
2817d9da78a2Sdrh #ifdef SQLITE_TCL_DEFAULT_FULLMUTEX
2818d9da78a2Sdrh   flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
2819d9da78a2Sdrh #else
2820d9da78a2Sdrh   flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX;
2821d9da78a2Sdrh #endif
2822d9da78a2Sdrh 
282322fbcb8dSdrh   if( objc==2 ){
282422fbcb8dSdrh     zArg = Tcl_GetStringFromObj(objv[1], 0);
282522fbcb8dSdrh     if( strcmp(zArg,"-version")==0 ){
28266f8a503dSdanielk1977       Tcl_AppendResult(interp,sqlite3_version,0);
2827647cb0e1Sdrh       return TCL_OK;
2828647cb0e1Sdrh     }
28299eb9e26bSdrh     if( strcmp(zArg,"-has-codec")==0 ){
28309eb9e26bSdrh #ifdef SQLITE_HAS_CODEC
283122fbcb8dSdrh       Tcl_AppendResult(interp,"1",0);
283222fbcb8dSdrh #else
283322fbcb8dSdrh       Tcl_AppendResult(interp,"0",0);
283422fbcb8dSdrh #endif
283522fbcb8dSdrh       return TCL_OK;
283622fbcb8dSdrh     }
2837fbc3eab8Sdrh   }
28383570ad93Sdrh   for(i=3; i+1<objc; i+=2){
28393570ad93Sdrh     zArg = Tcl_GetString(objv[i]);
284022fbcb8dSdrh     if( strcmp(zArg,"-key")==0 ){
28413570ad93Sdrh       pKey = Tcl_GetByteArrayFromObj(objv[i+1], &nKey);
28423570ad93Sdrh     }else if( strcmp(zArg, "-vfs")==0 ){
28433570ad93Sdrh       i++;
28443570ad93Sdrh       zVfs = Tcl_GetString(objv[i]);
28453570ad93Sdrh     }else if( strcmp(zArg, "-readonly")==0 ){
28463570ad93Sdrh       int b;
28473570ad93Sdrh       if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
28483570ad93Sdrh       if( b ){
284933f4e02aSdrh         flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
28503570ad93Sdrh         flags |= SQLITE_OPEN_READONLY;
28513570ad93Sdrh       }else{
28523570ad93Sdrh         flags &= ~SQLITE_OPEN_READONLY;
28533570ad93Sdrh         flags |= SQLITE_OPEN_READWRITE;
28543570ad93Sdrh       }
28553570ad93Sdrh     }else if( strcmp(zArg, "-create")==0 ){
28563570ad93Sdrh       int b;
28573570ad93Sdrh       if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
285833f4e02aSdrh       if( b && (flags & SQLITE_OPEN_READONLY)==0 ){
28593570ad93Sdrh         flags |= SQLITE_OPEN_CREATE;
28603570ad93Sdrh       }else{
28613570ad93Sdrh         flags &= ~SQLITE_OPEN_CREATE;
28623570ad93Sdrh       }
28639a6284c1Sdanielk1977     }else if( strcmp(zArg, "-nomutex")==0 ){
28649a6284c1Sdanielk1977       int b;
28659a6284c1Sdanielk1977       if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
28669a6284c1Sdanielk1977       if( b ){
28679a6284c1Sdanielk1977         flags |= SQLITE_OPEN_NOMUTEX;
2868039963adSdrh         flags &= ~SQLITE_OPEN_FULLMUTEX;
28699a6284c1Sdanielk1977       }else{
28709a6284c1Sdanielk1977         flags &= ~SQLITE_OPEN_NOMUTEX;
28719a6284c1Sdanielk1977       }
2872039963adSdrh    }else if( strcmp(zArg, "-fullmutex")==0 ){
2873039963adSdrh       int b;
2874039963adSdrh       if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
2875039963adSdrh       if( b ){
2876039963adSdrh         flags |= SQLITE_OPEN_FULLMUTEX;
2877039963adSdrh         flags &= ~SQLITE_OPEN_NOMUTEX;
2878039963adSdrh       }else{
2879039963adSdrh         flags &= ~SQLITE_OPEN_FULLMUTEX;
2880039963adSdrh       }
28813570ad93Sdrh     }else{
28823570ad93Sdrh       Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
28833570ad93Sdrh       return TCL_ERROR;
288422fbcb8dSdrh     }
288522fbcb8dSdrh   }
28863570ad93Sdrh   if( objc<3 || (objc&1)!=1 ){
288722fbcb8dSdrh     Tcl_WrongNumArgs(interp, 1, objv,
28883570ad93Sdrh       "HANDLE FILENAME ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
2889039963adSdrh       " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN?"
28909eb9e26bSdrh #ifdef SQLITE_HAS_CODEC
28913570ad93Sdrh       " ?-key CODECKEY?"
289222fbcb8dSdrh #endif
289322fbcb8dSdrh     );
289475897234Sdrh     return TCL_ERROR;
289575897234Sdrh   }
289675897234Sdrh   zErrMsg = 0;
28974cdc9e84Sdrh   p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
289875897234Sdrh   if( p==0 ){
2899bec3f402Sdrh     Tcl_SetResult(interp, "malloc failed", TCL_STATIC);
2900bec3f402Sdrh     return TCL_ERROR;
2901bec3f402Sdrh   }
2902bec3f402Sdrh   memset(p, 0, sizeof(*p));
290322fbcb8dSdrh   zFile = Tcl_GetStringFromObj(objv[2], 0);
2904882e8e4dSdrh   zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
29053570ad93Sdrh   sqlite3_open_v2(zFile, &p->db, flags, zVfs);
2906882e8e4dSdrh   Tcl_DStringFree(&translatedFilename);
290780290863Sdanielk1977   if( SQLITE_OK!=sqlite3_errcode(p->db) ){
29089404d50eSdrh     zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
290980290863Sdanielk1977     sqlite3_close(p->db);
291080290863Sdanielk1977     p->db = 0;
291180290863Sdanielk1977   }
29122011d5f5Sdrh #ifdef SQLITE_HAS_CODEC
2913f3a65f7eSdrh   if( p->db ){
29142011d5f5Sdrh     sqlite3_key(p->db, pKey, nKey);
2915f3a65f7eSdrh   }
2916eb8ed70dSdrh #endif
2917bec3f402Sdrh   if( p->db==0 ){
291875897234Sdrh     Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
2919bec3f402Sdrh     Tcl_Free((char*)p);
29209404d50eSdrh     sqlite3_free(zErrMsg);
292175897234Sdrh     return TCL_ERROR;
292275897234Sdrh   }
2923fb7e7651Sdrh   p->maxStmt = NUM_PREPARED_STMTS;
29245169bbc6Sdrh   p->interp = interp;
292522fbcb8dSdrh   zArg = Tcl_GetStringFromObj(objv[1], 0);
29264a4c11aaSdan   if( DbUseNre() ){
2927*a2c8a95bSdrh     Tcl_NRCreateCommand(interp, zArg, DbObjCmdAdaptor, DbObjCmd,
2928*a2c8a95bSdrh                         (char*)p, DbDeleteCmd);
29294a4c11aaSdan   }else{
293022fbcb8dSdrh     Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
29314a4c11aaSdan   }
293275897234Sdrh   return TCL_OK;
293375897234Sdrh }
293475897234Sdrh 
293575897234Sdrh /*
293690ca9753Sdrh ** Provide a dummy Tcl_InitStubs if we are using this as a static
293790ca9753Sdrh ** library.
293890ca9753Sdrh */
293990ca9753Sdrh #ifndef USE_TCL_STUBS
294090ca9753Sdrh # undef  Tcl_InitStubs
294190ca9753Sdrh # define Tcl_InitStubs(a,b,c)
294290ca9753Sdrh #endif
294390ca9753Sdrh 
294490ca9753Sdrh /*
294529bc4615Sdrh ** Make sure we have a PACKAGE_VERSION macro defined.  This will be
294629bc4615Sdrh ** defined automatically by the TEA makefile.  But other makefiles
294729bc4615Sdrh ** do not define it.
294829bc4615Sdrh */
294929bc4615Sdrh #ifndef PACKAGE_VERSION
295029bc4615Sdrh # define PACKAGE_VERSION SQLITE_VERSION
295129bc4615Sdrh #endif
295229bc4615Sdrh 
295329bc4615Sdrh /*
295475897234Sdrh ** Initialize this module.
295575897234Sdrh **
295675897234Sdrh ** This Tcl module contains only a single new Tcl command named "sqlite".
295775897234Sdrh ** (Hence there is no namespace.  There is no point in using a namespace
295875897234Sdrh ** if the extension only supplies one new name!)  The "sqlite" command is
295975897234Sdrh ** used to open a new SQLite database.  See the DbMain() routine above
296075897234Sdrh ** for additional information.
296175897234Sdrh */
2962ad6e1370Sdrh EXTERN int Sqlite3_Init(Tcl_Interp *interp){
296392febd92Sdrh   Tcl_InitStubs(interp, "8.4", 0);
2964ef4ac8f9Sdrh   Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
296529bc4615Sdrh   Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
296649766d6cSdrh   Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
296729bc4615Sdrh   Tcl_PkgProvide(interp, "sqlite", PACKAGE_VERSION);
296890ca9753Sdrh   return TCL_OK;
296990ca9753Sdrh }
2970ad6e1370Sdrh EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2971ad6e1370Sdrh EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
2972ad6e1370Sdrh EXTERN int Tclsqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
2973e2c3a659Sdrh EXTERN int Sqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
2974e2c3a659Sdrh EXTERN int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
2975e2c3a659Sdrh EXTERN int Sqlite3_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK; }
2976e2c3a659Sdrh EXTERN int Tclsqlite3_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK;}
2977e2c3a659Sdrh 
297849766d6cSdrh 
297949766d6cSdrh #ifndef SQLITE_3_SUFFIX_ONLY
2980ad6e1370Sdrh EXTERN int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2981ad6e1370Sdrh EXTERN int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
2982ad6e1370Sdrh EXTERN int Sqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
2983ad6e1370Sdrh EXTERN int Tclsqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; }
2984e2c3a659Sdrh EXTERN int Sqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
2985e2c3a659Sdrh EXTERN int Tclsqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
2986e2c3a659Sdrh EXTERN int Sqlite_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK; }
2987e2c3a659Sdrh EXTERN int Tclsqlite_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK;}
298849766d6cSdrh #endif
298975897234Sdrh 
29903e27c026Sdrh #ifdef TCLSH
29913e27c026Sdrh /*****************************************************************************
29923e27c026Sdrh ** The code that follows is used to build standalone TCL interpreters
29933570ad93Sdrh ** that are statically linked with SQLite.
299475897234Sdrh */
2995348784efSdrh 
2996348784efSdrh /*
29973e27c026Sdrh ** If the macro TCLSH is one, then put in code this for the
29983e27c026Sdrh ** "main" routine that will initialize Tcl and take input from
29993570ad93Sdrh ** standard input, or if a file is named on the command line
30003570ad93Sdrh ** the TCL interpreter reads and evaluates that file.
3001348784efSdrh */
30023e27c026Sdrh #if TCLSH==1
3003348784efSdrh static char zMainloop[] =
3004348784efSdrh   "set line {}\n"
3005348784efSdrh   "while {![eof stdin]} {\n"
3006348784efSdrh     "if {$line!=\"\"} {\n"
3007348784efSdrh       "puts -nonewline \"> \"\n"
3008348784efSdrh     "} else {\n"
3009348784efSdrh       "puts -nonewline \"% \"\n"
3010348784efSdrh     "}\n"
3011348784efSdrh     "flush stdout\n"
3012348784efSdrh     "append line [gets stdin]\n"
3013348784efSdrh     "if {[info complete $line]} {\n"
3014348784efSdrh       "if {[catch {uplevel #0 $line} result]} {\n"
3015348784efSdrh         "puts stderr \"Error: $result\"\n"
3016348784efSdrh       "} elseif {$result!=\"\"} {\n"
3017348784efSdrh         "puts $result\n"
3018348784efSdrh       "}\n"
3019348784efSdrh       "set line {}\n"
3020348784efSdrh     "} else {\n"
3021348784efSdrh       "append line \\n\n"
3022348784efSdrh     "}\n"
3023348784efSdrh   "}\n"
3024348784efSdrh ;
30253e27c026Sdrh #endif
30263e27c026Sdrh 
30273e27c026Sdrh /*
30283e27c026Sdrh ** If the macro TCLSH is two, then get the main loop code out of
30293e27c026Sdrh ** the separate file "spaceanal_tcl.h".
30303e27c026Sdrh */
30313e27c026Sdrh #if TCLSH==2
30323e27c026Sdrh static char zMainloop[] =
30333e27c026Sdrh #include "spaceanal_tcl.h"
30343e27c026Sdrh ;
30353e27c026Sdrh #endif
3036348784efSdrh 
3037348784efSdrh #define TCLSH_MAIN main   /* Needed to fake out mktclapp */
3038348784efSdrh int TCLSH_MAIN(int argc, char **argv){
3039348784efSdrh   Tcl_Interp *interp;
30400a549071Sdanielk1977 
30410a549071Sdanielk1977   /* Call sqlite3_shutdown() once before doing anything else. This is to
30420a549071Sdanielk1977   ** test that sqlite3_shutdown() can be safely called by a process before
30430a549071Sdanielk1977   ** sqlite3_initialize() is. */
30440a549071Sdanielk1977   sqlite3_shutdown();
30450a549071Sdanielk1977 
3046297ecf14Sdrh   Tcl_FindExecutable(argv[0]);
3047348784efSdrh   interp = Tcl_CreateInterp();
304838f8271fSdrh   Sqlite3_Init(interp);
3049d9b0257aSdrh #ifdef SQLITE_TEST
3050d1bf3512Sdrh   {
30512f999a67Sdrh     extern int Md5_Init(Tcl_Interp*);
30522f999a67Sdrh     extern int Sqliteconfig_Init(Tcl_Interp*);
3053d1bf3512Sdrh     extern int Sqlitetest1_Init(Tcl_Interp*);
30545c4d9703Sdrh     extern int Sqlitetest2_Init(Tcl_Interp*);
30555c4d9703Sdrh     extern int Sqlitetest3_Init(Tcl_Interp*);
3056a6064dcfSdrh     extern int Sqlitetest4_Init(Tcl_Interp*);
3057998b56c3Sdanielk1977     extern int Sqlitetest5_Init(Tcl_Interp*);
30589c06c953Sdrh     extern int Sqlitetest6_Init(Tcl_Interp*);
305929c636bcSdrh     extern int Sqlitetest7_Init(Tcl_Interp*);
3060b9bb7c18Sdrh     extern int Sqlitetest8_Init(Tcl_Interp*);
3061a713f2c3Sdanielk1977     extern int Sqlitetest9_Init(Tcl_Interp*);
30622366940dSdrh     extern int Sqlitetestasync_Init(Tcl_Interp*);
30631409be69Sdrh     extern int Sqlitetest_autoext_Init(Tcl_Interp*);
3064984bfaa4Sdrh     extern int Sqlitetest_func_Init(Tcl_Interp*);
306515926590Sdrh     extern int Sqlitetest_hexio_Init(Tcl_Interp*);
3066e1ab2193Sdan     extern int Sqlitetest_init_Init(Tcl_Interp*);
30672f999a67Sdrh     extern int Sqlitetest_malloc_Init(Tcl_Interp*);
30681a9ed0b2Sdanielk1977     extern int Sqlitetest_mutex_Init(Tcl_Interp*);
30692f999a67Sdrh     extern int Sqlitetestschema_Init(Tcl_Interp*);
30702f999a67Sdrh     extern int Sqlitetestsse_Init(Tcl_Interp*);
30712f999a67Sdrh     extern int Sqlitetesttclvar_Init(Tcl_Interp*);
307244918fa0Sdanielk1977     extern int SqlitetestThread_Init(Tcl_Interp*);
3073a15db353Sdanielk1977     extern int SqlitetestOnefile_Init();
30745d1f5aa6Sdanielk1977     extern int SqlitetestOsinst_Init(Tcl_Interp*);
30750410302eSdanielk1977     extern int Sqlitetestbackup_Init(Tcl_Interp*);
30762e66f0b9Sdrh 
30772f999a67Sdrh     Md5_Init(interp);
30782f999a67Sdrh     Sqliteconfig_Init(interp);
30796490bebdSdanielk1977     Sqlitetest1_Init(interp);
30805c4d9703Sdrh     Sqlitetest2_Init(interp);
3081de647130Sdrh     Sqlitetest3_Init(interp);
3082fc57d7bfSdanielk1977     Sqlitetest4_Init(interp);
3083998b56c3Sdanielk1977     Sqlitetest5_Init(interp);
30849c06c953Sdrh     Sqlitetest6_Init(interp);
308529c636bcSdrh     Sqlitetest7_Init(interp);
3086b9bb7c18Sdrh     Sqlitetest8_Init(interp);
3087a713f2c3Sdanielk1977     Sqlitetest9_Init(interp);
30882366940dSdrh     Sqlitetestasync_Init(interp);
30891409be69Sdrh     Sqlitetest_autoext_Init(interp);
3090984bfaa4Sdrh     Sqlitetest_func_Init(interp);
309115926590Sdrh     Sqlitetest_hexio_Init(interp);
3092e1ab2193Sdan     Sqlitetest_init_Init(interp);
30932f999a67Sdrh     Sqlitetest_malloc_Init(interp);
30941a9ed0b2Sdanielk1977     Sqlitetest_mutex_Init(interp);
30952f999a67Sdrh     Sqlitetestschema_Init(interp);
30962f999a67Sdrh     Sqlitetesttclvar_Init(interp);
309744918fa0Sdanielk1977     SqlitetestThread_Init(interp);
3098a15db353Sdanielk1977     SqlitetestOnefile_Init(interp);
30995d1f5aa6Sdanielk1977     SqlitetestOsinst_Init(interp);
31000410302eSdanielk1977     Sqlitetestbackup_Init(interp);
3101a15db353Sdanielk1977 
310289dec819Sdrh #ifdef SQLITE_SSE
31032e66f0b9Sdrh     Sqlitetestsse_Init(interp);
31042e66f0b9Sdrh #endif
3105d1bf3512Sdrh   }
3106d1bf3512Sdrh #endif
31073e27c026Sdrh   if( argc>=2 || TCLSH==2 ){
3108348784efSdrh     int i;
3109ad42c3a3Sshess     char zArgc[32];
3110ad42c3a3Sshess     sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-(3-TCLSH));
3111ad42c3a3Sshess     Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
3112348784efSdrh     Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
3113348784efSdrh     Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
311461212b69Sdrh     for(i=3-TCLSH; i<argc; i++){
3115348784efSdrh       Tcl_SetVar(interp, "argv", argv[i],
3116348784efSdrh           TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
3117348784efSdrh     }
31183e27c026Sdrh     if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
31190de8c112Sdrh       const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
3120a81c64a2Sdrh       if( zInfo==0 ) zInfo = Tcl_GetStringResult(interp);
3121c61053b7Sdrh       fprintf(stderr,"%s: %s\n", *argv, zInfo);
3122348784efSdrh       return 1;
3123348784efSdrh     }
31243e27c026Sdrh   }
31253e27c026Sdrh   if( argc<=1 || TCLSH==2 ){
3126348784efSdrh     Tcl_GlobalEval(interp, zMainloop);
3127348784efSdrh   }
3128348784efSdrh   return 0;
3129348784efSdrh }
3130348784efSdrh #endif /* TCLSH */
3131