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