xref: /freebsd/contrib/sqlite3/tea/generic/tclsqlite3.c (revision 4fe1295c964fa712dd763e3852187da8724ef79a)
1076b9443SCy Schubert #ifdef USE_SYSTEM_SQLITE
2076b9443SCy Schubert # include <sqlite3.h>
3076b9443SCy Schubert #else
4076b9443SCy Schubert #include "sqlite3.c"
5076b9443SCy Schubert #endif
6076b9443SCy Schubert /*
7076b9443SCy Schubert ** 2001 September 15
8076b9443SCy Schubert **
9076b9443SCy Schubert ** The author disclaims copyright to this source code.  In place of
10076b9443SCy Schubert ** a legal notice, here is a blessing:
11076b9443SCy Schubert **
12076b9443SCy Schubert **    May you do good and not evil.
13076b9443SCy Schubert **    May you find forgiveness for yourself and forgive others.
14076b9443SCy Schubert **    May you share freely, never taking more than you give.
15076b9443SCy Schubert **
16076b9443SCy Schubert *************************************************************************
17076b9443SCy Schubert ** A TCL Interface to SQLite.  Append this file to sqlite3.c and
18076b9443SCy Schubert ** compile the whole thing to build a TCL-enabled version of SQLite.
19076b9443SCy Schubert **
20076b9443SCy Schubert ** Compile-time options:
21076b9443SCy Schubert **
22076b9443SCy Schubert **  -DTCLSH         Add a "main()" routine that works as a tclsh.
23076b9443SCy Schubert **
24076b9443SCy Schubert **  -DTCLSH_INIT_PROC=name
25076b9443SCy Schubert **
26076b9443SCy Schubert **                  Invoke name(interp) to initialize the Tcl interpreter.
27076b9443SCy Schubert **                  If name(interp) returns a non-NULL string, then run
28076b9443SCy Schubert **                  that string as a Tcl script to launch the application.
29076b9443SCy Schubert **                  If name(interp) returns NULL, then run the regular
30076b9443SCy Schubert **                  tclsh-emulator code.
31076b9443SCy Schubert */
32076b9443SCy Schubert #ifdef TCLSH_INIT_PROC
33076b9443SCy Schubert # define TCLSH 1
34076b9443SCy Schubert #endif
35076b9443SCy Schubert 
36076b9443SCy Schubert /*
37076b9443SCy Schubert ** If requested, include the SQLite compiler options file for MSVC.
38076b9443SCy Schubert */
39076b9443SCy Schubert #if defined(INCLUDE_MSVC_H)
40076b9443SCy Schubert # include "msvc.h"
41076b9443SCy Schubert #endif
42076b9443SCy Schubert 
43076b9443SCy Schubert #if defined(INCLUDE_SQLITE_TCL_H)
44076b9443SCy Schubert # include "sqlite_tcl.h"
45076b9443SCy Schubert #else
46076b9443SCy Schubert # include "tcl.h"
47076b9443SCy Schubert # ifndef SQLITE_TCLAPI
48076b9443SCy Schubert #  define SQLITE_TCLAPI
49076b9443SCy Schubert # endif
50076b9443SCy Schubert #endif
51076b9443SCy Schubert #include <errno.h>
52076b9443SCy Schubert 
53076b9443SCy Schubert /*
54076b9443SCy Schubert ** Some additional include files are needed if this file is not
55076b9443SCy Schubert ** appended to the amalgamation.
56076b9443SCy Schubert */
57076b9443SCy Schubert #ifndef SQLITE_AMALGAMATION
58076b9443SCy Schubert # include "sqlite3.h"
59076b9443SCy Schubert # include <stdlib.h>
60076b9443SCy Schubert # include <string.h>
61076b9443SCy Schubert # include <assert.h>
62076b9443SCy Schubert   typedef unsigned char u8;
63076b9443SCy Schubert #endif
64076b9443SCy Schubert #include <ctype.h>
65076b9443SCy Schubert 
66076b9443SCy Schubert /* Used to get the current process ID */
67076b9443SCy Schubert #if !defined(_WIN32)
68076b9443SCy Schubert # include <signal.h>
69076b9443SCy Schubert # include <unistd.h>
70076b9443SCy Schubert # define GETPID getpid
71076b9443SCy Schubert #elif !defined(_WIN32_WCE)
72076b9443SCy Schubert # ifndef SQLITE_AMALGAMATION
73076b9443SCy Schubert #  ifndef WIN32_LEAN_AND_MEAN
74076b9443SCy Schubert #   define WIN32_LEAN_AND_MEAN
75076b9443SCy Schubert #  endif
76076b9443SCy Schubert #  include <windows.h>
77076b9443SCy Schubert # endif
78076b9443SCy Schubert # include <io.h>
79076b9443SCy Schubert # define isatty(h) _isatty(h)
80076b9443SCy Schubert # define GETPID (int)GetCurrentProcessId
81076b9443SCy Schubert #endif
82076b9443SCy Schubert 
83076b9443SCy Schubert /*
84076b9443SCy Schubert  * Windows needs to know which symbols to export.  Unix does not.
85076b9443SCy Schubert  * BUILD_sqlite should be undefined for Unix.
86076b9443SCy Schubert  */
87076b9443SCy Schubert #ifdef BUILD_sqlite
88076b9443SCy Schubert #undef TCL_STORAGE_CLASS
89076b9443SCy Schubert #define TCL_STORAGE_CLASS DLLEXPORT
90076b9443SCy Schubert #endif /* BUILD_sqlite */
91076b9443SCy Schubert 
92076b9443SCy Schubert #define NUM_PREPARED_STMTS 10
93076b9443SCy Schubert #define MAX_PREPARED_STMTS 100
94076b9443SCy Schubert 
95076b9443SCy Schubert /* Forward declaration */
96076b9443SCy Schubert typedef struct SqliteDb SqliteDb;
97076b9443SCy Schubert 
98076b9443SCy Schubert /*
99076b9443SCy Schubert ** New SQL functions can be created as TCL scripts.  Each such function
100076b9443SCy Schubert ** is described by an instance of the following structure.
10102273ca8SCy Schubert **
10202273ca8SCy Schubert ** Variable eType may be set to SQLITE_INTEGER, SQLITE_FLOAT, SQLITE_TEXT,
10302273ca8SCy Schubert ** SQLITE_BLOB or SQLITE_NULL. If it is SQLITE_NULL, then the implementation
10402273ca8SCy Schubert ** attempts to determine the type of the result based on the Tcl object.
10502273ca8SCy Schubert ** If it is SQLITE_TEXT or SQLITE_BLOB, then a text (sqlite3_result_text())
10602273ca8SCy Schubert ** or blob (sqlite3_result_blob()) is returned. If it is SQLITE_INTEGER
10702273ca8SCy Schubert ** or SQLITE_FLOAT, then an attempt is made to return an integer or float
10802273ca8SCy Schubert ** value, falling back to float and then text if this is not possible.
109076b9443SCy Schubert */
110076b9443SCy Schubert typedef struct SqlFunc SqlFunc;
111076b9443SCy Schubert struct SqlFunc {
112076b9443SCy Schubert   Tcl_Interp *interp;   /* The TCL interpret to execute the function */
113076b9443SCy Schubert   Tcl_Obj *pScript;     /* The Tcl_Obj representation of the script */
114076b9443SCy Schubert   SqliteDb *pDb;        /* Database connection that owns this function */
115076b9443SCy Schubert   int useEvalObjv;      /* True if it is safe to use Tcl_EvalObjv */
11602273ca8SCy Schubert   int eType;            /* Type of value to return */
117076b9443SCy Schubert   char *zName;          /* Name of this function */
118076b9443SCy Schubert   SqlFunc *pNext;       /* Next function on the list of them all */
119076b9443SCy Schubert };
120076b9443SCy Schubert 
121076b9443SCy Schubert /*
122076b9443SCy Schubert ** New collation sequences function can be created as TCL scripts.  Each such
123076b9443SCy Schubert ** function is described by an instance of the following structure.
124076b9443SCy Schubert */
125076b9443SCy Schubert typedef struct SqlCollate SqlCollate;
126076b9443SCy Schubert struct SqlCollate {
127076b9443SCy Schubert   Tcl_Interp *interp;   /* The TCL interpret to execute the function */
128076b9443SCy Schubert   char *zScript;        /* The script to be run */
129076b9443SCy Schubert   SqlCollate *pNext;    /* Next function on the list of them all */
130076b9443SCy Schubert };
131076b9443SCy Schubert 
132076b9443SCy Schubert /*
133076b9443SCy Schubert ** Prepared statements are cached for faster execution.  Each prepared
134076b9443SCy Schubert ** statement is described by an instance of the following structure.
135076b9443SCy Schubert */
136076b9443SCy Schubert typedef struct SqlPreparedStmt SqlPreparedStmt;
137076b9443SCy Schubert struct SqlPreparedStmt {
138076b9443SCy Schubert   SqlPreparedStmt *pNext;  /* Next in linked list */
139076b9443SCy Schubert   SqlPreparedStmt *pPrev;  /* Previous on the list */
140076b9443SCy Schubert   sqlite3_stmt *pStmt;     /* The prepared statement */
141076b9443SCy Schubert   int nSql;                /* chars in zSql[] */
142076b9443SCy Schubert   const char *zSql;        /* Text of the SQL statement */
143076b9443SCy Schubert   int nParm;               /* Size of apParm array */
144076b9443SCy Schubert   Tcl_Obj **apParm;        /* Array of referenced object pointers */
145076b9443SCy Schubert };
146076b9443SCy Schubert 
147076b9443SCy Schubert typedef struct IncrblobChannel IncrblobChannel;
148076b9443SCy Schubert 
149076b9443SCy Schubert /*
150076b9443SCy Schubert ** There is one instance of this structure for each SQLite database
151076b9443SCy Schubert ** that has been opened by the SQLite TCL interface.
152076b9443SCy Schubert **
153076b9443SCy Schubert ** If this module is built with SQLITE_TEST defined (to create the SQLite
154076b9443SCy Schubert ** testfixture executable), then it may be configured to use either
155076b9443SCy Schubert ** sqlite3_prepare_v2() or sqlite3_prepare() to prepare SQL statements.
156076b9443SCy Schubert ** If SqliteDb.bLegacyPrepare is true, sqlite3_prepare() is used.
157076b9443SCy Schubert */
158076b9443SCy Schubert struct SqliteDb {
159076b9443SCy Schubert   sqlite3 *db;               /* The "real" database structure. MUST BE FIRST */
160076b9443SCy Schubert   Tcl_Interp *interp;        /* The interpreter used for this database */
161076b9443SCy Schubert   char *zBusy;               /* The busy callback routine */
162076b9443SCy Schubert   char *zCommit;             /* The commit hook callback routine */
163076b9443SCy Schubert   char *zTrace;              /* The trace callback routine */
164076b9443SCy Schubert   char *zTraceV2;            /* The trace_v2 callback routine */
165076b9443SCy Schubert   char *zProfile;            /* The profile callback routine */
166076b9443SCy Schubert   char *zProgress;           /* The progress callback routine */
16702273ca8SCy Schubert   char *zBindFallback;       /* Callback to invoke on a binding miss */
168076b9443SCy Schubert   char *zAuth;               /* The authorization callback routine */
169076b9443SCy Schubert   int disableAuth;           /* Disable the authorizer if it exists */
170076b9443SCy Schubert   char *zNull;               /* Text to substitute for an SQL NULL value */
171076b9443SCy Schubert   SqlFunc *pFunc;            /* List of SQL functions */
172076b9443SCy Schubert   Tcl_Obj *pUpdateHook;      /* Update hook script (if any) */
173076b9443SCy Schubert   Tcl_Obj *pPreUpdateHook;   /* Pre-update hook script (if any) */
174076b9443SCy Schubert   Tcl_Obj *pRollbackHook;    /* Rollback hook script (if any) */
175076b9443SCy Schubert   Tcl_Obj *pWalHook;         /* WAL hook script (if any) */
176076b9443SCy Schubert   Tcl_Obj *pUnlockNotify;    /* Unlock notify script (if any) */
177076b9443SCy Schubert   SqlCollate *pCollate;      /* List of SQL collation functions */
178076b9443SCy Schubert   int rc;                    /* Return code of most recent sqlite3_exec() */
179076b9443SCy Schubert   Tcl_Obj *pCollateNeeded;   /* Collation needed script */
180076b9443SCy Schubert   SqlPreparedStmt *stmtList; /* List of prepared statements*/
181076b9443SCy Schubert   SqlPreparedStmt *stmtLast; /* Last statement in the list */
182076b9443SCy Schubert   int maxStmt;               /* The next maximum number of stmtList */
183076b9443SCy Schubert   int nStmt;                 /* Number of statements in stmtList */
184076b9443SCy Schubert   IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */
185076b9443SCy Schubert   int nStep, nSort, nIndex;  /* Statistics for most recent operation */
186076b9443SCy Schubert   int nVMStep;               /* Another statistic for most recent operation */
187076b9443SCy Schubert   int nTransaction;          /* Number of nested [transaction] methods */
188076b9443SCy Schubert   int openFlags;             /* Flags used to open.  (SQLITE_OPEN_URI) */
1890197ba46SCy Schubert   int nRef;                  /* Delete object when this reaches 0 */
190076b9443SCy Schubert #ifdef SQLITE_TEST
191076b9443SCy Schubert   int bLegacyPrepare;        /* True to use sqlite3_prepare() */
192076b9443SCy Schubert #endif
193076b9443SCy Schubert };
194076b9443SCy Schubert 
195076b9443SCy Schubert struct IncrblobChannel {
196076b9443SCy Schubert   sqlite3_blob *pBlob;      /* sqlite3 blob handle */
197076b9443SCy Schubert   SqliteDb *pDb;            /* Associated database connection */
198076b9443SCy Schubert   int iSeek;                /* Current seek offset */
199076b9443SCy Schubert   Tcl_Channel channel;      /* Channel identifier */
200076b9443SCy Schubert   IncrblobChannel *pNext;   /* Linked list of all open incrblob channels */
201076b9443SCy Schubert   IncrblobChannel *pPrev;   /* Linked list of all open incrblob channels */
202076b9443SCy Schubert };
203076b9443SCy Schubert 
204076b9443SCy Schubert /*
205076b9443SCy Schubert ** Compute a string length that is limited to what can be stored in
206076b9443SCy Schubert ** lower 30 bits of a 32-bit signed integer.
207076b9443SCy Schubert */
208076b9443SCy Schubert static int strlen30(const char *z){
209076b9443SCy Schubert   const char *z2 = z;
210076b9443SCy Schubert   while( *z2 ){ z2++; }
211076b9443SCy Schubert   return 0x3fffffff & (int)(z2 - z);
212076b9443SCy Schubert }
213076b9443SCy Schubert 
214076b9443SCy Schubert 
215076b9443SCy Schubert #ifndef SQLITE_OMIT_INCRBLOB
216076b9443SCy Schubert /*
217076b9443SCy Schubert ** Close all incrblob channels opened using database connection pDb.
218076b9443SCy Schubert ** This is called when shutting down the database connection.
219076b9443SCy Schubert */
220076b9443SCy Schubert static void closeIncrblobChannels(SqliteDb *pDb){
221076b9443SCy Schubert   IncrblobChannel *p;
222076b9443SCy Schubert   IncrblobChannel *pNext;
223076b9443SCy Schubert 
224076b9443SCy Schubert   for(p=pDb->pIncrblob; p; p=pNext){
225076b9443SCy Schubert     pNext = p->pNext;
226076b9443SCy Schubert 
227076b9443SCy Schubert     /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
228076b9443SCy Schubert     ** which deletes the IncrblobChannel structure at *p. So do not
229076b9443SCy Schubert     ** call Tcl_Free() here.
230076b9443SCy Schubert     */
231076b9443SCy Schubert     Tcl_UnregisterChannel(pDb->interp, p->channel);
232076b9443SCy Schubert   }
233076b9443SCy Schubert }
234076b9443SCy Schubert 
235076b9443SCy Schubert /*
236076b9443SCy Schubert ** Close an incremental blob channel.
237076b9443SCy Schubert */
238076b9443SCy Schubert static int SQLITE_TCLAPI incrblobClose(
239076b9443SCy Schubert   ClientData instanceData,
240076b9443SCy Schubert   Tcl_Interp *interp
241076b9443SCy Schubert ){
242076b9443SCy Schubert   IncrblobChannel *p = (IncrblobChannel *)instanceData;
243076b9443SCy Schubert   int rc = sqlite3_blob_close(p->pBlob);
244076b9443SCy Schubert   sqlite3 *db = p->pDb->db;
245076b9443SCy Schubert 
246076b9443SCy Schubert   /* Remove the channel from the SqliteDb.pIncrblob list. */
247076b9443SCy Schubert   if( p->pNext ){
248076b9443SCy Schubert     p->pNext->pPrev = p->pPrev;
249076b9443SCy Schubert   }
250076b9443SCy Schubert   if( p->pPrev ){
251076b9443SCy Schubert     p->pPrev->pNext = p->pNext;
252076b9443SCy Schubert   }
253076b9443SCy Schubert   if( p->pDb->pIncrblob==p ){
254076b9443SCy Schubert     p->pDb->pIncrblob = p->pNext;
255076b9443SCy Schubert   }
256076b9443SCy Schubert 
257076b9443SCy Schubert   /* Free the IncrblobChannel structure */
258076b9443SCy Schubert   Tcl_Free((char *)p);
259076b9443SCy Schubert 
260076b9443SCy Schubert   if( rc!=SQLITE_OK ){
261076b9443SCy Schubert     Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
262076b9443SCy Schubert     return TCL_ERROR;
263076b9443SCy Schubert   }
264076b9443SCy Schubert   return TCL_OK;
265076b9443SCy Schubert }
266076b9443SCy Schubert 
267076b9443SCy Schubert /*
268076b9443SCy Schubert ** Read data from an incremental blob channel.
269076b9443SCy Schubert */
270076b9443SCy Schubert static int SQLITE_TCLAPI incrblobInput(
271076b9443SCy Schubert   ClientData instanceData,
272076b9443SCy Schubert   char *buf,
273076b9443SCy Schubert   int bufSize,
274076b9443SCy Schubert   int *errorCodePtr
275076b9443SCy Schubert ){
276076b9443SCy Schubert   IncrblobChannel *p = (IncrblobChannel *)instanceData;
277076b9443SCy Schubert   int nRead = bufSize;         /* Number of bytes to read */
278076b9443SCy Schubert   int nBlob;                   /* Total size of the blob */
279076b9443SCy Schubert   int rc;                      /* sqlite error code */
280076b9443SCy Schubert 
281076b9443SCy Schubert   nBlob = sqlite3_blob_bytes(p->pBlob);
282076b9443SCy Schubert   if( (p->iSeek+nRead)>nBlob ){
283076b9443SCy Schubert     nRead = nBlob-p->iSeek;
284076b9443SCy Schubert   }
285076b9443SCy Schubert   if( nRead<=0 ){
286076b9443SCy Schubert     return 0;
287076b9443SCy Schubert   }
288076b9443SCy Schubert 
289076b9443SCy Schubert   rc = sqlite3_blob_read(p->pBlob, (void *)buf, nRead, p->iSeek);
290076b9443SCy Schubert   if( rc!=SQLITE_OK ){
291076b9443SCy Schubert     *errorCodePtr = rc;
292076b9443SCy Schubert     return -1;
293076b9443SCy Schubert   }
294076b9443SCy Schubert 
295076b9443SCy Schubert   p->iSeek += nRead;
296076b9443SCy Schubert   return nRead;
297076b9443SCy Schubert }
298076b9443SCy Schubert 
299076b9443SCy Schubert /*
300076b9443SCy Schubert ** Write data to an incremental blob channel.
301076b9443SCy Schubert */
302076b9443SCy Schubert static int SQLITE_TCLAPI incrblobOutput(
303076b9443SCy Schubert   ClientData instanceData,
304076b9443SCy Schubert   CONST char *buf,
305076b9443SCy Schubert   int toWrite,
306076b9443SCy Schubert   int *errorCodePtr
307076b9443SCy Schubert ){
308076b9443SCy Schubert   IncrblobChannel *p = (IncrblobChannel *)instanceData;
309076b9443SCy Schubert   int nWrite = toWrite;        /* Number of bytes to write */
310076b9443SCy Schubert   int nBlob;                   /* Total size of the blob */
311076b9443SCy Schubert   int rc;                      /* sqlite error code */
312076b9443SCy Schubert 
313076b9443SCy Schubert   nBlob = sqlite3_blob_bytes(p->pBlob);
314076b9443SCy Schubert   if( (p->iSeek+nWrite)>nBlob ){
315076b9443SCy Schubert     *errorCodePtr = EINVAL;
316076b9443SCy Schubert     return -1;
317076b9443SCy Schubert   }
318076b9443SCy Schubert   if( nWrite<=0 ){
319076b9443SCy Schubert     return 0;
320076b9443SCy Schubert   }
321076b9443SCy Schubert 
322076b9443SCy Schubert   rc = sqlite3_blob_write(p->pBlob, (void *)buf, nWrite, p->iSeek);
323076b9443SCy Schubert   if( rc!=SQLITE_OK ){
324076b9443SCy Schubert     *errorCodePtr = EIO;
325076b9443SCy Schubert     return -1;
326076b9443SCy Schubert   }
327076b9443SCy Schubert 
328076b9443SCy Schubert   p->iSeek += nWrite;
329076b9443SCy Schubert   return nWrite;
330076b9443SCy Schubert }
331076b9443SCy Schubert 
332076b9443SCy Schubert /*
333076b9443SCy Schubert ** Seek an incremental blob channel.
334076b9443SCy Schubert */
335076b9443SCy Schubert static int SQLITE_TCLAPI incrblobSeek(
336076b9443SCy Schubert   ClientData instanceData,
337076b9443SCy Schubert   long offset,
338076b9443SCy Schubert   int seekMode,
339076b9443SCy Schubert   int *errorCodePtr
340076b9443SCy Schubert ){
341076b9443SCy Schubert   IncrblobChannel *p = (IncrblobChannel *)instanceData;
342076b9443SCy Schubert 
343076b9443SCy Schubert   switch( seekMode ){
344076b9443SCy Schubert     case SEEK_SET:
345076b9443SCy Schubert       p->iSeek = offset;
346076b9443SCy Schubert       break;
347076b9443SCy Schubert     case SEEK_CUR:
348076b9443SCy Schubert       p->iSeek += offset;
349076b9443SCy Schubert       break;
350076b9443SCy Schubert     case SEEK_END:
351076b9443SCy Schubert       p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset;
352076b9443SCy Schubert       break;
353076b9443SCy Schubert 
354076b9443SCy Schubert     default: assert(!"Bad seekMode");
355076b9443SCy Schubert   }
356076b9443SCy Schubert 
357076b9443SCy Schubert   return p->iSeek;
358076b9443SCy Schubert }
359076b9443SCy Schubert 
360076b9443SCy Schubert 
361076b9443SCy Schubert static void SQLITE_TCLAPI incrblobWatch(
362076b9443SCy Schubert   ClientData instanceData,
363076b9443SCy Schubert   int mode
364076b9443SCy Schubert ){
365076b9443SCy Schubert   /* NO-OP */
366076b9443SCy Schubert }
367076b9443SCy Schubert static int SQLITE_TCLAPI incrblobHandle(
368076b9443SCy Schubert   ClientData instanceData,
369076b9443SCy Schubert   int dir,
370076b9443SCy Schubert   ClientData *hPtr
371076b9443SCy Schubert ){
372076b9443SCy Schubert   return TCL_ERROR;
373076b9443SCy Schubert }
374076b9443SCy Schubert 
375076b9443SCy Schubert static Tcl_ChannelType IncrblobChannelType = {
376076b9443SCy Schubert   "incrblob",                        /* typeName                             */
377076b9443SCy Schubert   TCL_CHANNEL_VERSION_2,             /* version                              */
378076b9443SCy Schubert   incrblobClose,                     /* closeProc                            */
379076b9443SCy Schubert   incrblobInput,                     /* inputProc                            */
380076b9443SCy Schubert   incrblobOutput,                    /* outputProc                           */
381076b9443SCy Schubert   incrblobSeek,                      /* seekProc                             */
382076b9443SCy Schubert   0,                                 /* setOptionProc                        */
383076b9443SCy Schubert   0,                                 /* getOptionProc                        */
384076b9443SCy Schubert   incrblobWatch,                     /* watchProc (this is a no-op)          */
385076b9443SCy Schubert   incrblobHandle,                    /* getHandleProc (always returns error) */
386076b9443SCy Schubert   0,                                 /* close2Proc                           */
387076b9443SCy Schubert   0,                                 /* blockModeProc                        */
388076b9443SCy Schubert   0,                                 /* flushProc                            */
389076b9443SCy Schubert   0,                                 /* handlerProc                          */
390076b9443SCy Schubert   0,                                 /* wideSeekProc                         */
391076b9443SCy Schubert };
392076b9443SCy Schubert 
393076b9443SCy Schubert /*
394076b9443SCy Schubert ** Create a new incrblob channel.
395076b9443SCy Schubert */
396076b9443SCy Schubert static int createIncrblobChannel(
397076b9443SCy Schubert   Tcl_Interp *interp,
398076b9443SCy Schubert   SqliteDb *pDb,
399076b9443SCy Schubert   const char *zDb,
400076b9443SCy Schubert   const char *zTable,
401076b9443SCy Schubert   const char *zColumn,
402076b9443SCy Schubert   sqlite_int64 iRow,
403076b9443SCy Schubert   int isReadonly
404076b9443SCy Schubert ){
405076b9443SCy Schubert   IncrblobChannel *p;
406076b9443SCy Schubert   sqlite3 *db = pDb->db;
407076b9443SCy Schubert   sqlite3_blob *pBlob;
408076b9443SCy Schubert   int rc;
409076b9443SCy Schubert   int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE);
410076b9443SCy Schubert 
411076b9443SCy Schubert   /* This variable is used to name the channels: "incrblob_[incr count]" */
412076b9443SCy Schubert   static int count = 0;
413076b9443SCy Schubert   char zChannel[64];
414076b9443SCy Schubert 
415076b9443SCy Schubert   rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob);
416076b9443SCy Schubert   if( rc!=SQLITE_OK ){
417076b9443SCy Schubert     Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
418076b9443SCy Schubert     return TCL_ERROR;
419076b9443SCy Schubert   }
420076b9443SCy Schubert 
421076b9443SCy Schubert   p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel));
422076b9443SCy Schubert   p->iSeek = 0;
423076b9443SCy Schubert   p->pBlob = pBlob;
424076b9443SCy Schubert 
425076b9443SCy Schubert   sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count);
426076b9443SCy Schubert   p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags);
427076b9443SCy Schubert   Tcl_RegisterChannel(interp, p->channel);
428076b9443SCy Schubert 
429076b9443SCy Schubert   /* Link the new channel into the SqliteDb.pIncrblob list. */
430076b9443SCy Schubert   p->pNext = pDb->pIncrblob;
431076b9443SCy Schubert   p->pPrev = 0;
432076b9443SCy Schubert   if( p->pNext ){
433076b9443SCy Schubert     p->pNext->pPrev = p;
434076b9443SCy Schubert   }
435076b9443SCy Schubert   pDb->pIncrblob = p;
436076b9443SCy Schubert   p->pDb = pDb;
437076b9443SCy Schubert 
438076b9443SCy Schubert   Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE);
439076b9443SCy Schubert   return TCL_OK;
440076b9443SCy Schubert }
441076b9443SCy Schubert #else  /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
442076b9443SCy Schubert   #define closeIncrblobChannels(pDb)
443076b9443SCy Schubert #endif
444076b9443SCy Schubert 
445076b9443SCy Schubert /*
446076b9443SCy Schubert ** Look at the script prefix in pCmd.  We will be executing this script
447076b9443SCy Schubert ** after first appending one or more arguments.  This routine analyzes
448076b9443SCy Schubert ** the script to see if it is safe to use Tcl_EvalObjv() on the script
449076b9443SCy Schubert ** rather than the more general Tcl_EvalEx().  Tcl_EvalObjv() is much
450076b9443SCy Schubert ** faster.
451076b9443SCy Schubert **
452076b9443SCy Schubert ** Scripts that are safe to use with Tcl_EvalObjv() consists of a
453076b9443SCy Schubert ** command name followed by zero or more arguments with no [...] or $
454076b9443SCy Schubert ** or {...} or ; to be seen anywhere.  Most callback scripts consist
455076b9443SCy Schubert ** of just a single procedure name and they meet this requirement.
456076b9443SCy Schubert */
457076b9443SCy Schubert static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
458076b9443SCy Schubert   /* We could try to do something with Tcl_Parse().  But we will instead
459076b9443SCy Schubert   ** just do a search for forbidden characters.  If any of the forbidden
460076b9443SCy Schubert   ** characters appear in pCmd, we will report the string as unsafe.
461076b9443SCy Schubert   */
462076b9443SCy Schubert   const char *z;
463076b9443SCy Schubert   int n;
464076b9443SCy Schubert   z = Tcl_GetStringFromObj(pCmd, &n);
465076b9443SCy Schubert   while( n-- > 0 ){
466076b9443SCy Schubert     int c = *(z++);
467076b9443SCy Schubert     if( c=='$' || c=='[' || c==';' ) return 0;
468076b9443SCy Schubert   }
469076b9443SCy Schubert   return 1;
470076b9443SCy Schubert }
471076b9443SCy Schubert 
472076b9443SCy Schubert /*
473076b9443SCy Schubert ** Find an SqlFunc structure with the given name.  Or create a new
474076b9443SCy Schubert ** one if an existing one cannot be found.  Return a pointer to the
475076b9443SCy Schubert ** structure.
476076b9443SCy Schubert */
477076b9443SCy Schubert static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
478076b9443SCy Schubert   SqlFunc *p, *pNew;
479076b9443SCy Schubert   int nName = strlen30(zName);
480076b9443SCy Schubert   pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + nName + 1 );
481076b9443SCy Schubert   pNew->zName = (char*)&pNew[1];
482076b9443SCy Schubert   memcpy(pNew->zName, zName, nName+1);
483076b9443SCy Schubert   for(p=pDb->pFunc; p; p=p->pNext){
484076b9443SCy Schubert     if( sqlite3_stricmp(p->zName, pNew->zName)==0 ){
485076b9443SCy Schubert       Tcl_Free((char*)pNew);
486076b9443SCy Schubert       return p;
487076b9443SCy Schubert     }
488076b9443SCy Schubert   }
489076b9443SCy Schubert   pNew->interp = pDb->interp;
490076b9443SCy Schubert   pNew->pDb = pDb;
491076b9443SCy Schubert   pNew->pScript = 0;
492076b9443SCy Schubert   pNew->pNext = pDb->pFunc;
493076b9443SCy Schubert   pDb->pFunc = pNew;
494076b9443SCy Schubert   return pNew;
495076b9443SCy Schubert }
496076b9443SCy Schubert 
497076b9443SCy Schubert /*
498076b9443SCy Schubert ** Free a single SqlPreparedStmt object.
499076b9443SCy Schubert */
500076b9443SCy Schubert static void dbFreeStmt(SqlPreparedStmt *pStmt){
501076b9443SCy Schubert #ifdef SQLITE_TEST
502076b9443SCy Schubert   if( sqlite3_sql(pStmt->pStmt)==0 ){
503076b9443SCy Schubert     Tcl_Free((char *)pStmt->zSql);
504076b9443SCy Schubert   }
505076b9443SCy Schubert #endif
506076b9443SCy Schubert   sqlite3_finalize(pStmt->pStmt);
507076b9443SCy Schubert   Tcl_Free((char *)pStmt);
508076b9443SCy Schubert }
509076b9443SCy Schubert 
510076b9443SCy Schubert /*
511076b9443SCy Schubert ** Finalize and free a list of prepared statements
512076b9443SCy Schubert */
513076b9443SCy Schubert static void flushStmtCache(SqliteDb *pDb){
514076b9443SCy Schubert   SqlPreparedStmt *pPreStmt;
515076b9443SCy Schubert   SqlPreparedStmt *pNext;
516076b9443SCy Schubert 
517076b9443SCy Schubert   for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pNext){
518076b9443SCy Schubert     pNext = pPreStmt->pNext;
519076b9443SCy Schubert     dbFreeStmt(pPreStmt);
520076b9443SCy Schubert   }
521076b9443SCy Schubert   pDb->nStmt = 0;
522076b9443SCy Schubert   pDb->stmtLast = 0;
523076b9443SCy Schubert   pDb->stmtList = 0;
524076b9443SCy Schubert }
525076b9443SCy Schubert 
526076b9443SCy Schubert /*
5270197ba46SCy Schubert ** Increment the reference counter on the SqliteDb object. The reference
5280197ba46SCy Schubert ** should be released by calling delDatabaseRef().
529076b9443SCy Schubert */
5300197ba46SCy Schubert static void addDatabaseRef(SqliteDb *pDb){
5310197ba46SCy Schubert   pDb->nRef++;
5320197ba46SCy Schubert }
5330197ba46SCy Schubert 
5340197ba46SCy Schubert /*
5350197ba46SCy Schubert ** Decrement the reference counter associated with the SqliteDb object.
5360197ba46SCy Schubert ** If it reaches zero, delete the object.
5370197ba46SCy Schubert */
5380197ba46SCy Schubert static void delDatabaseRef(SqliteDb *pDb){
5390197ba46SCy Schubert   assert( pDb->nRef>0 );
5400197ba46SCy Schubert   pDb->nRef--;
5410197ba46SCy Schubert   if( pDb->nRef==0 ){
542076b9443SCy Schubert     flushStmtCache(pDb);
543076b9443SCy Schubert     closeIncrblobChannels(pDb);
544076b9443SCy Schubert     sqlite3_close(pDb->db);
545076b9443SCy Schubert     while( pDb->pFunc ){
546076b9443SCy Schubert       SqlFunc *pFunc = pDb->pFunc;
547076b9443SCy Schubert       pDb->pFunc = pFunc->pNext;
548076b9443SCy Schubert       assert( pFunc->pDb==pDb );
549076b9443SCy Schubert       Tcl_DecrRefCount(pFunc->pScript);
550076b9443SCy Schubert       Tcl_Free((char*)pFunc);
551076b9443SCy Schubert     }
552076b9443SCy Schubert     while( pDb->pCollate ){
553076b9443SCy Schubert       SqlCollate *pCollate = pDb->pCollate;
554076b9443SCy Schubert       pDb->pCollate = pCollate->pNext;
555076b9443SCy Schubert       Tcl_Free((char*)pCollate);
556076b9443SCy Schubert     }
557076b9443SCy Schubert     if( pDb->zBusy ){
558076b9443SCy Schubert       Tcl_Free(pDb->zBusy);
559076b9443SCy Schubert     }
560076b9443SCy Schubert     if( pDb->zTrace ){
561076b9443SCy Schubert       Tcl_Free(pDb->zTrace);
562076b9443SCy Schubert     }
563076b9443SCy Schubert     if( pDb->zTraceV2 ){
564076b9443SCy Schubert       Tcl_Free(pDb->zTraceV2);
565076b9443SCy Schubert     }
566076b9443SCy Schubert     if( pDb->zProfile ){
567076b9443SCy Schubert       Tcl_Free(pDb->zProfile);
568076b9443SCy Schubert     }
56902273ca8SCy Schubert     if( pDb->zBindFallback ){
57002273ca8SCy Schubert       Tcl_Free(pDb->zBindFallback);
57102273ca8SCy Schubert     }
572076b9443SCy Schubert     if( pDb->zAuth ){
573076b9443SCy Schubert       Tcl_Free(pDb->zAuth);
574076b9443SCy Schubert     }
575076b9443SCy Schubert     if( pDb->zNull ){
576076b9443SCy Schubert       Tcl_Free(pDb->zNull);
577076b9443SCy Schubert     }
578076b9443SCy Schubert     if( pDb->pUpdateHook ){
579076b9443SCy Schubert       Tcl_DecrRefCount(pDb->pUpdateHook);
580076b9443SCy Schubert     }
581076b9443SCy Schubert     if( pDb->pPreUpdateHook ){
582076b9443SCy Schubert       Tcl_DecrRefCount(pDb->pPreUpdateHook);
583076b9443SCy Schubert     }
584076b9443SCy Schubert     if( pDb->pRollbackHook ){
585076b9443SCy Schubert       Tcl_DecrRefCount(pDb->pRollbackHook);
586076b9443SCy Schubert     }
587076b9443SCy Schubert     if( pDb->pWalHook ){
588076b9443SCy Schubert       Tcl_DecrRefCount(pDb->pWalHook);
589076b9443SCy Schubert     }
590076b9443SCy Schubert     if( pDb->pCollateNeeded ){
591076b9443SCy Schubert       Tcl_DecrRefCount(pDb->pCollateNeeded);
592076b9443SCy Schubert     }
593076b9443SCy Schubert     Tcl_Free((char*)pDb);
594076b9443SCy Schubert   }
5950197ba46SCy Schubert }
5960197ba46SCy Schubert 
5970197ba46SCy Schubert /*
5980197ba46SCy Schubert ** TCL calls this procedure when an sqlite3 database command is
5990197ba46SCy Schubert ** deleted.
6000197ba46SCy Schubert */
6010197ba46SCy Schubert static void SQLITE_TCLAPI DbDeleteCmd(void *db){
6020197ba46SCy Schubert   SqliteDb *pDb = (SqliteDb*)db;
6030197ba46SCy Schubert   delDatabaseRef(pDb);
6040197ba46SCy Schubert }
605076b9443SCy Schubert 
606076b9443SCy Schubert /*
607076b9443SCy Schubert ** This routine is called when a database file is locked while trying
608076b9443SCy Schubert ** to execute SQL.
609076b9443SCy Schubert */
610076b9443SCy Schubert static int DbBusyHandler(void *cd, int nTries){
611076b9443SCy Schubert   SqliteDb *pDb = (SqliteDb*)cd;
612076b9443SCy Schubert   int rc;
613076b9443SCy Schubert   char zVal[30];
614076b9443SCy Schubert 
615076b9443SCy Schubert   sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries);
616076b9443SCy Schubert   rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
617076b9443SCy Schubert   if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
618076b9443SCy Schubert     return 0;
619076b9443SCy Schubert   }
620076b9443SCy Schubert   return 1;
621076b9443SCy Schubert }
622076b9443SCy Schubert 
623076b9443SCy Schubert #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
624076b9443SCy Schubert /*
625076b9443SCy Schubert ** This routine is invoked as the 'progress callback' for the database.
626076b9443SCy Schubert */
627076b9443SCy Schubert static int DbProgressHandler(void *cd){
628076b9443SCy Schubert   SqliteDb *pDb = (SqliteDb*)cd;
629076b9443SCy Schubert   int rc;
630076b9443SCy Schubert 
631076b9443SCy Schubert   assert( pDb->zProgress );
632076b9443SCy Schubert   rc = Tcl_Eval(pDb->interp, pDb->zProgress);
633076b9443SCy Schubert   if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
634076b9443SCy Schubert     return 1;
635076b9443SCy Schubert   }
636076b9443SCy Schubert   return 0;
637076b9443SCy Schubert }
638076b9443SCy Schubert #endif
639076b9443SCy Schubert 
640076b9443SCy Schubert #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
641076b9443SCy Schubert     !defined(SQLITE_OMIT_DEPRECATED)
642076b9443SCy Schubert /*
643076b9443SCy Schubert ** This routine is called by the SQLite trace handler whenever a new
644076b9443SCy Schubert ** block of SQL is executed.  The TCL script in pDb->zTrace is executed.
645076b9443SCy Schubert */
646076b9443SCy Schubert static void DbTraceHandler(void *cd, const char *zSql){
647076b9443SCy Schubert   SqliteDb *pDb = (SqliteDb*)cd;
648076b9443SCy Schubert   Tcl_DString str;
649076b9443SCy Schubert 
650076b9443SCy Schubert   Tcl_DStringInit(&str);
651076b9443SCy Schubert   Tcl_DStringAppend(&str, pDb->zTrace, -1);
652076b9443SCy Schubert   Tcl_DStringAppendElement(&str, zSql);
653076b9443SCy Schubert   Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
654076b9443SCy Schubert   Tcl_DStringFree(&str);
655076b9443SCy Schubert   Tcl_ResetResult(pDb->interp);
656076b9443SCy Schubert }
657076b9443SCy Schubert #endif
658076b9443SCy Schubert 
659076b9443SCy Schubert #ifndef SQLITE_OMIT_TRACE
660076b9443SCy Schubert /*
661076b9443SCy Schubert ** This routine is called by the SQLite trace_v2 handler whenever a new
662076b9443SCy Schubert ** supported event is generated.  Unsupported event types are ignored.
663076b9443SCy Schubert ** The TCL script in pDb->zTraceV2 is executed, with the arguments for
664076b9443SCy Schubert ** the event appended to it (as list elements).
665076b9443SCy Schubert */
666076b9443SCy Schubert static int DbTraceV2Handler(
667076b9443SCy Schubert   unsigned type, /* One of the SQLITE_TRACE_* event types. */
668076b9443SCy Schubert   void *cd,      /* The original context data pointer. */
669076b9443SCy Schubert   void *pd,      /* Primary event data, depends on event type. */
670076b9443SCy Schubert   void *xd       /* Extra event data, depends on event type. */
671076b9443SCy Schubert ){
672076b9443SCy Schubert   SqliteDb *pDb = (SqliteDb*)cd;
673076b9443SCy Schubert   Tcl_Obj *pCmd;
674076b9443SCy Schubert 
675076b9443SCy Schubert   switch( type ){
676076b9443SCy Schubert     case SQLITE_TRACE_STMT: {
677076b9443SCy Schubert       sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;
678076b9443SCy Schubert       char *zSql = (char *)xd;
679076b9443SCy Schubert 
680076b9443SCy Schubert       pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
681076b9443SCy Schubert       Tcl_IncrRefCount(pCmd);
682076b9443SCy Schubert       Tcl_ListObjAppendElement(pDb->interp, pCmd,
683076b9443SCy Schubert                                Tcl_NewWideIntObj((Tcl_WideInt)pStmt));
684076b9443SCy Schubert       Tcl_ListObjAppendElement(pDb->interp, pCmd,
685076b9443SCy Schubert                                Tcl_NewStringObj(zSql, -1));
686076b9443SCy Schubert       Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
687076b9443SCy Schubert       Tcl_DecrRefCount(pCmd);
688076b9443SCy Schubert       Tcl_ResetResult(pDb->interp);
689076b9443SCy Schubert       break;
690076b9443SCy Schubert     }
691076b9443SCy Schubert     case SQLITE_TRACE_PROFILE: {
692076b9443SCy Schubert       sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;
693076b9443SCy Schubert       sqlite3_int64 ns = *(sqlite3_int64*)xd;
694076b9443SCy Schubert 
695076b9443SCy Schubert       pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
696076b9443SCy Schubert       Tcl_IncrRefCount(pCmd);
697076b9443SCy Schubert       Tcl_ListObjAppendElement(pDb->interp, pCmd,
698076b9443SCy Schubert                                Tcl_NewWideIntObj((Tcl_WideInt)pStmt));
699076b9443SCy Schubert       Tcl_ListObjAppendElement(pDb->interp, pCmd,
700076b9443SCy Schubert                                Tcl_NewWideIntObj((Tcl_WideInt)ns));
701076b9443SCy Schubert       Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
702076b9443SCy Schubert       Tcl_DecrRefCount(pCmd);
703076b9443SCy Schubert       Tcl_ResetResult(pDb->interp);
704076b9443SCy Schubert       break;
705076b9443SCy Schubert     }
706076b9443SCy Schubert     case SQLITE_TRACE_ROW: {
707076b9443SCy Schubert       sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;
708076b9443SCy Schubert 
709076b9443SCy Schubert       pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
710076b9443SCy Schubert       Tcl_IncrRefCount(pCmd);
711076b9443SCy Schubert       Tcl_ListObjAppendElement(pDb->interp, pCmd,
712076b9443SCy Schubert                                Tcl_NewWideIntObj((Tcl_WideInt)pStmt));
713076b9443SCy Schubert       Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
714076b9443SCy Schubert       Tcl_DecrRefCount(pCmd);
715076b9443SCy Schubert       Tcl_ResetResult(pDb->interp);
716076b9443SCy Schubert       break;
717076b9443SCy Schubert     }
718076b9443SCy Schubert     case SQLITE_TRACE_CLOSE: {
719076b9443SCy Schubert       sqlite3 *db = (sqlite3 *)pd;
720076b9443SCy Schubert 
721076b9443SCy Schubert       pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
722076b9443SCy Schubert       Tcl_IncrRefCount(pCmd);
723076b9443SCy Schubert       Tcl_ListObjAppendElement(pDb->interp, pCmd,
724076b9443SCy Schubert                                Tcl_NewWideIntObj((Tcl_WideInt)db));
725076b9443SCy Schubert       Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
726076b9443SCy Schubert       Tcl_DecrRefCount(pCmd);
727076b9443SCy Schubert       Tcl_ResetResult(pDb->interp);
728076b9443SCy Schubert       break;
729076b9443SCy Schubert     }
730076b9443SCy Schubert   }
731076b9443SCy Schubert   return SQLITE_OK;
732076b9443SCy Schubert }
733076b9443SCy Schubert #endif
734076b9443SCy Schubert 
735076b9443SCy Schubert #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
736076b9443SCy Schubert     !defined(SQLITE_OMIT_DEPRECATED)
737076b9443SCy Schubert /*
738076b9443SCy Schubert ** This routine is called by the SQLite profile handler after a statement
739076b9443SCy Schubert ** SQL has executed.  The TCL script in pDb->zProfile is evaluated.
740076b9443SCy Schubert */
741076b9443SCy Schubert static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
742076b9443SCy Schubert   SqliteDb *pDb = (SqliteDb*)cd;
743076b9443SCy Schubert   Tcl_DString str;
744076b9443SCy Schubert   char zTm[100];
745076b9443SCy Schubert 
746076b9443SCy Schubert   sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
747076b9443SCy Schubert   Tcl_DStringInit(&str);
748076b9443SCy Schubert   Tcl_DStringAppend(&str, pDb->zProfile, -1);
749076b9443SCy Schubert   Tcl_DStringAppendElement(&str, zSql);
750076b9443SCy Schubert   Tcl_DStringAppendElement(&str, zTm);
751076b9443SCy Schubert   Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
752076b9443SCy Schubert   Tcl_DStringFree(&str);
753076b9443SCy Schubert   Tcl_ResetResult(pDb->interp);
754076b9443SCy Schubert }
755076b9443SCy Schubert #endif
756076b9443SCy Schubert 
757076b9443SCy Schubert /*
758076b9443SCy Schubert ** This routine is called when a transaction is committed.  The
759076b9443SCy Schubert ** TCL script in pDb->zCommit is executed.  If it returns non-zero or
760076b9443SCy Schubert ** if it throws an exception, the transaction is rolled back instead
761076b9443SCy Schubert ** of being committed.
762076b9443SCy Schubert */
763076b9443SCy Schubert static int DbCommitHandler(void *cd){
764076b9443SCy Schubert   SqliteDb *pDb = (SqliteDb*)cd;
765076b9443SCy Schubert   int rc;
766076b9443SCy Schubert 
767076b9443SCy Schubert   rc = Tcl_Eval(pDb->interp, pDb->zCommit);
768076b9443SCy Schubert   if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
769076b9443SCy Schubert     return 1;
770076b9443SCy Schubert   }
771076b9443SCy Schubert   return 0;
772076b9443SCy Schubert }
773076b9443SCy Schubert 
774076b9443SCy Schubert static void DbRollbackHandler(void *clientData){
775076b9443SCy Schubert   SqliteDb *pDb = (SqliteDb*)clientData;
776076b9443SCy Schubert   assert(pDb->pRollbackHook);
777076b9443SCy Schubert   if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
778076b9443SCy Schubert     Tcl_BackgroundError(pDb->interp);
779076b9443SCy Schubert   }
780076b9443SCy Schubert }
781076b9443SCy Schubert 
782076b9443SCy Schubert /*
783076b9443SCy Schubert ** This procedure handles wal_hook callbacks.
784076b9443SCy Schubert */
785076b9443SCy Schubert static int DbWalHandler(
786076b9443SCy Schubert   void *clientData,
787076b9443SCy Schubert   sqlite3 *db,
788076b9443SCy Schubert   const char *zDb,
789076b9443SCy Schubert   int nEntry
790076b9443SCy Schubert ){
791076b9443SCy Schubert   int ret = SQLITE_OK;
792076b9443SCy Schubert   Tcl_Obj *p;
793076b9443SCy Schubert   SqliteDb *pDb = (SqliteDb*)clientData;
794076b9443SCy Schubert   Tcl_Interp *interp = pDb->interp;
795076b9443SCy Schubert   assert(pDb->pWalHook);
796076b9443SCy Schubert 
797076b9443SCy Schubert   assert( db==pDb->db );
798076b9443SCy Schubert   p = Tcl_DuplicateObj(pDb->pWalHook);
799076b9443SCy Schubert   Tcl_IncrRefCount(p);
800076b9443SCy Schubert   Tcl_ListObjAppendElement(interp, p, Tcl_NewStringObj(zDb, -1));
801076b9443SCy Schubert   Tcl_ListObjAppendElement(interp, p, Tcl_NewIntObj(nEntry));
802076b9443SCy Schubert   if( TCL_OK!=Tcl_EvalObjEx(interp, p, 0)
803076b9443SCy Schubert    || TCL_OK!=Tcl_GetIntFromObj(interp, Tcl_GetObjResult(interp), &ret)
804076b9443SCy Schubert   ){
805076b9443SCy Schubert     Tcl_BackgroundError(interp);
806076b9443SCy Schubert   }
807076b9443SCy Schubert   Tcl_DecrRefCount(p);
808076b9443SCy Schubert 
809076b9443SCy Schubert   return ret;
810076b9443SCy Schubert }
811076b9443SCy Schubert 
812076b9443SCy Schubert #if defined(SQLITE_TEST) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
813076b9443SCy Schubert static void setTestUnlockNotifyVars(Tcl_Interp *interp, int iArg, int nArg){
814076b9443SCy Schubert   char zBuf[64];
815076b9443SCy Schubert   sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", iArg);
816076b9443SCy Schubert   Tcl_SetVar(interp, "sqlite_unlock_notify_arg", zBuf, TCL_GLOBAL_ONLY);
817076b9443SCy Schubert   sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", nArg);
818076b9443SCy Schubert   Tcl_SetVar(interp, "sqlite_unlock_notify_argcount", zBuf, TCL_GLOBAL_ONLY);
819076b9443SCy Schubert }
820076b9443SCy Schubert #else
821076b9443SCy Schubert # define setTestUnlockNotifyVars(x,y,z)
822076b9443SCy Schubert #endif
823076b9443SCy Schubert 
824076b9443SCy Schubert #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
825076b9443SCy Schubert static void DbUnlockNotify(void **apArg, int nArg){
826076b9443SCy Schubert   int i;
827076b9443SCy Schubert   for(i=0; i<nArg; i++){
828076b9443SCy Schubert     const int flags = (TCL_EVAL_GLOBAL|TCL_EVAL_DIRECT);
829076b9443SCy Schubert     SqliteDb *pDb = (SqliteDb *)apArg[i];
830076b9443SCy Schubert     setTestUnlockNotifyVars(pDb->interp, i, nArg);
831076b9443SCy Schubert     assert( pDb->pUnlockNotify);
832076b9443SCy Schubert     Tcl_EvalObjEx(pDb->interp, pDb->pUnlockNotify, flags);
833076b9443SCy Schubert     Tcl_DecrRefCount(pDb->pUnlockNotify);
834076b9443SCy Schubert     pDb->pUnlockNotify = 0;
835076b9443SCy Schubert   }
836076b9443SCy Schubert }
837076b9443SCy Schubert #endif
838076b9443SCy Schubert 
839076b9443SCy Schubert #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
840076b9443SCy Schubert /*
841076b9443SCy Schubert ** Pre-update hook callback.
842076b9443SCy Schubert */
843076b9443SCy Schubert static void DbPreUpdateHandler(
844076b9443SCy Schubert   void *p,
845076b9443SCy Schubert   sqlite3 *db,
846076b9443SCy Schubert   int op,
847076b9443SCy Schubert   const char *zDb,
848076b9443SCy Schubert   const char *zTbl,
849076b9443SCy Schubert   sqlite_int64 iKey1,
850076b9443SCy Schubert   sqlite_int64 iKey2
851076b9443SCy Schubert ){
852076b9443SCy Schubert   SqliteDb *pDb = (SqliteDb *)p;
853076b9443SCy Schubert   Tcl_Obj *pCmd;
854076b9443SCy Schubert   static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"};
855076b9443SCy Schubert 
856076b9443SCy Schubert   assert( (SQLITE_DELETE-1)/9 == 0 );
857076b9443SCy Schubert   assert( (SQLITE_INSERT-1)/9 == 1 );
858076b9443SCy Schubert   assert( (SQLITE_UPDATE-1)/9 == 2 );
859076b9443SCy Schubert   assert( pDb->pPreUpdateHook );
860076b9443SCy Schubert   assert( db==pDb->db );
861076b9443SCy Schubert   assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
862076b9443SCy Schubert 
863076b9443SCy Schubert   pCmd = Tcl_DuplicateObj(pDb->pPreUpdateHook);
864076b9443SCy Schubert   Tcl_IncrRefCount(pCmd);
865076b9443SCy Schubert   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
866076b9443SCy Schubert   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
867076b9443SCy Schubert   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
868076b9443SCy Schubert   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey1));
869076b9443SCy Schubert   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey2));
870076b9443SCy Schubert   Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
871076b9443SCy Schubert   Tcl_DecrRefCount(pCmd);
872076b9443SCy Schubert }
873076b9443SCy Schubert #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
874076b9443SCy Schubert 
875076b9443SCy Schubert static void DbUpdateHandler(
876076b9443SCy Schubert   void *p,
877076b9443SCy Schubert   int op,
878076b9443SCy Schubert   const char *zDb,
879076b9443SCy Schubert   const char *zTbl,
880076b9443SCy Schubert   sqlite_int64 rowid
881076b9443SCy Schubert ){
882076b9443SCy Schubert   SqliteDb *pDb = (SqliteDb *)p;
883076b9443SCy Schubert   Tcl_Obj *pCmd;
884076b9443SCy Schubert   static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"};
885076b9443SCy Schubert 
886076b9443SCy Schubert   assert( (SQLITE_DELETE-1)/9 == 0 );
887076b9443SCy Schubert   assert( (SQLITE_INSERT-1)/9 == 1 );
888076b9443SCy Schubert   assert( (SQLITE_UPDATE-1)/9 == 2 );
889076b9443SCy Schubert 
890076b9443SCy Schubert   assert( pDb->pUpdateHook );
891076b9443SCy Schubert   assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
892076b9443SCy Schubert 
893076b9443SCy Schubert   pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
894076b9443SCy Schubert   Tcl_IncrRefCount(pCmd);
895076b9443SCy Schubert   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
896076b9443SCy Schubert   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
897076b9443SCy Schubert   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
898076b9443SCy Schubert   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
899076b9443SCy Schubert   Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
900076b9443SCy Schubert   Tcl_DecrRefCount(pCmd);
901076b9443SCy Schubert }
902076b9443SCy Schubert 
903076b9443SCy Schubert static void tclCollateNeeded(
904076b9443SCy Schubert   void *pCtx,
905076b9443SCy Schubert   sqlite3 *db,
906076b9443SCy Schubert   int enc,
907076b9443SCy Schubert   const char *zName
908076b9443SCy Schubert ){
909076b9443SCy Schubert   SqliteDb *pDb = (SqliteDb *)pCtx;
910076b9443SCy Schubert   Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
911076b9443SCy Schubert   Tcl_IncrRefCount(pScript);
912076b9443SCy Schubert   Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
913076b9443SCy Schubert   Tcl_EvalObjEx(pDb->interp, pScript, 0);
914076b9443SCy Schubert   Tcl_DecrRefCount(pScript);
915076b9443SCy Schubert }
916076b9443SCy Schubert 
917076b9443SCy Schubert /*
918076b9443SCy Schubert ** This routine is called to evaluate an SQL collation function implemented
919076b9443SCy Schubert ** using TCL script.
920076b9443SCy Schubert */
921076b9443SCy Schubert static int tclSqlCollate(
922076b9443SCy Schubert   void *pCtx,
923076b9443SCy Schubert   int nA,
924076b9443SCy Schubert   const void *zA,
925076b9443SCy Schubert   int nB,
926076b9443SCy Schubert   const void *zB
927076b9443SCy Schubert ){
928076b9443SCy Schubert   SqlCollate *p = (SqlCollate *)pCtx;
929076b9443SCy Schubert   Tcl_Obj *pCmd;
930076b9443SCy Schubert 
931076b9443SCy Schubert   pCmd = Tcl_NewStringObj(p->zScript, -1);
932076b9443SCy Schubert   Tcl_IncrRefCount(pCmd);
933076b9443SCy Schubert   Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
934076b9443SCy Schubert   Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
935076b9443SCy Schubert   Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
936076b9443SCy Schubert   Tcl_DecrRefCount(pCmd);
937076b9443SCy Schubert   return (atoi(Tcl_GetStringResult(p->interp)));
938076b9443SCy Schubert }
939076b9443SCy Schubert 
940076b9443SCy Schubert /*
941076b9443SCy Schubert ** This routine is called to evaluate an SQL function implemented
942076b9443SCy Schubert ** using TCL script.
943076b9443SCy Schubert */
944076b9443SCy Schubert static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
945076b9443SCy Schubert   SqlFunc *p = sqlite3_user_data(context);
946076b9443SCy Schubert   Tcl_Obj *pCmd;
947076b9443SCy Schubert   int i;
948076b9443SCy Schubert   int rc;
949076b9443SCy Schubert 
950076b9443SCy Schubert   if( argc==0 ){
951076b9443SCy Schubert     /* If there are no arguments to the function, call Tcl_EvalObjEx on the
952076b9443SCy Schubert     ** script object directly.  This allows the TCL compiler to generate
953076b9443SCy Schubert     ** bytecode for the command on the first invocation and thus make
954076b9443SCy Schubert     ** subsequent invocations much faster. */
955076b9443SCy Schubert     pCmd = p->pScript;
956076b9443SCy Schubert     Tcl_IncrRefCount(pCmd);
957076b9443SCy Schubert     rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
958076b9443SCy Schubert     Tcl_DecrRefCount(pCmd);
959076b9443SCy Schubert   }else{
960076b9443SCy Schubert     /* If there are arguments to the function, make a shallow copy of the
961076b9443SCy Schubert     ** script object, lappend the arguments, then evaluate the copy.
962076b9443SCy Schubert     **
963076b9443SCy Schubert     ** By "shallow" copy, we mean only the outer list Tcl_Obj is duplicated.
964076b9443SCy Schubert     ** The new Tcl_Obj contains pointers to the original list elements.
965076b9443SCy Schubert     ** That way, when Tcl_EvalObjv() is run and shimmers the first element
966076b9443SCy Schubert     ** of the list to tclCmdNameType, that alternate representation will
967076b9443SCy Schubert     ** be preserved and reused on the next invocation.
968076b9443SCy Schubert     */
969076b9443SCy Schubert     Tcl_Obj **aArg;
970076b9443SCy Schubert     int nArg;
971076b9443SCy Schubert     if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
972076b9443SCy Schubert       sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
973076b9443SCy Schubert       return;
974076b9443SCy Schubert     }
975076b9443SCy Schubert     pCmd = Tcl_NewListObj(nArg, aArg);
976076b9443SCy Schubert     Tcl_IncrRefCount(pCmd);
977076b9443SCy Schubert     for(i=0; i<argc; i++){
978076b9443SCy Schubert       sqlite3_value *pIn = argv[i];
979076b9443SCy Schubert       Tcl_Obj *pVal;
980076b9443SCy Schubert 
981076b9443SCy Schubert       /* Set pVal to contain the i'th column of this row. */
982076b9443SCy Schubert       switch( sqlite3_value_type(pIn) ){
983076b9443SCy Schubert         case SQLITE_BLOB: {
984076b9443SCy Schubert           int bytes = sqlite3_value_bytes(pIn);
985076b9443SCy Schubert           pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
986076b9443SCy Schubert           break;
987076b9443SCy Schubert         }
988076b9443SCy Schubert         case SQLITE_INTEGER: {
989076b9443SCy Schubert           sqlite_int64 v = sqlite3_value_int64(pIn);
990076b9443SCy Schubert           if( v>=-2147483647 && v<=2147483647 ){
991076b9443SCy Schubert             pVal = Tcl_NewIntObj((int)v);
992076b9443SCy Schubert           }else{
993076b9443SCy Schubert             pVal = Tcl_NewWideIntObj(v);
994076b9443SCy Schubert           }
995076b9443SCy Schubert           break;
996076b9443SCy Schubert         }
997076b9443SCy Schubert         case SQLITE_FLOAT: {
998076b9443SCy Schubert           double r = sqlite3_value_double(pIn);
999076b9443SCy Schubert           pVal = Tcl_NewDoubleObj(r);
1000076b9443SCy Schubert           break;
1001076b9443SCy Schubert         }
1002076b9443SCy Schubert         case SQLITE_NULL: {
1003076b9443SCy Schubert           pVal = Tcl_NewStringObj(p->pDb->zNull, -1);
1004076b9443SCy Schubert           break;
1005076b9443SCy Schubert         }
1006076b9443SCy Schubert         default: {
1007076b9443SCy Schubert           int bytes = sqlite3_value_bytes(pIn);
1008076b9443SCy Schubert           pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
1009076b9443SCy Schubert           break;
1010076b9443SCy Schubert         }
1011076b9443SCy Schubert       }
1012076b9443SCy Schubert       rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
1013076b9443SCy Schubert       if( rc ){
1014076b9443SCy Schubert         Tcl_DecrRefCount(pCmd);
1015076b9443SCy Schubert         sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
1016076b9443SCy Schubert         return;
1017076b9443SCy Schubert       }
1018076b9443SCy Schubert     }
1019076b9443SCy Schubert     if( !p->useEvalObjv ){
1020076b9443SCy Schubert       /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
1021076b9443SCy Schubert       ** is a list without a string representation.  To prevent this from
1022076b9443SCy Schubert       ** happening, make sure pCmd has a valid string representation */
1023076b9443SCy Schubert       Tcl_GetString(pCmd);
1024076b9443SCy Schubert     }
1025076b9443SCy Schubert     rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
1026076b9443SCy Schubert     Tcl_DecrRefCount(pCmd);
1027076b9443SCy Schubert   }
1028076b9443SCy Schubert 
1029076b9443SCy Schubert   if( rc && rc!=TCL_RETURN ){
1030076b9443SCy Schubert     sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
1031076b9443SCy Schubert   }else{
1032076b9443SCy Schubert     Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
1033076b9443SCy Schubert     int n;
1034076b9443SCy Schubert     u8 *data;
1035076b9443SCy Schubert     const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
1036076b9443SCy Schubert     char c = zType[0];
103702273ca8SCy Schubert     int eType = p->eType;
103802273ca8SCy Schubert 
103902273ca8SCy Schubert     if( eType==SQLITE_NULL ){
1040076b9443SCy Schubert       if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
1041076b9443SCy Schubert         /* Only return a BLOB type if the Tcl variable is a bytearray and
1042076b9443SCy Schubert         ** has no string representation. */
104302273ca8SCy Schubert         eType = SQLITE_BLOB;
104402273ca8SCy Schubert       }else if( (c=='b' && strcmp(zType,"boolean")==0)
104502273ca8SCy Schubert              || (c=='w' && strcmp(zType,"wideInt")==0)
104602273ca8SCy Schubert              || (c=='i' && strcmp(zType,"int")==0)
104702273ca8SCy Schubert       ){
104802273ca8SCy Schubert         eType = SQLITE_INTEGER;
104902273ca8SCy Schubert       }else if( c=='d' && strcmp(zType,"double")==0 ){
105002273ca8SCy Schubert         eType = SQLITE_FLOAT;
105102273ca8SCy Schubert       }else{
105202273ca8SCy Schubert         eType = SQLITE_TEXT;
105302273ca8SCy Schubert       }
105402273ca8SCy Schubert     }
105502273ca8SCy Schubert 
105602273ca8SCy Schubert     switch( eType ){
105702273ca8SCy Schubert       case SQLITE_BLOB: {
1058076b9443SCy Schubert         data = Tcl_GetByteArrayFromObj(pVar, &n);
1059076b9443SCy Schubert         sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
106002273ca8SCy Schubert         break;
106102273ca8SCy Schubert       }
106202273ca8SCy Schubert       case SQLITE_INTEGER: {
1063076b9443SCy Schubert         Tcl_WideInt v;
106402273ca8SCy Schubert         if( TCL_OK==Tcl_GetWideIntFromObj(0, pVar, &v) ){
1065076b9443SCy Schubert           sqlite3_result_int64(context, v);
106602273ca8SCy Schubert           break;
106702273ca8SCy Schubert         }
106802273ca8SCy Schubert         /* fall-through */
106902273ca8SCy Schubert       }
107002273ca8SCy Schubert       case SQLITE_FLOAT: {
107102273ca8SCy Schubert         double r;
107202273ca8SCy Schubert         if( TCL_OK==Tcl_GetDoubleFromObj(0, pVar, &r) ){
107302273ca8SCy Schubert           sqlite3_result_double(context, r);
107402273ca8SCy Schubert           break;
107502273ca8SCy Schubert         }
107602273ca8SCy Schubert         /* fall-through */
107702273ca8SCy Schubert       }
107802273ca8SCy Schubert       default: {
1079076b9443SCy Schubert         data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1080076b9443SCy Schubert         sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
108102273ca8SCy Schubert         break;
1082076b9443SCy Schubert       }
1083076b9443SCy Schubert     }
108402273ca8SCy Schubert 
108502273ca8SCy Schubert   }
1086076b9443SCy Schubert }
1087076b9443SCy Schubert 
1088076b9443SCy Schubert #ifndef SQLITE_OMIT_AUTHORIZATION
1089076b9443SCy Schubert /*
1090076b9443SCy Schubert ** This is the authentication function.  It appends the authentication
1091076b9443SCy Schubert ** type code and the two arguments to zCmd[] then invokes the result
1092076b9443SCy Schubert ** on the interpreter.  The reply is examined to determine if the
1093076b9443SCy Schubert ** authentication fails or succeeds.
1094076b9443SCy Schubert */
1095076b9443SCy Schubert static int auth_callback(
1096076b9443SCy Schubert   void *pArg,
1097076b9443SCy Schubert   int code,
1098076b9443SCy Schubert   const char *zArg1,
1099076b9443SCy Schubert   const char *zArg2,
1100076b9443SCy Schubert   const char *zArg3,
1101076b9443SCy Schubert   const char *zArg4
1102076b9443SCy Schubert #ifdef SQLITE_USER_AUTHENTICATION
1103076b9443SCy Schubert   ,const char *zArg5
1104076b9443SCy Schubert #endif
1105076b9443SCy Schubert ){
1106076b9443SCy Schubert   const char *zCode;
1107076b9443SCy Schubert   Tcl_DString str;
1108076b9443SCy Schubert   int rc;
1109076b9443SCy Schubert   const char *zReply;
1110076b9443SCy Schubert   /* EVIDENCE-OF: R-38590-62769 The first parameter to the authorizer
1111076b9443SCy Schubert   ** callback is a copy of the third parameter to the
1112076b9443SCy Schubert   ** sqlite3_set_authorizer() interface.
1113076b9443SCy Schubert   */
1114076b9443SCy Schubert   SqliteDb *pDb = (SqliteDb*)pArg;
1115076b9443SCy Schubert   if( pDb->disableAuth ) return SQLITE_OK;
1116076b9443SCy Schubert 
1117076b9443SCy Schubert   /* EVIDENCE-OF: R-56518-44310 The second parameter to the callback is an
1118076b9443SCy Schubert   ** integer action code that specifies the particular action to be
1119076b9443SCy Schubert   ** authorized. */
1120076b9443SCy Schubert   switch( code ){
1121076b9443SCy Schubert     case SQLITE_COPY              : zCode="SQLITE_COPY"; break;
1122076b9443SCy Schubert     case SQLITE_CREATE_INDEX      : zCode="SQLITE_CREATE_INDEX"; break;
1123076b9443SCy Schubert     case SQLITE_CREATE_TABLE      : zCode="SQLITE_CREATE_TABLE"; break;
1124076b9443SCy Schubert     case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
1125076b9443SCy Schubert     case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
1126076b9443SCy Schubert     case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
1127076b9443SCy Schubert     case SQLITE_CREATE_TEMP_VIEW  : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
1128076b9443SCy Schubert     case SQLITE_CREATE_TRIGGER    : zCode="SQLITE_CREATE_TRIGGER"; break;
1129076b9443SCy Schubert     case SQLITE_CREATE_VIEW       : zCode="SQLITE_CREATE_VIEW"; break;
1130076b9443SCy Schubert     case SQLITE_DELETE            : zCode="SQLITE_DELETE"; break;
1131076b9443SCy Schubert     case SQLITE_DROP_INDEX        : zCode="SQLITE_DROP_INDEX"; break;
1132076b9443SCy Schubert     case SQLITE_DROP_TABLE        : zCode="SQLITE_DROP_TABLE"; break;
1133076b9443SCy Schubert     case SQLITE_DROP_TEMP_INDEX   : zCode="SQLITE_DROP_TEMP_INDEX"; break;
1134076b9443SCy Schubert     case SQLITE_DROP_TEMP_TABLE   : zCode="SQLITE_DROP_TEMP_TABLE"; break;
1135076b9443SCy Schubert     case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
1136076b9443SCy Schubert     case SQLITE_DROP_TEMP_VIEW    : zCode="SQLITE_DROP_TEMP_VIEW"; break;
1137076b9443SCy Schubert     case SQLITE_DROP_TRIGGER      : zCode="SQLITE_DROP_TRIGGER"; break;
1138076b9443SCy Schubert     case SQLITE_DROP_VIEW         : zCode="SQLITE_DROP_VIEW"; break;
1139076b9443SCy Schubert     case SQLITE_INSERT            : zCode="SQLITE_INSERT"; break;
1140076b9443SCy Schubert     case SQLITE_PRAGMA            : zCode="SQLITE_PRAGMA"; break;
1141076b9443SCy Schubert     case SQLITE_READ              : zCode="SQLITE_READ"; break;
1142076b9443SCy Schubert     case SQLITE_SELECT            : zCode="SQLITE_SELECT"; break;
1143076b9443SCy Schubert     case SQLITE_TRANSACTION       : zCode="SQLITE_TRANSACTION"; break;
1144076b9443SCy Schubert     case SQLITE_UPDATE            : zCode="SQLITE_UPDATE"; break;
1145076b9443SCy Schubert     case SQLITE_ATTACH            : zCode="SQLITE_ATTACH"; break;
1146076b9443SCy Schubert     case SQLITE_DETACH            : zCode="SQLITE_DETACH"; break;
1147076b9443SCy Schubert     case SQLITE_ALTER_TABLE       : zCode="SQLITE_ALTER_TABLE"; break;
1148076b9443SCy Schubert     case SQLITE_REINDEX           : zCode="SQLITE_REINDEX"; break;
1149076b9443SCy Schubert     case SQLITE_ANALYZE           : zCode="SQLITE_ANALYZE"; break;
1150076b9443SCy Schubert     case SQLITE_CREATE_VTABLE     : zCode="SQLITE_CREATE_VTABLE"; break;
1151076b9443SCy Schubert     case SQLITE_DROP_VTABLE       : zCode="SQLITE_DROP_VTABLE"; break;
1152076b9443SCy Schubert     case SQLITE_FUNCTION          : zCode="SQLITE_FUNCTION"; break;
1153076b9443SCy Schubert     case SQLITE_SAVEPOINT         : zCode="SQLITE_SAVEPOINT"; break;
1154076b9443SCy Schubert     case SQLITE_RECURSIVE         : zCode="SQLITE_RECURSIVE"; break;
1155076b9443SCy Schubert     default                       : zCode="????"; break;
1156076b9443SCy Schubert   }
1157076b9443SCy Schubert   Tcl_DStringInit(&str);
1158076b9443SCy Schubert   Tcl_DStringAppend(&str, pDb->zAuth, -1);
1159076b9443SCy Schubert   Tcl_DStringAppendElement(&str, zCode);
1160076b9443SCy Schubert   Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
1161076b9443SCy Schubert   Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
1162076b9443SCy Schubert   Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
1163076b9443SCy Schubert   Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
1164076b9443SCy Schubert #ifdef SQLITE_USER_AUTHENTICATION
1165076b9443SCy Schubert   Tcl_DStringAppendElement(&str, zArg5 ? zArg5 : "");
1166076b9443SCy Schubert #endif
1167076b9443SCy Schubert   rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
1168076b9443SCy Schubert   Tcl_DStringFree(&str);
1169076b9443SCy Schubert   zReply = rc==TCL_OK ? Tcl_GetStringResult(pDb->interp) : "SQLITE_DENY";
1170076b9443SCy Schubert   if( strcmp(zReply,"SQLITE_OK")==0 ){
1171076b9443SCy Schubert     rc = SQLITE_OK;
1172076b9443SCy Schubert   }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
1173076b9443SCy Schubert     rc = SQLITE_DENY;
1174076b9443SCy Schubert   }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
1175076b9443SCy Schubert     rc = SQLITE_IGNORE;
1176076b9443SCy Schubert   }else{
1177076b9443SCy Schubert     rc = 999;
1178076b9443SCy Schubert   }
1179076b9443SCy Schubert   return rc;
1180076b9443SCy Schubert }
1181076b9443SCy Schubert #endif /* SQLITE_OMIT_AUTHORIZATION */
1182076b9443SCy Schubert 
1183076b9443SCy Schubert /*
1184076b9443SCy Schubert ** This routine reads a line of text from FILE in, stores
1185076b9443SCy Schubert ** the text in memory obtained from malloc() and returns a pointer
1186076b9443SCy Schubert ** to the text.  NULL is returned at end of file, or if malloc()
1187076b9443SCy Schubert ** fails.
1188076b9443SCy Schubert **
1189076b9443SCy Schubert ** The interface is like "readline" but no command-line editing
1190076b9443SCy Schubert ** is done.
1191076b9443SCy Schubert **
1192076b9443SCy Schubert ** copied from shell.c from '.import' command
1193076b9443SCy Schubert */
1194076b9443SCy Schubert static char *local_getline(char *zPrompt, FILE *in){
1195076b9443SCy Schubert   char *zLine;
1196076b9443SCy Schubert   int nLine;
1197076b9443SCy Schubert   int n;
1198076b9443SCy Schubert 
1199076b9443SCy Schubert   nLine = 100;
1200076b9443SCy Schubert   zLine = malloc( nLine );
1201076b9443SCy Schubert   if( zLine==0 ) return 0;
1202076b9443SCy Schubert   n = 0;
1203076b9443SCy Schubert   while( 1 ){
1204076b9443SCy Schubert     if( n+100>nLine ){
1205076b9443SCy Schubert       nLine = nLine*2 + 100;
1206076b9443SCy Schubert       zLine = realloc(zLine, nLine);
1207076b9443SCy Schubert       if( zLine==0 ) return 0;
1208076b9443SCy Schubert     }
1209076b9443SCy Schubert     if( fgets(&zLine[n], nLine - n, in)==0 ){
1210076b9443SCy Schubert       if( n==0 ){
1211076b9443SCy Schubert         free(zLine);
1212076b9443SCy Schubert         return 0;
1213076b9443SCy Schubert       }
1214076b9443SCy Schubert       zLine[n] = 0;
1215076b9443SCy Schubert       break;
1216076b9443SCy Schubert     }
1217076b9443SCy Schubert     while( zLine[n] ){ n++; }
1218076b9443SCy Schubert     if( n>0 && zLine[n-1]=='\n' ){
1219076b9443SCy Schubert       n--;
1220076b9443SCy Schubert       zLine[n] = 0;
1221076b9443SCy Schubert       break;
1222076b9443SCy Schubert     }
1223076b9443SCy Schubert   }
1224076b9443SCy Schubert   zLine = realloc( zLine, n+1 );
1225076b9443SCy Schubert   return zLine;
1226076b9443SCy Schubert }
1227076b9443SCy Schubert 
1228076b9443SCy Schubert 
1229076b9443SCy Schubert /*
1230076b9443SCy Schubert ** This function is part of the implementation of the command:
1231076b9443SCy Schubert **
1232076b9443SCy Schubert **   $db transaction [-deferred|-immediate|-exclusive] SCRIPT
1233076b9443SCy Schubert **
1234076b9443SCy Schubert ** It is invoked after evaluating the script SCRIPT to commit or rollback
1235076b9443SCy Schubert ** the transaction or savepoint opened by the [transaction] command.
1236076b9443SCy Schubert */
1237076b9443SCy Schubert static int SQLITE_TCLAPI DbTransPostCmd(
1238076b9443SCy Schubert   ClientData data[],                   /* data[0] is the Sqlite3Db* for $db */
1239076b9443SCy Schubert   Tcl_Interp *interp,                  /* Tcl interpreter */
1240076b9443SCy Schubert   int result                           /* Result of evaluating SCRIPT */
1241076b9443SCy Schubert ){
1242076b9443SCy Schubert   static const char *const azEnd[] = {
1243076b9443SCy Schubert     "RELEASE _tcl_transaction",        /* rc==TCL_ERROR, nTransaction!=0 */
1244076b9443SCy Schubert     "COMMIT",                          /* rc!=TCL_ERROR, nTransaction==0 */
1245076b9443SCy Schubert     "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction",
1246076b9443SCy Schubert     "ROLLBACK"                         /* rc==TCL_ERROR, nTransaction==0 */
1247076b9443SCy Schubert   };
1248076b9443SCy Schubert   SqliteDb *pDb = (SqliteDb*)data[0];
1249076b9443SCy Schubert   int rc = result;
1250076b9443SCy Schubert   const char *zEnd;
1251076b9443SCy Schubert 
1252076b9443SCy Schubert   pDb->nTransaction--;
1253076b9443SCy Schubert   zEnd = azEnd[(rc==TCL_ERROR)*2 + (pDb->nTransaction==0)];
1254076b9443SCy Schubert 
1255076b9443SCy Schubert   pDb->disableAuth++;
1256076b9443SCy Schubert   if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){
1257076b9443SCy Schubert       /* This is a tricky scenario to handle. The most likely cause of an
1258076b9443SCy Schubert       ** error is that the exec() above was an attempt to commit the
1259076b9443SCy Schubert       ** top-level transaction that returned SQLITE_BUSY. Or, less likely,
1260076b9443SCy Schubert       ** that an IO-error has occurred. In either case, throw a Tcl exception
1261076b9443SCy Schubert       ** and try to rollback the transaction.
1262076b9443SCy Schubert       **
1263076b9443SCy Schubert       ** But it could also be that the user executed one or more BEGIN,
1264076b9443SCy Schubert       ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing
1265076b9443SCy Schubert       ** this method's logic. Not clear how this would be best handled.
1266076b9443SCy Schubert       */
1267076b9443SCy Schubert     if( rc!=TCL_ERROR ){
1268076b9443SCy Schubert       Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
1269076b9443SCy Schubert       rc = TCL_ERROR;
1270076b9443SCy Schubert     }
1271076b9443SCy Schubert     sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
1272076b9443SCy Schubert   }
1273076b9443SCy Schubert   pDb->disableAuth--;
1274076b9443SCy Schubert 
12750197ba46SCy Schubert   delDatabaseRef(pDb);
1276076b9443SCy Schubert   return rc;
1277076b9443SCy Schubert }
1278076b9443SCy Schubert 
1279076b9443SCy Schubert /*
1280076b9443SCy Schubert ** Unless SQLITE_TEST is defined, this function is a simple wrapper around
1281076b9443SCy Schubert ** sqlite3_prepare_v2(). If SQLITE_TEST is defined, then it uses either
1282076b9443SCy Schubert ** sqlite3_prepare_v2() or legacy interface sqlite3_prepare(), depending
1283076b9443SCy Schubert ** on whether or not the [db_use_legacy_prepare] command has been used to
1284076b9443SCy Schubert ** configure the connection.
1285076b9443SCy Schubert */
1286076b9443SCy Schubert static int dbPrepare(
1287076b9443SCy Schubert   SqliteDb *pDb,                  /* Database object */
1288076b9443SCy Schubert   const char *zSql,               /* SQL to compile */
1289076b9443SCy Schubert   sqlite3_stmt **ppStmt,          /* OUT: Prepared statement */
1290076b9443SCy Schubert   const char **pzOut              /* OUT: Pointer to next SQL statement */
1291076b9443SCy Schubert ){
1292076b9443SCy Schubert   unsigned int prepFlags = 0;
1293076b9443SCy Schubert #ifdef SQLITE_TEST
1294076b9443SCy Schubert   if( pDb->bLegacyPrepare ){
1295076b9443SCy Schubert     return sqlite3_prepare(pDb->db, zSql, -1, ppStmt, pzOut);
1296076b9443SCy Schubert   }
1297076b9443SCy Schubert #endif
1298076b9443SCy Schubert   /* If the statement cache is large, use the SQLITE_PREPARE_PERSISTENT
1299076b9443SCy Schubert   ** flags, which uses less lookaside memory.  But if the cache is small,
1300076b9443SCy Schubert   ** omit that flag to make full use of lookaside */
1301076b9443SCy Schubert   if( pDb->maxStmt>5 ) prepFlags = SQLITE_PREPARE_PERSISTENT;
1302076b9443SCy Schubert 
1303076b9443SCy Schubert   return sqlite3_prepare_v3(pDb->db, zSql, -1, prepFlags, ppStmt, pzOut);
1304076b9443SCy Schubert }
1305076b9443SCy Schubert 
1306076b9443SCy Schubert /*
1307076b9443SCy Schubert ** Search the cache for a prepared-statement object that implements the
1308076b9443SCy Schubert ** first SQL statement in the buffer pointed to by parameter zIn. If
1309076b9443SCy Schubert ** no such prepared-statement can be found, allocate and prepare a new
1310076b9443SCy Schubert ** one. In either case, bind the current values of the relevant Tcl
1311076b9443SCy Schubert ** variables to any $var, :var or @var variables in the statement. Before
1312076b9443SCy Schubert ** returning, set *ppPreStmt to point to the prepared-statement object.
1313076b9443SCy Schubert **
1314076b9443SCy Schubert ** Output parameter *pzOut is set to point to the next SQL statement in
1315076b9443SCy Schubert ** buffer zIn, or to the '\0' byte at the end of zIn if there is no
1316076b9443SCy Schubert ** next statement.
1317076b9443SCy Schubert **
1318076b9443SCy Schubert ** If successful, TCL_OK is returned. Otherwise, TCL_ERROR is returned
1319076b9443SCy Schubert ** and an error message loaded into interpreter pDb->interp.
1320076b9443SCy Schubert */
1321076b9443SCy Schubert static int dbPrepareAndBind(
1322076b9443SCy Schubert   SqliteDb *pDb,                  /* Database object */
1323076b9443SCy Schubert   char const *zIn,                /* SQL to compile */
1324076b9443SCy Schubert   char const **pzOut,             /* OUT: Pointer to next SQL statement */
1325076b9443SCy Schubert   SqlPreparedStmt **ppPreStmt     /* OUT: Object used to cache statement */
1326076b9443SCy Schubert ){
1327076b9443SCy Schubert   const char *zSql = zIn;         /* Pointer to first SQL statement in zIn */
1328076b9443SCy Schubert   sqlite3_stmt *pStmt = 0;        /* Prepared statement object */
1329076b9443SCy Schubert   SqlPreparedStmt *pPreStmt;      /* Pointer to cached statement */
1330076b9443SCy Schubert   int nSql;                       /* Length of zSql in bytes */
1331076b9443SCy Schubert   int nVar = 0;                   /* Number of variables in statement */
1332076b9443SCy Schubert   int iParm = 0;                  /* Next free entry in apParm */
1333076b9443SCy Schubert   char c;
1334076b9443SCy Schubert   int i;
133502273ca8SCy Schubert   int needResultReset = 0;        /* Need to invoke Tcl_ResetResult() */
133602273ca8SCy Schubert   int rc = SQLITE_OK;             /* Value to return */
1337076b9443SCy Schubert   Tcl_Interp *interp = pDb->interp;
1338076b9443SCy Schubert 
1339076b9443SCy Schubert   *ppPreStmt = 0;
1340076b9443SCy Schubert 
1341076b9443SCy Schubert   /* Trim spaces from the start of zSql and calculate the remaining length. */
1342076b9443SCy Schubert   while( (c = zSql[0])==' ' || c=='\t' || c=='\r' || c=='\n' ){ zSql++; }
1343076b9443SCy Schubert   nSql = strlen30(zSql);
1344076b9443SCy Schubert 
1345076b9443SCy Schubert   for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pPreStmt->pNext){
1346076b9443SCy Schubert     int n = pPreStmt->nSql;
1347076b9443SCy Schubert     if( nSql>=n
1348076b9443SCy Schubert         && memcmp(pPreStmt->zSql, zSql, n)==0
1349076b9443SCy Schubert         && (zSql[n]==0 || zSql[n-1]==';')
1350076b9443SCy Schubert     ){
1351076b9443SCy Schubert       pStmt = pPreStmt->pStmt;
1352076b9443SCy Schubert       *pzOut = &zSql[pPreStmt->nSql];
1353076b9443SCy Schubert 
1354076b9443SCy Schubert       /* When a prepared statement is found, unlink it from the
1355076b9443SCy Schubert       ** cache list.  It will later be added back to the beginning
1356076b9443SCy Schubert       ** of the cache list in order to implement LRU replacement.
1357076b9443SCy Schubert       */
1358076b9443SCy Schubert       if( pPreStmt->pPrev ){
1359076b9443SCy Schubert         pPreStmt->pPrev->pNext = pPreStmt->pNext;
1360076b9443SCy Schubert       }else{
1361076b9443SCy Schubert         pDb->stmtList = pPreStmt->pNext;
1362076b9443SCy Schubert       }
1363076b9443SCy Schubert       if( pPreStmt->pNext ){
1364076b9443SCy Schubert         pPreStmt->pNext->pPrev = pPreStmt->pPrev;
1365076b9443SCy Schubert       }else{
1366076b9443SCy Schubert         pDb->stmtLast = pPreStmt->pPrev;
1367076b9443SCy Schubert       }
1368076b9443SCy Schubert       pDb->nStmt--;
1369076b9443SCy Schubert       nVar = sqlite3_bind_parameter_count(pStmt);
1370076b9443SCy Schubert       break;
1371076b9443SCy Schubert     }
1372076b9443SCy Schubert   }
1373076b9443SCy Schubert 
1374076b9443SCy Schubert   /* If no prepared statement was found. Compile the SQL text. Also allocate
1375076b9443SCy Schubert   ** a new SqlPreparedStmt structure.  */
1376076b9443SCy Schubert   if( pPreStmt==0 ){
1377076b9443SCy Schubert     int nByte;
1378076b9443SCy Schubert 
1379076b9443SCy Schubert     if( SQLITE_OK!=dbPrepare(pDb, zSql, &pStmt, pzOut) ){
1380076b9443SCy Schubert       Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
1381076b9443SCy Schubert       return TCL_ERROR;
1382076b9443SCy Schubert     }
1383076b9443SCy Schubert     if( pStmt==0 ){
1384076b9443SCy Schubert       if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
1385076b9443SCy Schubert         /* A compile-time error in the statement. */
1386076b9443SCy Schubert         Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
1387076b9443SCy Schubert         return TCL_ERROR;
1388076b9443SCy Schubert       }else{
1389076b9443SCy Schubert         /* The statement was a no-op.  Continue to the next statement
1390076b9443SCy Schubert         ** in the SQL string.
1391076b9443SCy Schubert         */
1392076b9443SCy Schubert         return TCL_OK;
1393076b9443SCy Schubert       }
1394076b9443SCy Schubert     }
1395076b9443SCy Schubert 
1396076b9443SCy Schubert     assert( pPreStmt==0 );
1397076b9443SCy Schubert     nVar = sqlite3_bind_parameter_count(pStmt);
1398076b9443SCy Schubert     nByte = sizeof(SqlPreparedStmt) + nVar*sizeof(Tcl_Obj *);
1399076b9443SCy Schubert     pPreStmt = (SqlPreparedStmt*)Tcl_Alloc(nByte);
1400076b9443SCy Schubert     memset(pPreStmt, 0, nByte);
1401076b9443SCy Schubert 
1402076b9443SCy Schubert     pPreStmt->pStmt = pStmt;
1403076b9443SCy Schubert     pPreStmt->nSql = (int)(*pzOut - zSql);
1404076b9443SCy Schubert     pPreStmt->zSql = sqlite3_sql(pStmt);
1405076b9443SCy Schubert     pPreStmt->apParm = (Tcl_Obj **)&pPreStmt[1];
1406076b9443SCy Schubert #ifdef SQLITE_TEST
1407076b9443SCy Schubert     if( pPreStmt->zSql==0 ){
1408076b9443SCy Schubert       char *zCopy = Tcl_Alloc(pPreStmt->nSql + 1);
1409076b9443SCy Schubert       memcpy(zCopy, zSql, pPreStmt->nSql);
1410076b9443SCy Schubert       zCopy[pPreStmt->nSql] = '\0';
1411076b9443SCy Schubert       pPreStmt->zSql = zCopy;
1412076b9443SCy Schubert     }
1413076b9443SCy Schubert #endif
1414076b9443SCy Schubert   }
1415076b9443SCy Schubert   assert( pPreStmt );
1416076b9443SCy Schubert   assert( strlen30(pPreStmt->zSql)==pPreStmt->nSql );
1417076b9443SCy Schubert   assert( 0==memcmp(pPreStmt->zSql, zSql, pPreStmt->nSql) );
1418076b9443SCy Schubert 
1419076b9443SCy Schubert   /* Bind values to parameters that begin with $ or : */
1420076b9443SCy Schubert   for(i=1; i<=nVar; i++){
1421076b9443SCy Schubert     const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
1422076b9443SCy Schubert     if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){
1423076b9443SCy Schubert       Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
142402273ca8SCy Schubert       if( pVar==0 && pDb->zBindFallback!=0 ){
142502273ca8SCy Schubert         Tcl_Obj *pCmd;
142602273ca8SCy Schubert         int rx;
142702273ca8SCy Schubert         pCmd = Tcl_NewStringObj(pDb->zBindFallback, -1);
142802273ca8SCy Schubert         Tcl_IncrRefCount(pCmd);
142902273ca8SCy Schubert         Tcl_ListObjAppendElement(interp, pCmd, Tcl_NewStringObj(zVar,-1));
143002273ca8SCy Schubert         if( needResultReset ) Tcl_ResetResult(interp);
143102273ca8SCy Schubert         needResultReset = 1;
143202273ca8SCy Schubert         rx = Tcl_EvalObjEx(interp, pCmd, TCL_EVAL_DIRECT);
143302273ca8SCy Schubert         Tcl_DecrRefCount(pCmd);
143402273ca8SCy Schubert         if( rx==TCL_OK ){
143502273ca8SCy Schubert           pVar = Tcl_GetObjResult(interp);
143602273ca8SCy Schubert         }else if( rx==TCL_ERROR ){
143702273ca8SCy Schubert           rc = TCL_ERROR;
143802273ca8SCy Schubert           break;
143902273ca8SCy Schubert         }else{
144002273ca8SCy Schubert           pVar = 0;
144102273ca8SCy Schubert         }
144202273ca8SCy Schubert       }
1443076b9443SCy Schubert       if( pVar ){
1444076b9443SCy Schubert         int n;
1445076b9443SCy Schubert         u8 *data;
1446076b9443SCy Schubert         const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
1447076b9443SCy Schubert         c = zType[0];
1448076b9443SCy Schubert         if( zVar[0]=='@' ||
1449076b9443SCy Schubert            (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){
1450076b9443SCy Schubert           /* Load a BLOB type if the Tcl variable is a bytearray and
1451076b9443SCy Schubert           ** it has no string representation or the host
1452076b9443SCy Schubert           ** parameter name begins with "@". */
1453076b9443SCy Schubert           data = Tcl_GetByteArrayFromObj(pVar, &n);
1454076b9443SCy Schubert           sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
1455076b9443SCy Schubert           Tcl_IncrRefCount(pVar);
1456076b9443SCy Schubert           pPreStmt->apParm[iParm++] = pVar;
1457076b9443SCy Schubert         }else if( c=='b' && strcmp(zType,"boolean")==0 ){
1458076b9443SCy Schubert           Tcl_GetIntFromObj(interp, pVar, &n);
1459076b9443SCy Schubert           sqlite3_bind_int(pStmt, i, n);
1460076b9443SCy Schubert         }else if( c=='d' && strcmp(zType,"double")==0 ){
1461076b9443SCy Schubert           double r;
1462076b9443SCy Schubert           Tcl_GetDoubleFromObj(interp, pVar, &r);
1463076b9443SCy Schubert           sqlite3_bind_double(pStmt, i, r);
1464076b9443SCy Schubert         }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
1465076b9443SCy Schubert               (c=='i' && strcmp(zType,"int")==0) ){
1466076b9443SCy Schubert           Tcl_WideInt v;
1467076b9443SCy Schubert           Tcl_GetWideIntFromObj(interp, pVar, &v);
1468076b9443SCy Schubert           sqlite3_bind_int64(pStmt, i, v);
1469076b9443SCy Schubert         }else{
1470076b9443SCy Schubert           data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1471076b9443SCy Schubert           sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
1472076b9443SCy Schubert           Tcl_IncrRefCount(pVar);
1473076b9443SCy Schubert           pPreStmt->apParm[iParm++] = pVar;
1474076b9443SCy Schubert         }
1475076b9443SCy Schubert       }else{
1476076b9443SCy Schubert         sqlite3_bind_null(pStmt, i);
1477076b9443SCy Schubert       }
147802273ca8SCy Schubert       if( needResultReset ) Tcl_ResetResult(pDb->interp);
1479076b9443SCy Schubert     }
1480076b9443SCy Schubert   }
1481076b9443SCy Schubert   pPreStmt->nParm = iParm;
1482076b9443SCy Schubert   *ppPreStmt = pPreStmt;
148302273ca8SCy Schubert   if( needResultReset && rc==TCL_OK ) Tcl_ResetResult(pDb->interp);
1484076b9443SCy Schubert 
148502273ca8SCy Schubert   return rc;
1486076b9443SCy Schubert }
1487076b9443SCy Schubert 
1488076b9443SCy Schubert /*
1489076b9443SCy Schubert ** Release a statement reference obtained by calling dbPrepareAndBind().
1490076b9443SCy Schubert ** There should be exactly one call to this function for each call to
1491076b9443SCy Schubert ** dbPrepareAndBind().
1492076b9443SCy Schubert **
1493076b9443SCy Schubert ** If the discard parameter is non-zero, then the statement is deleted
1494076b9443SCy Schubert ** immediately. Otherwise it is added to the LRU list and may be returned
1495076b9443SCy Schubert ** by a subsequent call to dbPrepareAndBind().
1496076b9443SCy Schubert */
1497076b9443SCy Schubert static void dbReleaseStmt(
1498076b9443SCy Schubert   SqliteDb *pDb,                  /* Database handle */
1499076b9443SCy Schubert   SqlPreparedStmt *pPreStmt,      /* Prepared statement handle to release */
1500076b9443SCy Schubert   int discard                     /* True to delete (not cache) the pPreStmt */
1501076b9443SCy Schubert ){
1502076b9443SCy Schubert   int i;
1503076b9443SCy Schubert 
1504076b9443SCy Schubert   /* Free the bound string and blob parameters */
1505076b9443SCy Schubert   for(i=0; i<pPreStmt->nParm; i++){
1506076b9443SCy Schubert     Tcl_DecrRefCount(pPreStmt->apParm[i]);
1507076b9443SCy Schubert   }
1508076b9443SCy Schubert   pPreStmt->nParm = 0;
1509076b9443SCy Schubert 
1510076b9443SCy Schubert   if( pDb->maxStmt<=0 || discard ){
1511076b9443SCy Schubert     /* If the cache is turned off, deallocated the statement */
1512076b9443SCy Schubert     dbFreeStmt(pPreStmt);
1513076b9443SCy Schubert   }else{
1514076b9443SCy Schubert     /* Add the prepared statement to the beginning of the cache list. */
1515076b9443SCy Schubert     pPreStmt->pNext = pDb->stmtList;
1516076b9443SCy Schubert     pPreStmt->pPrev = 0;
1517076b9443SCy Schubert     if( pDb->stmtList ){
1518076b9443SCy Schubert      pDb->stmtList->pPrev = pPreStmt;
1519076b9443SCy Schubert     }
1520076b9443SCy Schubert     pDb->stmtList = pPreStmt;
1521076b9443SCy Schubert     if( pDb->stmtLast==0 ){
1522076b9443SCy Schubert       assert( pDb->nStmt==0 );
1523076b9443SCy Schubert       pDb->stmtLast = pPreStmt;
1524076b9443SCy Schubert     }else{
1525076b9443SCy Schubert       assert( pDb->nStmt>0 );
1526076b9443SCy Schubert     }
1527076b9443SCy Schubert     pDb->nStmt++;
1528076b9443SCy Schubert 
1529076b9443SCy Schubert     /* If we have too many statement in cache, remove the surplus from
1530076b9443SCy Schubert     ** the end of the cache list.  */
1531076b9443SCy Schubert     while( pDb->nStmt>pDb->maxStmt ){
1532076b9443SCy Schubert       SqlPreparedStmt *pLast = pDb->stmtLast;
1533076b9443SCy Schubert       pDb->stmtLast = pLast->pPrev;
1534076b9443SCy Schubert       pDb->stmtLast->pNext = 0;
1535076b9443SCy Schubert       pDb->nStmt--;
1536076b9443SCy Schubert       dbFreeStmt(pLast);
1537076b9443SCy Schubert     }
1538076b9443SCy Schubert   }
1539076b9443SCy Schubert }
1540076b9443SCy Schubert 
1541076b9443SCy Schubert /*
1542076b9443SCy Schubert ** Structure used with dbEvalXXX() functions:
1543076b9443SCy Schubert **
1544076b9443SCy Schubert **   dbEvalInit()
1545076b9443SCy Schubert **   dbEvalStep()
1546076b9443SCy Schubert **   dbEvalFinalize()
1547076b9443SCy Schubert **   dbEvalRowInfo()
1548076b9443SCy Schubert **   dbEvalColumnValue()
1549076b9443SCy Schubert */
1550076b9443SCy Schubert typedef struct DbEvalContext DbEvalContext;
1551076b9443SCy Schubert struct DbEvalContext {
1552076b9443SCy Schubert   SqliteDb *pDb;                  /* Database handle */
1553076b9443SCy Schubert   Tcl_Obj *pSql;                  /* Object holding string zSql */
1554076b9443SCy Schubert   const char *zSql;               /* Remaining SQL to execute */
1555076b9443SCy Schubert   SqlPreparedStmt *pPreStmt;      /* Current statement */
1556076b9443SCy Schubert   int nCol;                       /* Number of columns returned by pStmt */
1557076b9443SCy Schubert   int evalFlags;                  /* Flags used */
1558076b9443SCy Schubert   Tcl_Obj *pArray;                /* Name of array variable */
1559076b9443SCy Schubert   Tcl_Obj **apColName;            /* Array of column names */
1560076b9443SCy Schubert };
1561076b9443SCy Schubert 
1562076b9443SCy Schubert #define SQLITE_EVAL_WITHOUTNULLS  0x00001  /* Unset array(*) for NULL */
1563076b9443SCy Schubert 
1564076b9443SCy Schubert /*
1565076b9443SCy Schubert ** Release any cache of column names currently held as part of
1566076b9443SCy Schubert ** the DbEvalContext structure passed as the first argument.
1567076b9443SCy Schubert */
1568076b9443SCy Schubert static void dbReleaseColumnNames(DbEvalContext *p){
1569076b9443SCy Schubert   if( p->apColName ){
1570076b9443SCy Schubert     int i;
1571076b9443SCy Schubert     for(i=0; i<p->nCol; i++){
1572076b9443SCy Schubert       Tcl_DecrRefCount(p->apColName[i]);
1573076b9443SCy Schubert     }
1574076b9443SCy Schubert     Tcl_Free((char *)p->apColName);
1575076b9443SCy Schubert     p->apColName = 0;
1576076b9443SCy Schubert   }
1577076b9443SCy Schubert   p->nCol = 0;
1578076b9443SCy Schubert }
1579076b9443SCy Schubert 
1580076b9443SCy Schubert /*
1581076b9443SCy Schubert ** Initialize a DbEvalContext structure.
1582076b9443SCy Schubert **
1583076b9443SCy Schubert ** If pArray is not NULL, then it contains the name of a Tcl array
1584076b9443SCy Schubert ** variable. The "*" member of this array is set to a list containing
1585076b9443SCy Schubert ** the names of the columns returned by the statement as part of each
1586076b9443SCy Schubert ** call to dbEvalStep(), in order from left to right. e.g. if the names
1587076b9443SCy Schubert ** of the returned columns are a, b and c, it does the equivalent of the
1588076b9443SCy Schubert ** tcl command:
1589076b9443SCy Schubert **
1590076b9443SCy Schubert **     set ${pArray}(*) {a b c}
1591076b9443SCy Schubert */
1592076b9443SCy Schubert static void dbEvalInit(
1593076b9443SCy Schubert   DbEvalContext *p,               /* Pointer to structure to initialize */
1594076b9443SCy Schubert   SqliteDb *pDb,                  /* Database handle */
1595076b9443SCy Schubert   Tcl_Obj *pSql,                  /* Object containing SQL script */
1596076b9443SCy Schubert   Tcl_Obj *pArray,                /* Name of Tcl array to set (*) element of */
1597076b9443SCy Schubert   int evalFlags                   /* Flags controlling evaluation */
1598076b9443SCy Schubert ){
1599076b9443SCy Schubert   memset(p, 0, sizeof(DbEvalContext));
1600076b9443SCy Schubert   p->pDb = pDb;
1601076b9443SCy Schubert   p->zSql = Tcl_GetString(pSql);
1602076b9443SCy Schubert   p->pSql = pSql;
1603076b9443SCy Schubert   Tcl_IncrRefCount(pSql);
1604076b9443SCy Schubert   if( pArray ){
1605076b9443SCy Schubert     p->pArray = pArray;
1606076b9443SCy Schubert     Tcl_IncrRefCount(pArray);
1607076b9443SCy Schubert   }
1608076b9443SCy Schubert   p->evalFlags = evalFlags;
16090197ba46SCy Schubert   addDatabaseRef(p->pDb);
1610076b9443SCy Schubert }
1611076b9443SCy Schubert 
1612076b9443SCy Schubert /*
1613076b9443SCy Schubert ** Obtain information about the row that the DbEvalContext passed as the
1614076b9443SCy Schubert ** first argument currently points to.
1615076b9443SCy Schubert */
1616076b9443SCy Schubert static void dbEvalRowInfo(
1617076b9443SCy Schubert   DbEvalContext *p,               /* Evaluation context */
1618076b9443SCy Schubert   int *pnCol,                     /* OUT: Number of column names */
1619076b9443SCy Schubert   Tcl_Obj ***papColName           /* OUT: Array of column names */
1620076b9443SCy Schubert ){
1621076b9443SCy Schubert   /* Compute column names */
1622076b9443SCy Schubert   if( 0==p->apColName ){
1623076b9443SCy Schubert     sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1624076b9443SCy Schubert     int i;                        /* Iterator variable */
1625076b9443SCy Schubert     int nCol;                     /* Number of columns returned by pStmt */
1626076b9443SCy Schubert     Tcl_Obj **apColName = 0;      /* Array of column names */
1627076b9443SCy Schubert 
1628076b9443SCy Schubert     p->nCol = nCol = sqlite3_column_count(pStmt);
1629076b9443SCy Schubert     if( nCol>0 && (papColName || p->pArray) ){
1630076b9443SCy Schubert       apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
1631076b9443SCy Schubert       for(i=0; i<nCol; i++){
1632076b9443SCy Schubert         apColName[i] = Tcl_NewStringObj(sqlite3_column_name(pStmt,i), -1);
1633076b9443SCy Schubert         Tcl_IncrRefCount(apColName[i]);
1634076b9443SCy Schubert       }
1635076b9443SCy Schubert       p->apColName = apColName;
1636076b9443SCy Schubert     }
1637076b9443SCy Schubert 
1638076b9443SCy Schubert     /* If results are being stored in an array variable, then create
1639076b9443SCy Schubert     ** the array(*) entry for that array
1640076b9443SCy Schubert     */
1641076b9443SCy Schubert     if( p->pArray ){
1642076b9443SCy Schubert       Tcl_Interp *interp = p->pDb->interp;
1643076b9443SCy Schubert       Tcl_Obj *pColList = Tcl_NewObj();
1644076b9443SCy Schubert       Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
1645076b9443SCy Schubert 
1646076b9443SCy Schubert       for(i=0; i<nCol; i++){
1647076b9443SCy Schubert         Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
1648076b9443SCy Schubert       }
1649076b9443SCy Schubert       Tcl_IncrRefCount(pStar);
1650076b9443SCy Schubert       Tcl_ObjSetVar2(interp, p->pArray, pStar, pColList, 0);
1651076b9443SCy Schubert       Tcl_DecrRefCount(pStar);
1652076b9443SCy Schubert     }
1653076b9443SCy Schubert   }
1654076b9443SCy Schubert 
1655076b9443SCy Schubert   if( papColName ){
1656076b9443SCy Schubert     *papColName = p->apColName;
1657076b9443SCy Schubert   }
1658076b9443SCy Schubert   if( pnCol ){
1659076b9443SCy Schubert     *pnCol = p->nCol;
1660076b9443SCy Schubert   }
1661076b9443SCy Schubert }
1662076b9443SCy Schubert 
1663076b9443SCy Schubert /*
1664076b9443SCy Schubert ** Return one of TCL_OK, TCL_BREAK or TCL_ERROR. If TCL_ERROR is
1665076b9443SCy Schubert ** returned, then an error message is stored in the interpreter before
1666076b9443SCy Schubert ** returning.
1667076b9443SCy Schubert **
1668076b9443SCy Schubert ** A return value of TCL_OK means there is a row of data available. The
1669076b9443SCy Schubert ** data may be accessed using dbEvalRowInfo() and dbEvalColumnValue(). This
1670076b9443SCy Schubert ** is analogous to a return of SQLITE_ROW from sqlite3_step(). If TCL_BREAK
1671076b9443SCy Schubert ** is returned, then the SQL script has finished executing and there are
1672076b9443SCy Schubert ** no further rows available. This is similar to SQLITE_DONE.
1673076b9443SCy Schubert */
1674076b9443SCy Schubert static int dbEvalStep(DbEvalContext *p){
1675076b9443SCy Schubert   const char *zPrevSql = 0;       /* Previous value of p->zSql */
1676076b9443SCy Schubert 
1677076b9443SCy Schubert   while( p->zSql[0] || p->pPreStmt ){
1678076b9443SCy Schubert     int rc;
1679076b9443SCy Schubert     if( p->pPreStmt==0 ){
1680076b9443SCy Schubert       zPrevSql = (p->zSql==zPrevSql ? 0 : p->zSql);
1681076b9443SCy Schubert       rc = dbPrepareAndBind(p->pDb, p->zSql, &p->zSql, &p->pPreStmt);
1682076b9443SCy Schubert       if( rc!=TCL_OK ) return rc;
1683076b9443SCy Schubert     }else{
1684076b9443SCy Schubert       int rcs;
1685076b9443SCy Schubert       SqliteDb *pDb = p->pDb;
1686076b9443SCy Schubert       SqlPreparedStmt *pPreStmt = p->pPreStmt;
1687076b9443SCy Schubert       sqlite3_stmt *pStmt = pPreStmt->pStmt;
1688076b9443SCy Schubert 
1689076b9443SCy Schubert       rcs = sqlite3_step(pStmt);
1690076b9443SCy Schubert       if( rcs==SQLITE_ROW ){
1691076b9443SCy Schubert         return TCL_OK;
1692076b9443SCy Schubert       }
1693076b9443SCy Schubert       if( p->pArray ){
1694076b9443SCy Schubert         dbEvalRowInfo(p, 0, 0);
1695076b9443SCy Schubert       }
1696076b9443SCy Schubert       rcs = sqlite3_reset(pStmt);
1697076b9443SCy Schubert 
1698076b9443SCy Schubert       pDb->nStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_FULLSCAN_STEP,1);
1699076b9443SCy Schubert       pDb->nSort = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_SORT,1);
1700076b9443SCy Schubert       pDb->nIndex = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_AUTOINDEX,1);
1701076b9443SCy Schubert       pDb->nVMStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_VM_STEP,1);
1702076b9443SCy Schubert       dbReleaseColumnNames(p);
1703076b9443SCy Schubert       p->pPreStmt = 0;
1704076b9443SCy Schubert 
1705076b9443SCy Schubert       if( rcs!=SQLITE_OK ){
1706076b9443SCy Schubert         /* If a run-time error occurs, report the error and stop reading
1707076b9443SCy Schubert         ** the SQL.  */
1708076b9443SCy Schubert         dbReleaseStmt(pDb, pPreStmt, 1);
1709076b9443SCy Schubert #if SQLITE_TEST
1710076b9443SCy Schubert         if( p->pDb->bLegacyPrepare && rcs==SQLITE_SCHEMA && zPrevSql ){
1711076b9443SCy Schubert           /* If the runtime error was an SQLITE_SCHEMA, and the database
1712076b9443SCy Schubert           ** handle is configured to use the legacy sqlite3_prepare()
1713076b9443SCy Schubert           ** interface, retry prepare()/step() on the same SQL statement.
1714076b9443SCy Schubert           ** This only happens once. If there is a second SQLITE_SCHEMA
1715076b9443SCy Schubert           ** error, the error will be returned to the caller. */
1716076b9443SCy Schubert           p->zSql = zPrevSql;
1717076b9443SCy Schubert           continue;
1718076b9443SCy Schubert         }
1719076b9443SCy Schubert #endif
1720076b9443SCy Schubert         Tcl_SetObjResult(pDb->interp,
1721076b9443SCy Schubert                          Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
1722076b9443SCy Schubert         return TCL_ERROR;
1723076b9443SCy Schubert       }else{
1724076b9443SCy Schubert         dbReleaseStmt(pDb, pPreStmt, 0);
1725076b9443SCy Schubert       }
1726076b9443SCy Schubert     }
1727076b9443SCy Schubert   }
1728076b9443SCy Schubert 
1729076b9443SCy Schubert   /* Finished */
1730076b9443SCy Schubert   return TCL_BREAK;
1731076b9443SCy Schubert }
1732076b9443SCy Schubert 
1733076b9443SCy Schubert /*
1734076b9443SCy Schubert ** Free all resources currently held by the DbEvalContext structure passed
1735076b9443SCy Schubert ** as the first argument. There should be exactly one call to this function
1736076b9443SCy Schubert ** for each call to dbEvalInit().
1737076b9443SCy Schubert */
1738076b9443SCy Schubert static void dbEvalFinalize(DbEvalContext *p){
1739076b9443SCy Schubert   if( p->pPreStmt ){
1740076b9443SCy Schubert     sqlite3_reset(p->pPreStmt->pStmt);
1741076b9443SCy Schubert     dbReleaseStmt(p->pDb, p->pPreStmt, 0);
1742076b9443SCy Schubert     p->pPreStmt = 0;
1743076b9443SCy Schubert   }
1744076b9443SCy Schubert   if( p->pArray ){
1745076b9443SCy Schubert     Tcl_DecrRefCount(p->pArray);
1746076b9443SCy Schubert     p->pArray = 0;
1747076b9443SCy Schubert   }
1748076b9443SCy Schubert   Tcl_DecrRefCount(p->pSql);
1749076b9443SCy Schubert   dbReleaseColumnNames(p);
17500197ba46SCy Schubert   delDatabaseRef(p->pDb);
1751076b9443SCy Schubert }
1752076b9443SCy Schubert 
1753076b9443SCy Schubert /*
1754076b9443SCy Schubert ** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains
1755076b9443SCy Schubert ** the value for the iCol'th column of the row currently pointed to by
1756076b9443SCy Schubert ** the DbEvalContext structure passed as the first argument.
1757076b9443SCy Schubert */
1758076b9443SCy Schubert static Tcl_Obj *dbEvalColumnValue(DbEvalContext *p, int iCol){
1759076b9443SCy Schubert   sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1760076b9443SCy Schubert   switch( sqlite3_column_type(pStmt, iCol) ){
1761076b9443SCy Schubert     case SQLITE_BLOB: {
1762076b9443SCy Schubert       int bytes = sqlite3_column_bytes(pStmt, iCol);
1763076b9443SCy Schubert       const char *zBlob = sqlite3_column_blob(pStmt, iCol);
1764076b9443SCy Schubert       if( !zBlob ) bytes = 0;
1765076b9443SCy Schubert       return Tcl_NewByteArrayObj((u8*)zBlob, bytes);
1766076b9443SCy Schubert     }
1767076b9443SCy Schubert     case SQLITE_INTEGER: {
1768076b9443SCy Schubert       sqlite_int64 v = sqlite3_column_int64(pStmt, iCol);
1769076b9443SCy Schubert       if( v>=-2147483647 && v<=2147483647 ){
1770076b9443SCy Schubert         return Tcl_NewIntObj((int)v);
1771076b9443SCy Schubert       }else{
1772076b9443SCy Schubert         return Tcl_NewWideIntObj(v);
1773076b9443SCy Schubert       }
1774076b9443SCy Schubert     }
1775076b9443SCy Schubert     case SQLITE_FLOAT: {
1776076b9443SCy Schubert       return Tcl_NewDoubleObj(sqlite3_column_double(pStmt, iCol));
1777076b9443SCy Schubert     }
1778076b9443SCy Schubert     case SQLITE_NULL: {
1779076b9443SCy Schubert       return Tcl_NewStringObj(p->pDb->zNull, -1);
1780076b9443SCy Schubert     }
1781076b9443SCy Schubert   }
1782076b9443SCy Schubert 
1783076b9443SCy Schubert   return Tcl_NewStringObj((char*)sqlite3_column_text(pStmt, iCol), -1);
1784076b9443SCy Schubert }
1785076b9443SCy Schubert 
1786076b9443SCy Schubert /*
1787076b9443SCy Schubert ** If using Tcl version 8.6 or greater, use the NR functions to avoid
1788076b9443SCy Schubert ** recursive evalution of scripts by the [db eval] and [db trans]
1789076b9443SCy Schubert ** commands. Even if the headers used while compiling the extension
1790076b9443SCy Schubert ** are 8.6 or newer, the code still tests the Tcl version at runtime.
1791076b9443SCy Schubert ** This allows stubs-enabled builds to be used with older Tcl libraries.
1792076b9443SCy Schubert */
1793076b9443SCy Schubert #if TCL_MAJOR_VERSION>8 || (TCL_MAJOR_VERSION==8 && TCL_MINOR_VERSION>=6)
1794076b9443SCy Schubert # define SQLITE_TCL_NRE 1
1795076b9443SCy Schubert static int DbUseNre(void){
1796076b9443SCy Schubert   int major, minor;
1797076b9443SCy Schubert   Tcl_GetVersion(&major, &minor, 0, 0);
1798076b9443SCy Schubert   return( (major==8 && minor>=6) || major>8 );
1799076b9443SCy Schubert }
1800076b9443SCy Schubert #else
1801076b9443SCy Schubert /*
1802076b9443SCy Schubert ** Compiling using headers earlier than 8.6. In this case NR cannot be
1803076b9443SCy Schubert ** used, so DbUseNre() to always return zero. Add #defines for the other
1804076b9443SCy Schubert ** Tcl_NRxxx() functions to prevent them from causing compilation errors,
1805076b9443SCy Schubert ** even though the only invocations of them are within conditional blocks
1806076b9443SCy Schubert ** of the form:
1807076b9443SCy Schubert **
1808076b9443SCy Schubert **   if( DbUseNre() ) { ... }
1809076b9443SCy Schubert */
1810076b9443SCy Schubert # define SQLITE_TCL_NRE 0
1811076b9443SCy Schubert # define DbUseNre() 0
1812076b9443SCy Schubert # define Tcl_NRAddCallback(a,b,c,d,e,f) (void)0
1813076b9443SCy Schubert # define Tcl_NREvalObj(a,b,c) 0
1814076b9443SCy Schubert # define Tcl_NRCreateCommand(a,b,c,d,e,f) (void)0
1815076b9443SCy Schubert #endif
1816076b9443SCy Schubert 
1817076b9443SCy Schubert /*
1818076b9443SCy Schubert ** This function is part of the implementation of the command:
1819076b9443SCy Schubert **
1820076b9443SCy Schubert **   $db eval SQL ?ARRAYNAME? SCRIPT
1821076b9443SCy Schubert */
1822076b9443SCy Schubert static int SQLITE_TCLAPI DbEvalNextCmd(
1823076b9443SCy Schubert   ClientData data[],                   /* data[0] is the (DbEvalContext*) */
1824076b9443SCy Schubert   Tcl_Interp *interp,                  /* Tcl interpreter */
1825076b9443SCy Schubert   int result                           /* Result so far */
1826076b9443SCy Schubert ){
1827076b9443SCy Schubert   int rc = result;                     /* Return code */
1828076b9443SCy Schubert 
1829076b9443SCy Schubert   /* The first element of the data[] array is a pointer to a DbEvalContext
1830076b9443SCy Schubert   ** structure allocated using Tcl_Alloc(). The second element of data[]
1831076b9443SCy Schubert   ** is a pointer to a Tcl_Obj containing the script to run for each row
1832076b9443SCy Schubert   ** returned by the queries encapsulated in data[0]. */
1833076b9443SCy Schubert   DbEvalContext *p = (DbEvalContext *)data[0];
1834076b9443SCy Schubert   Tcl_Obj *pScript = (Tcl_Obj *)data[1];
1835076b9443SCy Schubert   Tcl_Obj *pArray = p->pArray;
1836076b9443SCy Schubert 
1837076b9443SCy Schubert   while( (rc==TCL_OK || rc==TCL_CONTINUE) && TCL_OK==(rc = dbEvalStep(p)) ){
1838076b9443SCy Schubert     int i;
1839076b9443SCy Schubert     int nCol;
1840076b9443SCy Schubert     Tcl_Obj **apColName;
1841076b9443SCy Schubert     dbEvalRowInfo(p, &nCol, &apColName);
1842076b9443SCy Schubert     for(i=0; i<nCol; i++){
1843076b9443SCy Schubert       if( pArray==0 ){
1844076b9443SCy Schubert         Tcl_ObjSetVar2(interp, apColName[i], 0, dbEvalColumnValue(p,i), 0);
1845076b9443SCy Schubert       }else if( (p->evalFlags & SQLITE_EVAL_WITHOUTNULLS)!=0
1846076b9443SCy Schubert              && sqlite3_column_type(p->pPreStmt->pStmt, i)==SQLITE_NULL
1847076b9443SCy Schubert       ){
1848076b9443SCy Schubert         Tcl_UnsetVar2(interp, Tcl_GetString(pArray),
1849076b9443SCy Schubert                       Tcl_GetString(apColName[i]), 0);
1850076b9443SCy Schubert       }else{
1851076b9443SCy Schubert         Tcl_ObjSetVar2(interp, pArray, apColName[i], dbEvalColumnValue(p,i), 0);
1852076b9443SCy Schubert       }
1853076b9443SCy Schubert     }
1854076b9443SCy Schubert 
1855076b9443SCy Schubert     /* The required interpreter variables are now populated with the data
1856076b9443SCy Schubert     ** from the current row. If using NRE, schedule callbacks to evaluate
1857076b9443SCy Schubert     ** script pScript, then to invoke this function again to fetch the next
1858076b9443SCy Schubert     ** row (or clean up if there is no next row or the script throws an
1859076b9443SCy Schubert     ** exception). After scheduling the callbacks, return control to the
1860076b9443SCy Schubert     ** caller.
1861076b9443SCy Schubert     **
1862076b9443SCy Schubert     ** If not using NRE, evaluate pScript directly and continue with the
1863076b9443SCy Schubert     ** next iteration of this while(...) loop.  */
1864076b9443SCy Schubert     if( DbUseNre() ){
1865076b9443SCy Schubert       Tcl_NRAddCallback(interp, DbEvalNextCmd, (void*)p, (void*)pScript, 0, 0);
1866076b9443SCy Schubert       return Tcl_NREvalObj(interp, pScript, 0);
1867076b9443SCy Schubert     }else{
1868076b9443SCy Schubert       rc = Tcl_EvalObjEx(interp, pScript, 0);
1869076b9443SCy Schubert     }
1870076b9443SCy Schubert   }
1871076b9443SCy Schubert 
1872076b9443SCy Schubert   Tcl_DecrRefCount(pScript);
1873076b9443SCy Schubert   dbEvalFinalize(p);
1874076b9443SCy Schubert   Tcl_Free((char *)p);
1875076b9443SCy Schubert 
1876076b9443SCy Schubert   if( rc==TCL_OK || rc==TCL_BREAK ){
1877076b9443SCy Schubert     Tcl_ResetResult(interp);
1878076b9443SCy Schubert     rc = TCL_OK;
1879076b9443SCy Schubert   }
1880076b9443SCy Schubert   return rc;
1881076b9443SCy Schubert }
1882076b9443SCy Schubert 
1883076b9443SCy Schubert /*
1884076b9443SCy Schubert ** This function is used by the implementations of the following database
1885076b9443SCy Schubert ** handle sub-commands:
1886076b9443SCy Schubert **
1887076b9443SCy Schubert **   $db update_hook ?SCRIPT?
1888076b9443SCy Schubert **   $db wal_hook ?SCRIPT?
1889076b9443SCy Schubert **   $db commit_hook ?SCRIPT?
1890076b9443SCy Schubert **   $db preupdate hook ?SCRIPT?
1891076b9443SCy Schubert */
1892076b9443SCy Schubert static void DbHookCmd(
1893076b9443SCy Schubert   Tcl_Interp *interp,             /* Tcl interpreter */
1894076b9443SCy Schubert   SqliteDb *pDb,                  /* Database handle */
1895076b9443SCy Schubert   Tcl_Obj *pArg,                  /* SCRIPT argument (or NULL) */
1896076b9443SCy Schubert   Tcl_Obj **ppHook                /* Pointer to member of SqliteDb */
1897076b9443SCy Schubert ){
1898076b9443SCy Schubert   sqlite3 *db = pDb->db;
1899076b9443SCy Schubert 
1900076b9443SCy Schubert   if( *ppHook ){
1901076b9443SCy Schubert     Tcl_SetObjResult(interp, *ppHook);
1902076b9443SCy Schubert     if( pArg ){
1903076b9443SCy Schubert       Tcl_DecrRefCount(*ppHook);
1904076b9443SCy Schubert       *ppHook = 0;
1905076b9443SCy Schubert     }
1906076b9443SCy Schubert   }
1907076b9443SCy Schubert   if( pArg ){
1908076b9443SCy Schubert     assert( !(*ppHook) );
1909076b9443SCy Schubert     if( Tcl_GetCharLength(pArg)>0 ){
1910076b9443SCy Schubert       *ppHook = pArg;
1911076b9443SCy Schubert       Tcl_IncrRefCount(*ppHook);
1912076b9443SCy Schubert     }
1913076b9443SCy Schubert   }
1914076b9443SCy Schubert 
1915076b9443SCy Schubert #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
1916076b9443SCy Schubert   sqlite3_preupdate_hook(db, (pDb->pPreUpdateHook?DbPreUpdateHandler:0), pDb);
1917076b9443SCy Schubert #endif
1918076b9443SCy Schubert   sqlite3_update_hook(db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
1919076b9443SCy Schubert   sqlite3_rollback_hook(db, (pDb->pRollbackHook?DbRollbackHandler:0), pDb);
1920076b9443SCy Schubert   sqlite3_wal_hook(db, (pDb->pWalHook?DbWalHandler:0), pDb);
1921076b9443SCy Schubert }
1922076b9443SCy Schubert 
1923076b9443SCy Schubert /*
1924076b9443SCy Schubert ** The "sqlite" command below creates a new Tcl command for each
1925076b9443SCy Schubert ** connection it opens to an SQLite database.  This routine is invoked
1926076b9443SCy Schubert ** whenever one of those connection-specific commands is executed
1927076b9443SCy Schubert ** in Tcl.  For example, if you run Tcl code like this:
1928076b9443SCy Schubert **
1929076b9443SCy Schubert **       sqlite3 db1  "my_database"
1930076b9443SCy Schubert **       db1 close
1931076b9443SCy Schubert **
1932076b9443SCy Schubert ** The first command opens a connection to the "my_database" database
1933076b9443SCy Schubert ** and calls that connection "db1".  The second command causes this
1934076b9443SCy Schubert ** subroutine to be invoked.
1935076b9443SCy Schubert */
1936076b9443SCy Schubert static int SQLITE_TCLAPI DbObjCmd(
1937076b9443SCy Schubert   void *cd,
1938076b9443SCy Schubert   Tcl_Interp *interp,
1939076b9443SCy Schubert   int objc,
1940076b9443SCy Schubert   Tcl_Obj *const*objv
1941076b9443SCy Schubert ){
1942076b9443SCy Schubert   SqliteDb *pDb = (SqliteDb*)cd;
1943076b9443SCy Schubert   int choice;
1944076b9443SCy Schubert   int rc = TCL_OK;
1945076b9443SCy Schubert   static const char *DB_strs[] = {
194602273ca8SCy Schubert     "authorizer",             "backup",                "bind_fallback",
194702273ca8SCy Schubert     "busy",                   "cache",                 "changes",
194802273ca8SCy Schubert     "close",                  "collate",               "collation_needed",
1949f1b328b3SCy Schubert     "commit_hook",            "complete",              "config",
1950f1b328b3SCy Schubert     "copy",                   "deserialize",           "enable_load_extension",
1951*4fe1295cSCy Schubert     "errorcode",              "erroroffset",           "eval",
1952*4fe1295cSCy Schubert     "exists",                 "function",              "incrblob",
1953*4fe1295cSCy Schubert     "interrupt",              "last_insert_rowid",     "nullvalue",
1954*4fe1295cSCy Schubert     "onecolumn",              "preupdate",             "profile",
1955*4fe1295cSCy Schubert     "progress",               "rekey",                 "restore",
1956*4fe1295cSCy Schubert     "rollback_hook",          "serialize",             "status",
1957*4fe1295cSCy Schubert     "timeout",                "total_changes",         "trace",
1958*4fe1295cSCy Schubert     "trace_v2",               "transaction",           "unlock_notify",
1959*4fe1295cSCy Schubert     "update_hook",            "version",               "wal_hook",
1960*4fe1295cSCy Schubert     0
1961076b9443SCy Schubert   };
1962076b9443SCy Schubert   enum DB_enum {
196302273ca8SCy Schubert     DB_AUTHORIZER,            DB_BACKUP,               DB_BIND_FALLBACK,
196402273ca8SCy Schubert     DB_BUSY,                  DB_CACHE,                DB_CHANGES,
196502273ca8SCy Schubert     DB_CLOSE,                 DB_COLLATE,              DB_COLLATION_NEEDED,
1966f1b328b3SCy Schubert     DB_COMMIT_HOOK,           DB_COMPLETE,             DB_CONFIG,
1967f1b328b3SCy Schubert     DB_COPY,                  DB_DESERIALIZE,          DB_ENABLE_LOAD_EXTENSION,
1968*4fe1295cSCy Schubert     DB_ERRORCODE,             DB_ERROROFFSET,          DB_EVAL,
1969*4fe1295cSCy Schubert     DB_EXISTS,                DB_FUNCTION,             DB_INCRBLOB,
1970*4fe1295cSCy Schubert     DB_INTERRUPT,             DB_LAST_INSERT_ROWID,    DB_NULLVALUE,
1971*4fe1295cSCy Schubert     DB_ONECOLUMN,             DB_PREUPDATE,            DB_PROFILE,
1972*4fe1295cSCy Schubert     DB_PROGRESS,              DB_REKEY,                DB_RESTORE,
1973*4fe1295cSCy Schubert     DB_ROLLBACK_HOOK,         DB_SERIALIZE,            DB_STATUS,
1974*4fe1295cSCy Schubert     DB_TIMEOUT,               DB_TOTAL_CHANGES,        DB_TRACE,
1975*4fe1295cSCy Schubert     DB_TRACE_V2,              DB_TRANSACTION,          DB_UNLOCK_NOTIFY,
1976*4fe1295cSCy Schubert     DB_UPDATE_HOOK,           DB_VERSION,              DB_WAL_HOOK,
1977076b9443SCy Schubert   };
1978076b9443SCy Schubert   /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
1979076b9443SCy Schubert 
1980076b9443SCy Schubert   if( objc<2 ){
1981076b9443SCy Schubert     Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
1982076b9443SCy Schubert     return TCL_ERROR;
1983076b9443SCy Schubert   }
1984076b9443SCy Schubert   if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
1985076b9443SCy Schubert     return TCL_ERROR;
1986076b9443SCy Schubert   }
1987076b9443SCy Schubert 
1988076b9443SCy Schubert   switch( (enum DB_enum)choice ){
1989076b9443SCy Schubert 
1990076b9443SCy Schubert   /*    $db authorizer ?CALLBACK?
1991076b9443SCy Schubert   **
1992076b9443SCy Schubert   ** Invoke the given callback to authorize each SQL operation as it is
1993076b9443SCy Schubert   ** compiled.  5 arguments are appended to the callback before it is
1994076b9443SCy Schubert   ** invoked:
1995076b9443SCy Schubert   **
1996076b9443SCy Schubert   **   (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
1997076b9443SCy Schubert   **   (2) First descriptive name (depends on authorization type)
1998076b9443SCy Schubert   **   (3) Second descriptive name
1999076b9443SCy Schubert   **   (4) Name of the database (ex: "main", "temp")
2000076b9443SCy Schubert   **   (5) Name of trigger that is doing the access
2001076b9443SCy Schubert   **
2002076b9443SCy Schubert   ** The callback should return on of the following strings: SQLITE_OK,
2003076b9443SCy Schubert   ** SQLITE_IGNORE, or SQLITE_DENY.  Any other return value is an error.
2004076b9443SCy Schubert   **
2005076b9443SCy Schubert   ** If this method is invoked with no arguments, the current authorization
2006076b9443SCy Schubert   ** callback string is returned.
2007076b9443SCy Schubert   */
2008076b9443SCy Schubert   case DB_AUTHORIZER: {
2009076b9443SCy Schubert #ifdef SQLITE_OMIT_AUTHORIZATION
2010076b9443SCy Schubert     Tcl_AppendResult(interp, "authorization not available in this build",
2011076b9443SCy Schubert                      (char*)0);
2012076b9443SCy Schubert     return TCL_ERROR;
2013076b9443SCy Schubert #else
2014076b9443SCy Schubert     if( objc>3 ){
2015076b9443SCy Schubert       Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2016076b9443SCy Schubert       return TCL_ERROR;
2017076b9443SCy Schubert     }else if( objc==2 ){
2018076b9443SCy Schubert       if( pDb->zAuth ){
2019076b9443SCy Schubert         Tcl_AppendResult(interp, pDb->zAuth, (char*)0);
2020076b9443SCy Schubert       }
2021076b9443SCy Schubert     }else{
2022076b9443SCy Schubert       char *zAuth;
2023076b9443SCy Schubert       int len;
2024076b9443SCy Schubert       if( pDb->zAuth ){
2025076b9443SCy Schubert         Tcl_Free(pDb->zAuth);
2026076b9443SCy Schubert       }
2027076b9443SCy Schubert       zAuth = Tcl_GetStringFromObj(objv[2], &len);
2028076b9443SCy Schubert       if( zAuth && len>0 ){
2029076b9443SCy Schubert         pDb->zAuth = Tcl_Alloc( len + 1 );
2030076b9443SCy Schubert         memcpy(pDb->zAuth, zAuth, len+1);
2031076b9443SCy Schubert       }else{
2032076b9443SCy Schubert         pDb->zAuth = 0;
2033076b9443SCy Schubert       }
2034076b9443SCy Schubert       if( pDb->zAuth ){
2035076b9443SCy Schubert         typedef int (*sqlite3_auth_cb)(
2036076b9443SCy Schubert            void*,int,const char*,const char*,
2037076b9443SCy Schubert            const char*,const char*);
2038076b9443SCy Schubert         pDb->interp = interp;
2039076b9443SCy Schubert         sqlite3_set_authorizer(pDb->db,(sqlite3_auth_cb)auth_callback,pDb);
2040076b9443SCy Schubert       }else{
2041076b9443SCy Schubert         sqlite3_set_authorizer(pDb->db, 0, 0);
2042076b9443SCy Schubert       }
2043076b9443SCy Schubert     }
2044076b9443SCy Schubert #endif
2045076b9443SCy Schubert     break;
2046076b9443SCy Schubert   }
2047076b9443SCy Schubert 
2048076b9443SCy Schubert   /*    $db backup ?DATABASE? FILENAME
2049076b9443SCy Schubert   **
2050076b9443SCy Schubert   ** Open or create a database file named FILENAME.  Transfer the
2051076b9443SCy Schubert   ** content of local database DATABASE (default: "main") into the
2052076b9443SCy Schubert   ** FILENAME database.
2053076b9443SCy Schubert   */
2054076b9443SCy Schubert   case DB_BACKUP: {
2055076b9443SCy Schubert     const char *zDestFile;
2056076b9443SCy Schubert     const char *zSrcDb;
2057076b9443SCy Schubert     sqlite3 *pDest;
2058076b9443SCy Schubert     sqlite3_backup *pBackup;
2059076b9443SCy Schubert 
2060076b9443SCy Schubert     if( objc==3 ){
2061076b9443SCy Schubert       zSrcDb = "main";
2062076b9443SCy Schubert       zDestFile = Tcl_GetString(objv[2]);
2063076b9443SCy Schubert     }else if( objc==4 ){
2064076b9443SCy Schubert       zSrcDb = Tcl_GetString(objv[2]);
2065076b9443SCy Schubert       zDestFile = Tcl_GetString(objv[3]);
2066076b9443SCy Schubert     }else{
2067076b9443SCy Schubert       Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
2068076b9443SCy Schubert       return TCL_ERROR;
2069076b9443SCy Schubert     }
2070076b9443SCy Schubert     rc = sqlite3_open_v2(zDestFile, &pDest,
2071076b9443SCy Schubert                SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE| pDb->openFlags, 0);
2072076b9443SCy Schubert     if( rc!=SQLITE_OK ){
2073076b9443SCy Schubert       Tcl_AppendResult(interp, "cannot open target database: ",
2074076b9443SCy Schubert            sqlite3_errmsg(pDest), (char*)0);
2075076b9443SCy Schubert       sqlite3_close(pDest);
2076076b9443SCy Schubert       return TCL_ERROR;
2077076b9443SCy Schubert     }
2078076b9443SCy Schubert     pBackup = sqlite3_backup_init(pDest, "main", pDb->db, zSrcDb);
2079076b9443SCy Schubert     if( pBackup==0 ){
2080076b9443SCy Schubert       Tcl_AppendResult(interp, "backup failed: ",
2081076b9443SCy Schubert            sqlite3_errmsg(pDest), (char*)0);
2082076b9443SCy Schubert       sqlite3_close(pDest);
2083076b9443SCy Schubert       return TCL_ERROR;
2084076b9443SCy Schubert     }
2085076b9443SCy Schubert     while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
2086076b9443SCy Schubert     sqlite3_backup_finish(pBackup);
2087076b9443SCy Schubert     if( rc==SQLITE_DONE ){
2088076b9443SCy Schubert       rc = TCL_OK;
2089076b9443SCy Schubert     }else{
2090076b9443SCy Schubert       Tcl_AppendResult(interp, "backup failed: ",
2091076b9443SCy Schubert            sqlite3_errmsg(pDest), (char*)0);
2092076b9443SCy Schubert       rc = TCL_ERROR;
2093076b9443SCy Schubert     }
2094076b9443SCy Schubert     sqlite3_close(pDest);
2095076b9443SCy Schubert     break;
2096076b9443SCy Schubert   }
2097076b9443SCy Schubert 
209802273ca8SCy Schubert   /*    $db bind_fallback ?CALLBACK?
209902273ca8SCy Schubert   **
210002273ca8SCy Schubert   ** When resolving bind parameters in an SQL statement, if the parameter
210102273ca8SCy Schubert   ** cannot be associated with a TCL variable then invoke CALLBACK with a
210202273ca8SCy Schubert   ** single argument that is the name of the parameter and use the return
210302273ca8SCy Schubert   ** value of the CALLBACK as the binding.  If CALLBACK returns something
210402273ca8SCy Schubert   ** other than TCL_OK or TCL_ERROR then bind a NULL.
210502273ca8SCy Schubert   **
210602273ca8SCy Schubert   ** If CALLBACK is an empty string, then revert to the default behavior
210702273ca8SCy Schubert   ** which is to set the binding to NULL.
210802273ca8SCy Schubert   **
210902273ca8SCy Schubert   ** If CALLBACK returns an error, that causes the statement execution to
211002273ca8SCy Schubert   ** abort.  Hence, to configure a connection so that it throws an error
211102273ca8SCy Schubert   ** on an attempt to bind an unknown variable, do something like this:
211202273ca8SCy Schubert   **
211302273ca8SCy Schubert   **     proc bind_error {name} {error "no such variable: $name"}
211402273ca8SCy Schubert   **     db bind_fallback bind_error
211502273ca8SCy Schubert   */
211602273ca8SCy Schubert   case DB_BIND_FALLBACK: {
211702273ca8SCy Schubert     if( objc>3 ){
211802273ca8SCy Schubert       Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
211902273ca8SCy Schubert       return TCL_ERROR;
212002273ca8SCy Schubert     }else if( objc==2 ){
212102273ca8SCy Schubert       if( pDb->zBindFallback ){
212202273ca8SCy Schubert         Tcl_AppendResult(interp, pDb->zBindFallback, (char*)0);
212302273ca8SCy Schubert       }
212402273ca8SCy Schubert     }else{
212502273ca8SCy Schubert       char *zCallback;
212602273ca8SCy Schubert       int len;
212702273ca8SCy Schubert       if( pDb->zBindFallback ){
212802273ca8SCy Schubert         Tcl_Free(pDb->zBindFallback);
212902273ca8SCy Schubert       }
213002273ca8SCy Schubert       zCallback = Tcl_GetStringFromObj(objv[2], &len);
213102273ca8SCy Schubert       if( zCallback && len>0 ){
213202273ca8SCy Schubert         pDb->zBindFallback = Tcl_Alloc( len + 1 );
213302273ca8SCy Schubert         memcpy(pDb->zBindFallback, zCallback, len+1);
213402273ca8SCy Schubert       }else{
213502273ca8SCy Schubert         pDb->zBindFallback = 0;
213602273ca8SCy Schubert       }
213702273ca8SCy Schubert     }
213802273ca8SCy Schubert     break;
213902273ca8SCy Schubert   }
214002273ca8SCy Schubert 
2141076b9443SCy Schubert   /*    $db busy ?CALLBACK?
2142076b9443SCy Schubert   **
2143076b9443SCy Schubert   ** Invoke the given callback if an SQL statement attempts to open
2144076b9443SCy Schubert   ** a locked database file.
2145076b9443SCy Schubert   */
2146076b9443SCy Schubert   case DB_BUSY: {
2147076b9443SCy Schubert     if( objc>3 ){
2148076b9443SCy Schubert       Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
2149076b9443SCy Schubert       return TCL_ERROR;
2150076b9443SCy Schubert     }else if( objc==2 ){
2151076b9443SCy Schubert       if( pDb->zBusy ){
2152076b9443SCy Schubert         Tcl_AppendResult(interp, pDb->zBusy, (char*)0);
2153076b9443SCy Schubert       }
2154076b9443SCy Schubert     }else{
2155076b9443SCy Schubert       char *zBusy;
2156076b9443SCy Schubert       int len;
2157076b9443SCy Schubert       if( pDb->zBusy ){
2158076b9443SCy Schubert         Tcl_Free(pDb->zBusy);
2159076b9443SCy Schubert       }
2160076b9443SCy Schubert       zBusy = Tcl_GetStringFromObj(objv[2], &len);
2161076b9443SCy Schubert       if( zBusy && len>0 ){
2162076b9443SCy Schubert         pDb->zBusy = Tcl_Alloc( len + 1 );
2163076b9443SCy Schubert         memcpy(pDb->zBusy, zBusy, len+1);
2164076b9443SCy Schubert       }else{
2165076b9443SCy Schubert         pDb->zBusy = 0;
2166076b9443SCy Schubert       }
2167076b9443SCy Schubert       if( pDb->zBusy ){
2168076b9443SCy Schubert         pDb->interp = interp;
2169076b9443SCy Schubert         sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
2170076b9443SCy Schubert       }else{
2171076b9443SCy Schubert         sqlite3_busy_handler(pDb->db, 0, 0);
2172076b9443SCy Schubert       }
2173076b9443SCy Schubert     }
2174076b9443SCy Schubert     break;
2175076b9443SCy Schubert   }
2176076b9443SCy Schubert 
2177076b9443SCy Schubert   /*     $db cache flush
2178076b9443SCy Schubert   **     $db cache size n
2179076b9443SCy Schubert   **
2180076b9443SCy Schubert   ** Flush the prepared statement cache, or set the maximum number of
2181076b9443SCy Schubert   ** cached statements.
2182076b9443SCy Schubert   */
2183076b9443SCy Schubert   case DB_CACHE: {
2184076b9443SCy Schubert     char *subCmd;
2185076b9443SCy Schubert     int n;
2186076b9443SCy Schubert 
2187076b9443SCy Schubert     if( objc<=2 ){
2188076b9443SCy Schubert       Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
2189076b9443SCy Schubert       return TCL_ERROR;
2190076b9443SCy Schubert     }
2191076b9443SCy Schubert     subCmd = Tcl_GetStringFromObj( objv[2], 0 );
2192076b9443SCy Schubert     if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
2193076b9443SCy Schubert       if( objc!=3 ){
2194076b9443SCy Schubert         Tcl_WrongNumArgs(interp, 2, objv, "flush");
2195076b9443SCy Schubert         return TCL_ERROR;
2196076b9443SCy Schubert       }else{
2197076b9443SCy Schubert         flushStmtCache( pDb );
2198076b9443SCy Schubert       }
2199076b9443SCy Schubert     }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
2200076b9443SCy Schubert       if( objc!=4 ){
2201076b9443SCy Schubert         Tcl_WrongNumArgs(interp, 2, objv, "size n");
2202076b9443SCy Schubert         return TCL_ERROR;
2203076b9443SCy Schubert       }else{
2204076b9443SCy Schubert         if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
2205076b9443SCy Schubert           Tcl_AppendResult( interp, "cannot convert \"",
2206076b9443SCy Schubert                Tcl_GetStringFromObj(objv[3],0), "\" to integer", (char*)0);
2207076b9443SCy Schubert           return TCL_ERROR;
2208076b9443SCy Schubert         }else{
2209076b9443SCy Schubert           if( n<0 ){
2210076b9443SCy Schubert             flushStmtCache( pDb );
2211076b9443SCy Schubert             n = 0;
2212076b9443SCy Schubert           }else if( n>MAX_PREPARED_STMTS ){
2213076b9443SCy Schubert             n = MAX_PREPARED_STMTS;
2214076b9443SCy Schubert           }
2215076b9443SCy Schubert           pDb->maxStmt = n;
2216076b9443SCy Schubert         }
2217076b9443SCy Schubert       }
2218076b9443SCy Schubert     }else{
2219076b9443SCy Schubert       Tcl_AppendResult( interp, "bad option \"",
2220076b9443SCy Schubert           Tcl_GetStringFromObj(objv[2],0), "\": must be flush or size",
2221076b9443SCy Schubert           (char*)0);
2222076b9443SCy Schubert       return TCL_ERROR;
2223076b9443SCy Schubert     }
2224076b9443SCy Schubert     break;
2225076b9443SCy Schubert   }
2226076b9443SCy Schubert 
2227076b9443SCy Schubert   /*     $db changes
2228076b9443SCy Schubert   **
2229076b9443SCy Schubert   ** Return the number of rows that were modified, inserted, or deleted by
2230076b9443SCy Schubert   ** the most recent INSERT, UPDATE or DELETE statement, not including
2231076b9443SCy Schubert   ** any changes made by trigger programs.
2232076b9443SCy Schubert   */
2233076b9443SCy Schubert   case DB_CHANGES: {
2234076b9443SCy Schubert     Tcl_Obj *pResult;
2235076b9443SCy Schubert     if( objc!=2 ){
2236076b9443SCy Schubert       Tcl_WrongNumArgs(interp, 2, objv, "");
2237076b9443SCy Schubert       return TCL_ERROR;
2238076b9443SCy Schubert     }
2239076b9443SCy Schubert     pResult = Tcl_GetObjResult(interp);
22400197ba46SCy Schubert     Tcl_SetWideIntObj(pResult, sqlite3_changes64(pDb->db));
2241076b9443SCy Schubert     break;
2242076b9443SCy Schubert   }
2243076b9443SCy Schubert 
2244076b9443SCy Schubert   /*    $db close
2245076b9443SCy Schubert   **
2246076b9443SCy Schubert   ** Shutdown the database
2247076b9443SCy Schubert   */
2248076b9443SCy Schubert   case DB_CLOSE: {
2249076b9443SCy Schubert     Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
2250076b9443SCy Schubert     break;
2251076b9443SCy Schubert   }
2252076b9443SCy Schubert 
2253076b9443SCy Schubert   /*
2254076b9443SCy Schubert   **     $db collate NAME SCRIPT
2255076b9443SCy Schubert   **
2256076b9443SCy Schubert   ** Create a new SQL collation function called NAME.  Whenever
2257076b9443SCy Schubert   ** that function is called, invoke SCRIPT to evaluate the function.
2258076b9443SCy Schubert   */
2259076b9443SCy Schubert   case DB_COLLATE: {
2260076b9443SCy Schubert     SqlCollate *pCollate;
2261076b9443SCy Schubert     char *zName;
2262076b9443SCy Schubert     char *zScript;
2263076b9443SCy Schubert     int nScript;
2264076b9443SCy Schubert     if( objc!=4 ){
2265076b9443SCy Schubert       Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
2266076b9443SCy Schubert       return TCL_ERROR;
2267076b9443SCy Schubert     }
2268076b9443SCy Schubert     zName = Tcl_GetStringFromObj(objv[2], 0);
2269076b9443SCy Schubert     zScript = Tcl_GetStringFromObj(objv[3], &nScript);
2270076b9443SCy Schubert     pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
2271076b9443SCy Schubert     if( pCollate==0 ) return TCL_ERROR;
2272076b9443SCy Schubert     pCollate->interp = interp;
2273076b9443SCy Schubert     pCollate->pNext = pDb->pCollate;
2274076b9443SCy Schubert     pCollate->zScript = (char*)&pCollate[1];
2275076b9443SCy Schubert     pDb->pCollate = pCollate;
2276076b9443SCy Schubert     memcpy(pCollate->zScript, zScript, nScript+1);
2277076b9443SCy Schubert     if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
2278076b9443SCy Schubert         pCollate, tclSqlCollate) ){
2279076b9443SCy Schubert       Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
2280076b9443SCy Schubert       return TCL_ERROR;
2281076b9443SCy Schubert     }
2282076b9443SCy Schubert     break;
2283076b9443SCy Schubert   }
2284076b9443SCy Schubert 
2285076b9443SCy Schubert   /*
2286076b9443SCy Schubert   **     $db collation_needed SCRIPT
2287076b9443SCy Schubert   **
2288076b9443SCy Schubert   ** Create a new SQL collation function called NAME.  Whenever
2289076b9443SCy Schubert   ** that function is called, invoke SCRIPT to evaluate the function.
2290076b9443SCy Schubert   */
2291076b9443SCy Schubert   case DB_COLLATION_NEEDED: {
2292076b9443SCy Schubert     if( objc!=3 ){
2293076b9443SCy Schubert       Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
2294076b9443SCy Schubert       return TCL_ERROR;
2295076b9443SCy Schubert     }
2296076b9443SCy Schubert     if( pDb->pCollateNeeded ){
2297076b9443SCy Schubert       Tcl_DecrRefCount(pDb->pCollateNeeded);
2298076b9443SCy Schubert     }
2299076b9443SCy Schubert     pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
2300076b9443SCy Schubert     Tcl_IncrRefCount(pDb->pCollateNeeded);
2301076b9443SCy Schubert     sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
2302076b9443SCy Schubert     break;
2303076b9443SCy Schubert   }
2304076b9443SCy Schubert 
2305076b9443SCy Schubert   /*    $db commit_hook ?CALLBACK?
2306076b9443SCy Schubert   **
2307076b9443SCy Schubert   ** Invoke the given callback just before committing every SQL transaction.
2308076b9443SCy Schubert   ** If the callback throws an exception or returns non-zero, then the
2309076b9443SCy Schubert   ** transaction is aborted.  If CALLBACK is an empty string, the callback
2310076b9443SCy Schubert   ** is disabled.
2311076b9443SCy Schubert   */
2312076b9443SCy Schubert   case DB_COMMIT_HOOK: {
2313076b9443SCy Schubert     if( objc>3 ){
2314076b9443SCy Schubert       Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2315076b9443SCy Schubert       return TCL_ERROR;
2316076b9443SCy Schubert     }else if( objc==2 ){
2317076b9443SCy Schubert       if( pDb->zCommit ){
2318076b9443SCy Schubert         Tcl_AppendResult(interp, pDb->zCommit, (char*)0);
2319076b9443SCy Schubert       }
2320076b9443SCy Schubert     }else{
2321076b9443SCy Schubert       const char *zCommit;
2322076b9443SCy Schubert       int len;
2323076b9443SCy Schubert       if( pDb->zCommit ){
2324076b9443SCy Schubert         Tcl_Free(pDb->zCommit);
2325076b9443SCy Schubert       }
2326076b9443SCy Schubert       zCommit = Tcl_GetStringFromObj(objv[2], &len);
2327076b9443SCy Schubert       if( zCommit && len>0 ){
2328076b9443SCy Schubert         pDb->zCommit = Tcl_Alloc( len + 1 );
2329076b9443SCy Schubert         memcpy(pDb->zCommit, zCommit, len+1);
2330076b9443SCy Schubert       }else{
2331076b9443SCy Schubert         pDb->zCommit = 0;
2332076b9443SCy Schubert       }
2333076b9443SCy Schubert       if( pDb->zCommit ){
2334076b9443SCy Schubert         pDb->interp = interp;
2335076b9443SCy Schubert         sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
2336076b9443SCy Schubert       }else{
2337076b9443SCy Schubert         sqlite3_commit_hook(pDb->db, 0, 0);
2338076b9443SCy Schubert       }
2339076b9443SCy Schubert     }
2340076b9443SCy Schubert     break;
2341076b9443SCy Schubert   }
2342076b9443SCy Schubert 
2343076b9443SCy Schubert   /*    $db complete SQL
2344076b9443SCy Schubert   **
2345076b9443SCy Schubert   ** Return TRUE if SQL is a complete SQL statement.  Return FALSE if
2346076b9443SCy Schubert   ** additional lines of input are needed.  This is similar to the
2347076b9443SCy Schubert   ** built-in "info complete" command of Tcl.
2348076b9443SCy Schubert   */
2349076b9443SCy Schubert   case DB_COMPLETE: {
2350076b9443SCy Schubert #ifndef SQLITE_OMIT_COMPLETE
2351076b9443SCy Schubert     Tcl_Obj *pResult;
2352076b9443SCy Schubert     int isComplete;
2353076b9443SCy Schubert     if( objc!=3 ){
2354076b9443SCy Schubert       Tcl_WrongNumArgs(interp, 2, objv, "SQL");
2355076b9443SCy Schubert       return TCL_ERROR;
2356076b9443SCy Schubert     }
2357076b9443SCy Schubert     isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
2358076b9443SCy Schubert     pResult = Tcl_GetObjResult(interp);
2359076b9443SCy Schubert     Tcl_SetBooleanObj(pResult, isComplete);
2360076b9443SCy Schubert #endif
2361076b9443SCy Schubert     break;
2362076b9443SCy Schubert   }
2363076b9443SCy Schubert 
2364f1b328b3SCy Schubert   /*    $db config ?OPTION? ?BOOLEAN?
2365f1b328b3SCy Schubert   **
2366f1b328b3SCy Schubert   ** Configure the database connection using the sqlite3_db_config()
2367f1b328b3SCy Schubert   ** interface.
2368f1b328b3SCy Schubert   */
2369f1b328b3SCy Schubert   case DB_CONFIG: {
2370f1b328b3SCy Schubert     static const struct DbConfigChoices {
2371f1b328b3SCy Schubert       const char *zName;
2372f1b328b3SCy Schubert       int op;
2373f1b328b3SCy Schubert     } aDbConfig[] = {
23740e2816f5SCy Schubert         { "defensive",          SQLITE_DBCONFIG_DEFENSIVE             },
23750e2816f5SCy Schubert         { "dqs_ddl",            SQLITE_DBCONFIG_DQS_DDL               },
23760e2816f5SCy Schubert         { "dqs_dml",            SQLITE_DBCONFIG_DQS_DML               },
2377f1b328b3SCy Schubert         { "enable_fkey",        SQLITE_DBCONFIG_ENABLE_FKEY           },
23780e2816f5SCy Schubert         { "enable_qpsg",        SQLITE_DBCONFIG_ENABLE_QPSG           },
2379f1b328b3SCy Schubert         { "enable_trigger",     SQLITE_DBCONFIG_ENABLE_TRIGGER        },
2380f1b328b3SCy Schubert         { "enable_view",        SQLITE_DBCONFIG_ENABLE_VIEW           },
2381f1b328b3SCy Schubert         { "fts3_tokenizer",     SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
23820e2816f5SCy Schubert         { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    },
23830e2816f5SCy Schubert         { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    },
2384f1b328b3SCy Schubert         { "load_extension",     SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
2385f1b328b3SCy Schubert         { "no_ckpt_on_close",   SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      },
2386c998f2d3SCy Schubert         { "reset_database",     SQLITE_DBCONFIG_RESET_DATABASE        },
23870e2816f5SCy Schubert         { "trigger_eqp",        SQLITE_DBCONFIG_TRIGGER_EQP           },
23880e2816f5SCy Schubert         { "trusted_schema",     SQLITE_DBCONFIG_TRUSTED_SCHEMA        },
2389f1b328b3SCy Schubert         { "writable_schema",    SQLITE_DBCONFIG_WRITABLE_SCHEMA       },
2390f1b328b3SCy Schubert     };
2391f1b328b3SCy Schubert     Tcl_Obj *pResult;
2392f1b328b3SCy Schubert     int ii;
2393f1b328b3SCy Schubert     if( objc>4 ){
2394f1b328b3SCy Schubert       Tcl_WrongNumArgs(interp, 2, objv, "?OPTION? ?BOOLEAN?");
2395f1b328b3SCy Schubert       return TCL_ERROR;
2396f1b328b3SCy Schubert     }
2397f1b328b3SCy Schubert     if( objc==2 ){
2398f1b328b3SCy Schubert       /* With no arguments, list all configuration options and with the
2399f1b328b3SCy Schubert       ** current value */
2400f1b328b3SCy Schubert       pResult = Tcl_NewListObj(0,0);
2401f1b328b3SCy Schubert       for(ii=0; ii<sizeof(aDbConfig)/sizeof(aDbConfig[0]); ii++){
2402f1b328b3SCy Schubert         int v = 0;
2403f1b328b3SCy Schubert         sqlite3_db_config(pDb->db, aDbConfig[ii].op, -1, &v);
2404f1b328b3SCy Schubert         Tcl_ListObjAppendElement(interp, pResult,
2405f1b328b3SCy Schubert            Tcl_NewStringObj(aDbConfig[ii].zName,-1));
2406f1b328b3SCy Schubert         Tcl_ListObjAppendElement(interp, pResult,
2407f1b328b3SCy Schubert            Tcl_NewIntObj(v));
2408f1b328b3SCy Schubert       }
2409f1b328b3SCy Schubert     }else{
2410f1b328b3SCy Schubert       const char *zOpt = Tcl_GetString(objv[2]);
2411f1b328b3SCy Schubert       int onoff = -1;
2412f1b328b3SCy Schubert       int v = 0;
2413f1b328b3SCy Schubert       if( zOpt[0]=='-' ) zOpt++;
2414f1b328b3SCy Schubert       for(ii=0; ii<sizeof(aDbConfig)/sizeof(aDbConfig[0]); ii++){
2415f1b328b3SCy Schubert         if( strcmp(aDbConfig[ii].zName, zOpt)==0 ) break;
2416f1b328b3SCy Schubert       }
2417f1b328b3SCy Schubert       if( ii>=sizeof(aDbConfig)/sizeof(aDbConfig[0]) ){
2418f1b328b3SCy Schubert         Tcl_AppendResult(interp, "unknown config option: \"", zOpt,
2419f1b328b3SCy Schubert                                 "\"", (void*)0);
2420f1b328b3SCy Schubert         return TCL_ERROR;
2421f1b328b3SCy Schubert       }
2422f1b328b3SCy Schubert       if( objc==4 ){
2423f1b328b3SCy Schubert         if( Tcl_GetBooleanFromObj(interp, objv[3], &onoff) ){
2424f1b328b3SCy Schubert           return TCL_ERROR;
2425f1b328b3SCy Schubert         }
2426f1b328b3SCy Schubert       }
2427f1b328b3SCy Schubert       sqlite3_db_config(pDb->db, aDbConfig[ii].op, onoff, &v);
2428f1b328b3SCy Schubert       pResult = Tcl_NewIntObj(v);
2429f1b328b3SCy Schubert     }
2430f1b328b3SCy Schubert     Tcl_SetObjResult(interp, pResult);
2431f1b328b3SCy Schubert     break;
2432f1b328b3SCy Schubert   }
2433f1b328b3SCy Schubert 
2434076b9443SCy Schubert   /*    $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
2435076b9443SCy Schubert   **
2436076b9443SCy Schubert   ** Copy data into table from filename, optionally using SEPARATOR
2437076b9443SCy Schubert   ** as column separators.  If a column contains a null string, or the
2438076b9443SCy Schubert   ** value of NULLINDICATOR, a NULL is inserted for the column.
2439076b9443SCy Schubert   ** conflict-algorithm is one of the sqlite conflict algorithms:
2440076b9443SCy Schubert   **    rollback, abort, fail, ignore, replace
2441076b9443SCy Schubert   ** On success, return the number of lines processed, not necessarily same
2442076b9443SCy Schubert   ** as 'db changes' due to conflict-algorithm selected.
2443076b9443SCy Schubert   **
2444076b9443SCy Schubert   ** This code is basically an implementation/enhancement of
2445076b9443SCy Schubert   ** the sqlite3 shell.c ".import" command.
2446076b9443SCy Schubert   **
2447076b9443SCy Schubert   ** This command usage is equivalent to the sqlite2.x COPY statement,
2448076b9443SCy Schubert   ** which imports file data into a table using the PostgreSQL COPY file format:
2449076b9443SCy Schubert   **   $db copy $conflit_algo $table_name $filename \t \\N
2450076b9443SCy Schubert   */
2451076b9443SCy Schubert   case DB_COPY: {
2452076b9443SCy Schubert     char *zTable;               /* Insert data into this table */
2453076b9443SCy Schubert     char *zFile;                /* The file from which to extract data */
2454076b9443SCy Schubert     char *zConflict;            /* The conflict algorithm to use */
2455076b9443SCy Schubert     sqlite3_stmt *pStmt;        /* A statement */
2456076b9443SCy Schubert     int nCol;                   /* Number of columns in the table */
2457076b9443SCy Schubert     int nByte;                  /* Number of bytes in an SQL string */
2458076b9443SCy Schubert     int i, j;                   /* Loop counters */
2459076b9443SCy Schubert     int nSep;                   /* Number of bytes in zSep[] */
2460076b9443SCy Schubert     int nNull;                  /* Number of bytes in zNull[] */
2461076b9443SCy Schubert     char *zSql;                 /* An SQL statement */
2462076b9443SCy Schubert     char *zLine;                /* A single line of input from the file */
2463076b9443SCy Schubert     char **azCol;               /* zLine[] broken up into columns */
2464076b9443SCy Schubert     const char *zCommit;        /* How to commit changes */
2465076b9443SCy Schubert     FILE *in;                   /* The input file */
2466076b9443SCy Schubert     int lineno = 0;             /* Line number of input file */
2467076b9443SCy Schubert     char zLineNum[80];          /* Line number print buffer */
2468076b9443SCy Schubert     Tcl_Obj *pResult;           /* interp result */
2469076b9443SCy Schubert 
2470076b9443SCy Schubert     const char *zSep;
2471076b9443SCy Schubert     const char *zNull;
2472076b9443SCy Schubert     if( objc<5 || objc>7 ){
2473076b9443SCy Schubert       Tcl_WrongNumArgs(interp, 2, objv,
2474076b9443SCy Schubert          "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
2475076b9443SCy Schubert       return TCL_ERROR;
2476076b9443SCy Schubert     }
2477076b9443SCy Schubert     if( objc>=6 ){
2478076b9443SCy Schubert       zSep = Tcl_GetStringFromObj(objv[5], 0);
2479076b9443SCy Schubert     }else{
2480076b9443SCy Schubert       zSep = "\t";
2481076b9443SCy Schubert     }
2482076b9443SCy Schubert     if( objc>=7 ){
2483076b9443SCy Schubert       zNull = Tcl_GetStringFromObj(objv[6], 0);
2484076b9443SCy Schubert     }else{
2485076b9443SCy Schubert       zNull = "";
2486076b9443SCy Schubert     }
2487076b9443SCy Schubert     zConflict = Tcl_GetStringFromObj(objv[2], 0);
2488076b9443SCy Schubert     zTable = Tcl_GetStringFromObj(objv[3], 0);
2489076b9443SCy Schubert     zFile = Tcl_GetStringFromObj(objv[4], 0);
2490076b9443SCy Schubert     nSep = strlen30(zSep);
2491076b9443SCy Schubert     nNull = strlen30(zNull);
2492076b9443SCy Schubert     if( nSep==0 ){
2493076b9443SCy Schubert       Tcl_AppendResult(interp,"Error: non-null separator required for copy",
2494076b9443SCy Schubert                        (char*)0);
2495076b9443SCy Schubert       return TCL_ERROR;
2496076b9443SCy Schubert     }
2497076b9443SCy Schubert     if(strcmp(zConflict, "rollback") != 0 &&
2498076b9443SCy Schubert        strcmp(zConflict, "abort"   ) != 0 &&
2499076b9443SCy Schubert        strcmp(zConflict, "fail"    ) != 0 &&
2500076b9443SCy Schubert        strcmp(zConflict, "ignore"  ) != 0 &&
2501076b9443SCy Schubert        strcmp(zConflict, "replace" ) != 0 ) {
2502076b9443SCy Schubert       Tcl_AppendResult(interp, "Error: \"", zConflict,
2503076b9443SCy Schubert             "\", conflict-algorithm must be one of: rollback, "
2504076b9443SCy Schubert             "abort, fail, ignore, or replace", (char*)0);
2505076b9443SCy Schubert       return TCL_ERROR;
2506076b9443SCy Schubert     }
2507076b9443SCy Schubert     zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
2508076b9443SCy Schubert     if( zSql==0 ){
2509076b9443SCy Schubert       Tcl_AppendResult(interp, "Error: no such table: ", zTable, (char*)0);
2510076b9443SCy Schubert       return TCL_ERROR;
2511076b9443SCy Schubert     }
2512076b9443SCy Schubert     nByte = strlen30(zSql);
2513076b9443SCy Schubert     rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
2514076b9443SCy Schubert     sqlite3_free(zSql);
2515076b9443SCy Schubert     if( rc ){
2516076b9443SCy Schubert       Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0);
2517076b9443SCy Schubert       nCol = 0;
2518076b9443SCy Schubert     }else{
2519076b9443SCy Schubert       nCol = sqlite3_column_count(pStmt);
2520076b9443SCy Schubert     }
2521076b9443SCy Schubert     sqlite3_finalize(pStmt);
2522076b9443SCy Schubert     if( nCol==0 ) {
2523076b9443SCy Schubert       return TCL_ERROR;
2524076b9443SCy Schubert     }
2525076b9443SCy Schubert     zSql = malloc( nByte + 50 + nCol*2 );
2526076b9443SCy Schubert     if( zSql==0 ) {
2527076b9443SCy Schubert       Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0);
2528076b9443SCy Schubert       return TCL_ERROR;
2529076b9443SCy Schubert     }
2530076b9443SCy Schubert     sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
2531076b9443SCy Schubert          zConflict, zTable);
2532076b9443SCy Schubert     j = strlen30(zSql);
2533076b9443SCy Schubert     for(i=1; i<nCol; i++){
2534076b9443SCy Schubert       zSql[j++] = ',';
2535076b9443SCy Schubert       zSql[j++] = '?';
2536076b9443SCy Schubert     }
2537076b9443SCy Schubert     zSql[j++] = ')';
2538076b9443SCy Schubert     zSql[j] = 0;
2539076b9443SCy Schubert     rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
2540076b9443SCy Schubert     free(zSql);
2541076b9443SCy Schubert     if( rc ){
2542076b9443SCy Schubert       Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0);
2543076b9443SCy Schubert       sqlite3_finalize(pStmt);
2544076b9443SCy Schubert       return TCL_ERROR;
2545076b9443SCy Schubert     }
2546076b9443SCy Schubert     in = fopen(zFile, "rb");
2547076b9443SCy Schubert     if( in==0 ){
2548076b9443SCy Schubert       Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, (char*)0);
2549076b9443SCy Schubert       sqlite3_finalize(pStmt);
2550076b9443SCy Schubert       return TCL_ERROR;
2551076b9443SCy Schubert     }
2552076b9443SCy Schubert     azCol = malloc( sizeof(azCol[0])*(nCol+1) );
2553076b9443SCy Schubert     if( azCol==0 ) {
2554076b9443SCy Schubert       Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0);
2555076b9443SCy Schubert       fclose(in);
2556076b9443SCy Schubert       return TCL_ERROR;
2557076b9443SCy Schubert     }
2558076b9443SCy Schubert     (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
2559076b9443SCy Schubert     zCommit = "COMMIT";
2560076b9443SCy Schubert     while( (zLine = local_getline(0, in))!=0 ){
2561076b9443SCy Schubert       char *z;
2562076b9443SCy Schubert       lineno++;
2563076b9443SCy Schubert       azCol[0] = zLine;
2564076b9443SCy Schubert       for(i=0, z=zLine; *z; z++){
2565076b9443SCy Schubert         if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
2566076b9443SCy Schubert           *z = 0;
2567076b9443SCy Schubert           i++;
2568076b9443SCy Schubert           if( i<nCol ){
2569076b9443SCy Schubert             azCol[i] = &z[nSep];
2570076b9443SCy Schubert             z += nSep-1;
2571076b9443SCy Schubert           }
2572076b9443SCy Schubert         }
2573076b9443SCy Schubert       }
2574076b9443SCy Schubert       if( i+1!=nCol ){
2575076b9443SCy Schubert         char *zErr;
2576076b9443SCy Schubert         int nErr = strlen30(zFile) + 200;
2577076b9443SCy Schubert         zErr = malloc(nErr);
2578076b9443SCy Schubert         if( zErr ){
2579076b9443SCy Schubert           sqlite3_snprintf(nErr, zErr,
2580076b9443SCy Schubert              "Error: %s line %d: expected %d columns of data but found %d",
2581076b9443SCy Schubert              zFile, lineno, nCol, i+1);
2582076b9443SCy Schubert           Tcl_AppendResult(interp, zErr, (char*)0);
2583076b9443SCy Schubert           free(zErr);
2584076b9443SCy Schubert         }
2585076b9443SCy Schubert         zCommit = "ROLLBACK";
2586076b9443SCy Schubert         break;
2587076b9443SCy Schubert       }
2588076b9443SCy Schubert       for(i=0; i<nCol; i++){
2589076b9443SCy Schubert         /* check for null data, if so, bind as null */
2590076b9443SCy Schubert         if( (nNull>0 && strcmp(azCol[i], zNull)==0)
2591076b9443SCy Schubert           || strlen30(azCol[i])==0
2592076b9443SCy Schubert         ){
2593076b9443SCy Schubert           sqlite3_bind_null(pStmt, i+1);
2594076b9443SCy Schubert         }else{
2595076b9443SCy Schubert           sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
2596076b9443SCy Schubert         }
2597076b9443SCy Schubert       }
2598076b9443SCy Schubert       sqlite3_step(pStmt);
2599076b9443SCy Schubert       rc = sqlite3_reset(pStmt);
2600076b9443SCy Schubert       free(zLine);
2601076b9443SCy Schubert       if( rc!=SQLITE_OK ){
2602076b9443SCy Schubert         Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), (char*)0);
2603076b9443SCy Schubert         zCommit = "ROLLBACK";
2604076b9443SCy Schubert         break;
2605076b9443SCy Schubert       }
2606076b9443SCy Schubert     }
2607076b9443SCy Schubert     free(azCol);
2608076b9443SCy Schubert     fclose(in);
2609076b9443SCy Schubert     sqlite3_finalize(pStmt);
2610076b9443SCy Schubert     (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
2611076b9443SCy Schubert 
2612076b9443SCy Schubert     if( zCommit[0] == 'C' ){
2613076b9443SCy Schubert       /* success, set result as number of lines processed */
2614076b9443SCy Schubert       pResult = Tcl_GetObjResult(interp);
2615076b9443SCy Schubert       Tcl_SetIntObj(pResult, lineno);
2616076b9443SCy Schubert       rc = TCL_OK;
2617076b9443SCy Schubert     }else{
2618076b9443SCy Schubert       /* failure, append lineno where failed */
2619076b9443SCy Schubert       sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
2620076b9443SCy Schubert       Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,
2621076b9443SCy Schubert                        (char*)0);
2622076b9443SCy Schubert       rc = TCL_ERROR;
2623076b9443SCy Schubert     }
2624076b9443SCy Schubert     break;
2625076b9443SCy Schubert   }
2626076b9443SCy Schubert 
2627076b9443SCy Schubert   /*
2628bca4681bSCy Schubert   **     $db deserialize ?-maxsize N? ?-readonly BOOL? ?DATABASE? VALUE
2629076b9443SCy Schubert   **
2630076b9443SCy Schubert   ** Reopen DATABASE (default "main") using the content in $VALUE
2631076b9443SCy Schubert   */
2632076b9443SCy Schubert   case DB_DESERIALIZE: {
26330197ba46SCy Schubert #ifdef SQLITE_OMIT_DESERIALIZE
2634076b9443SCy Schubert     Tcl_AppendResult(interp, "MEMDB not available in this build",
2635076b9443SCy Schubert                      (char*)0);
2636076b9443SCy Schubert     rc = TCL_ERROR;
2637076b9443SCy Schubert #else
2638bca4681bSCy Schubert     const char *zSchema = 0;
2639bca4681bSCy Schubert     Tcl_Obj *pValue = 0;
2640076b9443SCy Schubert     unsigned char *pBA;
2641076b9443SCy Schubert     unsigned char *pData;
2642076b9443SCy Schubert     int len, xrc;
2643bca4681bSCy Schubert     sqlite3_int64 mxSize = 0;
2644bca4681bSCy Schubert     int i;
2645bca4681bSCy Schubert     int isReadonly = 0;
2646076b9443SCy Schubert 
2647bca4681bSCy Schubert 
2648bca4681bSCy Schubert     if( objc<3 ){
2649076b9443SCy Schubert       Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? VALUE");
2650076b9443SCy Schubert       rc = TCL_ERROR;
2651076b9443SCy Schubert       break;
2652076b9443SCy Schubert     }
2653bca4681bSCy Schubert     for(i=2; i<objc-1; i++){
2654bca4681bSCy Schubert       const char *z = Tcl_GetString(objv[i]);
2655bca4681bSCy Schubert       if( strcmp(z,"-maxsize")==0 && i<objc-2 ){
26560197ba46SCy Schubert         Tcl_WideInt x;
26570197ba46SCy Schubert         rc = Tcl_GetWideIntFromObj(interp, objv[++i], &x);
2658bca4681bSCy Schubert         if( rc ) goto deserialize_error;
26590197ba46SCy Schubert         mxSize = x;
2660bca4681bSCy Schubert         continue;
2661bca4681bSCy Schubert       }
2662bca4681bSCy Schubert       if( strcmp(z,"-readonly")==0 && i<objc-2 ){
2663bca4681bSCy Schubert         rc = Tcl_GetBooleanFromObj(interp, objv[++i], &isReadonly);
2664bca4681bSCy Schubert         if( rc ) goto deserialize_error;
2665bca4681bSCy Schubert         continue;
2666bca4681bSCy Schubert       }
2667bca4681bSCy Schubert       if( zSchema==0 && i==objc-2 && z[0]!='-' ){
2668bca4681bSCy Schubert         zSchema = z;
2669bca4681bSCy Schubert         continue;
2670bca4681bSCy Schubert       }
2671bca4681bSCy Schubert       Tcl_AppendResult(interp, "unknown option: ", z, (char*)0);
2672bca4681bSCy Schubert       rc = TCL_ERROR;
2673bca4681bSCy Schubert       goto deserialize_error;
2674bca4681bSCy Schubert     }
2675bca4681bSCy Schubert     pValue = objv[objc-1];
2676076b9443SCy Schubert     pBA = Tcl_GetByteArrayFromObj(pValue, &len);
2677076b9443SCy Schubert     pData = sqlite3_malloc64( len );
2678076b9443SCy Schubert     if( pData==0 && len>0 ){
2679076b9443SCy Schubert       Tcl_AppendResult(interp, "out of memory", (char*)0);
2680076b9443SCy Schubert       rc = TCL_ERROR;
2681076b9443SCy Schubert     }else{
2682bca4681bSCy Schubert       int flags;
2683076b9443SCy Schubert       if( len>0 ) memcpy(pData, pBA, len);
2684bca4681bSCy Schubert       if( isReadonly ){
2685bca4681bSCy Schubert         flags = SQLITE_DESERIALIZE_FREEONCLOSE | SQLITE_DESERIALIZE_READONLY;
2686bca4681bSCy Schubert       }else{
2687bca4681bSCy Schubert         flags = SQLITE_DESERIALIZE_FREEONCLOSE | SQLITE_DESERIALIZE_RESIZEABLE;
2688bca4681bSCy Schubert       }
2689bca4681bSCy Schubert       xrc = sqlite3_deserialize(pDb->db, zSchema, pData, len, len, flags);
2690076b9443SCy Schubert       if( xrc ){
2691076b9443SCy Schubert         Tcl_AppendResult(interp, "unable to set MEMDB content", (char*)0);
2692076b9443SCy Schubert         rc = TCL_ERROR;
2693076b9443SCy Schubert       }
2694bca4681bSCy Schubert       if( mxSize>0 ){
2695bca4681bSCy Schubert         sqlite3_file_control(pDb->db, zSchema,SQLITE_FCNTL_SIZE_LIMIT,&mxSize);
2696076b9443SCy Schubert       }
2697bca4681bSCy Schubert     }
2698bca4681bSCy Schubert deserialize_error:
2699076b9443SCy Schubert #endif
2700076b9443SCy Schubert     break;
2701076b9443SCy Schubert   }
2702076b9443SCy Schubert 
2703076b9443SCy Schubert   /*
2704076b9443SCy Schubert   **    $db enable_load_extension BOOLEAN
2705076b9443SCy Schubert   **
2706076b9443SCy Schubert   ** Turn the extension loading feature on or off.  It if off by
2707076b9443SCy Schubert   ** default.
2708076b9443SCy Schubert   */
2709076b9443SCy Schubert   case DB_ENABLE_LOAD_EXTENSION: {
2710076b9443SCy Schubert #ifndef SQLITE_OMIT_LOAD_EXTENSION
2711076b9443SCy Schubert     int onoff;
2712076b9443SCy Schubert     if( objc!=3 ){
2713076b9443SCy Schubert       Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
2714076b9443SCy Schubert       return TCL_ERROR;
2715076b9443SCy Schubert     }
2716076b9443SCy Schubert     if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
2717076b9443SCy Schubert       return TCL_ERROR;
2718076b9443SCy Schubert     }
2719076b9443SCy Schubert     sqlite3_enable_load_extension(pDb->db, onoff);
2720076b9443SCy Schubert     break;
2721076b9443SCy Schubert #else
2722076b9443SCy Schubert     Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
2723076b9443SCy Schubert                      (char*)0);
2724076b9443SCy Schubert     return TCL_ERROR;
2725076b9443SCy Schubert #endif
2726076b9443SCy Schubert   }
2727076b9443SCy Schubert 
2728076b9443SCy Schubert   /*
2729076b9443SCy Schubert   **    $db errorcode
2730076b9443SCy Schubert   **
2731076b9443SCy Schubert   ** Return the numeric error code that was returned by the most recent
2732076b9443SCy Schubert   ** call to sqlite3_exec().
2733076b9443SCy Schubert   */
2734076b9443SCy Schubert   case DB_ERRORCODE: {
2735076b9443SCy Schubert     Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
2736076b9443SCy Schubert     break;
2737076b9443SCy Schubert   }
2738076b9443SCy Schubert 
2739076b9443SCy Schubert   /*
2740*4fe1295cSCy Schubert   **    $db erroroffset
2741*4fe1295cSCy Schubert   **
2742*4fe1295cSCy Schubert   ** Return the numeric error code that was returned by the most recent
2743*4fe1295cSCy Schubert   ** call to sqlite3_exec().
2744*4fe1295cSCy Schubert   */
2745*4fe1295cSCy Schubert   case DB_ERROROFFSET: {
2746*4fe1295cSCy Schubert     Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_error_offset(pDb->db)));
2747*4fe1295cSCy Schubert     break;
2748*4fe1295cSCy Schubert   }
2749*4fe1295cSCy Schubert 
2750*4fe1295cSCy Schubert   /*
2751076b9443SCy Schubert   **    $db exists $sql
2752076b9443SCy Schubert   **    $db onecolumn $sql
2753076b9443SCy Schubert   **
2754076b9443SCy Schubert   ** The onecolumn method is the equivalent of:
2755076b9443SCy Schubert   **     lindex [$db eval $sql] 0
2756076b9443SCy Schubert   */
2757076b9443SCy Schubert   case DB_EXISTS:
2758076b9443SCy Schubert   case DB_ONECOLUMN: {
2759076b9443SCy Schubert     Tcl_Obj *pResult = 0;
2760076b9443SCy Schubert     DbEvalContext sEval;
2761076b9443SCy Schubert     if( objc!=3 ){
2762076b9443SCy Schubert       Tcl_WrongNumArgs(interp, 2, objv, "SQL");
2763076b9443SCy Schubert       return TCL_ERROR;
2764076b9443SCy Schubert     }
2765076b9443SCy Schubert 
2766076b9443SCy Schubert     dbEvalInit(&sEval, pDb, objv[2], 0, 0);
2767076b9443SCy Schubert     rc = dbEvalStep(&sEval);
2768076b9443SCy Schubert     if( choice==DB_ONECOLUMN ){
2769076b9443SCy Schubert       if( rc==TCL_OK ){
2770076b9443SCy Schubert         pResult = dbEvalColumnValue(&sEval, 0);
2771076b9443SCy Schubert       }else if( rc==TCL_BREAK ){
2772076b9443SCy Schubert         Tcl_ResetResult(interp);
2773076b9443SCy Schubert       }
2774076b9443SCy Schubert     }else if( rc==TCL_BREAK || rc==TCL_OK ){
2775076b9443SCy Schubert       pResult = Tcl_NewBooleanObj(rc==TCL_OK);
2776076b9443SCy Schubert     }
2777076b9443SCy Schubert     dbEvalFinalize(&sEval);
2778076b9443SCy Schubert     if( pResult ) Tcl_SetObjResult(interp, pResult);
2779076b9443SCy Schubert 
2780076b9443SCy Schubert     if( rc==TCL_BREAK ){
2781076b9443SCy Schubert       rc = TCL_OK;
2782076b9443SCy Schubert     }
2783076b9443SCy Schubert     break;
2784076b9443SCy Schubert   }
2785076b9443SCy Schubert 
2786076b9443SCy Schubert   /*
2787076b9443SCy Schubert   **    $db eval ?options? $sql ?array? ?{  ...code... }?
2788076b9443SCy Schubert   **
2789076b9443SCy Schubert   ** The SQL statement in $sql is evaluated.  For each row, the values are
2790076b9443SCy Schubert   ** placed in elements of the array named "array" and ...code... is executed.
2791076b9443SCy Schubert   ** If "array" and "code" are omitted, then no callback is every invoked.
2792076b9443SCy Schubert   ** If "array" is an empty string, then the values are placed in variables
2793076b9443SCy Schubert   ** that have the same name as the fields extracted by the query.
2794076b9443SCy Schubert   */
2795076b9443SCy Schubert   case DB_EVAL: {
2796076b9443SCy Schubert     int evalFlags = 0;
2797076b9443SCy Schubert     const char *zOpt;
2798076b9443SCy Schubert     while( objc>3 && (zOpt = Tcl_GetString(objv[2]))!=0 && zOpt[0]=='-' ){
2799076b9443SCy Schubert       if( strcmp(zOpt, "-withoutnulls")==0 ){
2800076b9443SCy Schubert         evalFlags |= SQLITE_EVAL_WITHOUTNULLS;
2801076b9443SCy Schubert       }
2802076b9443SCy Schubert       else{
2803076b9443SCy Schubert         Tcl_AppendResult(interp, "unknown option: \"", zOpt, "\"", (void*)0);
2804076b9443SCy Schubert         return TCL_ERROR;
2805076b9443SCy Schubert       }
2806076b9443SCy Schubert       objc--;
2807076b9443SCy Schubert       objv++;
2808076b9443SCy Schubert     }
2809076b9443SCy Schubert     if( objc<3 || objc>5 ){
2810076b9443SCy Schubert       Tcl_WrongNumArgs(interp, 2, objv,
2811076b9443SCy Schubert           "?OPTIONS? SQL ?ARRAY-NAME? ?SCRIPT?");
2812076b9443SCy Schubert       return TCL_ERROR;
2813076b9443SCy Schubert     }
2814076b9443SCy Schubert 
2815076b9443SCy Schubert     if( objc==3 ){
2816076b9443SCy Schubert       DbEvalContext sEval;
2817076b9443SCy Schubert       Tcl_Obj *pRet = Tcl_NewObj();
2818076b9443SCy Schubert       Tcl_IncrRefCount(pRet);
2819076b9443SCy Schubert       dbEvalInit(&sEval, pDb, objv[2], 0, 0);
2820076b9443SCy Schubert       while( TCL_OK==(rc = dbEvalStep(&sEval)) ){
2821076b9443SCy Schubert         int i;
2822076b9443SCy Schubert         int nCol;
2823076b9443SCy Schubert         dbEvalRowInfo(&sEval, &nCol, 0);
2824076b9443SCy Schubert         for(i=0; i<nCol; i++){
2825076b9443SCy Schubert           Tcl_ListObjAppendElement(interp, pRet, dbEvalColumnValue(&sEval, i));
2826076b9443SCy Schubert         }
2827076b9443SCy Schubert       }
2828076b9443SCy Schubert       dbEvalFinalize(&sEval);
2829076b9443SCy Schubert       if( rc==TCL_BREAK ){
2830076b9443SCy Schubert         Tcl_SetObjResult(interp, pRet);
2831076b9443SCy Schubert         rc = TCL_OK;
2832076b9443SCy Schubert       }
2833076b9443SCy Schubert       Tcl_DecrRefCount(pRet);
2834076b9443SCy Schubert     }else{
2835076b9443SCy Schubert       ClientData cd2[2];
2836076b9443SCy Schubert       DbEvalContext *p;
2837076b9443SCy Schubert       Tcl_Obj *pArray = 0;
2838076b9443SCy Schubert       Tcl_Obj *pScript;
2839076b9443SCy Schubert 
2840076b9443SCy Schubert       if( objc>=5 && *(char *)Tcl_GetString(objv[3]) ){
2841076b9443SCy Schubert         pArray = objv[3];
2842076b9443SCy Schubert       }
2843076b9443SCy Schubert       pScript = objv[objc-1];
2844076b9443SCy Schubert       Tcl_IncrRefCount(pScript);
2845076b9443SCy Schubert 
2846076b9443SCy Schubert       p = (DbEvalContext *)Tcl_Alloc(sizeof(DbEvalContext));
2847076b9443SCy Schubert       dbEvalInit(p, pDb, objv[2], pArray, evalFlags);
2848076b9443SCy Schubert 
2849076b9443SCy Schubert       cd2[0] = (void *)p;
2850076b9443SCy Schubert       cd2[1] = (void *)pScript;
2851076b9443SCy Schubert       rc = DbEvalNextCmd(cd2, interp, TCL_OK);
2852076b9443SCy Schubert     }
2853076b9443SCy Schubert     break;
2854076b9443SCy Schubert   }
2855076b9443SCy Schubert 
2856076b9443SCy Schubert   /*
2857f1b328b3SCy Schubert   **     $db function NAME [OPTIONS] SCRIPT
2858076b9443SCy Schubert   **
2859076b9443SCy Schubert   ** Create a new SQL function called NAME.  Whenever that function is
2860076b9443SCy Schubert   ** called, invoke SCRIPT to evaluate the function.
2861f1b328b3SCy Schubert   **
2862f1b328b3SCy Schubert   ** Options:
2863f1b328b3SCy Schubert   **         --argcount N           Function has exactly N arguments
2864f1b328b3SCy Schubert   **         --deterministic        The function is pure
2865f1b328b3SCy Schubert   **         --directonly           Prohibit use inside triggers and views
28660e2816f5SCy Schubert   **         --innocuous            Has no side effects or information leaks
2867f1b328b3SCy Schubert   **         --returntype TYPE      Specify the return type of the function
2868076b9443SCy Schubert   */
2869076b9443SCy Schubert   case DB_FUNCTION: {
2870076b9443SCy Schubert     int flags = SQLITE_UTF8;
2871076b9443SCy Schubert     SqlFunc *pFunc;
2872076b9443SCy Schubert     Tcl_Obj *pScript;
2873076b9443SCy Schubert     char *zName;
2874076b9443SCy Schubert     int nArg = -1;
2875076b9443SCy Schubert     int i;
287602273ca8SCy Schubert     int eType = SQLITE_NULL;
2877076b9443SCy Schubert     if( objc<4 ){
2878076b9443SCy Schubert       Tcl_WrongNumArgs(interp, 2, objv, "NAME ?SWITCHES? SCRIPT");
2879076b9443SCy Schubert       return TCL_ERROR;
2880076b9443SCy Schubert     }
2881076b9443SCy Schubert     for(i=3; i<(objc-1); i++){
2882076b9443SCy Schubert       const char *z = Tcl_GetString(objv[i]);
2883076b9443SCy Schubert       int n = strlen30(z);
288402273ca8SCy Schubert       if( n>1 && strncmp(z, "-argcount",n)==0 ){
2885076b9443SCy Schubert         if( i==(objc-2) ){
2886076b9443SCy Schubert           Tcl_AppendResult(interp, "option requires an argument: ", z,(char*)0);
2887076b9443SCy Schubert           return TCL_ERROR;
2888076b9443SCy Schubert         }
2889076b9443SCy Schubert         if( Tcl_GetIntFromObj(interp, objv[i+1], &nArg) ) return TCL_ERROR;
2890076b9443SCy Schubert         if( nArg<0 ){
2891076b9443SCy Schubert           Tcl_AppendResult(interp, "number of arguments must be non-negative",
2892076b9443SCy Schubert                            (char*)0);
2893076b9443SCy Schubert           return TCL_ERROR;
2894076b9443SCy Schubert         }
2895076b9443SCy Schubert         i++;
2896076b9443SCy Schubert       }else
289702273ca8SCy Schubert       if( n>1 && strncmp(z, "-deterministic",n)==0 ){
2898076b9443SCy Schubert         flags |= SQLITE_DETERMINISTIC;
289902273ca8SCy Schubert       }else
2900f1b328b3SCy Schubert       if( n>1 && strncmp(z, "-directonly",n)==0 ){
2901f1b328b3SCy Schubert         flags |= SQLITE_DIRECTONLY;
2902f1b328b3SCy Schubert       }else
29030e2816f5SCy Schubert       if( n>1 && strncmp(z, "-innocuous",n)==0 ){
29040e2816f5SCy Schubert         flags |= SQLITE_INNOCUOUS;
29050e2816f5SCy Schubert       }else
290602273ca8SCy Schubert       if( n>1 && strncmp(z, "-returntype", n)==0 ){
290702273ca8SCy Schubert         const char *azType[] = {"integer", "real", "text", "blob", "any", 0};
290802273ca8SCy Schubert         assert( SQLITE_INTEGER==1 && SQLITE_FLOAT==2 && SQLITE_TEXT==3 );
290902273ca8SCy Schubert         assert( SQLITE_BLOB==4 && SQLITE_NULL==5 );
291002273ca8SCy Schubert         if( i==(objc-2) ){
291102273ca8SCy Schubert           Tcl_AppendResult(interp, "option requires an argument: ", z,(char*)0);
291202273ca8SCy Schubert           return TCL_ERROR;
291302273ca8SCy Schubert         }
291402273ca8SCy Schubert         i++;
291502273ca8SCy Schubert         if( Tcl_GetIndexFromObj(interp, objv[i], azType, "type", 0, &eType) ){
291602273ca8SCy Schubert           return TCL_ERROR;
291702273ca8SCy Schubert         }
291802273ca8SCy Schubert         eType++;
2919076b9443SCy Schubert       }else{
2920076b9443SCy Schubert         Tcl_AppendResult(interp, "bad option \"", z,
2921f1b328b3SCy Schubert             "\": must be -argcount, -deterministic, -directonly,"
29220e2816f5SCy Schubert             " -innocuous, or -returntype", (char*)0
2923076b9443SCy Schubert         );
2924076b9443SCy Schubert         return TCL_ERROR;
2925076b9443SCy Schubert       }
2926076b9443SCy Schubert     }
2927076b9443SCy Schubert 
2928076b9443SCy Schubert     pScript = objv[objc-1];
2929076b9443SCy Schubert     zName = Tcl_GetStringFromObj(objv[2], 0);
2930076b9443SCy Schubert     pFunc = findSqlFunc(pDb, zName);
2931076b9443SCy Schubert     if( pFunc==0 ) return TCL_ERROR;
2932076b9443SCy Schubert     if( pFunc->pScript ){
2933076b9443SCy Schubert       Tcl_DecrRefCount(pFunc->pScript);
2934076b9443SCy Schubert     }
2935076b9443SCy Schubert     pFunc->pScript = pScript;
2936076b9443SCy Schubert     Tcl_IncrRefCount(pScript);
2937076b9443SCy Schubert     pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
293802273ca8SCy Schubert     pFunc->eType = eType;
2939076b9443SCy Schubert     rc = sqlite3_create_function(pDb->db, zName, nArg, flags,
2940076b9443SCy Schubert         pFunc, tclSqlFunc, 0, 0);
2941076b9443SCy Schubert     if( rc!=SQLITE_OK ){
2942076b9443SCy Schubert       rc = TCL_ERROR;
2943076b9443SCy Schubert       Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
2944076b9443SCy Schubert     }
2945076b9443SCy Schubert     break;
2946076b9443SCy Schubert   }
2947076b9443SCy Schubert 
2948076b9443SCy Schubert   /*
2949076b9443SCy Schubert   **     $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
2950076b9443SCy Schubert   */
2951076b9443SCy Schubert   case DB_INCRBLOB: {
2952076b9443SCy Schubert #ifdef SQLITE_OMIT_INCRBLOB
2953076b9443SCy Schubert     Tcl_AppendResult(interp, "incrblob not available in this build", (char*)0);
2954076b9443SCy Schubert     return TCL_ERROR;
2955076b9443SCy Schubert #else
2956076b9443SCy Schubert     int isReadonly = 0;
2957076b9443SCy Schubert     const char *zDb = "main";
2958076b9443SCy Schubert     const char *zTable;
2959076b9443SCy Schubert     const char *zColumn;
2960076b9443SCy Schubert     Tcl_WideInt iRow;
2961076b9443SCy Schubert 
2962076b9443SCy Schubert     /* Check for the -readonly option */
2963076b9443SCy Schubert     if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
2964076b9443SCy Schubert       isReadonly = 1;
2965076b9443SCy Schubert     }
2966076b9443SCy Schubert 
2967076b9443SCy Schubert     if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
2968076b9443SCy Schubert       Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
2969076b9443SCy Schubert       return TCL_ERROR;
2970076b9443SCy Schubert     }
2971076b9443SCy Schubert 
2972076b9443SCy Schubert     if( objc==(6+isReadonly) ){
2973076b9443SCy Schubert       zDb = Tcl_GetString(objv[2]);
2974076b9443SCy Schubert     }
2975076b9443SCy Schubert     zTable = Tcl_GetString(objv[objc-3]);
2976076b9443SCy Schubert     zColumn = Tcl_GetString(objv[objc-2]);
2977076b9443SCy Schubert     rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
2978076b9443SCy Schubert 
2979076b9443SCy Schubert     if( rc==TCL_OK ){
2980076b9443SCy Schubert       rc = createIncrblobChannel(
2981076b9443SCy Schubert           interp, pDb, zDb, zTable, zColumn, (sqlite3_int64)iRow, isReadonly
2982076b9443SCy Schubert       );
2983076b9443SCy Schubert     }
2984076b9443SCy Schubert #endif
2985076b9443SCy Schubert     break;
2986076b9443SCy Schubert   }
2987076b9443SCy Schubert 
2988076b9443SCy Schubert   /*
2989076b9443SCy Schubert   **     $db interrupt
2990076b9443SCy Schubert   **
2991076b9443SCy Schubert   ** Interrupt the execution of the inner-most SQL interpreter.  This
2992076b9443SCy Schubert   ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
2993076b9443SCy Schubert   */
2994076b9443SCy Schubert   case DB_INTERRUPT: {
2995076b9443SCy Schubert     sqlite3_interrupt(pDb->db);
2996076b9443SCy Schubert     break;
2997076b9443SCy Schubert   }
2998076b9443SCy Schubert 
2999076b9443SCy Schubert   /*
3000076b9443SCy Schubert   **     $db nullvalue ?STRING?
3001076b9443SCy Schubert   **
3002076b9443SCy Schubert   ** Change text used when a NULL comes back from the database. If ?STRING?
3003076b9443SCy Schubert   ** is not present, then the current string used for NULL is returned.
3004076b9443SCy Schubert   ** If STRING is present, then STRING is returned.
3005076b9443SCy Schubert   **
3006076b9443SCy Schubert   */
3007076b9443SCy Schubert   case DB_NULLVALUE: {
3008076b9443SCy Schubert     if( objc!=2 && objc!=3 ){
3009076b9443SCy Schubert       Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
3010076b9443SCy Schubert       return TCL_ERROR;
3011076b9443SCy Schubert     }
3012076b9443SCy Schubert     if( objc==3 ){
3013076b9443SCy Schubert       int len;
3014076b9443SCy Schubert       char *zNull = Tcl_GetStringFromObj(objv[2], &len);
3015076b9443SCy Schubert       if( pDb->zNull ){
3016076b9443SCy Schubert         Tcl_Free(pDb->zNull);
3017076b9443SCy Schubert       }
3018076b9443SCy Schubert       if( zNull && len>0 ){
3019076b9443SCy Schubert         pDb->zNull = Tcl_Alloc( len + 1 );
3020076b9443SCy Schubert         memcpy(pDb->zNull, zNull, len);
3021076b9443SCy Schubert         pDb->zNull[len] = '\0';
3022076b9443SCy Schubert       }else{
3023076b9443SCy Schubert         pDb->zNull = 0;
3024076b9443SCy Schubert       }
3025076b9443SCy Schubert     }
3026076b9443SCy Schubert     Tcl_SetObjResult(interp, Tcl_NewStringObj(pDb->zNull, -1));
3027076b9443SCy Schubert     break;
3028076b9443SCy Schubert   }
3029076b9443SCy Schubert 
3030076b9443SCy Schubert   /*
3031076b9443SCy Schubert   **     $db last_insert_rowid
3032076b9443SCy Schubert   **
3033076b9443SCy Schubert   ** Return an integer which is the ROWID for the most recent insert.
3034076b9443SCy Schubert   */
3035076b9443SCy Schubert   case DB_LAST_INSERT_ROWID: {
3036076b9443SCy Schubert     Tcl_Obj *pResult;
3037076b9443SCy Schubert     Tcl_WideInt rowid;
3038076b9443SCy Schubert     if( objc!=2 ){
3039076b9443SCy Schubert       Tcl_WrongNumArgs(interp, 2, objv, "");
3040076b9443SCy Schubert       return TCL_ERROR;
3041076b9443SCy Schubert     }
3042076b9443SCy Schubert     rowid = sqlite3_last_insert_rowid(pDb->db);
3043076b9443SCy Schubert     pResult = Tcl_GetObjResult(interp);
3044076b9443SCy Schubert     Tcl_SetWideIntObj(pResult, rowid);
3045076b9443SCy Schubert     break;
3046076b9443SCy Schubert   }
3047076b9443SCy Schubert 
3048076b9443SCy Schubert   /*
3049076b9443SCy Schubert   ** The DB_ONECOLUMN method is implemented together with DB_EXISTS.
3050076b9443SCy Schubert   */
3051076b9443SCy Schubert 
3052076b9443SCy Schubert   /*    $db progress ?N CALLBACK?
3053076b9443SCy Schubert   **
3054076b9443SCy Schubert   ** Invoke the given callback every N virtual machine opcodes while executing
3055076b9443SCy Schubert   ** queries.
3056076b9443SCy Schubert   */
3057076b9443SCy Schubert   case DB_PROGRESS: {
3058076b9443SCy Schubert     if( objc==2 ){
3059076b9443SCy Schubert       if( pDb->zProgress ){
3060076b9443SCy Schubert         Tcl_AppendResult(interp, pDb->zProgress, (char*)0);
3061076b9443SCy Schubert       }
3062076b9443SCy Schubert     }else if( objc==4 ){
3063076b9443SCy Schubert       char *zProgress;
3064076b9443SCy Schubert       int len;
3065076b9443SCy Schubert       int N;
3066076b9443SCy Schubert       if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
3067076b9443SCy Schubert         return TCL_ERROR;
3068076b9443SCy Schubert       };
3069076b9443SCy Schubert       if( pDb->zProgress ){
3070076b9443SCy Schubert         Tcl_Free(pDb->zProgress);
3071076b9443SCy Schubert       }
3072076b9443SCy Schubert       zProgress = Tcl_GetStringFromObj(objv[3], &len);
3073076b9443SCy Schubert       if( zProgress && len>0 ){
3074076b9443SCy Schubert         pDb->zProgress = Tcl_Alloc( len + 1 );
3075076b9443SCy Schubert         memcpy(pDb->zProgress, zProgress, len+1);
3076076b9443SCy Schubert       }else{
3077076b9443SCy Schubert         pDb->zProgress = 0;
3078076b9443SCy Schubert       }
3079076b9443SCy Schubert #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
3080076b9443SCy Schubert       if( pDb->zProgress ){
3081076b9443SCy Schubert         pDb->interp = interp;
3082076b9443SCy Schubert         sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
3083076b9443SCy Schubert       }else{
3084076b9443SCy Schubert         sqlite3_progress_handler(pDb->db, 0, 0, 0);
3085076b9443SCy Schubert       }
3086076b9443SCy Schubert #endif
3087076b9443SCy Schubert     }else{
3088076b9443SCy Schubert       Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
3089076b9443SCy Schubert       return TCL_ERROR;
3090076b9443SCy Schubert     }
3091076b9443SCy Schubert     break;
3092076b9443SCy Schubert   }
3093076b9443SCy Schubert 
3094076b9443SCy Schubert   /*    $db profile ?CALLBACK?
3095076b9443SCy Schubert   **
3096076b9443SCy Schubert   ** Make arrangements to invoke the CALLBACK routine after each SQL statement
3097076b9443SCy Schubert   ** that has run.  The text of the SQL and the amount of elapse time are
3098076b9443SCy Schubert   ** appended to CALLBACK before the script is run.
3099076b9443SCy Schubert   */
3100076b9443SCy Schubert   case DB_PROFILE: {
3101076b9443SCy Schubert     if( objc>3 ){
3102076b9443SCy Schubert       Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
3103076b9443SCy Schubert       return TCL_ERROR;
3104076b9443SCy Schubert     }else if( objc==2 ){
3105076b9443SCy Schubert       if( pDb->zProfile ){
3106076b9443SCy Schubert         Tcl_AppendResult(interp, pDb->zProfile, (char*)0);
3107076b9443SCy Schubert       }
3108076b9443SCy Schubert     }else{
3109076b9443SCy Schubert       char *zProfile;
3110076b9443SCy Schubert       int len;
3111076b9443SCy Schubert       if( pDb->zProfile ){
3112076b9443SCy Schubert         Tcl_Free(pDb->zProfile);
3113076b9443SCy Schubert       }
3114076b9443SCy Schubert       zProfile = Tcl_GetStringFromObj(objv[2], &len);
3115076b9443SCy Schubert       if( zProfile && len>0 ){
3116076b9443SCy Schubert         pDb->zProfile = Tcl_Alloc( len + 1 );
3117076b9443SCy Schubert         memcpy(pDb->zProfile, zProfile, len+1);
3118076b9443SCy Schubert       }else{
3119076b9443SCy Schubert         pDb->zProfile = 0;
3120076b9443SCy Schubert       }
3121076b9443SCy Schubert #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
3122076b9443SCy Schubert     !defined(SQLITE_OMIT_DEPRECATED)
3123076b9443SCy Schubert       if( pDb->zProfile ){
3124076b9443SCy Schubert         pDb->interp = interp;
3125076b9443SCy Schubert         sqlite3_profile(pDb->db, DbProfileHandler, pDb);
3126076b9443SCy Schubert       }else{
3127076b9443SCy Schubert         sqlite3_profile(pDb->db, 0, 0);
3128076b9443SCy Schubert       }
3129076b9443SCy Schubert #endif
3130076b9443SCy Schubert     }
3131076b9443SCy Schubert     break;
3132076b9443SCy Schubert   }
3133076b9443SCy Schubert 
3134076b9443SCy Schubert   /*
3135076b9443SCy Schubert   **     $db rekey KEY
3136076b9443SCy Schubert   **
3137076b9443SCy Schubert   ** Change the encryption key on the currently open database.
3138076b9443SCy Schubert   */
3139076b9443SCy Schubert   case DB_REKEY: {
3140076b9443SCy Schubert     if( objc!=3 ){
3141076b9443SCy Schubert       Tcl_WrongNumArgs(interp, 2, objv, "KEY");
3142076b9443SCy Schubert       return TCL_ERROR;
3143076b9443SCy Schubert     }
3144076b9443SCy Schubert     break;
3145076b9443SCy Schubert   }
3146076b9443SCy Schubert 
3147076b9443SCy Schubert   /*    $db restore ?DATABASE? FILENAME
3148076b9443SCy Schubert   **
3149076b9443SCy Schubert   ** Open a database file named FILENAME.  Transfer the content
3150076b9443SCy Schubert   ** of FILENAME into the local database DATABASE (default: "main").
3151076b9443SCy Schubert   */
3152076b9443SCy Schubert   case DB_RESTORE: {
3153076b9443SCy Schubert     const char *zSrcFile;
3154076b9443SCy Schubert     const char *zDestDb;
3155076b9443SCy Schubert     sqlite3 *pSrc;
3156076b9443SCy Schubert     sqlite3_backup *pBackup;
3157076b9443SCy Schubert     int nTimeout = 0;
3158076b9443SCy Schubert 
3159076b9443SCy Schubert     if( objc==3 ){
3160076b9443SCy Schubert       zDestDb = "main";
3161076b9443SCy Schubert       zSrcFile = Tcl_GetString(objv[2]);
3162076b9443SCy Schubert     }else if( objc==4 ){
3163076b9443SCy Schubert       zDestDb = Tcl_GetString(objv[2]);
3164076b9443SCy Schubert       zSrcFile = Tcl_GetString(objv[3]);
3165076b9443SCy Schubert     }else{
3166076b9443SCy Schubert       Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
3167076b9443SCy Schubert       return TCL_ERROR;
3168076b9443SCy Schubert     }
3169076b9443SCy Schubert     rc = sqlite3_open_v2(zSrcFile, &pSrc,
3170076b9443SCy Schubert                          SQLITE_OPEN_READONLY | pDb->openFlags, 0);
3171076b9443SCy Schubert     if( rc!=SQLITE_OK ){
3172076b9443SCy Schubert       Tcl_AppendResult(interp, "cannot open source database: ",
3173076b9443SCy Schubert            sqlite3_errmsg(pSrc), (char*)0);
3174076b9443SCy Schubert       sqlite3_close(pSrc);
3175076b9443SCy Schubert       return TCL_ERROR;
3176076b9443SCy Schubert     }
3177076b9443SCy Schubert     pBackup = sqlite3_backup_init(pDb->db, zDestDb, pSrc, "main");
3178076b9443SCy Schubert     if( pBackup==0 ){
3179076b9443SCy Schubert       Tcl_AppendResult(interp, "restore failed: ",
3180076b9443SCy Schubert            sqlite3_errmsg(pDb->db), (char*)0);
3181076b9443SCy Schubert       sqlite3_close(pSrc);
3182076b9443SCy Schubert       return TCL_ERROR;
3183076b9443SCy Schubert     }
3184076b9443SCy Schubert     while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
3185076b9443SCy Schubert               || rc==SQLITE_BUSY ){
3186076b9443SCy Schubert       if( rc==SQLITE_BUSY ){
3187076b9443SCy Schubert         if( nTimeout++ >= 3 ) break;
3188076b9443SCy Schubert         sqlite3_sleep(100);
3189076b9443SCy Schubert       }
3190076b9443SCy Schubert     }
3191076b9443SCy Schubert     sqlite3_backup_finish(pBackup);
3192076b9443SCy Schubert     if( rc==SQLITE_DONE ){
3193076b9443SCy Schubert       rc = TCL_OK;
3194076b9443SCy Schubert     }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
3195076b9443SCy Schubert       Tcl_AppendResult(interp, "restore failed: source database busy",
3196076b9443SCy Schubert                        (char*)0);
3197076b9443SCy Schubert       rc = TCL_ERROR;
3198076b9443SCy Schubert     }else{
3199076b9443SCy Schubert       Tcl_AppendResult(interp, "restore failed: ",
3200076b9443SCy Schubert            sqlite3_errmsg(pDb->db), (char*)0);
3201076b9443SCy Schubert       rc = TCL_ERROR;
3202076b9443SCy Schubert     }
3203076b9443SCy Schubert     sqlite3_close(pSrc);
3204076b9443SCy Schubert     break;
3205076b9443SCy Schubert   }
3206076b9443SCy Schubert 
3207076b9443SCy Schubert   /*
3208076b9443SCy Schubert   **     $db serialize ?DATABASE?
3209076b9443SCy Schubert   **
3210076b9443SCy Schubert   ** Return a serialization of a database.
3211076b9443SCy Schubert   */
3212076b9443SCy Schubert   case DB_SERIALIZE: {
32130197ba46SCy Schubert #ifdef SQLITE_OMIT_DESERIALIZE
3214076b9443SCy Schubert     Tcl_AppendResult(interp, "MEMDB not available in this build",
3215076b9443SCy Schubert                      (char*)0);
3216076b9443SCy Schubert     rc = TCL_ERROR;
3217076b9443SCy Schubert #else
3218076b9443SCy Schubert     const char *zSchema = objc>=3 ? Tcl_GetString(objv[2]) : "main";
3219076b9443SCy Schubert     sqlite3_int64 sz = 0;
3220076b9443SCy Schubert     unsigned char *pData;
3221076b9443SCy Schubert     if( objc!=2 && objc!=3 ){
3222076b9443SCy Schubert       Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE?");
3223076b9443SCy Schubert       rc = TCL_ERROR;
3224076b9443SCy Schubert     }else{
3225076b9443SCy Schubert       int needFree;
3226076b9443SCy Schubert       pData = sqlite3_serialize(pDb->db, zSchema, &sz, SQLITE_SERIALIZE_NOCOPY);
3227076b9443SCy Schubert       if( pData ){
3228076b9443SCy Schubert         needFree = 0;
3229076b9443SCy Schubert       }else{
3230076b9443SCy Schubert         pData = sqlite3_serialize(pDb->db, zSchema, &sz, 0);
3231076b9443SCy Schubert         needFree = 1;
3232076b9443SCy Schubert       }
3233076b9443SCy Schubert       Tcl_SetObjResult(interp, Tcl_NewByteArrayObj(pData,sz));
3234076b9443SCy Schubert       if( needFree ) sqlite3_free(pData);
3235076b9443SCy Schubert     }
3236076b9443SCy Schubert #endif
3237076b9443SCy Schubert     break;
3238076b9443SCy Schubert   }
3239076b9443SCy Schubert 
3240076b9443SCy Schubert   /*
3241076b9443SCy Schubert   **     $db status (step|sort|autoindex|vmstep)
3242076b9443SCy Schubert   **
3243076b9443SCy Schubert   ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or
3244076b9443SCy Schubert   ** SQLITE_STMTSTATUS_SORT for the most recent eval.
3245076b9443SCy Schubert   */
3246076b9443SCy Schubert   case DB_STATUS: {
3247076b9443SCy Schubert     int v;
3248076b9443SCy Schubert     const char *zOp;
3249076b9443SCy Schubert     if( objc!=3 ){
3250076b9443SCy Schubert       Tcl_WrongNumArgs(interp, 2, objv, "(step|sort|autoindex)");
3251076b9443SCy Schubert       return TCL_ERROR;
3252076b9443SCy Schubert     }
3253076b9443SCy Schubert     zOp = Tcl_GetString(objv[2]);
3254076b9443SCy Schubert     if( strcmp(zOp, "step")==0 ){
3255076b9443SCy Schubert       v = pDb->nStep;
3256076b9443SCy Schubert     }else if( strcmp(zOp, "sort")==0 ){
3257076b9443SCy Schubert       v = pDb->nSort;
3258076b9443SCy Schubert     }else if( strcmp(zOp, "autoindex")==0 ){
3259076b9443SCy Schubert       v = pDb->nIndex;
3260076b9443SCy Schubert     }else if( strcmp(zOp, "vmstep")==0 ){
3261076b9443SCy Schubert       v = pDb->nVMStep;
3262076b9443SCy Schubert     }else{
3263076b9443SCy Schubert       Tcl_AppendResult(interp,
3264076b9443SCy Schubert             "bad argument: should be autoindex, step, sort or vmstep",
3265076b9443SCy Schubert             (char*)0);
3266076b9443SCy Schubert       return TCL_ERROR;
3267076b9443SCy Schubert     }
3268076b9443SCy Schubert     Tcl_SetObjResult(interp, Tcl_NewIntObj(v));
3269076b9443SCy Schubert     break;
3270076b9443SCy Schubert   }
3271076b9443SCy Schubert 
3272076b9443SCy Schubert   /*
3273076b9443SCy Schubert   **     $db timeout MILLESECONDS
3274076b9443SCy Schubert   **
3275076b9443SCy Schubert   ** Delay for the number of milliseconds specified when a file is locked.
3276076b9443SCy Schubert   */
3277076b9443SCy Schubert   case DB_TIMEOUT: {
3278076b9443SCy Schubert     int ms;
3279076b9443SCy Schubert     if( objc!=3 ){
3280076b9443SCy Schubert       Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
3281076b9443SCy Schubert       return TCL_ERROR;
3282076b9443SCy Schubert     }
3283076b9443SCy Schubert     if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
3284076b9443SCy Schubert     sqlite3_busy_timeout(pDb->db, ms);
3285076b9443SCy Schubert     break;
3286076b9443SCy Schubert   }
3287076b9443SCy Schubert 
3288076b9443SCy Schubert   /*
3289076b9443SCy Schubert   **     $db total_changes
3290076b9443SCy Schubert   **
3291076b9443SCy Schubert   ** Return the number of rows that were modified, inserted, or deleted
3292076b9443SCy Schubert   ** since the database handle was created.
3293076b9443SCy Schubert   */
3294076b9443SCy Schubert   case DB_TOTAL_CHANGES: {
3295076b9443SCy Schubert     Tcl_Obj *pResult;
3296076b9443SCy Schubert     if( objc!=2 ){
3297076b9443SCy Schubert       Tcl_WrongNumArgs(interp, 2, objv, "");
3298076b9443SCy Schubert       return TCL_ERROR;
3299076b9443SCy Schubert     }
3300076b9443SCy Schubert     pResult = Tcl_GetObjResult(interp);
33010197ba46SCy Schubert     Tcl_SetWideIntObj(pResult, sqlite3_total_changes64(pDb->db));
3302076b9443SCy Schubert     break;
3303076b9443SCy Schubert   }
3304076b9443SCy Schubert 
3305076b9443SCy Schubert   /*    $db trace ?CALLBACK?
3306076b9443SCy Schubert   **
3307076b9443SCy Schubert   ** Make arrangements to invoke the CALLBACK routine for each SQL statement
3308076b9443SCy Schubert   ** that is executed.  The text of the SQL is appended to CALLBACK before
3309076b9443SCy Schubert   ** it is executed.
3310076b9443SCy Schubert   */
3311076b9443SCy Schubert   case DB_TRACE: {
3312076b9443SCy Schubert     if( objc>3 ){
3313076b9443SCy Schubert       Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
3314076b9443SCy Schubert       return TCL_ERROR;
3315076b9443SCy Schubert     }else if( objc==2 ){
3316076b9443SCy Schubert       if( pDb->zTrace ){
3317076b9443SCy Schubert         Tcl_AppendResult(interp, pDb->zTrace, (char*)0);
3318076b9443SCy Schubert       }
3319076b9443SCy Schubert     }else{
3320076b9443SCy Schubert       char *zTrace;
3321076b9443SCy Schubert       int len;
3322076b9443SCy Schubert       if( pDb->zTrace ){
3323076b9443SCy Schubert         Tcl_Free(pDb->zTrace);
3324076b9443SCy Schubert       }
3325076b9443SCy Schubert       zTrace = Tcl_GetStringFromObj(objv[2], &len);
3326076b9443SCy Schubert       if( zTrace && len>0 ){
3327076b9443SCy Schubert         pDb->zTrace = Tcl_Alloc( len + 1 );
3328076b9443SCy Schubert         memcpy(pDb->zTrace, zTrace, len+1);
3329076b9443SCy Schubert       }else{
3330076b9443SCy Schubert         pDb->zTrace = 0;
3331076b9443SCy Schubert       }
3332076b9443SCy Schubert #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \
3333076b9443SCy Schubert     !defined(SQLITE_OMIT_DEPRECATED)
3334076b9443SCy Schubert       if( pDb->zTrace ){
3335076b9443SCy Schubert         pDb->interp = interp;
3336076b9443SCy Schubert         sqlite3_trace(pDb->db, DbTraceHandler, pDb);
3337076b9443SCy Schubert       }else{
3338076b9443SCy Schubert         sqlite3_trace(pDb->db, 0, 0);
3339076b9443SCy Schubert       }
3340076b9443SCy Schubert #endif
3341076b9443SCy Schubert     }
3342076b9443SCy Schubert     break;
3343076b9443SCy Schubert   }
3344076b9443SCy Schubert 
3345076b9443SCy Schubert   /*    $db trace_v2 ?CALLBACK? ?MASK?
3346076b9443SCy Schubert   **
3347076b9443SCy Schubert   ** Make arrangements to invoke the CALLBACK routine for each trace event
3348076b9443SCy Schubert   ** matching the mask that is generated.  The parameters are appended to
3349076b9443SCy Schubert   ** CALLBACK before it is executed.
3350076b9443SCy Schubert   */
3351076b9443SCy Schubert   case DB_TRACE_V2: {
3352076b9443SCy Schubert     if( objc>4 ){
3353076b9443SCy Schubert       Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK? ?MASK?");
3354076b9443SCy Schubert       return TCL_ERROR;
3355076b9443SCy Schubert     }else if( objc==2 ){
3356076b9443SCy Schubert       if( pDb->zTraceV2 ){
3357076b9443SCy Schubert         Tcl_AppendResult(interp, pDb->zTraceV2, (char*)0);
3358076b9443SCy Schubert       }
3359076b9443SCy Schubert     }else{
3360076b9443SCy Schubert       char *zTraceV2;
3361076b9443SCy Schubert       int len;
3362076b9443SCy Schubert       Tcl_WideInt wMask = 0;
3363076b9443SCy Schubert       if( objc==4 ){
3364076b9443SCy Schubert         static const char *TTYPE_strs[] = {
3365076b9443SCy Schubert           "statement", "profile", "row", "close", 0
3366076b9443SCy Schubert         };
3367076b9443SCy Schubert         enum TTYPE_enum {
3368076b9443SCy Schubert           TTYPE_STMT, TTYPE_PROFILE, TTYPE_ROW, TTYPE_CLOSE
3369076b9443SCy Schubert         };
3370076b9443SCy Schubert         int i;
3371076b9443SCy Schubert         if( TCL_OK!=Tcl_ListObjLength(interp, objv[3], &len) ){
3372076b9443SCy Schubert           return TCL_ERROR;
3373076b9443SCy Schubert         }
3374076b9443SCy Schubert         for(i=0; i<len; i++){
3375076b9443SCy Schubert           Tcl_Obj *pObj;
3376076b9443SCy Schubert           int ttype;
3377076b9443SCy Schubert           if( TCL_OK!=Tcl_ListObjIndex(interp, objv[3], i, &pObj) ){
3378076b9443SCy Schubert             return TCL_ERROR;
3379076b9443SCy Schubert           }
3380076b9443SCy Schubert           if( Tcl_GetIndexFromObj(interp, pObj, TTYPE_strs, "trace type",
3381076b9443SCy Schubert                                   0, &ttype)!=TCL_OK ){
3382076b9443SCy Schubert             Tcl_WideInt wType;
3383076b9443SCy Schubert             Tcl_Obj *pError = Tcl_DuplicateObj(Tcl_GetObjResult(interp));
3384076b9443SCy Schubert             Tcl_IncrRefCount(pError);
3385076b9443SCy Schubert             if( TCL_OK==Tcl_GetWideIntFromObj(interp, pObj, &wType) ){
3386076b9443SCy Schubert               Tcl_DecrRefCount(pError);
3387076b9443SCy Schubert               wMask |= wType;
3388076b9443SCy Schubert             }else{
3389076b9443SCy Schubert               Tcl_SetObjResult(interp, pError);
3390076b9443SCy Schubert               Tcl_DecrRefCount(pError);
3391076b9443SCy Schubert               return TCL_ERROR;
3392076b9443SCy Schubert             }
3393076b9443SCy Schubert           }else{
3394076b9443SCy Schubert             switch( (enum TTYPE_enum)ttype ){
3395076b9443SCy Schubert               case TTYPE_STMT:    wMask |= SQLITE_TRACE_STMT;    break;
3396076b9443SCy Schubert               case TTYPE_PROFILE: wMask |= SQLITE_TRACE_PROFILE; break;
3397076b9443SCy Schubert               case TTYPE_ROW:     wMask |= SQLITE_TRACE_ROW;     break;
3398076b9443SCy Schubert               case TTYPE_CLOSE:   wMask |= SQLITE_TRACE_CLOSE;   break;
3399076b9443SCy Schubert             }
3400076b9443SCy Schubert           }
3401076b9443SCy Schubert         }
3402076b9443SCy Schubert       }else{
3403076b9443SCy Schubert         wMask = SQLITE_TRACE_STMT; /* use the "legacy" default */
3404076b9443SCy Schubert       }
3405076b9443SCy Schubert       if( pDb->zTraceV2 ){
3406076b9443SCy Schubert         Tcl_Free(pDb->zTraceV2);
3407076b9443SCy Schubert       }
3408076b9443SCy Schubert       zTraceV2 = Tcl_GetStringFromObj(objv[2], &len);
3409076b9443SCy Schubert       if( zTraceV2 && len>0 ){
3410076b9443SCy Schubert         pDb->zTraceV2 = Tcl_Alloc( len + 1 );
3411076b9443SCy Schubert         memcpy(pDb->zTraceV2, zTraceV2, len+1);
3412076b9443SCy Schubert       }else{
3413076b9443SCy Schubert         pDb->zTraceV2 = 0;
3414076b9443SCy Schubert       }
3415076b9443SCy Schubert #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
3416076b9443SCy Schubert       if( pDb->zTraceV2 ){
3417076b9443SCy Schubert         pDb->interp = interp;
3418076b9443SCy Schubert         sqlite3_trace_v2(pDb->db, (unsigned)wMask, DbTraceV2Handler, pDb);
3419076b9443SCy Schubert       }else{
3420076b9443SCy Schubert         sqlite3_trace_v2(pDb->db, 0, 0, 0);
3421076b9443SCy Schubert       }
3422076b9443SCy Schubert #endif
3423076b9443SCy Schubert     }
3424076b9443SCy Schubert     break;
3425076b9443SCy Schubert   }
3426076b9443SCy Schubert 
3427076b9443SCy Schubert   /*    $db transaction [-deferred|-immediate|-exclusive] SCRIPT
3428076b9443SCy Schubert   **
3429076b9443SCy Schubert   ** Start a new transaction (if we are not already in the midst of a
3430076b9443SCy Schubert   ** transaction) and execute the TCL script SCRIPT.  After SCRIPT
3431076b9443SCy Schubert   ** completes, either commit the transaction or roll it back if SCRIPT
3432076b9443SCy Schubert   ** throws an exception.  Or if no new transation was started, do nothing.
3433076b9443SCy Schubert   ** pass the exception on up the stack.
3434076b9443SCy Schubert   **
3435076b9443SCy Schubert   ** This command was inspired by Dave Thomas's talk on Ruby at the
3436076b9443SCy Schubert   ** 2005 O'Reilly Open Source Convention (OSCON).
3437076b9443SCy Schubert   */
3438076b9443SCy Schubert   case DB_TRANSACTION: {
3439076b9443SCy Schubert     Tcl_Obj *pScript;
3440076b9443SCy Schubert     const char *zBegin = "SAVEPOINT _tcl_transaction";
3441076b9443SCy Schubert     if( objc!=3 && objc!=4 ){
3442076b9443SCy Schubert       Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
3443076b9443SCy Schubert       return TCL_ERROR;
3444076b9443SCy Schubert     }
3445076b9443SCy Schubert 
3446076b9443SCy Schubert     if( pDb->nTransaction==0 && objc==4 ){
3447076b9443SCy Schubert       static const char *TTYPE_strs[] = {
3448076b9443SCy Schubert         "deferred",   "exclusive",  "immediate", 0
3449076b9443SCy Schubert       };
3450076b9443SCy Schubert       enum TTYPE_enum {
3451076b9443SCy Schubert         TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
3452076b9443SCy Schubert       };
3453076b9443SCy Schubert       int ttype;
3454076b9443SCy Schubert       if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
3455076b9443SCy Schubert                               0, &ttype) ){
3456076b9443SCy Schubert         return TCL_ERROR;
3457076b9443SCy Schubert       }
3458076b9443SCy Schubert       switch( (enum TTYPE_enum)ttype ){
3459076b9443SCy Schubert         case TTYPE_DEFERRED:    /* no-op */;                 break;
3460076b9443SCy Schubert         case TTYPE_EXCLUSIVE:   zBegin = "BEGIN EXCLUSIVE";  break;
3461076b9443SCy Schubert         case TTYPE_IMMEDIATE:   zBegin = "BEGIN IMMEDIATE";  break;
3462076b9443SCy Schubert       }
3463076b9443SCy Schubert     }
3464076b9443SCy Schubert     pScript = objv[objc-1];
3465076b9443SCy Schubert 
3466076b9443SCy Schubert     /* Run the SQLite BEGIN command to open a transaction or savepoint. */
3467076b9443SCy Schubert     pDb->disableAuth++;
3468076b9443SCy Schubert     rc = sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
3469076b9443SCy Schubert     pDb->disableAuth--;
3470076b9443SCy Schubert     if( rc!=SQLITE_OK ){
3471076b9443SCy Schubert       Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
3472076b9443SCy Schubert       return TCL_ERROR;
3473076b9443SCy Schubert     }
3474076b9443SCy Schubert     pDb->nTransaction++;
3475076b9443SCy Schubert 
3476076b9443SCy Schubert     /* If using NRE, schedule a callback to invoke the script pScript, then
3477076b9443SCy Schubert     ** a second callback to commit (or rollback) the transaction or savepoint
3478076b9443SCy Schubert     ** opened above. If not using NRE, evaluate the script directly, then
3479076b9443SCy Schubert     ** call function DbTransPostCmd() to commit (or rollback) the transaction
3480076b9443SCy Schubert     ** or savepoint.  */
34810197ba46SCy Schubert     addDatabaseRef(pDb);          /* DbTransPostCmd() calls delDatabaseRef() */
3482076b9443SCy Schubert     if( DbUseNre() ){
3483076b9443SCy Schubert       Tcl_NRAddCallback(interp, DbTransPostCmd, cd, 0, 0, 0);
3484076b9443SCy Schubert       (void)Tcl_NREvalObj(interp, pScript, 0);
3485076b9443SCy Schubert     }else{
3486076b9443SCy Schubert       rc = DbTransPostCmd(&cd, interp, Tcl_EvalObjEx(interp, pScript, 0));
3487076b9443SCy Schubert     }
3488076b9443SCy Schubert     break;
3489076b9443SCy Schubert   }
3490076b9443SCy Schubert 
3491076b9443SCy Schubert   /*
3492076b9443SCy Schubert   **    $db unlock_notify ?script?
3493076b9443SCy Schubert   */
3494076b9443SCy Schubert   case DB_UNLOCK_NOTIFY: {
3495076b9443SCy Schubert #ifndef SQLITE_ENABLE_UNLOCK_NOTIFY
3496076b9443SCy Schubert     Tcl_AppendResult(interp, "unlock_notify not available in this build",
3497076b9443SCy Schubert                      (char*)0);
3498076b9443SCy Schubert     rc = TCL_ERROR;
3499076b9443SCy Schubert #else
3500076b9443SCy Schubert     if( objc!=2 && objc!=3 ){
3501076b9443SCy Schubert       Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
3502076b9443SCy Schubert       rc = TCL_ERROR;
3503076b9443SCy Schubert     }else{
3504076b9443SCy Schubert       void (*xNotify)(void **, int) = 0;
3505076b9443SCy Schubert       void *pNotifyArg = 0;
3506076b9443SCy Schubert 
3507076b9443SCy Schubert       if( pDb->pUnlockNotify ){
3508076b9443SCy Schubert         Tcl_DecrRefCount(pDb->pUnlockNotify);
3509076b9443SCy Schubert         pDb->pUnlockNotify = 0;
3510076b9443SCy Schubert       }
3511076b9443SCy Schubert 
3512076b9443SCy Schubert       if( objc==3 ){
3513076b9443SCy Schubert         xNotify = DbUnlockNotify;
3514076b9443SCy Schubert         pNotifyArg = (void *)pDb;
3515076b9443SCy Schubert         pDb->pUnlockNotify = objv[2];
3516076b9443SCy Schubert         Tcl_IncrRefCount(pDb->pUnlockNotify);
3517076b9443SCy Schubert       }
3518076b9443SCy Schubert 
3519076b9443SCy Schubert       if( sqlite3_unlock_notify(pDb->db, xNotify, pNotifyArg) ){
3520076b9443SCy Schubert         Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
3521076b9443SCy Schubert         rc = TCL_ERROR;
3522076b9443SCy Schubert       }
3523076b9443SCy Schubert     }
3524076b9443SCy Schubert #endif
3525076b9443SCy Schubert     break;
3526076b9443SCy Schubert   }
3527076b9443SCy Schubert 
3528076b9443SCy Schubert   /*
3529076b9443SCy Schubert   **    $db preupdate_hook count
3530076b9443SCy Schubert   **    $db preupdate_hook hook ?SCRIPT?
3531076b9443SCy Schubert   **    $db preupdate_hook new INDEX
3532076b9443SCy Schubert   **    $db preupdate_hook old INDEX
3533076b9443SCy Schubert   */
3534076b9443SCy Schubert   case DB_PREUPDATE: {
3535076b9443SCy Schubert #ifndef SQLITE_ENABLE_PREUPDATE_HOOK
3536076b9443SCy Schubert     Tcl_AppendResult(interp, "preupdate_hook was omitted at compile-time",
3537076b9443SCy Schubert                      (char*)0);
3538076b9443SCy Schubert     rc = TCL_ERROR;
3539076b9443SCy Schubert #else
3540076b9443SCy Schubert     static const char *azSub[] = {"count", "depth", "hook", "new", "old", 0};
3541076b9443SCy Schubert     enum DbPreupdateSubCmd {
3542076b9443SCy Schubert       PRE_COUNT, PRE_DEPTH, PRE_HOOK, PRE_NEW, PRE_OLD
3543076b9443SCy Schubert     };
3544076b9443SCy Schubert     int iSub;
3545076b9443SCy Schubert 
3546076b9443SCy Schubert     if( objc<3 ){
3547076b9443SCy Schubert       Tcl_WrongNumArgs(interp, 2, objv, "SUB-COMMAND ?ARGS?");
3548076b9443SCy Schubert     }
3549076b9443SCy Schubert     if( Tcl_GetIndexFromObj(interp, objv[2], azSub, "sub-command", 0, &iSub) ){
3550076b9443SCy Schubert       return TCL_ERROR;
3551076b9443SCy Schubert     }
3552076b9443SCy Schubert 
3553076b9443SCy Schubert     switch( (enum DbPreupdateSubCmd)iSub ){
3554076b9443SCy Schubert       case PRE_COUNT: {
3555076b9443SCy Schubert         int nCol = sqlite3_preupdate_count(pDb->db);
3556076b9443SCy Schubert         Tcl_SetObjResult(interp, Tcl_NewIntObj(nCol));
3557076b9443SCy Schubert         break;
3558076b9443SCy Schubert       }
3559076b9443SCy Schubert 
3560076b9443SCy Schubert       case PRE_HOOK: {
3561076b9443SCy Schubert         if( objc>4 ){
3562076b9443SCy Schubert           Tcl_WrongNumArgs(interp, 2, objv, "hook ?SCRIPT?");
3563076b9443SCy Schubert           return TCL_ERROR;
3564076b9443SCy Schubert         }
3565076b9443SCy Schubert         DbHookCmd(interp, pDb, (objc==4 ? objv[3] : 0), &pDb->pPreUpdateHook);
3566076b9443SCy Schubert         break;
3567076b9443SCy Schubert       }
3568076b9443SCy Schubert 
3569076b9443SCy Schubert       case PRE_DEPTH: {
3570076b9443SCy Schubert         Tcl_Obj *pRet;
3571076b9443SCy Schubert         if( objc!=3 ){
3572076b9443SCy Schubert           Tcl_WrongNumArgs(interp, 3, objv, "");
3573076b9443SCy Schubert           return TCL_ERROR;
3574076b9443SCy Schubert         }
3575076b9443SCy Schubert         pRet = Tcl_NewIntObj(sqlite3_preupdate_depth(pDb->db));
3576076b9443SCy Schubert         Tcl_SetObjResult(interp, pRet);
3577076b9443SCy Schubert         break;
3578076b9443SCy Schubert       }
3579076b9443SCy Schubert 
3580076b9443SCy Schubert       case PRE_NEW:
3581076b9443SCy Schubert       case PRE_OLD: {
3582076b9443SCy Schubert         int iIdx;
3583076b9443SCy Schubert         sqlite3_value *pValue;
3584076b9443SCy Schubert         if( objc!=4 ){
3585076b9443SCy Schubert           Tcl_WrongNumArgs(interp, 3, objv, "INDEX");
3586076b9443SCy Schubert           return TCL_ERROR;
3587076b9443SCy Schubert         }
3588076b9443SCy Schubert         if( Tcl_GetIntFromObj(interp, objv[3], &iIdx) ){
3589076b9443SCy Schubert           return TCL_ERROR;
3590076b9443SCy Schubert         }
3591076b9443SCy Schubert 
3592076b9443SCy Schubert         if( iSub==PRE_OLD ){
3593076b9443SCy Schubert           rc = sqlite3_preupdate_old(pDb->db, iIdx, &pValue);
3594076b9443SCy Schubert         }else{
3595076b9443SCy Schubert           assert( iSub==PRE_NEW );
3596076b9443SCy Schubert           rc = sqlite3_preupdate_new(pDb->db, iIdx, &pValue);
3597076b9443SCy Schubert         }
3598076b9443SCy Schubert 
3599076b9443SCy Schubert         if( rc==SQLITE_OK ){
3600076b9443SCy Schubert           Tcl_Obj *pObj;
3601076b9443SCy Schubert           pObj = Tcl_NewStringObj((char*)sqlite3_value_text(pValue), -1);
3602076b9443SCy Schubert           Tcl_SetObjResult(interp, pObj);
3603076b9443SCy Schubert         }else{
3604076b9443SCy Schubert           Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
3605076b9443SCy Schubert           return TCL_ERROR;
3606076b9443SCy Schubert         }
3607076b9443SCy Schubert       }
3608076b9443SCy Schubert     }
3609076b9443SCy Schubert #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
3610076b9443SCy Schubert     break;
3611076b9443SCy Schubert   }
3612076b9443SCy Schubert 
3613076b9443SCy Schubert   /*
3614076b9443SCy Schubert   **    $db wal_hook ?script?
3615076b9443SCy Schubert   **    $db update_hook ?script?
3616076b9443SCy Schubert   **    $db rollback_hook ?script?
3617076b9443SCy Schubert   */
3618076b9443SCy Schubert   case DB_WAL_HOOK:
3619076b9443SCy Schubert   case DB_UPDATE_HOOK:
3620076b9443SCy Schubert   case DB_ROLLBACK_HOOK: {
3621076b9443SCy Schubert     /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
3622076b9443SCy Schubert     ** whether [$db update_hook] or [$db rollback_hook] was invoked.
3623076b9443SCy Schubert     */
3624076b9443SCy Schubert     Tcl_Obj **ppHook = 0;
3625076b9443SCy Schubert     if( choice==DB_WAL_HOOK ) ppHook = &pDb->pWalHook;
3626076b9443SCy Schubert     if( choice==DB_UPDATE_HOOK ) ppHook = &pDb->pUpdateHook;
3627076b9443SCy Schubert     if( choice==DB_ROLLBACK_HOOK ) ppHook = &pDb->pRollbackHook;
3628076b9443SCy Schubert     if( objc>3 ){
3629076b9443SCy Schubert        Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
3630076b9443SCy Schubert        return TCL_ERROR;
3631076b9443SCy Schubert     }
3632076b9443SCy Schubert 
3633076b9443SCy Schubert     DbHookCmd(interp, pDb, (objc==3 ? objv[2] : 0), ppHook);
3634076b9443SCy Schubert     break;
3635076b9443SCy Schubert   }
3636076b9443SCy Schubert 
3637076b9443SCy Schubert   /*    $db version
3638076b9443SCy Schubert   **
3639076b9443SCy Schubert   ** Return the version string for this database.
3640076b9443SCy Schubert   */
3641076b9443SCy Schubert   case DB_VERSION: {
3642076b9443SCy Schubert     int i;
3643076b9443SCy Schubert     for(i=2; i<objc; i++){
3644076b9443SCy Schubert       const char *zArg = Tcl_GetString(objv[i]);
3645076b9443SCy Schubert       /* Optional arguments to $db version are used for testing purpose */
3646076b9443SCy Schubert #ifdef SQLITE_TEST
3647076b9443SCy Schubert       /* $db version -use-legacy-prepare BOOLEAN
3648076b9443SCy Schubert       **
3649076b9443SCy Schubert       ** Turn the use of legacy sqlite3_prepare() on or off.
3650076b9443SCy Schubert       */
3651076b9443SCy Schubert       if( strcmp(zArg, "-use-legacy-prepare")==0 && i+1<objc ){
3652076b9443SCy Schubert         i++;
3653076b9443SCy Schubert         if( Tcl_GetBooleanFromObj(interp, objv[i], &pDb->bLegacyPrepare) ){
3654076b9443SCy Schubert           return TCL_ERROR;
3655076b9443SCy Schubert         }
3656076b9443SCy Schubert       }else
3657076b9443SCy Schubert 
3658076b9443SCy Schubert       /* $db version -last-stmt-ptr
3659076b9443SCy Schubert       **
3660076b9443SCy Schubert       ** Return a string which is a hex encoding of the pointer to the
3661076b9443SCy Schubert       ** most recent sqlite3_stmt in the statement cache.
3662076b9443SCy Schubert       */
3663076b9443SCy Schubert       if( strcmp(zArg, "-last-stmt-ptr")==0 ){
3664076b9443SCy Schubert         char zBuf[100];
3665076b9443SCy Schubert         sqlite3_snprintf(sizeof(zBuf), zBuf, "%p",
3666076b9443SCy Schubert                          pDb->stmtList ? pDb->stmtList->pStmt: 0);
3667076b9443SCy Schubert         Tcl_SetResult(interp, zBuf, TCL_VOLATILE);
3668076b9443SCy Schubert       }else
3669076b9443SCy Schubert #endif /* SQLITE_TEST */
3670076b9443SCy Schubert       {
3671076b9443SCy Schubert         Tcl_AppendResult(interp, "unknown argument: ", zArg, (char*)0);
3672076b9443SCy Schubert         return TCL_ERROR;
3673076b9443SCy Schubert       }
3674076b9443SCy Schubert     }
3675076b9443SCy Schubert     if( i==2 ){
3676076b9443SCy Schubert       Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
3677076b9443SCy Schubert     }
3678076b9443SCy Schubert     break;
3679076b9443SCy Schubert   }
3680076b9443SCy Schubert 
3681076b9443SCy Schubert 
3682076b9443SCy Schubert   } /* End of the SWITCH statement */
3683076b9443SCy Schubert   return rc;
3684076b9443SCy Schubert }
3685076b9443SCy Schubert 
3686076b9443SCy Schubert #if SQLITE_TCL_NRE
3687076b9443SCy Schubert /*
3688076b9443SCy Schubert ** Adaptor that provides an objCmd interface to the NRE-enabled
3689076b9443SCy Schubert ** interface implementation.
3690076b9443SCy Schubert */
3691076b9443SCy Schubert static int SQLITE_TCLAPI DbObjCmdAdaptor(
3692076b9443SCy Schubert   void *cd,
3693076b9443SCy Schubert   Tcl_Interp *interp,
3694076b9443SCy Schubert   int objc,
3695076b9443SCy Schubert   Tcl_Obj *const*objv
3696076b9443SCy Schubert ){
3697076b9443SCy Schubert   return Tcl_NRCallObjProc(interp, DbObjCmd, cd, objc, objv);
3698076b9443SCy Schubert }
3699076b9443SCy Schubert #endif /* SQLITE_TCL_NRE */
3700076b9443SCy Schubert 
3701076b9443SCy Schubert /*
3702076b9443SCy Schubert ** Issue the usage message when the "sqlite3" command arguments are
3703076b9443SCy Schubert ** incorrect.
3704076b9443SCy Schubert */
3705076b9443SCy Schubert static int sqliteCmdUsage(
3706076b9443SCy Schubert   Tcl_Interp *interp,
3707076b9443SCy Schubert   Tcl_Obj *const*objv
3708076b9443SCy Schubert ){
3709076b9443SCy Schubert   Tcl_WrongNumArgs(interp, 1, objv,
3710076b9443SCy Schubert     "HANDLE ?FILENAME? ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
37110e2816f5SCy Schubert     " ?-nofollow BOOLEAN?"
3712076b9443SCy Schubert     " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN? ?-uri BOOLEAN?"
3713076b9443SCy Schubert   );
3714076b9443SCy Schubert   return TCL_ERROR;
3715076b9443SCy Schubert }
3716076b9443SCy Schubert 
3717076b9443SCy Schubert /*
3718076b9443SCy Schubert **   sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
3719076b9443SCy Schubert **                           ?-create BOOLEAN? ?-nomutex BOOLEAN?
37200e2816f5SCy Schubert **                           ?-nofollow BOOLEAN?
3721076b9443SCy Schubert **
3722076b9443SCy Schubert ** This is the main Tcl command.  When the "sqlite" Tcl command is
3723076b9443SCy Schubert ** invoked, this routine runs to process that command.
3724076b9443SCy Schubert **
3725076b9443SCy Schubert ** The first argument, DBNAME, is an arbitrary name for a new
3726076b9443SCy Schubert ** database connection.  This command creates a new command named
3727076b9443SCy Schubert ** DBNAME that is used to control that connection.  The database
3728076b9443SCy Schubert ** connection is deleted when the DBNAME command is deleted.
3729076b9443SCy Schubert **
3730076b9443SCy Schubert ** The second argument is the name of the database file.
3731076b9443SCy Schubert **
3732076b9443SCy Schubert */
3733076b9443SCy Schubert static int SQLITE_TCLAPI DbMain(
3734076b9443SCy Schubert   void *cd,
3735076b9443SCy Schubert   Tcl_Interp *interp,
3736076b9443SCy Schubert   int objc,
3737076b9443SCy Schubert   Tcl_Obj *const*objv
3738076b9443SCy Schubert ){
3739076b9443SCy Schubert   SqliteDb *p;
3740076b9443SCy Schubert   const char *zArg;
3741076b9443SCy Schubert   char *zErrMsg;
3742076b9443SCy Schubert   int i;
3743076b9443SCy Schubert   const char *zFile = 0;
3744076b9443SCy Schubert   const char *zVfs = 0;
3745076b9443SCy Schubert   int flags;
3746b622dc25SCy Schubert   int bTranslateFileName = 1;
3747076b9443SCy Schubert   Tcl_DString translatedFilename;
3748076b9443SCy Schubert   int rc;
3749076b9443SCy Schubert 
3750076b9443SCy Schubert   /* In normal use, each TCL interpreter runs in a single thread.  So
3751076b9443SCy Schubert   ** by default, we can turn off mutexing on SQLite database connections.
3752076b9443SCy Schubert   ** However, for testing purposes it is useful to have mutexes turned
3753076b9443SCy Schubert   ** on.  So, by default, mutexes default off.  But if compiled with
3754076b9443SCy Schubert   ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on.
3755076b9443SCy Schubert   */
3756076b9443SCy Schubert #ifdef SQLITE_TCL_DEFAULT_FULLMUTEX
3757076b9443SCy Schubert   flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
3758076b9443SCy Schubert #else
3759076b9443SCy Schubert   flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX;
3760076b9443SCy Schubert #endif
3761076b9443SCy Schubert 
3762076b9443SCy Schubert   if( objc==1 ) return sqliteCmdUsage(interp, objv);
3763076b9443SCy Schubert   if( objc==2 ){
3764076b9443SCy Schubert     zArg = Tcl_GetStringFromObj(objv[1], 0);
3765076b9443SCy Schubert     if( strcmp(zArg,"-version")==0 ){
3766076b9443SCy Schubert       Tcl_AppendResult(interp,sqlite3_libversion(), (char*)0);
3767076b9443SCy Schubert       return TCL_OK;
3768076b9443SCy Schubert     }
3769076b9443SCy Schubert     if( strcmp(zArg,"-sourceid")==0 ){
3770076b9443SCy Schubert       Tcl_AppendResult(interp,sqlite3_sourceid(), (char*)0);
3771076b9443SCy Schubert       return TCL_OK;
3772076b9443SCy Schubert     }
3773076b9443SCy Schubert     if( strcmp(zArg,"-has-codec")==0 ){
3774076b9443SCy Schubert       Tcl_AppendResult(interp,"0",(char*)0);
3775076b9443SCy Schubert       return TCL_OK;
3776076b9443SCy Schubert     }
3777076b9443SCy Schubert     if( zArg[0]=='-' ) return sqliteCmdUsage(interp, objv);
3778076b9443SCy Schubert   }
3779076b9443SCy Schubert   for(i=2; i<objc; i++){
3780076b9443SCy Schubert     zArg = Tcl_GetString(objv[i]);
3781076b9443SCy Schubert     if( zArg[0]!='-' ){
3782076b9443SCy Schubert       if( zFile!=0 ) return sqliteCmdUsage(interp, objv);
3783076b9443SCy Schubert       zFile = zArg;
3784076b9443SCy Schubert       continue;
3785076b9443SCy Schubert     }
3786076b9443SCy Schubert     if( i==objc-1 ) return sqliteCmdUsage(interp, objv);
3787076b9443SCy Schubert     i++;
3788076b9443SCy Schubert     if( strcmp(zArg,"-key")==0 ){
3789b622dc25SCy Schubert       /* no-op */
3790076b9443SCy Schubert     }else if( strcmp(zArg, "-vfs")==0 ){
3791076b9443SCy Schubert       zVfs = Tcl_GetString(objv[i]);
3792076b9443SCy Schubert     }else if( strcmp(zArg, "-readonly")==0 ){
3793076b9443SCy Schubert       int b;
3794076b9443SCy Schubert       if( Tcl_GetBooleanFromObj(interp, objv[i], &b) ) return TCL_ERROR;
3795076b9443SCy Schubert       if( b ){
3796076b9443SCy Schubert         flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
3797076b9443SCy Schubert         flags |= SQLITE_OPEN_READONLY;
3798076b9443SCy Schubert       }else{
3799076b9443SCy Schubert         flags &= ~SQLITE_OPEN_READONLY;
3800076b9443SCy Schubert         flags |= SQLITE_OPEN_READWRITE;
3801076b9443SCy Schubert       }
3802076b9443SCy Schubert     }else if( strcmp(zArg, "-create")==0 ){
3803076b9443SCy Schubert       int b;
3804076b9443SCy Schubert       if( Tcl_GetBooleanFromObj(interp, objv[i], &b) ) return TCL_ERROR;
3805076b9443SCy Schubert       if( b && (flags & SQLITE_OPEN_READONLY)==0 ){
3806076b9443SCy Schubert         flags |= SQLITE_OPEN_CREATE;
3807076b9443SCy Schubert       }else{
3808076b9443SCy Schubert         flags &= ~SQLITE_OPEN_CREATE;
3809076b9443SCy Schubert       }
38100e2816f5SCy Schubert     }else if( strcmp(zArg, "-nofollow")==0 ){
38110e2816f5SCy Schubert       int b;
38120e2816f5SCy Schubert       if( Tcl_GetBooleanFromObj(interp, objv[i], &b) ) return TCL_ERROR;
38130e2816f5SCy Schubert       if( b ){
38140e2816f5SCy Schubert         flags |= SQLITE_OPEN_NOFOLLOW;
38150e2816f5SCy Schubert       }else{
38160e2816f5SCy Schubert         flags &= ~SQLITE_OPEN_NOFOLLOW;
38170e2816f5SCy Schubert       }
3818076b9443SCy Schubert     }else if( strcmp(zArg, "-nomutex")==0 ){
3819076b9443SCy Schubert       int b;
3820076b9443SCy Schubert       if( Tcl_GetBooleanFromObj(interp, objv[i], &b) ) return TCL_ERROR;
3821076b9443SCy Schubert       if( b ){
3822076b9443SCy Schubert         flags |= SQLITE_OPEN_NOMUTEX;
3823076b9443SCy Schubert         flags &= ~SQLITE_OPEN_FULLMUTEX;
3824076b9443SCy Schubert       }else{
3825076b9443SCy Schubert         flags &= ~SQLITE_OPEN_NOMUTEX;
3826076b9443SCy Schubert       }
3827076b9443SCy Schubert     }else if( strcmp(zArg, "-fullmutex")==0 ){
3828076b9443SCy Schubert       int b;
3829076b9443SCy Schubert       if( Tcl_GetBooleanFromObj(interp, objv[i], &b) ) return TCL_ERROR;
3830076b9443SCy Schubert       if( b ){
3831076b9443SCy Schubert         flags |= SQLITE_OPEN_FULLMUTEX;
3832076b9443SCy Schubert         flags &= ~SQLITE_OPEN_NOMUTEX;
3833076b9443SCy Schubert       }else{
3834076b9443SCy Schubert         flags &= ~SQLITE_OPEN_FULLMUTEX;
3835076b9443SCy Schubert       }
3836076b9443SCy Schubert     }else if( strcmp(zArg, "-uri")==0 ){
3837076b9443SCy Schubert       int b;
3838076b9443SCy Schubert       if( Tcl_GetBooleanFromObj(interp, objv[i], &b) ) return TCL_ERROR;
3839076b9443SCy Schubert       if( b ){
3840076b9443SCy Schubert         flags |= SQLITE_OPEN_URI;
3841076b9443SCy Schubert       }else{
3842076b9443SCy Schubert         flags &= ~SQLITE_OPEN_URI;
3843076b9443SCy Schubert       }
3844b622dc25SCy Schubert     }else if( strcmp(zArg, "-translatefilename")==0 ){
3845b622dc25SCy Schubert       if( Tcl_GetBooleanFromObj(interp, objv[i], &bTranslateFileName) ){
3846b622dc25SCy Schubert         return TCL_ERROR;
3847b622dc25SCy Schubert       }
3848076b9443SCy Schubert     }else{
3849076b9443SCy Schubert       Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
3850076b9443SCy Schubert       return TCL_ERROR;
3851076b9443SCy Schubert     }
3852076b9443SCy Schubert   }
3853076b9443SCy Schubert   zErrMsg = 0;
3854076b9443SCy Schubert   p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
3855076b9443SCy Schubert   memset(p, 0, sizeof(*p));
3856076b9443SCy Schubert   if( zFile==0 ) zFile = "";
3857b622dc25SCy Schubert   if( bTranslateFileName ){
3858076b9443SCy Schubert     zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
3859b622dc25SCy Schubert   }
3860076b9443SCy Schubert   rc = sqlite3_open_v2(zFile, &p->db, flags, zVfs);
3861b622dc25SCy Schubert   if( bTranslateFileName ){
3862076b9443SCy Schubert     Tcl_DStringFree(&translatedFilename);
3863b622dc25SCy Schubert   }
3864076b9443SCy Schubert   if( p->db ){
3865076b9443SCy Schubert     if( SQLITE_OK!=sqlite3_errcode(p->db) ){
3866076b9443SCy Schubert       zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
3867076b9443SCy Schubert       sqlite3_close(p->db);
3868076b9443SCy Schubert       p->db = 0;
3869076b9443SCy Schubert     }
3870076b9443SCy Schubert   }else{
3871076b9443SCy Schubert     zErrMsg = sqlite3_mprintf("%s", sqlite3_errstr(rc));
3872076b9443SCy Schubert   }
3873076b9443SCy Schubert   if( p->db==0 ){
3874076b9443SCy Schubert     Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
3875076b9443SCy Schubert     Tcl_Free((char*)p);
3876076b9443SCy Schubert     sqlite3_free(zErrMsg);
3877076b9443SCy Schubert     return TCL_ERROR;
3878076b9443SCy Schubert   }
3879076b9443SCy Schubert   p->maxStmt = NUM_PREPARED_STMTS;
3880076b9443SCy Schubert   p->openFlags = flags & SQLITE_OPEN_URI;
3881076b9443SCy Schubert   p->interp = interp;
3882076b9443SCy Schubert   zArg = Tcl_GetStringFromObj(objv[1], 0);
3883076b9443SCy Schubert   if( DbUseNre() ){
3884076b9443SCy Schubert     Tcl_NRCreateCommand(interp, zArg, DbObjCmdAdaptor, DbObjCmd,
3885076b9443SCy Schubert                         (char*)p, DbDeleteCmd);
3886076b9443SCy Schubert   }else{
3887076b9443SCy Schubert     Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
3888076b9443SCy Schubert   }
38890197ba46SCy Schubert   p->nRef = 1;
3890076b9443SCy Schubert   return TCL_OK;
3891076b9443SCy Schubert }
3892076b9443SCy Schubert 
3893076b9443SCy Schubert /*
3894076b9443SCy Schubert ** Provide a dummy Tcl_InitStubs if we are using this as a static
3895076b9443SCy Schubert ** library.
3896076b9443SCy Schubert */
3897076b9443SCy Schubert #ifndef USE_TCL_STUBS
3898076b9443SCy Schubert # undef  Tcl_InitStubs
3899076b9443SCy Schubert # define Tcl_InitStubs(a,b,c) TCL_VERSION
3900076b9443SCy Schubert #endif
3901076b9443SCy Schubert 
3902076b9443SCy Schubert /*
3903076b9443SCy Schubert ** Make sure we have a PACKAGE_VERSION macro defined.  This will be
3904076b9443SCy Schubert ** defined automatically by the TEA makefile.  But other makefiles
3905076b9443SCy Schubert ** do not define it.
3906076b9443SCy Schubert */
3907076b9443SCy Schubert #ifndef PACKAGE_VERSION
3908076b9443SCy Schubert # define PACKAGE_VERSION SQLITE_VERSION
3909076b9443SCy Schubert #endif
3910076b9443SCy Schubert 
3911076b9443SCy Schubert /*
3912076b9443SCy Schubert ** Initialize this module.
3913076b9443SCy Schubert **
3914076b9443SCy Schubert ** This Tcl module contains only a single new Tcl command named "sqlite".
3915076b9443SCy Schubert ** (Hence there is no namespace.  There is no point in using a namespace
3916076b9443SCy Schubert ** if the extension only supplies one new name!)  The "sqlite" command is
3917076b9443SCy Schubert ** used to open a new SQLite database.  See the DbMain() routine above
3918076b9443SCy Schubert ** for additional information.
3919076b9443SCy Schubert **
3920076b9443SCy Schubert ** The EXTERN macros are required by TCL in order to work on windows.
3921076b9443SCy Schubert */
3922076b9443SCy Schubert EXTERN int Sqlite3_Init(Tcl_Interp *interp){
3923076b9443SCy Schubert   int rc = Tcl_InitStubs(interp, "8.4", 0) ? TCL_OK : TCL_ERROR;
3924076b9443SCy Schubert   if( rc==TCL_OK ){
3925076b9443SCy Schubert     Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
3926076b9443SCy Schubert #ifndef SQLITE_3_SUFFIX_ONLY
3927076b9443SCy Schubert     /* The "sqlite" alias is undocumented.  It is here only to support
3928076b9443SCy Schubert     ** legacy scripts.  All new scripts should use only the "sqlite3"
3929076b9443SCy Schubert     ** command. */
3930076b9443SCy Schubert     Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
3931076b9443SCy Schubert #endif
3932076b9443SCy Schubert     rc = Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
3933076b9443SCy Schubert   }
3934076b9443SCy Schubert   return rc;
3935076b9443SCy Schubert }
3936076b9443SCy Schubert EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3937076b9443SCy Schubert EXTERN int Sqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3938076b9443SCy Schubert EXTERN int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3939076b9443SCy Schubert 
3940076b9443SCy Schubert /* Because it accesses the file-system and uses persistent state, SQLite
3941076b9443SCy Schubert ** is not considered appropriate for safe interpreters.  Hence, we cause
3942076b9443SCy Schubert ** the _SafeInit() interfaces return TCL_ERROR.
3943076b9443SCy Schubert */
3944076b9443SCy Schubert EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_ERROR; }
3945076b9443SCy Schubert EXTERN int Sqlite3_SafeUnload(Tcl_Interp *interp, int flags){return TCL_ERROR;}
3946076b9443SCy Schubert 
3947076b9443SCy Schubert 
3948076b9443SCy Schubert 
3949076b9443SCy Schubert #ifndef SQLITE_3_SUFFIX_ONLY
3950076b9443SCy Schubert int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3951076b9443SCy Schubert int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3952076b9443SCy Schubert int Sqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3953076b9443SCy Schubert int Tclsqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3954076b9443SCy Schubert #endif
3955076b9443SCy Schubert 
3956076b9443SCy Schubert /*
3957076b9443SCy Schubert ** If the TCLSH macro is defined, add code to make a stand-alone program.
3958076b9443SCy Schubert */
3959076b9443SCy Schubert #if defined(TCLSH)
3960076b9443SCy Schubert 
3961076b9443SCy Schubert /* This is the main routine for an ordinary TCL shell.  If there are
3962076b9443SCy Schubert ** are arguments, run the first argument as a script.  Otherwise,
3963076b9443SCy Schubert ** read TCL commands from standard input
3964076b9443SCy Schubert */
3965076b9443SCy Schubert static const char *tclsh_main_loop(void){
3966076b9443SCy Schubert   static const char zMainloop[] =
3967076b9443SCy Schubert     "if {[llength $argv]>=1} {\n"
3968076b9443SCy Schubert       "set argv0 [lindex $argv 0]\n"
3969076b9443SCy Schubert       "set argv [lrange $argv 1 end]\n"
3970076b9443SCy Schubert       "source $argv0\n"
3971076b9443SCy Schubert     "} else {\n"
3972076b9443SCy Schubert       "set line {}\n"
3973076b9443SCy Schubert       "while {![eof stdin]} {\n"
3974076b9443SCy Schubert         "if {$line!=\"\"} {\n"
3975076b9443SCy Schubert           "puts -nonewline \"> \"\n"
3976076b9443SCy Schubert         "} else {\n"
3977076b9443SCy Schubert           "puts -nonewline \"% \"\n"
3978076b9443SCy Schubert         "}\n"
3979076b9443SCy Schubert         "flush stdout\n"
3980076b9443SCy Schubert         "append line [gets stdin]\n"
3981076b9443SCy Schubert         "if {[info complete $line]} {\n"
3982076b9443SCy Schubert           "if {[catch {uplevel #0 $line} result]} {\n"
3983076b9443SCy Schubert             "puts stderr \"Error: $result\"\n"
3984076b9443SCy Schubert           "} elseif {$result!=\"\"} {\n"
3985076b9443SCy Schubert             "puts $result\n"
3986076b9443SCy Schubert           "}\n"
3987076b9443SCy Schubert           "set line {}\n"
3988076b9443SCy Schubert         "} else {\n"
3989076b9443SCy Schubert           "append line \\n\n"
3990076b9443SCy Schubert         "}\n"
3991076b9443SCy Schubert       "}\n"
3992076b9443SCy Schubert     "}\n"
3993076b9443SCy Schubert   ;
3994076b9443SCy Schubert   return zMainloop;
3995076b9443SCy Schubert }
3996076b9443SCy Schubert 
39970197ba46SCy Schubert #ifndef TCLSH_MAIN
39980197ba46SCy Schubert # define TCLSH_MAIN main
39990197ba46SCy Schubert #endif
4000076b9443SCy Schubert int SQLITE_CDECL TCLSH_MAIN(int argc, char **argv){
4001076b9443SCy Schubert   Tcl_Interp *interp;
4002076b9443SCy Schubert   int i;
4003076b9443SCy Schubert   const char *zScript = 0;
4004076b9443SCy Schubert   char zArgc[32];
4005076b9443SCy Schubert #if defined(TCLSH_INIT_PROC)
4006076b9443SCy Schubert   extern const char *TCLSH_INIT_PROC(Tcl_Interp*);
4007076b9443SCy Schubert #endif
4008076b9443SCy Schubert 
4009076b9443SCy Schubert #if !defined(_WIN32_WCE)
4010076b9443SCy Schubert   if( getenv("SQLITE_DEBUG_BREAK") ){
4011076b9443SCy Schubert     if( isatty(0) && isatty(2) ){
4012076b9443SCy Schubert       fprintf(stderr,
4013076b9443SCy Schubert           "attach debugger to process %d and press any key to continue.\n",
4014076b9443SCy Schubert           GETPID());
4015076b9443SCy Schubert       fgetc(stdin);
4016076b9443SCy Schubert     }else{
4017076b9443SCy Schubert #if defined(_WIN32) || defined(WIN32)
4018076b9443SCy Schubert       DebugBreak();
4019076b9443SCy Schubert #elif defined(SIGTRAP)
4020076b9443SCy Schubert       raise(SIGTRAP);
4021076b9443SCy Schubert #endif
4022076b9443SCy Schubert     }
4023076b9443SCy Schubert   }
4024076b9443SCy Schubert #endif
4025076b9443SCy Schubert 
4026076b9443SCy Schubert   /* Call sqlite3_shutdown() once before doing anything else. This is to
4027076b9443SCy Schubert   ** test that sqlite3_shutdown() can be safely called by a process before
4028076b9443SCy Schubert   ** sqlite3_initialize() is. */
4029076b9443SCy Schubert   sqlite3_shutdown();
4030076b9443SCy Schubert 
4031076b9443SCy Schubert   Tcl_FindExecutable(argv[0]);
4032076b9443SCy Schubert   Tcl_SetSystemEncoding(NULL, "utf-8");
4033076b9443SCy Schubert   interp = Tcl_CreateInterp();
4034076b9443SCy Schubert   Sqlite3_Init(interp);
4035076b9443SCy Schubert 
4036076b9443SCy Schubert   sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-1);
4037076b9443SCy Schubert   Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
4038076b9443SCy Schubert   Tcl_SetVar(interp,"argv0",argv[0],TCL_GLOBAL_ONLY);
4039076b9443SCy Schubert   Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
4040076b9443SCy Schubert   for(i=1; i<argc; i++){
4041076b9443SCy Schubert     Tcl_SetVar(interp, "argv", argv[i],
4042076b9443SCy Schubert         TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
4043076b9443SCy Schubert   }
4044076b9443SCy Schubert #if defined(TCLSH_INIT_PROC)
4045076b9443SCy Schubert   zScript = TCLSH_INIT_PROC(interp);
4046076b9443SCy Schubert #endif
4047076b9443SCy Schubert   if( zScript==0 ){
4048076b9443SCy Schubert     zScript = tclsh_main_loop();
4049076b9443SCy Schubert   }
4050076b9443SCy Schubert   if( Tcl_GlobalEval(interp, zScript)!=TCL_OK ){
4051076b9443SCy Schubert     const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
4052076b9443SCy Schubert     if( zInfo==0 ) zInfo = Tcl_GetStringResult(interp);
4053076b9443SCy Schubert     fprintf(stderr,"%s: %s\n", *argv, zInfo);
4054076b9443SCy Schubert     return 1;
4055076b9443SCy Schubert   }
4056076b9443SCy Schubert   return 0;
4057076b9443SCy Schubert }
4058076b9443SCy Schubert #endif /* TCLSH */
4059