xref: /sqlite-3.40.0/src/tclsqlite.c (revision cc285c5a)
1 /*
2 ** 2001 September 15
3 **
4 ** The author disclaims copyright to this source code.  In place of
5 ** a legal notice, here is a blessing:
6 **
7 **    May you do good and not evil.
8 **    May you find forgiveness for yourself and forgive others.
9 **    May you share freely, never taking more than you give.
10 **
11 *************************************************************************
12 ** A TCL Interface to SQLite.  Append this file to sqlite3.c and
13 ** compile the whole thing to build a TCL-enabled version of SQLite.
14 **
15 ** Compile-time options:
16 **
17 **  -DTCLSH=1             Add a "main()" routine that works as a tclsh.
18 **
19 **  -DSQLITE_TCLMD5       When used in conjuction with -DTCLSH=1, add
20 **                        four new commands to the TCL interpreter for
21 **                        generating MD5 checksums:  md5, md5file,
22 **                        md5-10x8, and md5file-10x8.
23 **
24 **  -DSQLITE_TEST         When used in conjuction with -DTCLSH=1, add
25 **                        hundreds of new commands used for testing
26 **                        SQLite.  This option implies -DSQLITE_TCLMD5.
27 */
28 
29 /*
30 ** If requested, include the SQLite compiler options file for MSVC.
31 */
32 #if defined(INCLUDE_MSVC_H)
33 #include "msvc.h"
34 #endif
35 
36 #include "tcl.h"
37 #include <errno.h>
38 
39 /*
40 ** Some additional include files are needed if this file is not
41 ** appended to the amalgamation.
42 */
43 #ifndef SQLITE_AMALGAMATION
44 # include "sqlite3.h"
45 # include <stdlib.h>
46 # include <string.h>
47 # include <assert.h>
48   typedef unsigned char u8;
49 #endif
50 #include <ctype.h>
51 
52 /* Used to get the current process ID */
53 #if !defined(_WIN32)
54 # include <unistd.h>
55 # define GETPID getpid
56 #elif !defined(_WIN32_WCE)
57 # ifndef SQLITE_AMALGAMATION
58 #  define WIN32_LEAN_AND_MEAN
59 #  include <windows.h>
60 # endif
61 # define GETPID (int)GetCurrentProcessId
62 #endif
63 
64 /*
65  * Windows needs to know which symbols to export.  Unix does not.
66  * BUILD_sqlite should be undefined for Unix.
67  */
68 #ifdef BUILD_sqlite
69 #undef TCL_STORAGE_CLASS
70 #define TCL_STORAGE_CLASS DLLEXPORT
71 #endif /* BUILD_sqlite */
72 
73 #define NUM_PREPARED_STMTS 10
74 #define MAX_PREPARED_STMTS 100
75 
76 /* Forward declaration */
77 typedef struct SqliteDb SqliteDb;
78 
79 /*
80 ** New SQL functions can be created as TCL scripts.  Each such function
81 ** is described by an instance of the following structure.
82 */
83 typedef struct SqlFunc SqlFunc;
84 struct SqlFunc {
85   Tcl_Interp *interp;   /* The TCL interpret to execute the function */
86   Tcl_Obj *pScript;     /* The Tcl_Obj representation of the script */
87   SqliteDb *pDb;        /* Database connection that owns this function */
88   int useEvalObjv;      /* True if it is safe to use Tcl_EvalObjv */
89   char *zName;          /* Name of this function */
90   SqlFunc *pNext;       /* Next function on the list of them all */
91 };
92 
93 /*
94 ** New collation sequences function can be created as TCL scripts.  Each such
95 ** function is described by an instance of the following structure.
96 */
97 typedef struct SqlCollate SqlCollate;
98 struct SqlCollate {
99   Tcl_Interp *interp;   /* The TCL interpret to execute the function */
100   char *zScript;        /* The script to be run */
101   SqlCollate *pNext;    /* Next function on the list of them all */
102 };
103 
104 /*
105 ** Prepared statements are cached for faster execution.  Each prepared
106 ** statement is described by an instance of the following structure.
107 */
108 typedef struct SqlPreparedStmt SqlPreparedStmt;
109 struct SqlPreparedStmt {
110   SqlPreparedStmt *pNext;  /* Next in linked list */
111   SqlPreparedStmt *pPrev;  /* Previous on the list */
112   sqlite3_stmt *pStmt;     /* The prepared statement */
113   int nSql;                /* chars in zSql[] */
114   const char *zSql;        /* Text of the SQL statement */
115   int nParm;               /* Size of apParm array */
116   Tcl_Obj **apParm;        /* Array of referenced object pointers */
117 };
118 
119 typedef struct IncrblobChannel IncrblobChannel;
120 
121 /*
122 ** There is one instance of this structure for each SQLite database
123 ** that has been opened by the SQLite TCL interface.
124 **
125 ** If this module is built with SQLITE_TEST defined (to create the SQLite
126 ** testfixture executable), then it may be configured to use either
127 ** sqlite3_prepare_v2() or sqlite3_prepare() to prepare SQL statements.
128 ** If SqliteDb.bLegacyPrepare is true, sqlite3_prepare() is used.
129 */
130 struct SqliteDb {
131   sqlite3 *db;               /* The "real" database structure. MUST BE FIRST */
132   Tcl_Interp *interp;        /* The interpreter used for this database */
133   char *zBusy;               /* The busy callback routine */
134   char *zCommit;             /* The commit hook callback routine */
135   char *zTrace;              /* The trace callback routine */
136   char *zProfile;            /* The profile callback routine */
137   char *zProgress;           /* The progress callback routine */
138   char *zAuth;               /* The authorization callback routine */
139   int disableAuth;           /* Disable the authorizer if it exists */
140   char *zNull;               /* Text to substitute for an SQL NULL value */
141   SqlFunc *pFunc;            /* List of SQL functions */
142   Tcl_Obj *pUpdateHook;      /* Update hook script (if any) */
143   Tcl_Obj *pRollbackHook;    /* Rollback hook script (if any) */
144   Tcl_Obj *pWalHook;         /* WAL hook script (if any) */
145   Tcl_Obj *pUnlockNotify;    /* Unlock notify script (if any) */
146   SqlCollate *pCollate;      /* List of SQL collation functions */
147   int rc;                    /* Return code of most recent sqlite3_exec() */
148   Tcl_Obj *pCollateNeeded;   /* Collation needed script */
149   SqlPreparedStmt *stmtList; /* List of prepared statements*/
150   SqlPreparedStmt *stmtLast; /* Last statement in the list */
151   int maxStmt;               /* The next maximum number of stmtList */
152   int nStmt;                 /* Number of statements in stmtList */
153   IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */
154   int nStep, nSort, nIndex;  /* Statistics for most recent operation */
155   int nTransaction;          /* Number of nested [transaction] methods */
156 #ifdef SQLITE_TEST
157   int bLegacyPrepare;        /* True to use sqlite3_prepare() */
158 #endif
159 };
160 
161 struct IncrblobChannel {
162   sqlite3_blob *pBlob;      /* sqlite3 blob handle */
163   SqliteDb *pDb;            /* Associated database connection */
164   int iSeek;                /* Current seek offset */
165   Tcl_Channel channel;      /* Channel identifier */
166   IncrblobChannel *pNext;   /* Linked list of all open incrblob channels */
167   IncrblobChannel *pPrev;   /* Linked list of all open incrblob channels */
168 };
169 
170 /*
171 ** Compute a string length that is limited to what can be stored in
172 ** lower 30 bits of a 32-bit signed integer.
173 */
174 static int strlen30(const char *z){
175   const char *z2 = z;
176   while( *z2 ){ z2++; }
177   return 0x3fffffff & (int)(z2 - z);
178 }
179 
180 
181 #ifndef SQLITE_OMIT_INCRBLOB
182 /*
183 ** Close all incrblob channels opened using database connection pDb.
184 ** This is called when shutting down the database connection.
185 */
186 static void closeIncrblobChannels(SqliteDb *pDb){
187   IncrblobChannel *p;
188   IncrblobChannel *pNext;
189 
190   for(p=pDb->pIncrblob; p; p=pNext){
191     pNext = p->pNext;
192 
193     /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
194     ** which deletes the IncrblobChannel structure at *p. So do not
195     ** call Tcl_Free() here.
196     */
197     Tcl_UnregisterChannel(pDb->interp, p->channel);
198   }
199 }
200 
201 /*
202 ** Close an incremental blob channel.
203 */
204 static int incrblobClose(ClientData instanceData, Tcl_Interp *interp){
205   IncrblobChannel *p = (IncrblobChannel *)instanceData;
206   int rc = sqlite3_blob_close(p->pBlob);
207   sqlite3 *db = p->pDb->db;
208 
209   /* Remove the channel from the SqliteDb.pIncrblob list. */
210   if( p->pNext ){
211     p->pNext->pPrev = p->pPrev;
212   }
213   if( p->pPrev ){
214     p->pPrev->pNext = p->pNext;
215   }
216   if( p->pDb->pIncrblob==p ){
217     p->pDb->pIncrblob = p->pNext;
218   }
219 
220   /* Free the IncrblobChannel structure */
221   Tcl_Free((char *)p);
222 
223   if( rc!=SQLITE_OK ){
224     Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
225     return TCL_ERROR;
226   }
227   return TCL_OK;
228 }
229 
230 /*
231 ** Read data from an incremental blob channel.
232 */
233 static int incrblobInput(
234   ClientData instanceData,
235   char *buf,
236   int bufSize,
237   int *errorCodePtr
238 ){
239   IncrblobChannel *p = (IncrblobChannel *)instanceData;
240   int nRead = bufSize;         /* Number of bytes to read */
241   int nBlob;                   /* Total size of the blob */
242   int rc;                      /* sqlite error code */
243 
244   nBlob = sqlite3_blob_bytes(p->pBlob);
245   if( (p->iSeek+nRead)>nBlob ){
246     nRead = nBlob-p->iSeek;
247   }
248   if( nRead<=0 ){
249     return 0;
250   }
251 
252   rc = sqlite3_blob_read(p->pBlob, (void *)buf, nRead, p->iSeek);
253   if( rc!=SQLITE_OK ){
254     *errorCodePtr = rc;
255     return -1;
256   }
257 
258   p->iSeek += nRead;
259   return nRead;
260 }
261 
262 /*
263 ** Write data to an incremental blob channel.
264 */
265 static int incrblobOutput(
266   ClientData instanceData,
267   CONST char *buf,
268   int toWrite,
269   int *errorCodePtr
270 ){
271   IncrblobChannel *p = (IncrblobChannel *)instanceData;
272   int nWrite = toWrite;        /* Number of bytes to write */
273   int nBlob;                   /* Total size of the blob */
274   int rc;                      /* sqlite error code */
275 
276   nBlob = sqlite3_blob_bytes(p->pBlob);
277   if( (p->iSeek+nWrite)>nBlob ){
278     *errorCodePtr = EINVAL;
279     return -1;
280   }
281   if( nWrite<=0 ){
282     return 0;
283   }
284 
285   rc = sqlite3_blob_write(p->pBlob, (void *)buf, nWrite, p->iSeek);
286   if( rc!=SQLITE_OK ){
287     *errorCodePtr = EIO;
288     return -1;
289   }
290 
291   p->iSeek += nWrite;
292   return nWrite;
293 }
294 
295 /*
296 ** Seek an incremental blob channel.
297 */
298 static int incrblobSeek(
299   ClientData instanceData,
300   long offset,
301   int seekMode,
302   int *errorCodePtr
303 ){
304   IncrblobChannel *p = (IncrblobChannel *)instanceData;
305 
306   switch( seekMode ){
307     case SEEK_SET:
308       p->iSeek = offset;
309       break;
310     case SEEK_CUR:
311       p->iSeek += offset;
312       break;
313     case SEEK_END:
314       p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset;
315       break;
316 
317     default: assert(!"Bad seekMode");
318   }
319 
320   return p->iSeek;
321 }
322 
323 
324 static void incrblobWatch(ClientData instanceData, int mode){
325   /* NO-OP */
326 }
327 static int incrblobHandle(ClientData instanceData, int dir, ClientData *hPtr){
328   return TCL_ERROR;
329 }
330 
331 static Tcl_ChannelType IncrblobChannelType = {
332   "incrblob",                        /* typeName                             */
333   TCL_CHANNEL_VERSION_2,             /* version                              */
334   incrblobClose,                     /* closeProc                            */
335   incrblobInput,                     /* inputProc                            */
336   incrblobOutput,                    /* outputProc                           */
337   incrblobSeek,                      /* seekProc                             */
338   0,                                 /* setOptionProc                        */
339   0,                                 /* getOptionProc                        */
340   incrblobWatch,                     /* watchProc (this is a no-op)          */
341   incrblobHandle,                    /* getHandleProc (always returns error) */
342   0,                                 /* close2Proc                           */
343   0,                                 /* blockModeProc                        */
344   0,                                 /* flushProc                            */
345   0,                                 /* handlerProc                          */
346   0,                                 /* wideSeekProc                         */
347 };
348 
349 /*
350 ** Create a new incrblob channel.
351 */
352 static int createIncrblobChannel(
353   Tcl_Interp *interp,
354   SqliteDb *pDb,
355   const char *zDb,
356   const char *zTable,
357   const char *zColumn,
358   sqlite_int64 iRow,
359   int isReadonly
360 ){
361   IncrblobChannel *p;
362   sqlite3 *db = pDb->db;
363   sqlite3_blob *pBlob;
364   int rc;
365   int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE);
366 
367   /* This variable is used to name the channels: "incrblob_[incr count]" */
368   static int count = 0;
369   char zChannel[64];
370 
371   rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob);
372   if( rc!=SQLITE_OK ){
373     Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
374     return TCL_ERROR;
375   }
376 
377   p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel));
378   p->iSeek = 0;
379   p->pBlob = pBlob;
380 
381   sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count);
382   p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags);
383   Tcl_RegisterChannel(interp, p->channel);
384 
385   /* Link the new channel into the SqliteDb.pIncrblob list. */
386   p->pNext = pDb->pIncrblob;
387   p->pPrev = 0;
388   if( p->pNext ){
389     p->pNext->pPrev = p;
390   }
391   pDb->pIncrblob = p;
392   p->pDb = pDb;
393 
394   Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE);
395   return TCL_OK;
396 }
397 #else  /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
398   #define closeIncrblobChannels(pDb)
399 #endif
400 
401 /*
402 ** Look at the script prefix in pCmd.  We will be executing this script
403 ** after first appending one or more arguments.  This routine analyzes
404 ** the script to see if it is safe to use Tcl_EvalObjv() on the script
405 ** rather than the more general Tcl_EvalEx().  Tcl_EvalObjv() is much
406 ** faster.
407 **
408 ** Scripts that are safe to use with Tcl_EvalObjv() consists of a
409 ** command name followed by zero or more arguments with no [...] or $
410 ** or {...} or ; to be seen anywhere.  Most callback scripts consist
411 ** of just a single procedure name and they meet this requirement.
412 */
413 static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
414   /* We could try to do something with Tcl_Parse().  But we will instead
415   ** just do a search for forbidden characters.  If any of the forbidden
416   ** characters appear in pCmd, we will report the string as unsafe.
417   */
418   const char *z;
419   int n;
420   z = Tcl_GetStringFromObj(pCmd, &n);
421   while( n-- > 0 ){
422     int c = *(z++);
423     if( c=='$' || c=='[' || c==';' ) return 0;
424   }
425   return 1;
426 }
427 
428 /*
429 ** Find an SqlFunc structure with the given name.  Or create a new
430 ** one if an existing one cannot be found.  Return a pointer to the
431 ** structure.
432 */
433 static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
434   SqlFunc *p, *pNew;
435   int nName = strlen30(zName);
436   pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + nName + 1 );
437   pNew->zName = (char*)&pNew[1];
438   memcpy(pNew->zName, zName, nName+1);
439   for(p=pDb->pFunc; p; p=p->pNext){
440     if( sqlite3_stricmp(p->zName, pNew->zName)==0 ){
441       Tcl_Free((char*)pNew);
442       return p;
443     }
444   }
445   pNew->interp = pDb->interp;
446   pNew->pDb = pDb;
447   pNew->pScript = 0;
448   pNew->pNext = pDb->pFunc;
449   pDb->pFunc = pNew;
450   return pNew;
451 }
452 
453 /*
454 ** Free a single SqlPreparedStmt object.
455 */
456 static void dbFreeStmt(SqlPreparedStmt *pStmt){
457 #ifdef SQLITE_TEST
458   if( sqlite3_sql(pStmt->pStmt)==0 ){
459     Tcl_Free((char *)pStmt->zSql);
460   }
461 #endif
462   sqlite3_finalize(pStmt->pStmt);
463   Tcl_Free((char *)pStmt);
464 }
465 
466 /*
467 ** Finalize and free a list of prepared statements
468 */
469 static void flushStmtCache(SqliteDb *pDb){
470   SqlPreparedStmt *pPreStmt;
471   SqlPreparedStmt *pNext;
472 
473   for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pNext){
474     pNext = pPreStmt->pNext;
475     dbFreeStmt(pPreStmt);
476   }
477   pDb->nStmt = 0;
478   pDb->stmtLast = 0;
479   pDb->stmtList = 0;
480 }
481 
482 /*
483 ** TCL calls this procedure when an sqlite3 database command is
484 ** deleted.
485 */
486 static void DbDeleteCmd(void *db){
487   SqliteDb *pDb = (SqliteDb*)db;
488   flushStmtCache(pDb);
489   closeIncrblobChannels(pDb);
490   sqlite3_close(pDb->db);
491   while( pDb->pFunc ){
492     SqlFunc *pFunc = pDb->pFunc;
493     pDb->pFunc = pFunc->pNext;
494     assert( pFunc->pDb==pDb );
495     Tcl_DecrRefCount(pFunc->pScript);
496     Tcl_Free((char*)pFunc);
497   }
498   while( pDb->pCollate ){
499     SqlCollate *pCollate = pDb->pCollate;
500     pDb->pCollate = pCollate->pNext;
501     Tcl_Free((char*)pCollate);
502   }
503   if( pDb->zBusy ){
504     Tcl_Free(pDb->zBusy);
505   }
506   if( pDb->zTrace ){
507     Tcl_Free(pDb->zTrace);
508   }
509   if( pDb->zProfile ){
510     Tcl_Free(pDb->zProfile);
511   }
512   if( pDb->zAuth ){
513     Tcl_Free(pDb->zAuth);
514   }
515   if( pDb->zNull ){
516     Tcl_Free(pDb->zNull);
517   }
518   if( pDb->pUpdateHook ){
519     Tcl_DecrRefCount(pDb->pUpdateHook);
520   }
521   if( pDb->pRollbackHook ){
522     Tcl_DecrRefCount(pDb->pRollbackHook);
523   }
524   if( pDb->pWalHook ){
525     Tcl_DecrRefCount(pDb->pWalHook);
526   }
527   if( pDb->pCollateNeeded ){
528     Tcl_DecrRefCount(pDb->pCollateNeeded);
529   }
530   Tcl_Free((char*)pDb);
531 }
532 
533 /*
534 ** This routine is called when a database file is locked while trying
535 ** to execute SQL.
536 */
537 static int DbBusyHandler(void *cd, int nTries){
538   SqliteDb *pDb = (SqliteDb*)cd;
539   int rc;
540   char zVal[30];
541 
542   sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries);
543   rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0);
544   if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
545     return 0;
546   }
547   return 1;
548 }
549 
550 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
551 /*
552 ** This routine is invoked as the 'progress callback' for the database.
553 */
554 static int DbProgressHandler(void *cd){
555   SqliteDb *pDb = (SqliteDb*)cd;
556   int rc;
557 
558   assert( pDb->zProgress );
559   rc = Tcl_Eval(pDb->interp, pDb->zProgress);
560   if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
561     return 1;
562   }
563   return 0;
564 }
565 #endif
566 
567 #ifndef SQLITE_OMIT_TRACE
568 /*
569 ** This routine is called by the SQLite trace handler whenever a new
570 ** block of SQL is executed.  The TCL script in pDb->zTrace is executed.
571 */
572 static void DbTraceHandler(void *cd, const char *zSql){
573   SqliteDb *pDb = (SqliteDb*)cd;
574   Tcl_DString str;
575 
576   Tcl_DStringInit(&str);
577   Tcl_DStringAppend(&str, pDb->zTrace, -1);
578   Tcl_DStringAppendElement(&str, zSql);
579   Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
580   Tcl_DStringFree(&str);
581   Tcl_ResetResult(pDb->interp);
582 }
583 #endif
584 
585 #ifndef SQLITE_OMIT_TRACE
586 /*
587 ** This routine is called by the SQLite profile handler after a statement
588 ** SQL has executed.  The TCL script in pDb->zProfile is evaluated.
589 */
590 static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){
591   SqliteDb *pDb = (SqliteDb*)cd;
592   Tcl_DString str;
593   char zTm[100];
594 
595   sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm);
596   Tcl_DStringInit(&str);
597   Tcl_DStringAppend(&str, pDb->zProfile, -1);
598   Tcl_DStringAppendElement(&str, zSql);
599   Tcl_DStringAppendElement(&str, zTm);
600   Tcl_Eval(pDb->interp, Tcl_DStringValue(&str));
601   Tcl_DStringFree(&str);
602   Tcl_ResetResult(pDb->interp);
603 }
604 #endif
605 
606 /*
607 ** This routine is called when a transaction is committed.  The
608 ** TCL script in pDb->zCommit is executed.  If it returns non-zero or
609 ** if it throws an exception, the transaction is rolled back instead
610 ** of being committed.
611 */
612 static int DbCommitHandler(void *cd){
613   SqliteDb *pDb = (SqliteDb*)cd;
614   int rc;
615 
616   rc = Tcl_Eval(pDb->interp, pDb->zCommit);
617   if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
618     return 1;
619   }
620   return 0;
621 }
622 
623 static void DbRollbackHandler(void *clientData){
624   SqliteDb *pDb = (SqliteDb*)clientData;
625   assert(pDb->pRollbackHook);
626   if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
627     Tcl_BackgroundError(pDb->interp);
628   }
629 }
630 
631 /*
632 ** This procedure handles wal_hook callbacks.
633 */
634 static int DbWalHandler(
635   void *clientData,
636   sqlite3 *db,
637   const char *zDb,
638   int nEntry
639 ){
640   int ret = SQLITE_OK;
641   Tcl_Obj *p;
642   SqliteDb *pDb = (SqliteDb*)clientData;
643   Tcl_Interp *interp = pDb->interp;
644   assert(pDb->pWalHook);
645 
646   assert( db==pDb->db );
647   p = Tcl_DuplicateObj(pDb->pWalHook);
648   Tcl_IncrRefCount(p);
649   Tcl_ListObjAppendElement(interp, p, Tcl_NewStringObj(zDb, -1));
650   Tcl_ListObjAppendElement(interp, p, Tcl_NewIntObj(nEntry));
651   if( TCL_OK!=Tcl_EvalObjEx(interp, p, 0)
652    || TCL_OK!=Tcl_GetIntFromObj(interp, Tcl_GetObjResult(interp), &ret)
653   ){
654     Tcl_BackgroundError(interp);
655   }
656   Tcl_DecrRefCount(p);
657 
658   return ret;
659 }
660 
661 #if defined(SQLITE_TEST) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
662 static void setTestUnlockNotifyVars(Tcl_Interp *interp, int iArg, int nArg){
663   char zBuf[64];
664   sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", iArg);
665   Tcl_SetVar(interp, "sqlite_unlock_notify_arg", zBuf, TCL_GLOBAL_ONLY);
666   sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", nArg);
667   Tcl_SetVar(interp, "sqlite_unlock_notify_argcount", zBuf, TCL_GLOBAL_ONLY);
668 }
669 #else
670 # define setTestUnlockNotifyVars(x,y,z)
671 #endif
672 
673 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
674 static void DbUnlockNotify(void **apArg, int nArg){
675   int i;
676   for(i=0; i<nArg; i++){
677     const int flags = (TCL_EVAL_GLOBAL|TCL_EVAL_DIRECT);
678     SqliteDb *pDb = (SqliteDb *)apArg[i];
679     setTestUnlockNotifyVars(pDb->interp, i, nArg);
680     assert( pDb->pUnlockNotify);
681     Tcl_EvalObjEx(pDb->interp, pDb->pUnlockNotify, flags);
682     Tcl_DecrRefCount(pDb->pUnlockNotify);
683     pDb->pUnlockNotify = 0;
684   }
685 }
686 #endif
687 
688 static void DbUpdateHandler(
689   void *p,
690   int op,
691   const char *zDb,
692   const char *zTbl,
693   sqlite_int64 rowid
694 ){
695   SqliteDb *pDb = (SqliteDb *)p;
696   Tcl_Obj *pCmd;
697 
698   assert( pDb->pUpdateHook );
699   assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
700 
701   pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
702   Tcl_IncrRefCount(pCmd);
703   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(
704     ( (op==SQLITE_INSERT)?"INSERT":(op==SQLITE_UPDATE)?"UPDATE":"DELETE"), -1));
705   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
706   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
707   Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
708   Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
709   Tcl_DecrRefCount(pCmd);
710 }
711 
712 static void tclCollateNeeded(
713   void *pCtx,
714   sqlite3 *db,
715   int enc,
716   const char *zName
717 ){
718   SqliteDb *pDb = (SqliteDb *)pCtx;
719   Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
720   Tcl_IncrRefCount(pScript);
721   Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
722   Tcl_EvalObjEx(pDb->interp, pScript, 0);
723   Tcl_DecrRefCount(pScript);
724 }
725 
726 /*
727 ** This routine is called to evaluate an SQL collation function implemented
728 ** using TCL script.
729 */
730 static int tclSqlCollate(
731   void *pCtx,
732   int nA,
733   const void *zA,
734   int nB,
735   const void *zB
736 ){
737   SqlCollate *p = (SqlCollate *)pCtx;
738   Tcl_Obj *pCmd;
739 
740   pCmd = Tcl_NewStringObj(p->zScript, -1);
741   Tcl_IncrRefCount(pCmd);
742   Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
743   Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
744   Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
745   Tcl_DecrRefCount(pCmd);
746   return (atoi(Tcl_GetStringResult(p->interp)));
747 }
748 
749 /*
750 ** This routine is called to evaluate an SQL function implemented
751 ** using TCL script.
752 */
753 static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
754   SqlFunc *p = sqlite3_user_data(context);
755   Tcl_Obj *pCmd;
756   int i;
757   int rc;
758 
759   if( argc==0 ){
760     /* If there are no arguments to the function, call Tcl_EvalObjEx on the
761     ** script object directly.  This allows the TCL compiler to generate
762     ** bytecode for the command on the first invocation and thus make
763     ** subsequent invocations much faster. */
764     pCmd = p->pScript;
765     Tcl_IncrRefCount(pCmd);
766     rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
767     Tcl_DecrRefCount(pCmd);
768   }else{
769     /* If there are arguments to the function, make a shallow copy of the
770     ** script object, lappend the arguments, then evaluate the copy.
771     **
772     ** By "shallow" copy, we mean only the outer list Tcl_Obj is duplicated.
773     ** The new Tcl_Obj contains pointers to the original list elements.
774     ** That way, when Tcl_EvalObjv() is run and shimmers the first element
775     ** of the list to tclCmdNameType, that alternate representation will
776     ** be preserved and reused on the next invocation.
777     */
778     Tcl_Obj **aArg;
779     int nArg;
780     if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
781       sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
782       return;
783     }
784     pCmd = Tcl_NewListObj(nArg, aArg);
785     Tcl_IncrRefCount(pCmd);
786     for(i=0; i<argc; i++){
787       sqlite3_value *pIn = argv[i];
788       Tcl_Obj *pVal;
789 
790       /* Set pVal to contain the i'th column of this row. */
791       switch( sqlite3_value_type(pIn) ){
792         case SQLITE_BLOB: {
793           int bytes = sqlite3_value_bytes(pIn);
794           pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
795           break;
796         }
797         case SQLITE_INTEGER: {
798           sqlite_int64 v = sqlite3_value_int64(pIn);
799           if( v>=-2147483647 && v<=2147483647 ){
800             pVal = Tcl_NewIntObj((int)v);
801           }else{
802             pVal = Tcl_NewWideIntObj(v);
803           }
804           break;
805         }
806         case SQLITE_FLOAT: {
807           double r = sqlite3_value_double(pIn);
808           pVal = Tcl_NewDoubleObj(r);
809           break;
810         }
811         case SQLITE_NULL: {
812           pVal = Tcl_NewStringObj(p->pDb->zNull, -1);
813           break;
814         }
815         default: {
816           int bytes = sqlite3_value_bytes(pIn);
817           pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
818           break;
819         }
820       }
821       rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
822       if( rc ){
823         Tcl_DecrRefCount(pCmd);
824         sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
825         return;
826       }
827     }
828     if( !p->useEvalObjv ){
829       /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
830       ** is a list without a string representation.  To prevent this from
831       ** happening, make sure pCmd has a valid string representation */
832       Tcl_GetString(pCmd);
833     }
834     rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
835     Tcl_DecrRefCount(pCmd);
836   }
837 
838   if( rc && rc!=TCL_RETURN ){
839     sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
840   }else{
841     Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
842     int n;
843     u8 *data;
844     const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
845     char c = zType[0];
846     if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
847       /* Only return a BLOB type if the Tcl variable is a bytearray and
848       ** has no string representation. */
849       data = Tcl_GetByteArrayFromObj(pVar, &n);
850       sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
851     }else if( c=='b' && strcmp(zType,"boolean")==0 ){
852       Tcl_GetIntFromObj(0, pVar, &n);
853       sqlite3_result_int(context, n);
854     }else if( c=='d' && strcmp(zType,"double")==0 ){
855       double r;
856       Tcl_GetDoubleFromObj(0, pVar, &r);
857       sqlite3_result_double(context, r);
858     }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
859           (c=='i' && strcmp(zType,"int")==0) ){
860       Tcl_WideInt v;
861       Tcl_GetWideIntFromObj(0, pVar, &v);
862       sqlite3_result_int64(context, v);
863     }else{
864       data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
865       sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
866     }
867   }
868 }
869 
870 #ifndef SQLITE_OMIT_AUTHORIZATION
871 /*
872 ** This is the authentication function.  It appends the authentication
873 ** type code and the two arguments to zCmd[] then invokes the result
874 ** on the interpreter.  The reply is examined to determine if the
875 ** authentication fails or succeeds.
876 */
877 static int auth_callback(
878   void *pArg,
879   int code,
880   const char *zArg1,
881   const char *zArg2,
882   const char *zArg3,
883   const char *zArg4
884 #ifdef SQLITE_USER_AUTHENTICATION
885   ,const char *zArg5
886 #endif
887 ){
888   const char *zCode;
889   Tcl_DString str;
890   int rc;
891   const char *zReply;
892   SqliteDb *pDb = (SqliteDb*)pArg;
893   if( pDb->disableAuth ) return SQLITE_OK;
894 
895   switch( code ){
896     case SQLITE_COPY              : zCode="SQLITE_COPY"; break;
897     case SQLITE_CREATE_INDEX      : zCode="SQLITE_CREATE_INDEX"; break;
898     case SQLITE_CREATE_TABLE      : zCode="SQLITE_CREATE_TABLE"; break;
899     case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
900     case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
901     case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
902     case SQLITE_CREATE_TEMP_VIEW  : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
903     case SQLITE_CREATE_TRIGGER    : zCode="SQLITE_CREATE_TRIGGER"; break;
904     case SQLITE_CREATE_VIEW       : zCode="SQLITE_CREATE_VIEW"; break;
905     case SQLITE_DELETE            : zCode="SQLITE_DELETE"; break;
906     case SQLITE_DROP_INDEX        : zCode="SQLITE_DROP_INDEX"; break;
907     case SQLITE_DROP_TABLE        : zCode="SQLITE_DROP_TABLE"; break;
908     case SQLITE_DROP_TEMP_INDEX   : zCode="SQLITE_DROP_TEMP_INDEX"; break;
909     case SQLITE_DROP_TEMP_TABLE   : zCode="SQLITE_DROP_TEMP_TABLE"; break;
910     case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
911     case SQLITE_DROP_TEMP_VIEW    : zCode="SQLITE_DROP_TEMP_VIEW"; break;
912     case SQLITE_DROP_TRIGGER      : zCode="SQLITE_DROP_TRIGGER"; break;
913     case SQLITE_DROP_VIEW         : zCode="SQLITE_DROP_VIEW"; break;
914     case SQLITE_INSERT            : zCode="SQLITE_INSERT"; break;
915     case SQLITE_PRAGMA            : zCode="SQLITE_PRAGMA"; break;
916     case SQLITE_READ              : zCode="SQLITE_READ"; break;
917     case SQLITE_SELECT            : zCode="SQLITE_SELECT"; break;
918     case SQLITE_TRANSACTION       : zCode="SQLITE_TRANSACTION"; break;
919     case SQLITE_UPDATE            : zCode="SQLITE_UPDATE"; break;
920     case SQLITE_ATTACH            : zCode="SQLITE_ATTACH"; break;
921     case SQLITE_DETACH            : zCode="SQLITE_DETACH"; break;
922     case SQLITE_ALTER_TABLE       : zCode="SQLITE_ALTER_TABLE"; break;
923     case SQLITE_REINDEX           : zCode="SQLITE_REINDEX"; break;
924     case SQLITE_ANALYZE           : zCode="SQLITE_ANALYZE"; break;
925     case SQLITE_CREATE_VTABLE     : zCode="SQLITE_CREATE_VTABLE"; break;
926     case SQLITE_DROP_VTABLE       : zCode="SQLITE_DROP_VTABLE"; break;
927     case SQLITE_FUNCTION          : zCode="SQLITE_FUNCTION"; break;
928     case SQLITE_SAVEPOINT         : zCode="SQLITE_SAVEPOINT"; break;
929     case SQLITE_RECURSIVE         : zCode="SQLITE_RECURSIVE"; break;
930     default                       : zCode="????"; break;
931   }
932   Tcl_DStringInit(&str);
933   Tcl_DStringAppend(&str, pDb->zAuth, -1);
934   Tcl_DStringAppendElement(&str, zCode);
935   Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
936   Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
937   Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
938   Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
939 #ifdef SQLITE_USER_AUTHENTICATION
940   Tcl_DStringAppendElement(&str, zArg5 ? zArg5 : "");
941 #endif
942   rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str));
943   Tcl_DStringFree(&str);
944   zReply = rc==TCL_OK ? Tcl_GetStringResult(pDb->interp) : "SQLITE_DENY";
945   if( strcmp(zReply,"SQLITE_OK")==0 ){
946     rc = SQLITE_OK;
947   }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
948     rc = SQLITE_DENY;
949   }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
950     rc = SQLITE_IGNORE;
951   }else{
952     rc = 999;
953   }
954   return rc;
955 }
956 #endif /* SQLITE_OMIT_AUTHORIZATION */
957 
958 /*
959 ** This routine reads a line of text from FILE in, stores
960 ** the text in memory obtained from malloc() and returns a pointer
961 ** to the text.  NULL is returned at end of file, or if malloc()
962 ** fails.
963 **
964 ** The interface is like "readline" but no command-line editing
965 ** is done.
966 **
967 ** copied from shell.c from '.import' command
968 */
969 static char *local_getline(char *zPrompt, FILE *in){
970   char *zLine;
971   int nLine;
972   int n;
973 
974   nLine = 100;
975   zLine = malloc( nLine );
976   if( zLine==0 ) return 0;
977   n = 0;
978   while( 1 ){
979     if( n+100>nLine ){
980       nLine = nLine*2 + 100;
981       zLine = realloc(zLine, nLine);
982       if( zLine==0 ) return 0;
983     }
984     if( fgets(&zLine[n], nLine - n, in)==0 ){
985       if( n==0 ){
986         free(zLine);
987         return 0;
988       }
989       zLine[n] = 0;
990       break;
991     }
992     while( zLine[n] ){ n++; }
993     if( n>0 && zLine[n-1]=='\n' ){
994       n--;
995       zLine[n] = 0;
996       break;
997     }
998   }
999   zLine = realloc( zLine, n+1 );
1000   return zLine;
1001 }
1002 
1003 
1004 /*
1005 ** This function is part of the implementation of the command:
1006 **
1007 **   $db transaction [-deferred|-immediate|-exclusive] SCRIPT
1008 **
1009 ** It is invoked after evaluating the script SCRIPT to commit or rollback
1010 ** the transaction or savepoint opened by the [transaction] command.
1011 */
1012 static int DbTransPostCmd(
1013   ClientData data[],                   /* data[0] is the Sqlite3Db* for $db */
1014   Tcl_Interp *interp,                  /* Tcl interpreter */
1015   int result                           /* Result of evaluating SCRIPT */
1016 ){
1017   static const char *const azEnd[] = {
1018     "RELEASE _tcl_transaction",        /* rc==TCL_ERROR, nTransaction!=0 */
1019     "COMMIT",                          /* rc!=TCL_ERROR, nTransaction==0 */
1020     "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction",
1021     "ROLLBACK"                         /* rc==TCL_ERROR, nTransaction==0 */
1022   };
1023   SqliteDb *pDb = (SqliteDb*)data[0];
1024   int rc = result;
1025   const char *zEnd;
1026 
1027   pDb->nTransaction--;
1028   zEnd = azEnd[(rc==TCL_ERROR)*2 + (pDb->nTransaction==0)];
1029 
1030   pDb->disableAuth++;
1031   if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){
1032       /* This is a tricky scenario to handle. The most likely cause of an
1033       ** error is that the exec() above was an attempt to commit the
1034       ** top-level transaction that returned SQLITE_BUSY. Or, less likely,
1035       ** that an IO-error has occurred. In either case, throw a Tcl exception
1036       ** and try to rollback the transaction.
1037       **
1038       ** But it could also be that the user executed one or more BEGIN,
1039       ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing
1040       ** this method's logic. Not clear how this would be best handled.
1041       */
1042     if( rc!=TCL_ERROR ){
1043       Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
1044       rc = TCL_ERROR;
1045     }
1046     sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
1047   }
1048   pDb->disableAuth--;
1049 
1050   return rc;
1051 }
1052 
1053 /*
1054 ** Unless SQLITE_TEST is defined, this function is a simple wrapper around
1055 ** sqlite3_prepare_v2(). If SQLITE_TEST is defined, then it uses either
1056 ** sqlite3_prepare_v2() or legacy interface sqlite3_prepare(), depending
1057 ** on whether or not the [db_use_legacy_prepare] command has been used to
1058 ** configure the connection.
1059 */
1060 static int dbPrepare(
1061   SqliteDb *pDb,                  /* Database object */
1062   const char *zSql,               /* SQL to compile */
1063   sqlite3_stmt **ppStmt,          /* OUT: Prepared statement */
1064   const char **pzOut              /* OUT: Pointer to next SQL statement */
1065 ){
1066 #ifdef SQLITE_TEST
1067   if( pDb->bLegacyPrepare ){
1068     return sqlite3_prepare(pDb->db, zSql, -1, ppStmt, pzOut);
1069   }
1070 #endif
1071   return sqlite3_prepare_v2(pDb->db, zSql, -1, ppStmt, pzOut);
1072 }
1073 
1074 /*
1075 ** Search the cache for a prepared-statement object that implements the
1076 ** first SQL statement in the buffer pointed to by parameter zIn. If
1077 ** no such prepared-statement can be found, allocate and prepare a new
1078 ** one. In either case, bind the current values of the relevant Tcl
1079 ** variables to any $var, :var or @var variables in the statement. Before
1080 ** returning, set *ppPreStmt to point to the prepared-statement object.
1081 **
1082 ** Output parameter *pzOut is set to point to the next SQL statement in
1083 ** buffer zIn, or to the '\0' byte at the end of zIn if there is no
1084 ** next statement.
1085 **
1086 ** If successful, TCL_OK is returned. Otherwise, TCL_ERROR is returned
1087 ** and an error message loaded into interpreter pDb->interp.
1088 */
1089 static int dbPrepareAndBind(
1090   SqliteDb *pDb,                  /* Database object */
1091   char const *zIn,                /* SQL to compile */
1092   char const **pzOut,             /* OUT: Pointer to next SQL statement */
1093   SqlPreparedStmt **ppPreStmt     /* OUT: Object used to cache statement */
1094 ){
1095   const char *zSql = zIn;         /* Pointer to first SQL statement in zIn */
1096   sqlite3_stmt *pStmt = 0;        /* Prepared statement object */
1097   SqlPreparedStmt *pPreStmt;      /* Pointer to cached statement */
1098   int nSql;                       /* Length of zSql in bytes */
1099   int nVar = 0;                   /* Number of variables in statement */
1100   int iParm = 0;                  /* Next free entry in apParm */
1101   char c;
1102   int i;
1103   Tcl_Interp *interp = pDb->interp;
1104 
1105   *ppPreStmt = 0;
1106 
1107   /* Trim spaces from the start of zSql and calculate the remaining length. */
1108   while( (c = zSql[0])==' ' || c=='\t' || c=='\r' || c=='\n' ){ zSql++; }
1109   nSql = strlen30(zSql);
1110 
1111   for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pPreStmt->pNext){
1112     int n = pPreStmt->nSql;
1113     if( nSql>=n
1114         && memcmp(pPreStmt->zSql, zSql, n)==0
1115         && (zSql[n]==0 || zSql[n-1]==';')
1116     ){
1117       pStmt = pPreStmt->pStmt;
1118       *pzOut = &zSql[pPreStmt->nSql];
1119 
1120       /* When a prepared statement is found, unlink it from the
1121       ** cache list.  It will later be added back to the beginning
1122       ** of the cache list in order to implement LRU replacement.
1123       */
1124       if( pPreStmt->pPrev ){
1125         pPreStmt->pPrev->pNext = pPreStmt->pNext;
1126       }else{
1127         pDb->stmtList = pPreStmt->pNext;
1128       }
1129       if( pPreStmt->pNext ){
1130         pPreStmt->pNext->pPrev = pPreStmt->pPrev;
1131       }else{
1132         pDb->stmtLast = pPreStmt->pPrev;
1133       }
1134       pDb->nStmt--;
1135       nVar = sqlite3_bind_parameter_count(pStmt);
1136       break;
1137     }
1138   }
1139 
1140   /* If no prepared statement was found. Compile the SQL text. Also allocate
1141   ** a new SqlPreparedStmt structure.  */
1142   if( pPreStmt==0 ){
1143     int nByte;
1144 
1145     if( SQLITE_OK!=dbPrepare(pDb, zSql, &pStmt, pzOut) ){
1146       Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
1147       return TCL_ERROR;
1148     }
1149     if( pStmt==0 ){
1150       if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
1151         /* A compile-time error in the statement. */
1152         Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
1153         return TCL_ERROR;
1154       }else{
1155         /* The statement was a no-op.  Continue to the next statement
1156         ** in the SQL string.
1157         */
1158         return TCL_OK;
1159       }
1160     }
1161 
1162     assert( pPreStmt==0 );
1163     nVar = sqlite3_bind_parameter_count(pStmt);
1164     nByte = sizeof(SqlPreparedStmt) + nVar*sizeof(Tcl_Obj *);
1165     pPreStmt = (SqlPreparedStmt*)Tcl_Alloc(nByte);
1166     memset(pPreStmt, 0, nByte);
1167 
1168     pPreStmt->pStmt = pStmt;
1169     pPreStmt->nSql = (int)(*pzOut - zSql);
1170     pPreStmt->zSql = sqlite3_sql(pStmt);
1171     pPreStmt->apParm = (Tcl_Obj **)&pPreStmt[1];
1172 #ifdef SQLITE_TEST
1173     if( pPreStmt->zSql==0 ){
1174       char *zCopy = Tcl_Alloc(pPreStmt->nSql + 1);
1175       memcpy(zCopy, zSql, pPreStmt->nSql);
1176       zCopy[pPreStmt->nSql] = '\0';
1177       pPreStmt->zSql = zCopy;
1178     }
1179 #endif
1180   }
1181   assert( pPreStmt );
1182   assert( strlen30(pPreStmt->zSql)==pPreStmt->nSql );
1183   assert( 0==memcmp(pPreStmt->zSql, zSql, pPreStmt->nSql) );
1184 
1185   /* Bind values to parameters that begin with $ or : */
1186   for(i=1; i<=nVar; i++){
1187     const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
1188     if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){
1189       Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
1190       if( pVar ){
1191         int n;
1192         u8 *data;
1193         const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
1194         char c = zType[0];
1195         if( zVar[0]=='@' ||
1196            (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){
1197           /* Load a BLOB type if the Tcl variable is a bytearray and
1198           ** it has no string representation or the host
1199           ** parameter name begins with "@". */
1200           data = Tcl_GetByteArrayFromObj(pVar, &n);
1201           sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
1202           Tcl_IncrRefCount(pVar);
1203           pPreStmt->apParm[iParm++] = pVar;
1204         }else if( c=='b' && strcmp(zType,"boolean")==0 ){
1205           Tcl_GetIntFromObj(interp, pVar, &n);
1206           sqlite3_bind_int(pStmt, i, n);
1207         }else if( c=='d' && strcmp(zType,"double")==0 ){
1208           double r;
1209           Tcl_GetDoubleFromObj(interp, pVar, &r);
1210           sqlite3_bind_double(pStmt, i, r);
1211         }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
1212               (c=='i' && strcmp(zType,"int")==0) ){
1213           Tcl_WideInt v;
1214           Tcl_GetWideIntFromObj(interp, pVar, &v);
1215           sqlite3_bind_int64(pStmt, i, v);
1216         }else{
1217           data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
1218           sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC);
1219           Tcl_IncrRefCount(pVar);
1220           pPreStmt->apParm[iParm++] = pVar;
1221         }
1222       }else{
1223         sqlite3_bind_null(pStmt, i);
1224       }
1225     }
1226   }
1227   pPreStmt->nParm = iParm;
1228   *ppPreStmt = pPreStmt;
1229 
1230   return TCL_OK;
1231 }
1232 
1233 /*
1234 ** Release a statement reference obtained by calling dbPrepareAndBind().
1235 ** There should be exactly one call to this function for each call to
1236 ** dbPrepareAndBind().
1237 **
1238 ** If the discard parameter is non-zero, then the statement is deleted
1239 ** immediately. Otherwise it is added to the LRU list and may be returned
1240 ** by a subsequent call to dbPrepareAndBind().
1241 */
1242 static void dbReleaseStmt(
1243   SqliteDb *pDb,                  /* Database handle */
1244   SqlPreparedStmt *pPreStmt,      /* Prepared statement handle to release */
1245   int discard                     /* True to delete (not cache) the pPreStmt */
1246 ){
1247   int i;
1248 
1249   /* Free the bound string and blob parameters */
1250   for(i=0; i<pPreStmt->nParm; i++){
1251     Tcl_DecrRefCount(pPreStmt->apParm[i]);
1252   }
1253   pPreStmt->nParm = 0;
1254 
1255   if( pDb->maxStmt<=0 || discard ){
1256     /* If the cache is turned off, deallocated the statement */
1257     dbFreeStmt(pPreStmt);
1258   }else{
1259     /* Add the prepared statement to the beginning of the cache list. */
1260     pPreStmt->pNext = pDb->stmtList;
1261     pPreStmt->pPrev = 0;
1262     if( pDb->stmtList ){
1263      pDb->stmtList->pPrev = pPreStmt;
1264     }
1265     pDb->stmtList = pPreStmt;
1266     if( pDb->stmtLast==0 ){
1267       assert( pDb->nStmt==0 );
1268       pDb->stmtLast = pPreStmt;
1269     }else{
1270       assert( pDb->nStmt>0 );
1271     }
1272     pDb->nStmt++;
1273 
1274     /* If we have too many statement in cache, remove the surplus from
1275     ** the end of the cache list.  */
1276     while( pDb->nStmt>pDb->maxStmt ){
1277       SqlPreparedStmt *pLast = pDb->stmtLast;
1278       pDb->stmtLast = pLast->pPrev;
1279       pDb->stmtLast->pNext = 0;
1280       pDb->nStmt--;
1281       dbFreeStmt(pLast);
1282     }
1283   }
1284 }
1285 
1286 /*
1287 ** Structure used with dbEvalXXX() functions:
1288 **
1289 **   dbEvalInit()
1290 **   dbEvalStep()
1291 **   dbEvalFinalize()
1292 **   dbEvalRowInfo()
1293 **   dbEvalColumnValue()
1294 */
1295 typedef struct DbEvalContext DbEvalContext;
1296 struct DbEvalContext {
1297   SqliteDb *pDb;                  /* Database handle */
1298   Tcl_Obj *pSql;                  /* Object holding string zSql */
1299   const char *zSql;               /* Remaining SQL to execute */
1300   SqlPreparedStmt *pPreStmt;      /* Current statement */
1301   int nCol;                       /* Number of columns returned by pStmt */
1302   Tcl_Obj *pArray;                /* Name of array variable */
1303   Tcl_Obj **apColName;            /* Array of column names */
1304 };
1305 
1306 /*
1307 ** Release any cache of column names currently held as part of
1308 ** the DbEvalContext structure passed as the first argument.
1309 */
1310 static void dbReleaseColumnNames(DbEvalContext *p){
1311   if( p->apColName ){
1312     int i;
1313     for(i=0; i<p->nCol; i++){
1314       Tcl_DecrRefCount(p->apColName[i]);
1315     }
1316     Tcl_Free((char *)p->apColName);
1317     p->apColName = 0;
1318   }
1319   p->nCol = 0;
1320 }
1321 
1322 /*
1323 ** Initialize a DbEvalContext structure.
1324 **
1325 ** If pArray is not NULL, then it contains the name of a Tcl array
1326 ** variable. The "*" member of this array is set to a list containing
1327 ** the names of the columns returned by the statement as part of each
1328 ** call to dbEvalStep(), in order from left to right. e.g. if the names
1329 ** of the returned columns are a, b and c, it does the equivalent of the
1330 ** tcl command:
1331 **
1332 **     set ${pArray}(*) {a b c}
1333 */
1334 static void dbEvalInit(
1335   DbEvalContext *p,               /* Pointer to structure to initialize */
1336   SqliteDb *pDb,                  /* Database handle */
1337   Tcl_Obj *pSql,                  /* Object containing SQL script */
1338   Tcl_Obj *pArray                 /* Name of Tcl array to set (*) element of */
1339 ){
1340   memset(p, 0, sizeof(DbEvalContext));
1341   p->pDb = pDb;
1342   p->zSql = Tcl_GetString(pSql);
1343   p->pSql = pSql;
1344   Tcl_IncrRefCount(pSql);
1345   if( pArray ){
1346     p->pArray = pArray;
1347     Tcl_IncrRefCount(pArray);
1348   }
1349 }
1350 
1351 /*
1352 ** Obtain information about the row that the DbEvalContext passed as the
1353 ** first argument currently points to.
1354 */
1355 static void dbEvalRowInfo(
1356   DbEvalContext *p,               /* Evaluation context */
1357   int *pnCol,                     /* OUT: Number of column names */
1358   Tcl_Obj ***papColName           /* OUT: Array of column names */
1359 ){
1360   /* Compute column names */
1361   if( 0==p->apColName ){
1362     sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1363     int i;                        /* Iterator variable */
1364     int nCol;                     /* Number of columns returned by pStmt */
1365     Tcl_Obj **apColName = 0;      /* Array of column names */
1366 
1367     p->nCol = nCol = sqlite3_column_count(pStmt);
1368     if( nCol>0 && (papColName || p->pArray) ){
1369       apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
1370       for(i=0; i<nCol; i++){
1371         apColName[i] = Tcl_NewStringObj(sqlite3_column_name(pStmt,i), -1);
1372         Tcl_IncrRefCount(apColName[i]);
1373       }
1374       p->apColName = apColName;
1375     }
1376 
1377     /* If results are being stored in an array variable, then create
1378     ** the array(*) entry for that array
1379     */
1380     if( p->pArray ){
1381       Tcl_Interp *interp = p->pDb->interp;
1382       Tcl_Obj *pColList = Tcl_NewObj();
1383       Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
1384 
1385       for(i=0; i<nCol; i++){
1386         Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
1387       }
1388       Tcl_IncrRefCount(pStar);
1389       Tcl_ObjSetVar2(interp, p->pArray, pStar, pColList, 0);
1390       Tcl_DecrRefCount(pStar);
1391     }
1392   }
1393 
1394   if( papColName ){
1395     *papColName = p->apColName;
1396   }
1397   if( pnCol ){
1398     *pnCol = p->nCol;
1399   }
1400 }
1401 
1402 /*
1403 ** Return one of TCL_OK, TCL_BREAK or TCL_ERROR. If TCL_ERROR is
1404 ** returned, then an error message is stored in the interpreter before
1405 ** returning.
1406 **
1407 ** A return value of TCL_OK means there is a row of data available. The
1408 ** data may be accessed using dbEvalRowInfo() and dbEvalColumnValue(). This
1409 ** is analogous to a return of SQLITE_ROW from sqlite3_step(). If TCL_BREAK
1410 ** is returned, then the SQL script has finished executing and there are
1411 ** no further rows available. This is similar to SQLITE_DONE.
1412 */
1413 static int dbEvalStep(DbEvalContext *p){
1414   const char *zPrevSql = 0;       /* Previous value of p->zSql */
1415 
1416   while( p->zSql[0] || p->pPreStmt ){
1417     int rc;
1418     if( p->pPreStmt==0 ){
1419       zPrevSql = (p->zSql==zPrevSql ? 0 : p->zSql);
1420       rc = dbPrepareAndBind(p->pDb, p->zSql, &p->zSql, &p->pPreStmt);
1421       if( rc!=TCL_OK ) return rc;
1422     }else{
1423       int rcs;
1424       SqliteDb *pDb = p->pDb;
1425       SqlPreparedStmt *pPreStmt = p->pPreStmt;
1426       sqlite3_stmt *pStmt = pPreStmt->pStmt;
1427 
1428       rcs = sqlite3_step(pStmt);
1429       if( rcs==SQLITE_ROW ){
1430         return TCL_OK;
1431       }
1432       if( p->pArray ){
1433         dbEvalRowInfo(p, 0, 0);
1434       }
1435       rcs = sqlite3_reset(pStmt);
1436 
1437       pDb->nStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_FULLSCAN_STEP,1);
1438       pDb->nSort = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_SORT,1);
1439       pDb->nIndex = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_AUTOINDEX,1);
1440       dbReleaseColumnNames(p);
1441       p->pPreStmt = 0;
1442 
1443       if( rcs!=SQLITE_OK ){
1444         /* If a run-time error occurs, report the error and stop reading
1445         ** the SQL.  */
1446         dbReleaseStmt(pDb, pPreStmt, 1);
1447 #if SQLITE_TEST
1448         if( p->pDb->bLegacyPrepare && rcs==SQLITE_SCHEMA && zPrevSql ){
1449           /* If the runtime error was an SQLITE_SCHEMA, and the database
1450           ** handle is configured to use the legacy sqlite3_prepare()
1451           ** interface, retry prepare()/step() on the same SQL statement.
1452           ** This only happens once. If there is a second SQLITE_SCHEMA
1453           ** error, the error will be returned to the caller. */
1454           p->zSql = zPrevSql;
1455           continue;
1456         }
1457 #endif
1458         Tcl_SetObjResult(pDb->interp,
1459                          Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
1460         return TCL_ERROR;
1461       }else{
1462         dbReleaseStmt(pDb, pPreStmt, 0);
1463       }
1464     }
1465   }
1466 
1467   /* Finished */
1468   return TCL_BREAK;
1469 }
1470 
1471 /*
1472 ** Free all resources currently held by the DbEvalContext structure passed
1473 ** as the first argument. There should be exactly one call to this function
1474 ** for each call to dbEvalInit().
1475 */
1476 static void dbEvalFinalize(DbEvalContext *p){
1477   if( p->pPreStmt ){
1478     sqlite3_reset(p->pPreStmt->pStmt);
1479     dbReleaseStmt(p->pDb, p->pPreStmt, 0);
1480     p->pPreStmt = 0;
1481   }
1482   if( p->pArray ){
1483     Tcl_DecrRefCount(p->pArray);
1484     p->pArray = 0;
1485   }
1486   Tcl_DecrRefCount(p->pSql);
1487   dbReleaseColumnNames(p);
1488 }
1489 
1490 /*
1491 ** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains
1492 ** the value for the iCol'th column of the row currently pointed to by
1493 ** the DbEvalContext structure passed as the first argument.
1494 */
1495 static Tcl_Obj *dbEvalColumnValue(DbEvalContext *p, int iCol){
1496   sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
1497   switch( sqlite3_column_type(pStmt, iCol) ){
1498     case SQLITE_BLOB: {
1499       int bytes = sqlite3_column_bytes(pStmt, iCol);
1500       const char *zBlob = sqlite3_column_blob(pStmt, iCol);
1501       if( !zBlob ) bytes = 0;
1502       return Tcl_NewByteArrayObj((u8*)zBlob, bytes);
1503     }
1504     case SQLITE_INTEGER: {
1505       sqlite_int64 v = sqlite3_column_int64(pStmt, iCol);
1506       if( v>=-2147483647 && v<=2147483647 ){
1507         return Tcl_NewIntObj((int)v);
1508       }else{
1509         return Tcl_NewWideIntObj(v);
1510       }
1511     }
1512     case SQLITE_FLOAT: {
1513       return Tcl_NewDoubleObj(sqlite3_column_double(pStmt, iCol));
1514     }
1515     case SQLITE_NULL: {
1516       return Tcl_NewStringObj(p->pDb->zNull, -1);
1517     }
1518   }
1519 
1520   return Tcl_NewStringObj((char*)sqlite3_column_text(pStmt, iCol), -1);
1521 }
1522 
1523 /*
1524 ** If using Tcl version 8.6 or greater, use the NR functions to avoid
1525 ** recursive evalution of scripts by the [db eval] and [db trans]
1526 ** commands. Even if the headers used while compiling the extension
1527 ** are 8.6 or newer, the code still tests the Tcl version at runtime.
1528 ** This allows stubs-enabled builds to be used with older Tcl libraries.
1529 */
1530 #if TCL_MAJOR_VERSION>8 || (TCL_MAJOR_VERSION==8 && TCL_MINOR_VERSION>=6)
1531 # define SQLITE_TCL_NRE 1
1532 static int DbUseNre(void){
1533   int major, minor;
1534   Tcl_GetVersion(&major, &minor, 0, 0);
1535   return( (major==8 && minor>=6) || major>8 );
1536 }
1537 #else
1538 /*
1539 ** Compiling using headers earlier than 8.6. In this case NR cannot be
1540 ** used, so DbUseNre() to always return zero. Add #defines for the other
1541 ** Tcl_NRxxx() functions to prevent them from causing compilation errors,
1542 ** even though the only invocations of them are within conditional blocks
1543 ** of the form:
1544 **
1545 **   if( DbUseNre() ) { ... }
1546 */
1547 # define SQLITE_TCL_NRE 0
1548 # define DbUseNre() 0
1549 # define Tcl_NRAddCallback(a,b,c,d,e,f) (void)0
1550 # define Tcl_NREvalObj(a,b,c) 0
1551 # define Tcl_NRCreateCommand(a,b,c,d,e,f) (void)0
1552 #endif
1553 
1554 /*
1555 ** This function is part of the implementation of the command:
1556 **
1557 **   $db eval SQL ?ARRAYNAME? SCRIPT
1558 */
1559 static int DbEvalNextCmd(
1560   ClientData data[],                   /* data[0] is the (DbEvalContext*) */
1561   Tcl_Interp *interp,                  /* Tcl interpreter */
1562   int result                           /* Result so far */
1563 ){
1564   int rc = result;                     /* Return code */
1565 
1566   /* The first element of the data[] array is a pointer to a DbEvalContext
1567   ** structure allocated using Tcl_Alloc(). The second element of data[]
1568   ** is a pointer to a Tcl_Obj containing the script to run for each row
1569   ** returned by the queries encapsulated in data[0]. */
1570   DbEvalContext *p = (DbEvalContext *)data[0];
1571   Tcl_Obj *pScript = (Tcl_Obj *)data[1];
1572   Tcl_Obj *pArray = p->pArray;
1573 
1574   while( (rc==TCL_OK || rc==TCL_CONTINUE) && TCL_OK==(rc = dbEvalStep(p)) ){
1575     int i;
1576     int nCol;
1577     Tcl_Obj **apColName;
1578     dbEvalRowInfo(p, &nCol, &apColName);
1579     for(i=0; i<nCol; i++){
1580       Tcl_Obj *pVal = dbEvalColumnValue(p, i);
1581       if( pArray==0 ){
1582         Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0);
1583       }else{
1584         Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0);
1585       }
1586     }
1587 
1588     /* The required interpreter variables are now populated with the data
1589     ** from the current row. If using NRE, schedule callbacks to evaluate
1590     ** script pScript, then to invoke this function again to fetch the next
1591     ** row (or clean up if there is no next row or the script throws an
1592     ** exception). After scheduling the callbacks, return control to the
1593     ** caller.
1594     **
1595     ** If not using NRE, evaluate pScript directly and continue with the
1596     ** next iteration of this while(...) loop.  */
1597     if( DbUseNre() ){
1598       Tcl_NRAddCallback(interp, DbEvalNextCmd, (void*)p, (void*)pScript, 0, 0);
1599       return Tcl_NREvalObj(interp, pScript, 0);
1600     }else{
1601       rc = Tcl_EvalObjEx(interp, pScript, 0);
1602     }
1603   }
1604 
1605   Tcl_DecrRefCount(pScript);
1606   dbEvalFinalize(p);
1607   Tcl_Free((char *)p);
1608 
1609   if( rc==TCL_OK || rc==TCL_BREAK ){
1610     Tcl_ResetResult(interp);
1611     rc = TCL_OK;
1612   }
1613   return rc;
1614 }
1615 
1616 /*
1617 ** The "sqlite" command below creates a new Tcl command for each
1618 ** connection it opens to an SQLite database.  This routine is invoked
1619 ** whenever one of those connection-specific commands is executed
1620 ** in Tcl.  For example, if you run Tcl code like this:
1621 **
1622 **       sqlite3 db1  "my_database"
1623 **       db1 close
1624 **
1625 ** The first command opens a connection to the "my_database" database
1626 ** and calls that connection "db1".  The second command causes this
1627 ** subroutine to be invoked.
1628 */
1629 static int DbObjCmd(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
1630   SqliteDb *pDb = (SqliteDb*)cd;
1631   int choice;
1632   int rc = TCL_OK;
1633   static const char *DB_strs[] = {
1634     "authorizer",         "backup",            "busy",
1635     "cache",              "changes",           "close",
1636     "collate",            "collation_needed",  "commit_hook",
1637     "complete",           "copy",              "enable_load_extension",
1638     "errorcode",          "eval",              "exists",
1639     "function",           "incrblob",          "interrupt",
1640     "last_insert_rowid",  "nullvalue",         "onecolumn",
1641     "profile",            "progress",          "rekey",
1642     "restore",            "rollback_hook",     "status",
1643     "timeout",            "total_changes",     "trace",
1644     "transaction",        "unlock_notify",     "update_hook",
1645     "version",            "wal_hook",          0
1646   };
1647   enum DB_enum {
1648     DB_AUTHORIZER,        DB_BACKUP,           DB_BUSY,
1649     DB_CACHE,             DB_CHANGES,          DB_CLOSE,
1650     DB_COLLATE,           DB_COLLATION_NEEDED, DB_COMMIT_HOOK,
1651     DB_COMPLETE,          DB_COPY,             DB_ENABLE_LOAD_EXTENSION,
1652     DB_ERRORCODE,         DB_EVAL,             DB_EXISTS,
1653     DB_FUNCTION,          DB_INCRBLOB,         DB_INTERRUPT,
1654     DB_LAST_INSERT_ROWID, DB_NULLVALUE,        DB_ONECOLUMN,
1655     DB_PROFILE,           DB_PROGRESS,         DB_REKEY,
1656     DB_RESTORE,           DB_ROLLBACK_HOOK,    DB_STATUS,
1657     DB_TIMEOUT,           DB_TOTAL_CHANGES,    DB_TRACE,
1658     DB_TRANSACTION,       DB_UNLOCK_NOTIFY,    DB_UPDATE_HOOK,
1659     DB_VERSION,           DB_WAL_HOOK
1660   };
1661   /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */
1662 
1663   if( objc<2 ){
1664     Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ...");
1665     return TCL_ERROR;
1666   }
1667   if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){
1668     return TCL_ERROR;
1669   }
1670 
1671   switch( (enum DB_enum)choice ){
1672 
1673   /*    $db authorizer ?CALLBACK?
1674   **
1675   ** Invoke the given callback to authorize each SQL operation as it is
1676   ** compiled.  5 arguments are appended to the callback before it is
1677   ** invoked:
1678   **
1679   **   (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...)
1680   **   (2) First descriptive name (depends on authorization type)
1681   **   (3) Second descriptive name
1682   **   (4) Name of the database (ex: "main", "temp")
1683   **   (5) Name of trigger that is doing the access
1684   **
1685   ** The callback should return on of the following strings: SQLITE_OK,
1686   ** SQLITE_IGNORE, or SQLITE_DENY.  Any other return value is an error.
1687   **
1688   ** If this method is invoked with no arguments, the current authorization
1689   ** callback string is returned.
1690   */
1691   case DB_AUTHORIZER: {
1692 #ifdef SQLITE_OMIT_AUTHORIZATION
1693     Tcl_AppendResult(interp, "authorization not available in this build",
1694                      (char*)0);
1695     return TCL_ERROR;
1696 #else
1697     if( objc>3 ){
1698       Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
1699       return TCL_ERROR;
1700     }else if( objc==2 ){
1701       if( pDb->zAuth ){
1702         Tcl_AppendResult(interp, pDb->zAuth, (char*)0);
1703       }
1704     }else{
1705       char *zAuth;
1706       int len;
1707       if( pDb->zAuth ){
1708         Tcl_Free(pDb->zAuth);
1709       }
1710       zAuth = Tcl_GetStringFromObj(objv[2], &len);
1711       if( zAuth && len>0 ){
1712         pDb->zAuth = Tcl_Alloc( len + 1 );
1713         memcpy(pDb->zAuth, zAuth, len+1);
1714       }else{
1715         pDb->zAuth = 0;
1716       }
1717       if( pDb->zAuth ){
1718         typedef int (*sqlite3_auth_cb)(
1719            void*,int,const char*,const char*,
1720            const char*,const char*);
1721         pDb->interp = interp;
1722         sqlite3_set_authorizer(pDb->db,(sqlite3_auth_cb)auth_callback,pDb);
1723       }else{
1724         sqlite3_set_authorizer(pDb->db, 0, 0);
1725       }
1726     }
1727 #endif
1728     break;
1729   }
1730 
1731   /*    $db backup ?DATABASE? FILENAME
1732   **
1733   ** Open or create a database file named FILENAME.  Transfer the
1734   ** content of local database DATABASE (default: "main") into the
1735   ** FILENAME database.
1736   */
1737   case DB_BACKUP: {
1738     const char *zDestFile;
1739     const char *zSrcDb;
1740     sqlite3 *pDest;
1741     sqlite3_backup *pBackup;
1742 
1743     if( objc==3 ){
1744       zSrcDb = "main";
1745       zDestFile = Tcl_GetString(objv[2]);
1746     }else if( objc==4 ){
1747       zSrcDb = Tcl_GetString(objv[2]);
1748       zDestFile = Tcl_GetString(objv[3]);
1749     }else{
1750       Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
1751       return TCL_ERROR;
1752     }
1753     rc = sqlite3_open(zDestFile, &pDest);
1754     if( rc!=SQLITE_OK ){
1755       Tcl_AppendResult(interp, "cannot open target database: ",
1756            sqlite3_errmsg(pDest), (char*)0);
1757       sqlite3_close(pDest);
1758       return TCL_ERROR;
1759     }
1760     pBackup = sqlite3_backup_init(pDest, "main", pDb->db, zSrcDb);
1761     if( pBackup==0 ){
1762       Tcl_AppendResult(interp, "backup failed: ",
1763            sqlite3_errmsg(pDest), (char*)0);
1764       sqlite3_close(pDest);
1765       return TCL_ERROR;
1766     }
1767     while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
1768     sqlite3_backup_finish(pBackup);
1769     if( rc==SQLITE_DONE ){
1770       rc = TCL_OK;
1771     }else{
1772       Tcl_AppendResult(interp, "backup failed: ",
1773            sqlite3_errmsg(pDest), (char*)0);
1774       rc = TCL_ERROR;
1775     }
1776     sqlite3_close(pDest);
1777     break;
1778   }
1779 
1780   /*    $db busy ?CALLBACK?
1781   **
1782   ** Invoke the given callback if an SQL statement attempts to open
1783   ** a locked database file.
1784   */
1785   case DB_BUSY: {
1786     if( objc>3 ){
1787       Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK");
1788       return TCL_ERROR;
1789     }else if( objc==2 ){
1790       if( pDb->zBusy ){
1791         Tcl_AppendResult(interp, pDb->zBusy, (char*)0);
1792       }
1793     }else{
1794       char *zBusy;
1795       int len;
1796       if( pDb->zBusy ){
1797         Tcl_Free(pDb->zBusy);
1798       }
1799       zBusy = Tcl_GetStringFromObj(objv[2], &len);
1800       if( zBusy && len>0 ){
1801         pDb->zBusy = Tcl_Alloc( len + 1 );
1802         memcpy(pDb->zBusy, zBusy, len+1);
1803       }else{
1804         pDb->zBusy = 0;
1805       }
1806       if( pDb->zBusy ){
1807         pDb->interp = interp;
1808         sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb);
1809       }else{
1810         sqlite3_busy_handler(pDb->db, 0, 0);
1811       }
1812     }
1813     break;
1814   }
1815 
1816   /*     $db cache flush
1817   **     $db cache size n
1818   **
1819   ** Flush the prepared statement cache, or set the maximum number of
1820   ** cached statements.
1821   */
1822   case DB_CACHE: {
1823     char *subCmd;
1824     int n;
1825 
1826     if( objc<=2 ){
1827       Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?");
1828       return TCL_ERROR;
1829     }
1830     subCmd = Tcl_GetStringFromObj( objv[2], 0 );
1831     if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){
1832       if( objc!=3 ){
1833         Tcl_WrongNumArgs(interp, 2, objv, "flush");
1834         return TCL_ERROR;
1835       }else{
1836         flushStmtCache( pDb );
1837       }
1838     }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){
1839       if( objc!=4 ){
1840         Tcl_WrongNumArgs(interp, 2, objv, "size n");
1841         return TCL_ERROR;
1842       }else{
1843         if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){
1844           Tcl_AppendResult( interp, "cannot convert \"",
1845                Tcl_GetStringFromObj(objv[3],0), "\" to integer", (char*)0);
1846           return TCL_ERROR;
1847         }else{
1848           if( n<0 ){
1849             flushStmtCache( pDb );
1850             n = 0;
1851           }else if( n>MAX_PREPARED_STMTS ){
1852             n = MAX_PREPARED_STMTS;
1853           }
1854           pDb->maxStmt = n;
1855         }
1856       }
1857     }else{
1858       Tcl_AppendResult( interp, "bad option \"",
1859           Tcl_GetStringFromObj(objv[2],0), "\": must be flush or size",
1860           (char*)0);
1861       return TCL_ERROR;
1862     }
1863     break;
1864   }
1865 
1866   /*     $db changes
1867   **
1868   ** Return the number of rows that were modified, inserted, or deleted by
1869   ** the most recent INSERT, UPDATE or DELETE statement, not including
1870   ** any changes made by trigger programs.
1871   */
1872   case DB_CHANGES: {
1873     Tcl_Obj *pResult;
1874     if( objc!=2 ){
1875       Tcl_WrongNumArgs(interp, 2, objv, "");
1876       return TCL_ERROR;
1877     }
1878     pResult = Tcl_GetObjResult(interp);
1879     Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db));
1880     break;
1881   }
1882 
1883   /*    $db close
1884   **
1885   ** Shutdown the database
1886   */
1887   case DB_CLOSE: {
1888     Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0));
1889     break;
1890   }
1891 
1892   /*
1893   **     $db collate NAME SCRIPT
1894   **
1895   ** Create a new SQL collation function called NAME.  Whenever
1896   ** that function is called, invoke SCRIPT to evaluate the function.
1897   */
1898   case DB_COLLATE: {
1899     SqlCollate *pCollate;
1900     char *zName;
1901     char *zScript;
1902     int nScript;
1903     if( objc!=4 ){
1904       Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT");
1905       return TCL_ERROR;
1906     }
1907     zName = Tcl_GetStringFromObj(objv[2], 0);
1908     zScript = Tcl_GetStringFromObj(objv[3], &nScript);
1909     pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 );
1910     if( pCollate==0 ) return TCL_ERROR;
1911     pCollate->interp = interp;
1912     pCollate->pNext = pDb->pCollate;
1913     pCollate->zScript = (char*)&pCollate[1];
1914     pDb->pCollate = pCollate;
1915     memcpy(pCollate->zScript, zScript, nScript+1);
1916     if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8,
1917         pCollate, tclSqlCollate) ){
1918       Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
1919       return TCL_ERROR;
1920     }
1921     break;
1922   }
1923 
1924   /*
1925   **     $db collation_needed SCRIPT
1926   **
1927   ** Create a new SQL collation function called NAME.  Whenever
1928   ** that function is called, invoke SCRIPT to evaluate the function.
1929   */
1930   case DB_COLLATION_NEEDED: {
1931     if( objc!=3 ){
1932       Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT");
1933       return TCL_ERROR;
1934     }
1935     if( pDb->pCollateNeeded ){
1936       Tcl_DecrRefCount(pDb->pCollateNeeded);
1937     }
1938     pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]);
1939     Tcl_IncrRefCount(pDb->pCollateNeeded);
1940     sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded);
1941     break;
1942   }
1943 
1944   /*    $db commit_hook ?CALLBACK?
1945   **
1946   ** Invoke the given callback just before committing every SQL transaction.
1947   ** If the callback throws an exception or returns non-zero, then the
1948   ** transaction is aborted.  If CALLBACK is an empty string, the callback
1949   ** is disabled.
1950   */
1951   case DB_COMMIT_HOOK: {
1952     if( objc>3 ){
1953       Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
1954       return TCL_ERROR;
1955     }else if( objc==2 ){
1956       if( pDb->zCommit ){
1957         Tcl_AppendResult(interp, pDb->zCommit, (char*)0);
1958       }
1959     }else{
1960       const char *zCommit;
1961       int len;
1962       if( pDb->zCommit ){
1963         Tcl_Free(pDb->zCommit);
1964       }
1965       zCommit = Tcl_GetStringFromObj(objv[2], &len);
1966       if( zCommit && len>0 ){
1967         pDb->zCommit = Tcl_Alloc( len + 1 );
1968         memcpy(pDb->zCommit, zCommit, len+1);
1969       }else{
1970         pDb->zCommit = 0;
1971       }
1972       if( pDb->zCommit ){
1973         pDb->interp = interp;
1974         sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb);
1975       }else{
1976         sqlite3_commit_hook(pDb->db, 0, 0);
1977       }
1978     }
1979     break;
1980   }
1981 
1982   /*    $db complete SQL
1983   **
1984   ** Return TRUE if SQL is a complete SQL statement.  Return FALSE if
1985   ** additional lines of input are needed.  This is similar to the
1986   ** built-in "info complete" command of Tcl.
1987   */
1988   case DB_COMPLETE: {
1989 #ifndef SQLITE_OMIT_COMPLETE
1990     Tcl_Obj *pResult;
1991     int isComplete;
1992     if( objc!=3 ){
1993       Tcl_WrongNumArgs(interp, 2, objv, "SQL");
1994       return TCL_ERROR;
1995     }
1996     isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) );
1997     pResult = Tcl_GetObjResult(interp);
1998     Tcl_SetBooleanObj(pResult, isComplete);
1999 #endif
2000     break;
2001   }
2002 
2003   /*    $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR?
2004   **
2005   ** Copy data into table from filename, optionally using SEPARATOR
2006   ** as column separators.  If a column contains a null string, or the
2007   ** value of NULLINDICATOR, a NULL is inserted for the column.
2008   ** conflict-algorithm is one of the sqlite conflict algorithms:
2009   **    rollback, abort, fail, ignore, replace
2010   ** On success, return the number of lines processed, not necessarily same
2011   ** as 'db changes' due to conflict-algorithm selected.
2012   **
2013   ** This code is basically an implementation/enhancement of
2014   ** the sqlite3 shell.c ".import" command.
2015   **
2016   ** This command usage is equivalent to the sqlite2.x COPY statement,
2017   ** which imports file data into a table using the PostgreSQL COPY file format:
2018   **   $db copy $conflit_algo $table_name $filename \t \\N
2019   */
2020   case DB_COPY: {
2021     char *zTable;               /* Insert data into this table */
2022     char *zFile;                /* The file from which to extract data */
2023     char *zConflict;            /* The conflict algorithm to use */
2024     sqlite3_stmt *pStmt;        /* A statement */
2025     int nCol;                   /* Number of columns in the table */
2026     int nByte;                  /* Number of bytes in an SQL string */
2027     int i, j;                   /* Loop counters */
2028     int nSep;                   /* Number of bytes in zSep[] */
2029     int nNull;                  /* Number of bytes in zNull[] */
2030     char *zSql;                 /* An SQL statement */
2031     char *zLine;                /* A single line of input from the file */
2032     char **azCol;               /* zLine[] broken up into columns */
2033     const char *zCommit;        /* How to commit changes */
2034     FILE *in;                   /* The input file */
2035     int lineno = 0;             /* Line number of input file */
2036     char zLineNum[80];          /* Line number print buffer */
2037     Tcl_Obj *pResult;           /* interp result */
2038 
2039     const char *zSep;
2040     const char *zNull;
2041     if( objc<5 || objc>7 ){
2042       Tcl_WrongNumArgs(interp, 2, objv,
2043          "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?");
2044       return TCL_ERROR;
2045     }
2046     if( objc>=6 ){
2047       zSep = Tcl_GetStringFromObj(objv[5], 0);
2048     }else{
2049       zSep = "\t";
2050     }
2051     if( objc>=7 ){
2052       zNull = Tcl_GetStringFromObj(objv[6], 0);
2053     }else{
2054       zNull = "";
2055     }
2056     zConflict = Tcl_GetStringFromObj(objv[2], 0);
2057     zTable = Tcl_GetStringFromObj(objv[3], 0);
2058     zFile = Tcl_GetStringFromObj(objv[4], 0);
2059     nSep = strlen30(zSep);
2060     nNull = strlen30(zNull);
2061     if( nSep==0 ){
2062       Tcl_AppendResult(interp,"Error: non-null separator required for copy",
2063                        (char*)0);
2064       return TCL_ERROR;
2065     }
2066     if(strcmp(zConflict, "rollback") != 0 &&
2067        strcmp(zConflict, "abort"   ) != 0 &&
2068        strcmp(zConflict, "fail"    ) != 0 &&
2069        strcmp(zConflict, "ignore"  ) != 0 &&
2070        strcmp(zConflict, "replace" ) != 0 ) {
2071       Tcl_AppendResult(interp, "Error: \"", zConflict,
2072             "\", conflict-algorithm must be one of: rollback, "
2073             "abort, fail, ignore, or replace", (char*)0);
2074       return TCL_ERROR;
2075     }
2076     zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
2077     if( zSql==0 ){
2078       Tcl_AppendResult(interp, "Error: no such table: ", zTable, (char*)0);
2079       return TCL_ERROR;
2080     }
2081     nByte = strlen30(zSql);
2082     rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
2083     sqlite3_free(zSql);
2084     if( rc ){
2085       Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0);
2086       nCol = 0;
2087     }else{
2088       nCol = sqlite3_column_count(pStmt);
2089     }
2090     sqlite3_finalize(pStmt);
2091     if( nCol==0 ) {
2092       return TCL_ERROR;
2093     }
2094     zSql = malloc( nByte + 50 + nCol*2 );
2095     if( zSql==0 ) {
2096       Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0);
2097       return TCL_ERROR;
2098     }
2099     sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?",
2100          zConflict, zTable);
2101     j = strlen30(zSql);
2102     for(i=1; i<nCol; i++){
2103       zSql[j++] = ',';
2104       zSql[j++] = '?';
2105     }
2106     zSql[j++] = ')';
2107     zSql[j] = 0;
2108     rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0);
2109     free(zSql);
2110     if( rc ){
2111       Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0);
2112       sqlite3_finalize(pStmt);
2113       return TCL_ERROR;
2114     }
2115     in = fopen(zFile, "rb");
2116     if( in==0 ){
2117       Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL);
2118       sqlite3_finalize(pStmt);
2119       return TCL_ERROR;
2120     }
2121     azCol = malloc( sizeof(azCol[0])*(nCol+1) );
2122     if( azCol==0 ) {
2123       Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0);
2124       fclose(in);
2125       return TCL_ERROR;
2126     }
2127     (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0);
2128     zCommit = "COMMIT";
2129     while( (zLine = local_getline(0, in))!=0 ){
2130       char *z;
2131       lineno++;
2132       azCol[0] = zLine;
2133       for(i=0, z=zLine; *z; z++){
2134         if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){
2135           *z = 0;
2136           i++;
2137           if( i<nCol ){
2138             azCol[i] = &z[nSep];
2139             z += nSep-1;
2140           }
2141         }
2142       }
2143       if( i+1!=nCol ){
2144         char *zErr;
2145         int nErr = strlen30(zFile) + 200;
2146         zErr = malloc(nErr);
2147         if( zErr ){
2148           sqlite3_snprintf(nErr, zErr,
2149              "Error: %s line %d: expected %d columns of data but found %d",
2150              zFile, lineno, nCol, i+1);
2151           Tcl_AppendResult(interp, zErr, (char*)0);
2152           free(zErr);
2153         }
2154         zCommit = "ROLLBACK";
2155         break;
2156       }
2157       for(i=0; i<nCol; i++){
2158         /* check for null data, if so, bind as null */
2159         if( (nNull>0 && strcmp(azCol[i], zNull)==0)
2160           || strlen30(azCol[i])==0
2161         ){
2162           sqlite3_bind_null(pStmt, i+1);
2163         }else{
2164           sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
2165         }
2166       }
2167       sqlite3_step(pStmt);
2168       rc = sqlite3_reset(pStmt);
2169       free(zLine);
2170       if( rc!=SQLITE_OK ){
2171         Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), (char*)0);
2172         zCommit = "ROLLBACK";
2173         break;
2174       }
2175     }
2176     free(azCol);
2177     fclose(in);
2178     sqlite3_finalize(pStmt);
2179     (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0);
2180 
2181     if( zCommit[0] == 'C' ){
2182       /* success, set result as number of lines processed */
2183       pResult = Tcl_GetObjResult(interp);
2184       Tcl_SetIntObj(pResult, lineno);
2185       rc = TCL_OK;
2186     }else{
2187       /* failure, append lineno where failed */
2188       sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno);
2189       Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,
2190                        (char*)0);
2191       rc = TCL_ERROR;
2192     }
2193     break;
2194   }
2195 
2196   /*
2197   **    $db enable_load_extension BOOLEAN
2198   **
2199   ** Turn the extension loading feature on or off.  It if off by
2200   ** default.
2201   */
2202   case DB_ENABLE_LOAD_EXTENSION: {
2203 #ifndef SQLITE_OMIT_LOAD_EXTENSION
2204     int onoff;
2205     if( objc!=3 ){
2206       Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN");
2207       return TCL_ERROR;
2208     }
2209     if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
2210       return TCL_ERROR;
2211     }
2212     sqlite3_enable_load_extension(pDb->db, onoff);
2213     break;
2214 #else
2215     Tcl_AppendResult(interp, "extension loading is turned off at compile-time",
2216                      (char*)0);
2217     return TCL_ERROR;
2218 #endif
2219   }
2220 
2221   /*
2222   **    $db errorcode
2223   **
2224   ** Return the numeric error code that was returned by the most recent
2225   ** call to sqlite3_exec().
2226   */
2227   case DB_ERRORCODE: {
2228     Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db)));
2229     break;
2230   }
2231 
2232   /*
2233   **    $db exists $sql
2234   **    $db onecolumn $sql
2235   **
2236   ** The onecolumn method is the equivalent of:
2237   **     lindex [$db eval $sql] 0
2238   */
2239   case DB_EXISTS:
2240   case DB_ONECOLUMN: {
2241     DbEvalContext sEval;
2242     if( objc!=3 ){
2243       Tcl_WrongNumArgs(interp, 2, objv, "SQL");
2244       return TCL_ERROR;
2245     }
2246 
2247     dbEvalInit(&sEval, pDb, objv[2], 0);
2248     rc = dbEvalStep(&sEval);
2249     if( choice==DB_ONECOLUMN ){
2250       if( rc==TCL_OK ){
2251         Tcl_SetObjResult(interp, dbEvalColumnValue(&sEval, 0));
2252       }else if( rc==TCL_BREAK ){
2253         Tcl_ResetResult(interp);
2254       }
2255     }else if( rc==TCL_BREAK || rc==TCL_OK ){
2256       Tcl_SetObjResult(interp, Tcl_NewBooleanObj(rc==TCL_OK));
2257     }
2258     dbEvalFinalize(&sEval);
2259 
2260     if( rc==TCL_BREAK ){
2261       rc = TCL_OK;
2262     }
2263     break;
2264   }
2265 
2266   /*
2267   **    $db eval $sql ?array? ?{  ...code... }?
2268   **
2269   ** The SQL statement in $sql is evaluated.  For each row, the values are
2270   ** placed in elements of the array named "array" and ...code... is executed.
2271   ** If "array" and "code" are omitted, then no callback is every invoked.
2272   ** If "array" is an empty string, then the values are placed in variables
2273   ** that have the same name as the fields extracted by the query.
2274   */
2275   case DB_EVAL: {
2276     if( objc<3 || objc>5 ){
2277       Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?");
2278       return TCL_ERROR;
2279     }
2280 
2281     if( objc==3 ){
2282       DbEvalContext sEval;
2283       Tcl_Obj *pRet = Tcl_NewObj();
2284       Tcl_IncrRefCount(pRet);
2285       dbEvalInit(&sEval, pDb, objv[2], 0);
2286       while( TCL_OK==(rc = dbEvalStep(&sEval)) ){
2287         int i;
2288         int nCol;
2289         dbEvalRowInfo(&sEval, &nCol, 0);
2290         for(i=0; i<nCol; i++){
2291           Tcl_ListObjAppendElement(interp, pRet, dbEvalColumnValue(&sEval, i));
2292         }
2293       }
2294       dbEvalFinalize(&sEval);
2295       if( rc==TCL_BREAK ){
2296         Tcl_SetObjResult(interp, pRet);
2297         rc = TCL_OK;
2298       }
2299       Tcl_DecrRefCount(pRet);
2300     }else{
2301       ClientData cd[2];
2302       DbEvalContext *p;
2303       Tcl_Obj *pArray = 0;
2304       Tcl_Obj *pScript;
2305 
2306       if( objc==5 && *(char *)Tcl_GetString(objv[3]) ){
2307         pArray = objv[3];
2308       }
2309       pScript = objv[objc-1];
2310       Tcl_IncrRefCount(pScript);
2311 
2312       p = (DbEvalContext *)Tcl_Alloc(sizeof(DbEvalContext));
2313       dbEvalInit(p, pDb, objv[2], pArray);
2314 
2315       cd[0] = (void *)p;
2316       cd[1] = (void *)pScript;
2317       rc = DbEvalNextCmd(cd, interp, TCL_OK);
2318     }
2319     break;
2320   }
2321 
2322   /*
2323   **     $db function NAME [-argcount N] SCRIPT
2324   **
2325   ** Create a new SQL function called NAME.  Whenever that function is
2326   ** called, invoke SCRIPT to evaluate the function.
2327   */
2328   case DB_FUNCTION: {
2329     SqlFunc *pFunc;
2330     Tcl_Obj *pScript;
2331     char *zName;
2332     int nArg = -1;
2333     if( objc==6 ){
2334       const char *z = Tcl_GetString(objv[3]);
2335       int n = strlen30(z);
2336       if( n>2 && strncmp(z, "-argcount",n)==0 ){
2337         if( Tcl_GetIntFromObj(interp, objv[4], &nArg) ) return TCL_ERROR;
2338         if( nArg<0 ){
2339           Tcl_AppendResult(interp, "number of arguments must be non-negative",
2340                            (char*)0);
2341           return TCL_ERROR;
2342         }
2343       }
2344       pScript = objv[5];
2345     }else if( objc!=4 ){
2346       Tcl_WrongNumArgs(interp, 2, objv, "NAME [-argcount N] SCRIPT");
2347       return TCL_ERROR;
2348     }else{
2349       pScript = objv[3];
2350     }
2351     zName = Tcl_GetStringFromObj(objv[2], 0);
2352     pFunc = findSqlFunc(pDb, zName);
2353     if( pFunc==0 ) return TCL_ERROR;
2354     if( pFunc->pScript ){
2355       Tcl_DecrRefCount(pFunc->pScript);
2356     }
2357     pFunc->pScript = pScript;
2358     Tcl_IncrRefCount(pScript);
2359     pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript);
2360     rc = sqlite3_create_function(pDb->db, zName, nArg, SQLITE_UTF8,
2361         pFunc, tclSqlFunc, 0, 0);
2362     if( rc!=SQLITE_OK ){
2363       rc = TCL_ERROR;
2364       Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
2365     }
2366     break;
2367   }
2368 
2369   /*
2370   **     $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID
2371   */
2372   case DB_INCRBLOB: {
2373 #ifdef SQLITE_OMIT_INCRBLOB
2374     Tcl_AppendResult(interp, "incrblob not available in this build", (char*)0);
2375     return TCL_ERROR;
2376 #else
2377     int isReadonly = 0;
2378     const char *zDb = "main";
2379     const char *zTable;
2380     const char *zColumn;
2381     Tcl_WideInt iRow;
2382 
2383     /* Check for the -readonly option */
2384     if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){
2385       isReadonly = 1;
2386     }
2387 
2388     if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){
2389       Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID");
2390       return TCL_ERROR;
2391     }
2392 
2393     if( objc==(6+isReadonly) ){
2394       zDb = Tcl_GetString(objv[2]);
2395     }
2396     zTable = Tcl_GetString(objv[objc-3]);
2397     zColumn = Tcl_GetString(objv[objc-2]);
2398     rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow);
2399 
2400     if( rc==TCL_OK ){
2401       rc = createIncrblobChannel(
2402           interp, pDb, zDb, zTable, zColumn, (sqlite3_int64)iRow, isReadonly
2403       );
2404     }
2405 #endif
2406     break;
2407   }
2408 
2409   /*
2410   **     $db interrupt
2411   **
2412   ** Interrupt the execution of the inner-most SQL interpreter.  This
2413   ** causes the SQL statement to return an error of SQLITE_INTERRUPT.
2414   */
2415   case DB_INTERRUPT: {
2416     sqlite3_interrupt(pDb->db);
2417     break;
2418   }
2419 
2420   /*
2421   **     $db nullvalue ?STRING?
2422   **
2423   ** Change text used when a NULL comes back from the database. If ?STRING?
2424   ** is not present, then the current string used for NULL is returned.
2425   ** If STRING is present, then STRING is returned.
2426   **
2427   */
2428   case DB_NULLVALUE: {
2429     if( objc!=2 && objc!=3 ){
2430       Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE");
2431       return TCL_ERROR;
2432     }
2433     if( objc==3 ){
2434       int len;
2435       char *zNull = Tcl_GetStringFromObj(objv[2], &len);
2436       if( pDb->zNull ){
2437         Tcl_Free(pDb->zNull);
2438       }
2439       if( zNull && len>0 ){
2440         pDb->zNull = Tcl_Alloc( len + 1 );
2441         memcpy(pDb->zNull, zNull, len);
2442         pDb->zNull[len] = '\0';
2443       }else{
2444         pDb->zNull = 0;
2445       }
2446     }
2447     Tcl_SetObjResult(interp, Tcl_NewStringObj(pDb->zNull, -1));
2448     break;
2449   }
2450 
2451   /*
2452   **     $db last_insert_rowid
2453   **
2454   ** Return an integer which is the ROWID for the most recent insert.
2455   */
2456   case DB_LAST_INSERT_ROWID: {
2457     Tcl_Obj *pResult;
2458     Tcl_WideInt rowid;
2459     if( objc!=2 ){
2460       Tcl_WrongNumArgs(interp, 2, objv, "");
2461       return TCL_ERROR;
2462     }
2463     rowid = sqlite3_last_insert_rowid(pDb->db);
2464     pResult = Tcl_GetObjResult(interp);
2465     Tcl_SetWideIntObj(pResult, rowid);
2466     break;
2467   }
2468 
2469   /*
2470   ** The DB_ONECOLUMN method is implemented together with DB_EXISTS.
2471   */
2472 
2473   /*    $db progress ?N CALLBACK?
2474   **
2475   ** Invoke the given callback every N virtual machine opcodes while executing
2476   ** queries.
2477   */
2478   case DB_PROGRESS: {
2479     if( objc==2 ){
2480       if( pDb->zProgress ){
2481         Tcl_AppendResult(interp, pDb->zProgress, (char*)0);
2482       }
2483     }else if( objc==4 ){
2484       char *zProgress;
2485       int len;
2486       int N;
2487       if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){
2488         return TCL_ERROR;
2489       };
2490       if( pDb->zProgress ){
2491         Tcl_Free(pDb->zProgress);
2492       }
2493       zProgress = Tcl_GetStringFromObj(objv[3], &len);
2494       if( zProgress && len>0 ){
2495         pDb->zProgress = Tcl_Alloc( len + 1 );
2496         memcpy(pDb->zProgress, zProgress, len+1);
2497       }else{
2498         pDb->zProgress = 0;
2499       }
2500 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2501       if( pDb->zProgress ){
2502         pDb->interp = interp;
2503         sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb);
2504       }else{
2505         sqlite3_progress_handler(pDb->db, 0, 0, 0);
2506       }
2507 #endif
2508     }else{
2509       Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK");
2510       return TCL_ERROR;
2511     }
2512     break;
2513   }
2514 
2515   /*    $db profile ?CALLBACK?
2516   **
2517   ** Make arrangements to invoke the CALLBACK routine after each SQL statement
2518   ** that has run.  The text of the SQL and the amount of elapse time are
2519   ** appended to CALLBACK before the script is run.
2520   */
2521   case DB_PROFILE: {
2522     if( objc>3 ){
2523       Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2524       return TCL_ERROR;
2525     }else if( objc==2 ){
2526       if( pDb->zProfile ){
2527         Tcl_AppendResult(interp, pDb->zProfile, (char*)0);
2528       }
2529     }else{
2530       char *zProfile;
2531       int len;
2532       if( pDb->zProfile ){
2533         Tcl_Free(pDb->zProfile);
2534       }
2535       zProfile = Tcl_GetStringFromObj(objv[2], &len);
2536       if( zProfile && len>0 ){
2537         pDb->zProfile = Tcl_Alloc( len + 1 );
2538         memcpy(pDb->zProfile, zProfile, len+1);
2539       }else{
2540         pDb->zProfile = 0;
2541       }
2542 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
2543       if( pDb->zProfile ){
2544         pDb->interp = interp;
2545         sqlite3_profile(pDb->db, DbProfileHandler, pDb);
2546       }else{
2547         sqlite3_profile(pDb->db, 0, 0);
2548       }
2549 #endif
2550     }
2551     break;
2552   }
2553 
2554   /*
2555   **     $db rekey KEY
2556   **
2557   ** Change the encryption key on the currently open database.
2558   */
2559   case DB_REKEY: {
2560 #ifdef SQLITE_HAS_CODEC
2561     int nKey;
2562     void *pKey;
2563 #endif
2564     if( objc!=3 ){
2565       Tcl_WrongNumArgs(interp, 2, objv, "KEY");
2566       return TCL_ERROR;
2567     }
2568 #ifdef SQLITE_HAS_CODEC
2569     pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
2570     rc = sqlite3_rekey(pDb->db, pKey, nKey);
2571     if( rc ){
2572       Tcl_AppendResult(interp, sqlite3_errstr(rc), (char*)0);
2573       rc = TCL_ERROR;
2574     }
2575 #endif
2576     break;
2577   }
2578 
2579   /*    $db restore ?DATABASE? FILENAME
2580   **
2581   ** Open a database file named FILENAME.  Transfer the content
2582   ** of FILENAME into the local database DATABASE (default: "main").
2583   */
2584   case DB_RESTORE: {
2585     const char *zSrcFile;
2586     const char *zDestDb;
2587     sqlite3 *pSrc;
2588     sqlite3_backup *pBackup;
2589     int nTimeout = 0;
2590 
2591     if( objc==3 ){
2592       zDestDb = "main";
2593       zSrcFile = Tcl_GetString(objv[2]);
2594     }else if( objc==4 ){
2595       zDestDb = Tcl_GetString(objv[2]);
2596       zSrcFile = Tcl_GetString(objv[3]);
2597     }else{
2598       Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME");
2599       return TCL_ERROR;
2600     }
2601     rc = sqlite3_open_v2(zSrcFile, &pSrc, SQLITE_OPEN_READONLY, 0);
2602     if( rc!=SQLITE_OK ){
2603       Tcl_AppendResult(interp, "cannot open source database: ",
2604            sqlite3_errmsg(pSrc), (char*)0);
2605       sqlite3_close(pSrc);
2606       return TCL_ERROR;
2607     }
2608     pBackup = sqlite3_backup_init(pDb->db, zDestDb, pSrc, "main");
2609     if( pBackup==0 ){
2610       Tcl_AppendResult(interp, "restore failed: ",
2611            sqlite3_errmsg(pDb->db), (char*)0);
2612       sqlite3_close(pSrc);
2613       return TCL_ERROR;
2614     }
2615     while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
2616               || rc==SQLITE_BUSY ){
2617       if( rc==SQLITE_BUSY ){
2618         if( nTimeout++ >= 3 ) break;
2619         sqlite3_sleep(100);
2620       }
2621     }
2622     sqlite3_backup_finish(pBackup);
2623     if( rc==SQLITE_DONE ){
2624       rc = TCL_OK;
2625     }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
2626       Tcl_AppendResult(interp, "restore failed: source database busy",
2627                        (char*)0);
2628       rc = TCL_ERROR;
2629     }else{
2630       Tcl_AppendResult(interp, "restore failed: ",
2631            sqlite3_errmsg(pDb->db), (char*)0);
2632       rc = TCL_ERROR;
2633     }
2634     sqlite3_close(pSrc);
2635     break;
2636   }
2637 
2638   /*
2639   **     $db status (step|sort|autoindex)
2640   **
2641   ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or
2642   ** SQLITE_STMTSTATUS_SORT for the most recent eval.
2643   */
2644   case DB_STATUS: {
2645     int v;
2646     const char *zOp;
2647     if( objc!=3 ){
2648       Tcl_WrongNumArgs(interp, 2, objv, "(step|sort|autoindex)");
2649       return TCL_ERROR;
2650     }
2651     zOp = Tcl_GetString(objv[2]);
2652     if( strcmp(zOp, "step")==0 ){
2653       v = pDb->nStep;
2654     }else if( strcmp(zOp, "sort")==0 ){
2655       v = pDb->nSort;
2656     }else if( strcmp(zOp, "autoindex")==0 ){
2657       v = pDb->nIndex;
2658     }else{
2659       Tcl_AppendResult(interp,
2660             "bad argument: should be autoindex, step, or sort",
2661             (char*)0);
2662       return TCL_ERROR;
2663     }
2664     Tcl_SetObjResult(interp, Tcl_NewIntObj(v));
2665     break;
2666   }
2667 
2668   /*
2669   **     $db timeout MILLESECONDS
2670   **
2671   ** Delay for the number of milliseconds specified when a file is locked.
2672   */
2673   case DB_TIMEOUT: {
2674     int ms;
2675     if( objc!=3 ){
2676       Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS");
2677       return TCL_ERROR;
2678     }
2679     if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR;
2680     sqlite3_busy_timeout(pDb->db, ms);
2681     break;
2682   }
2683 
2684   /*
2685   **     $db total_changes
2686   **
2687   ** Return the number of rows that were modified, inserted, or deleted
2688   ** since the database handle was created.
2689   */
2690   case DB_TOTAL_CHANGES: {
2691     Tcl_Obj *pResult;
2692     if( objc!=2 ){
2693       Tcl_WrongNumArgs(interp, 2, objv, "");
2694       return TCL_ERROR;
2695     }
2696     pResult = Tcl_GetObjResult(interp);
2697     Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db));
2698     break;
2699   }
2700 
2701   /*    $db trace ?CALLBACK?
2702   **
2703   ** Make arrangements to invoke the CALLBACK routine for each SQL statement
2704   ** that is executed.  The text of the SQL is appended to CALLBACK before
2705   ** it is executed.
2706   */
2707   case DB_TRACE: {
2708     if( objc>3 ){
2709       Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?");
2710       return TCL_ERROR;
2711     }else if( objc==2 ){
2712       if( pDb->zTrace ){
2713         Tcl_AppendResult(interp, pDb->zTrace, (char*)0);
2714       }
2715     }else{
2716       char *zTrace;
2717       int len;
2718       if( pDb->zTrace ){
2719         Tcl_Free(pDb->zTrace);
2720       }
2721       zTrace = Tcl_GetStringFromObj(objv[2], &len);
2722       if( zTrace && len>0 ){
2723         pDb->zTrace = Tcl_Alloc( len + 1 );
2724         memcpy(pDb->zTrace, zTrace, len+1);
2725       }else{
2726         pDb->zTrace = 0;
2727       }
2728 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
2729       if( pDb->zTrace ){
2730         pDb->interp = interp;
2731         sqlite3_trace(pDb->db, DbTraceHandler, pDb);
2732       }else{
2733         sqlite3_trace(pDb->db, 0, 0);
2734       }
2735 #endif
2736     }
2737     break;
2738   }
2739 
2740   /*    $db transaction [-deferred|-immediate|-exclusive] SCRIPT
2741   **
2742   ** Start a new transaction (if we are not already in the midst of a
2743   ** transaction) and execute the TCL script SCRIPT.  After SCRIPT
2744   ** completes, either commit the transaction or roll it back if SCRIPT
2745   ** throws an exception.  Or if no new transation was started, do nothing.
2746   ** pass the exception on up the stack.
2747   **
2748   ** This command was inspired by Dave Thomas's talk on Ruby at the
2749   ** 2005 O'Reilly Open Source Convention (OSCON).
2750   */
2751   case DB_TRANSACTION: {
2752     Tcl_Obj *pScript;
2753     const char *zBegin = "SAVEPOINT _tcl_transaction";
2754     if( objc!=3 && objc!=4 ){
2755       Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT");
2756       return TCL_ERROR;
2757     }
2758 
2759     if( pDb->nTransaction==0 && objc==4 ){
2760       static const char *TTYPE_strs[] = {
2761         "deferred",   "exclusive",  "immediate", 0
2762       };
2763       enum TTYPE_enum {
2764         TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
2765       };
2766       int ttype;
2767       if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type",
2768                               0, &ttype) ){
2769         return TCL_ERROR;
2770       }
2771       switch( (enum TTYPE_enum)ttype ){
2772         case TTYPE_DEFERRED:    /* no-op */;                 break;
2773         case TTYPE_EXCLUSIVE:   zBegin = "BEGIN EXCLUSIVE";  break;
2774         case TTYPE_IMMEDIATE:   zBegin = "BEGIN IMMEDIATE";  break;
2775       }
2776     }
2777     pScript = objv[objc-1];
2778 
2779     /* Run the SQLite BEGIN command to open a transaction or savepoint. */
2780     pDb->disableAuth++;
2781     rc = sqlite3_exec(pDb->db, zBegin, 0, 0, 0);
2782     pDb->disableAuth--;
2783     if( rc!=SQLITE_OK ){
2784       Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
2785       return TCL_ERROR;
2786     }
2787     pDb->nTransaction++;
2788 
2789     /* If using NRE, schedule a callback to invoke the script pScript, then
2790     ** a second callback to commit (or rollback) the transaction or savepoint
2791     ** opened above. If not using NRE, evaluate the script directly, then
2792     ** call function DbTransPostCmd() to commit (or rollback) the transaction
2793     ** or savepoint.  */
2794     if( DbUseNre() ){
2795       Tcl_NRAddCallback(interp, DbTransPostCmd, cd, 0, 0, 0);
2796       (void)Tcl_NREvalObj(interp, pScript, 0);
2797     }else{
2798       rc = DbTransPostCmd(&cd, interp, Tcl_EvalObjEx(interp, pScript, 0));
2799     }
2800     break;
2801   }
2802 
2803   /*
2804   **    $db unlock_notify ?script?
2805   */
2806   case DB_UNLOCK_NOTIFY: {
2807 #ifndef SQLITE_ENABLE_UNLOCK_NOTIFY
2808     Tcl_AppendResult(interp, "unlock_notify not available in this build",
2809                      (char*)0);
2810     rc = TCL_ERROR;
2811 #else
2812     if( objc!=2 && objc!=3 ){
2813       Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
2814       rc = TCL_ERROR;
2815     }else{
2816       void (*xNotify)(void **, int) = 0;
2817       void *pNotifyArg = 0;
2818 
2819       if( pDb->pUnlockNotify ){
2820         Tcl_DecrRefCount(pDb->pUnlockNotify);
2821         pDb->pUnlockNotify = 0;
2822       }
2823 
2824       if( objc==3 ){
2825         xNotify = DbUnlockNotify;
2826         pNotifyArg = (void *)pDb;
2827         pDb->pUnlockNotify = objv[2];
2828         Tcl_IncrRefCount(pDb->pUnlockNotify);
2829       }
2830 
2831       if( sqlite3_unlock_notify(pDb->db, xNotify, pNotifyArg) ){
2832         Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
2833         rc = TCL_ERROR;
2834       }
2835     }
2836 #endif
2837     break;
2838   }
2839 
2840   /*
2841   **    $db wal_hook ?script?
2842   **    $db update_hook ?script?
2843   **    $db rollback_hook ?script?
2844   */
2845   case DB_WAL_HOOK:
2846   case DB_UPDATE_HOOK:
2847   case DB_ROLLBACK_HOOK: {
2848 
2849     /* set ppHook to point at pUpdateHook or pRollbackHook, depending on
2850     ** whether [$db update_hook] or [$db rollback_hook] was invoked.
2851     */
2852     Tcl_Obj **ppHook;
2853     if( choice==DB_UPDATE_HOOK ){
2854       ppHook = &pDb->pUpdateHook;
2855     }else if( choice==DB_WAL_HOOK ){
2856       ppHook = &pDb->pWalHook;
2857     }else{
2858       ppHook = &pDb->pRollbackHook;
2859     }
2860 
2861     if( objc!=2 && objc!=3 ){
2862        Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?");
2863        return TCL_ERROR;
2864     }
2865     if( *ppHook ){
2866       Tcl_SetObjResult(interp, *ppHook);
2867       if( objc==3 ){
2868         Tcl_DecrRefCount(*ppHook);
2869         *ppHook = 0;
2870       }
2871     }
2872     if( objc==3 ){
2873       assert( !(*ppHook) );
2874       if( Tcl_GetCharLength(objv[2])>0 ){
2875         *ppHook = objv[2];
2876         Tcl_IncrRefCount(*ppHook);
2877       }
2878     }
2879 
2880     sqlite3_update_hook(pDb->db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb);
2881     sqlite3_rollback_hook(pDb->db,(pDb->pRollbackHook?DbRollbackHandler:0),pDb);
2882     sqlite3_wal_hook(pDb->db,(pDb->pWalHook?DbWalHandler:0),pDb);
2883 
2884     break;
2885   }
2886 
2887   /*    $db version
2888   **
2889   ** Return the version string for this database.
2890   */
2891   case DB_VERSION: {
2892     Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC);
2893     break;
2894   }
2895 
2896 
2897   } /* End of the SWITCH statement */
2898   return rc;
2899 }
2900 
2901 #if SQLITE_TCL_NRE
2902 /*
2903 ** Adaptor that provides an objCmd interface to the NRE-enabled
2904 ** interface implementation.
2905 */
2906 static int DbObjCmdAdaptor(
2907   void *cd,
2908   Tcl_Interp *interp,
2909   int objc,
2910   Tcl_Obj *const*objv
2911 ){
2912   return Tcl_NRCallObjProc(interp, DbObjCmd, cd, objc, objv);
2913 }
2914 #endif /* SQLITE_TCL_NRE */
2915 
2916 /*
2917 **   sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
2918 **                           ?-create BOOLEAN? ?-nomutex BOOLEAN?
2919 **
2920 ** This is the main Tcl command.  When the "sqlite" Tcl command is
2921 ** invoked, this routine runs to process that command.
2922 **
2923 ** The first argument, DBNAME, is an arbitrary name for a new
2924 ** database connection.  This command creates a new command named
2925 ** DBNAME that is used to control that connection.  The database
2926 ** connection is deleted when the DBNAME command is deleted.
2927 **
2928 ** The second argument is the name of the database file.
2929 **
2930 */
2931 static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){
2932   SqliteDb *p;
2933   const char *zArg;
2934   char *zErrMsg;
2935   int i;
2936   const char *zFile;
2937   const char *zVfs = 0;
2938   int flags;
2939   Tcl_DString translatedFilename;
2940 #ifdef SQLITE_HAS_CODEC
2941   void *pKey = 0;
2942   int nKey = 0;
2943 #endif
2944   int rc;
2945 
2946   /* In normal use, each TCL interpreter runs in a single thread.  So
2947   ** by default, we can turn of mutexing on SQLite database connections.
2948   ** However, for testing purposes it is useful to have mutexes turned
2949   ** on.  So, by default, mutexes default off.  But if compiled with
2950   ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on.
2951   */
2952 #ifdef SQLITE_TCL_DEFAULT_FULLMUTEX
2953   flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
2954 #else
2955   flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX;
2956 #endif
2957 
2958   if( objc==2 ){
2959     zArg = Tcl_GetStringFromObj(objv[1], 0);
2960     if( strcmp(zArg,"-version")==0 ){
2961       Tcl_AppendResult(interp,sqlite3_libversion(), (char*)0);
2962       return TCL_OK;
2963     }
2964     if( strcmp(zArg,"-has-codec")==0 ){
2965 #ifdef SQLITE_HAS_CODEC
2966       Tcl_AppendResult(interp,"1",(char*)0);
2967 #else
2968       Tcl_AppendResult(interp,"0",(char*)0);
2969 #endif
2970       return TCL_OK;
2971     }
2972   }
2973   for(i=3; i+1<objc; i+=2){
2974     zArg = Tcl_GetString(objv[i]);
2975     if( strcmp(zArg,"-key")==0 ){
2976 #ifdef SQLITE_HAS_CODEC
2977       pKey = Tcl_GetByteArrayFromObj(objv[i+1], &nKey);
2978 #endif
2979     }else if( strcmp(zArg, "-vfs")==0 ){
2980       zVfs = Tcl_GetString(objv[i+1]);
2981     }else if( strcmp(zArg, "-readonly")==0 ){
2982       int b;
2983       if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
2984       if( b ){
2985         flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
2986         flags |= SQLITE_OPEN_READONLY;
2987       }else{
2988         flags &= ~SQLITE_OPEN_READONLY;
2989         flags |= SQLITE_OPEN_READWRITE;
2990       }
2991     }else if( strcmp(zArg, "-create")==0 ){
2992       int b;
2993       if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
2994       if( b && (flags & SQLITE_OPEN_READONLY)==0 ){
2995         flags |= SQLITE_OPEN_CREATE;
2996       }else{
2997         flags &= ~SQLITE_OPEN_CREATE;
2998       }
2999     }else if( strcmp(zArg, "-nomutex")==0 ){
3000       int b;
3001       if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3002       if( b ){
3003         flags |= SQLITE_OPEN_NOMUTEX;
3004         flags &= ~SQLITE_OPEN_FULLMUTEX;
3005       }else{
3006         flags &= ~SQLITE_OPEN_NOMUTEX;
3007       }
3008     }else if( strcmp(zArg, "-fullmutex")==0 ){
3009       int b;
3010       if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3011       if( b ){
3012         flags |= SQLITE_OPEN_FULLMUTEX;
3013         flags &= ~SQLITE_OPEN_NOMUTEX;
3014       }else{
3015         flags &= ~SQLITE_OPEN_FULLMUTEX;
3016       }
3017     }else if( strcmp(zArg, "-uri")==0 ){
3018       int b;
3019       if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
3020       if( b ){
3021         flags |= SQLITE_OPEN_URI;
3022       }else{
3023         flags &= ~SQLITE_OPEN_URI;
3024       }
3025     }else{
3026       Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
3027       return TCL_ERROR;
3028     }
3029   }
3030   if( objc<3 || (objc&1)!=1 ){
3031     Tcl_WrongNumArgs(interp, 1, objv,
3032       "HANDLE FILENAME ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
3033       " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN? ?-uri BOOLEAN?"
3034 #ifdef SQLITE_HAS_CODEC
3035       " ?-key CODECKEY?"
3036 #endif
3037     );
3038     return TCL_ERROR;
3039   }
3040   zErrMsg = 0;
3041   p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
3042   if( p==0 ){
3043     Tcl_SetResult(interp, (char *)"malloc failed", TCL_STATIC);
3044     return TCL_ERROR;
3045   }
3046   memset(p, 0, sizeof(*p));
3047   zFile = Tcl_GetStringFromObj(objv[2], 0);
3048   zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
3049   rc = sqlite3_open_v2(zFile, &p->db, flags, zVfs);
3050   Tcl_DStringFree(&translatedFilename);
3051   if( p->db ){
3052     if( SQLITE_OK!=sqlite3_errcode(p->db) ){
3053       zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
3054       sqlite3_close(p->db);
3055       p->db = 0;
3056     }
3057   }else{
3058     zErrMsg = sqlite3_mprintf("%s", sqlite3_errstr(rc));
3059   }
3060 #ifdef SQLITE_HAS_CODEC
3061   if( p->db ){
3062     sqlite3_key(p->db, pKey, nKey);
3063   }
3064 #endif
3065   if( p->db==0 ){
3066     Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE);
3067     Tcl_Free((char*)p);
3068     sqlite3_free(zErrMsg);
3069     return TCL_ERROR;
3070   }
3071   p->maxStmt = NUM_PREPARED_STMTS;
3072   p->interp = interp;
3073   zArg = Tcl_GetStringFromObj(objv[1], 0);
3074   if( DbUseNre() ){
3075     Tcl_NRCreateCommand(interp, zArg, DbObjCmdAdaptor, DbObjCmd,
3076                         (char*)p, DbDeleteCmd);
3077   }else{
3078     Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd);
3079   }
3080   return TCL_OK;
3081 }
3082 
3083 /*
3084 ** Provide a dummy Tcl_InitStubs if we are using this as a static
3085 ** library.
3086 */
3087 #ifndef USE_TCL_STUBS
3088 # undef  Tcl_InitStubs
3089 # define Tcl_InitStubs(a,b,c) TCL_VERSION
3090 #endif
3091 
3092 /*
3093 ** Make sure we have a PACKAGE_VERSION macro defined.  This will be
3094 ** defined automatically by the TEA makefile.  But other makefiles
3095 ** do not define it.
3096 */
3097 #ifndef PACKAGE_VERSION
3098 # define PACKAGE_VERSION SQLITE_VERSION
3099 #endif
3100 
3101 /*
3102 ** Initialize this module.
3103 **
3104 ** This Tcl module contains only a single new Tcl command named "sqlite".
3105 ** (Hence there is no namespace.  There is no point in using a namespace
3106 ** if the extension only supplies one new name!)  The "sqlite" command is
3107 ** used to open a new SQLite database.  See the DbMain() routine above
3108 ** for additional information.
3109 **
3110 ** The EXTERN macros are required by TCL in order to work on windows.
3111 */
3112 EXTERN int Sqlite3_Init(Tcl_Interp *interp){
3113   int rc = Tcl_InitStubs(interp, "8.4", 0) ? TCL_OK : TCL_ERROR;
3114   if( rc==TCL_OK ){
3115     Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0);
3116 #ifndef SQLITE_3_SUFFIX_ONLY
3117     /* The "sqlite" alias is undocumented.  It is here only to support
3118     ** legacy scripts.  All new scripts should use only the "sqlite3"
3119     ** command. */
3120     Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0);
3121 #endif
3122     rc = Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION);
3123   }
3124   return rc;
3125 }
3126 EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3127 EXTERN int Sqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3128 EXTERN int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3129 
3130 /* Because it accesses the file-system and uses persistent state, SQLite
3131 ** is not considered appropriate for safe interpreters.  Hence, we deliberately
3132 ** omit the _SafeInit() interfaces.
3133 */
3134 
3135 #ifndef SQLITE_3_SUFFIX_ONLY
3136 int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3137 int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
3138 int Sqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3139 int Tclsqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
3140 #endif
3141 
3142 #ifdef TCLSH
3143 /*****************************************************************************
3144 ** All of the code that follows is used to build standalone TCL interpreters
3145 ** that are statically linked with SQLite.  Enable these by compiling
3146 ** with -DTCLSH=n where n can be 1 or 2.  An n of 1 generates a standard
3147 ** tclsh but with SQLite built in.  An n of 2 generates the SQLite space
3148 ** analysis program.
3149 */
3150 
3151 #if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
3152 /*
3153  * This code implements the MD5 message-digest algorithm.
3154  * The algorithm is due to Ron Rivest.  This code was
3155  * written by Colin Plumb in 1993, no copyright is claimed.
3156  * This code is in the public domain; do with it what you wish.
3157  *
3158  * Equivalent code is available from RSA Data Security, Inc.
3159  * This code has been tested against that, and is equivalent,
3160  * except that you don't need to include two pages of legalese
3161  * with every copy.
3162  *
3163  * To compute the message digest of a chunk of bytes, declare an
3164  * MD5Context structure, pass it to MD5Init, call MD5Update as
3165  * needed on buffers full of bytes, and then call MD5Final, which
3166  * will fill a supplied 16-byte array with the digest.
3167  */
3168 
3169 /*
3170  * If compiled on a machine that doesn't have a 32-bit integer,
3171  * you just set "uint32" to the appropriate datatype for an
3172  * unsigned 32-bit integer.  For example:
3173  *
3174  *       cc -Duint32='unsigned long' md5.c
3175  *
3176  */
3177 #ifndef uint32
3178 #  define uint32 unsigned int
3179 #endif
3180 
3181 struct MD5Context {
3182   int isInit;
3183   uint32 buf[4];
3184   uint32 bits[2];
3185   unsigned char in[64];
3186 };
3187 typedef struct MD5Context MD5Context;
3188 
3189 /*
3190  * Note: this code is harmless on little-endian machines.
3191  */
3192 static void byteReverse (unsigned char *buf, unsigned longs){
3193         uint32 t;
3194         do {
3195                 t = (uint32)((unsigned)buf[3]<<8 | buf[2]) << 16 |
3196                             ((unsigned)buf[1]<<8 | buf[0]);
3197                 *(uint32 *)buf = t;
3198                 buf += 4;
3199         } while (--longs);
3200 }
3201 /* The four core functions - F1 is optimized somewhat */
3202 
3203 /* #define F1(x, y, z) (x & y | ~x & z) */
3204 #define F1(x, y, z) (z ^ (x & (y ^ z)))
3205 #define F2(x, y, z) F1(z, x, y)
3206 #define F3(x, y, z) (x ^ y ^ z)
3207 #define F4(x, y, z) (y ^ (x | ~z))
3208 
3209 /* This is the central step in the MD5 algorithm. */
3210 #define MD5STEP(f, w, x, y, z, data, s) \
3211         ( w += f(x, y, z) + data,  w = w<<s | w>>(32-s),  w += x )
3212 
3213 /*
3214  * The core of the MD5 algorithm, this alters an existing MD5 hash to
3215  * reflect the addition of 16 longwords of new data.  MD5Update blocks
3216  * the data and converts bytes into longwords for this routine.
3217  */
3218 static void MD5Transform(uint32 buf[4], const uint32 in[16]){
3219         register uint32 a, b, c, d;
3220 
3221         a = buf[0];
3222         b = buf[1];
3223         c = buf[2];
3224         d = buf[3];
3225 
3226         MD5STEP(F1, a, b, c, d, in[ 0]+0xd76aa478,  7);
3227         MD5STEP(F1, d, a, b, c, in[ 1]+0xe8c7b756, 12);
3228         MD5STEP(F1, c, d, a, b, in[ 2]+0x242070db, 17);
3229         MD5STEP(F1, b, c, d, a, in[ 3]+0xc1bdceee, 22);
3230         MD5STEP(F1, a, b, c, d, in[ 4]+0xf57c0faf,  7);
3231         MD5STEP(F1, d, a, b, c, in[ 5]+0x4787c62a, 12);
3232         MD5STEP(F1, c, d, a, b, in[ 6]+0xa8304613, 17);
3233         MD5STEP(F1, b, c, d, a, in[ 7]+0xfd469501, 22);
3234         MD5STEP(F1, a, b, c, d, in[ 8]+0x698098d8,  7);
3235         MD5STEP(F1, d, a, b, c, in[ 9]+0x8b44f7af, 12);
3236         MD5STEP(F1, c, d, a, b, in[10]+0xffff5bb1, 17);
3237         MD5STEP(F1, b, c, d, a, in[11]+0x895cd7be, 22);
3238         MD5STEP(F1, a, b, c, d, in[12]+0x6b901122,  7);
3239         MD5STEP(F1, d, a, b, c, in[13]+0xfd987193, 12);
3240         MD5STEP(F1, c, d, a, b, in[14]+0xa679438e, 17);
3241         MD5STEP(F1, b, c, d, a, in[15]+0x49b40821, 22);
3242 
3243         MD5STEP(F2, a, b, c, d, in[ 1]+0xf61e2562,  5);
3244         MD5STEP(F2, d, a, b, c, in[ 6]+0xc040b340,  9);
3245         MD5STEP(F2, c, d, a, b, in[11]+0x265e5a51, 14);
3246         MD5STEP(F2, b, c, d, a, in[ 0]+0xe9b6c7aa, 20);
3247         MD5STEP(F2, a, b, c, d, in[ 5]+0xd62f105d,  5);
3248         MD5STEP(F2, d, a, b, c, in[10]+0x02441453,  9);
3249         MD5STEP(F2, c, d, a, b, in[15]+0xd8a1e681, 14);
3250         MD5STEP(F2, b, c, d, a, in[ 4]+0xe7d3fbc8, 20);
3251         MD5STEP(F2, a, b, c, d, in[ 9]+0x21e1cde6,  5);
3252         MD5STEP(F2, d, a, b, c, in[14]+0xc33707d6,  9);
3253         MD5STEP(F2, c, d, a, b, in[ 3]+0xf4d50d87, 14);
3254         MD5STEP(F2, b, c, d, a, in[ 8]+0x455a14ed, 20);
3255         MD5STEP(F2, a, b, c, d, in[13]+0xa9e3e905,  5);
3256         MD5STEP(F2, d, a, b, c, in[ 2]+0xfcefa3f8,  9);
3257         MD5STEP(F2, c, d, a, b, in[ 7]+0x676f02d9, 14);
3258         MD5STEP(F2, b, c, d, a, in[12]+0x8d2a4c8a, 20);
3259 
3260         MD5STEP(F3, a, b, c, d, in[ 5]+0xfffa3942,  4);
3261         MD5STEP(F3, d, a, b, c, in[ 8]+0x8771f681, 11);
3262         MD5STEP(F3, c, d, a, b, in[11]+0x6d9d6122, 16);
3263         MD5STEP(F3, b, c, d, a, in[14]+0xfde5380c, 23);
3264         MD5STEP(F3, a, b, c, d, in[ 1]+0xa4beea44,  4);
3265         MD5STEP(F3, d, a, b, c, in[ 4]+0x4bdecfa9, 11);
3266         MD5STEP(F3, c, d, a, b, in[ 7]+0xf6bb4b60, 16);
3267         MD5STEP(F3, b, c, d, a, in[10]+0xbebfbc70, 23);
3268         MD5STEP(F3, a, b, c, d, in[13]+0x289b7ec6,  4);
3269         MD5STEP(F3, d, a, b, c, in[ 0]+0xeaa127fa, 11);
3270         MD5STEP(F3, c, d, a, b, in[ 3]+0xd4ef3085, 16);
3271         MD5STEP(F3, b, c, d, a, in[ 6]+0x04881d05, 23);
3272         MD5STEP(F3, a, b, c, d, in[ 9]+0xd9d4d039,  4);
3273         MD5STEP(F3, d, a, b, c, in[12]+0xe6db99e5, 11);
3274         MD5STEP(F3, c, d, a, b, in[15]+0x1fa27cf8, 16);
3275         MD5STEP(F3, b, c, d, a, in[ 2]+0xc4ac5665, 23);
3276 
3277         MD5STEP(F4, a, b, c, d, in[ 0]+0xf4292244,  6);
3278         MD5STEP(F4, d, a, b, c, in[ 7]+0x432aff97, 10);
3279         MD5STEP(F4, c, d, a, b, in[14]+0xab9423a7, 15);
3280         MD5STEP(F4, b, c, d, a, in[ 5]+0xfc93a039, 21);
3281         MD5STEP(F4, a, b, c, d, in[12]+0x655b59c3,  6);
3282         MD5STEP(F4, d, a, b, c, in[ 3]+0x8f0ccc92, 10);
3283         MD5STEP(F4, c, d, a, b, in[10]+0xffeff47d, 15);
3284         MD5STEP(F4, b, c, d, a, in[ 1]+0x85845dd1, 21);
3285         MD5STEP(F4, a, b, c, d, in[ 8]+0x6fa87e4f,  6);
3286         MD5STEP(F4, d, a, b, c, in[15]+0xfe2ce6e0, 10);
3287         MD5STEP(F4, c, d, a, b, in[ 6]+0xa3014314, 15);
3288         MD5STEP(F4, b, c, d, a, in[13]+0x4e0811a1, 21);
3289         MD5STEP(F4, a, b, c, d, in[ 4]+0xf7537e82,  6);
3290         MD5STEP(F4, d, a, b, c, in[11]+0xbd3af235, 10);
3291         MD5STEP(F4, c, d, a, b, in[ 2]+0x2ad7d2bb, 15);
3292         MD5STEP(F4, b, c, d, a, in[ 9]+0xeb86d391, 21);
3293 
3294         buf[0] += a;
3295         buf[1] += b;
3296         buf[2] += c;
3297         buf[3] += d;
3298 }
3299 
3300 /*
3301  * Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious
3302  * initialization constants.
3303  */
3304 static void MD5Init(MD5Context *ctx){
3305         ctx->isInit = 1;
3306         ctx->buf[0] = 0x67452301;
3307         ctx->buf[1] = 0xefcdab89;
3308         ctx->buf[2] = 0x98badcfe;
3309         ctx->buf[3] = 0x10325476;
3310         ctx->bits[0] = 0;
3311         ctx->bits[1] = 0;
3312 }
3313 
3314 /*
3315  * Update context to reflect the concatenation of another buffer full
3316  * of bytes.
3317  */
3318 static
3319 void MD5Update(MD5Context *ctx, const unsigned char *buf, unsigned int len){
3320         uint32 t;
3321 
3322         /* Update bitcount */
3323 
3324         t = ctx->bits[0];
3325         if ((ctx->bits[0] = t + ((uint32)len << 3)) < t)
3326                 ctx->bits[1]++; /* Carry from low to high */
3327         ctx->bits[1] += len >> 29;
3328 
3329         t = (t >> 3) & 0x3f;    /* Bytes already in shsInfo->data */
3330 
3331         /* Handle any leading odd-sized chunks */
3332 
3333         if ( t ) {
3334                 unsigned char *p = (unsigned char *)ctx->in + t;
3335 
3336                 t = 64-t;
3337                 if (len < t) {
3338                         memcpy(p, buf, len);
3339                         return;
3340                 }
3341                 memcpy(p, buf, t);
3342                 byteReverse(ctx->in, 16);
3343                 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3344                 buf += t;
3345                 len -= t;
3346         }
3347 
3348         /* Process data in 64-byte chunks */
3349 
3350         while (len >= 64) {
3351                 memcpy(ctx->in, buf, 64);
3352                 byteReverse(ctx->in, 16);
3353                 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3354                 buf += 64;
3355                 len -= 64;
3356         }
3357 
3358         /* Handle any remaining bytes of data. */
3359 
3360         memcpy(ctx->in, buf, len);
3361 }
3362 
3363 /*
3364  * Final wrapup - pad to 64-byte boundary with the bit pattern
3365  * 1 0* (64-bit count of bits processed, MSB-first)
3366  */
3367 static void MD5Final(unsigned char digest[16], MD5Context *ctx){
3368         unsigned count;
3369         unsigned char *p;
3370 
3371         /* Compute number of bytes mod 64 */
3372         count = (ctx->bits[0] >> 3) & 0x3F;
3373 
3374         /* Set the first char of padding to 0x80.  This is safe since there is
3375            always at least one byte free */
3376         p = ctx->in + count;
3377         *p++ = 0x80;
3378 
3379         /* Bytes of padding needed to make 64 bytes */
3380         count = 64 - 1 - count;
3381 
3382         /* Pad out to 56 mod 64 */
3383         if (count < 8) {
3384                 /* Two lots of padding:  Pad the first block to 64 bytes */
3385                 memset(p, 0, count);
3386                 byteReverse(ctx->in, 16);
3387                 MD5Transform(ctx->buf, (uint32 *)ctx->in);
3388 
3389                 /* Now fill the next block with 56 bytes */
3390                 memset(ctx->in, 0, 56);
3391         } else {
3392                 /* Pad block to 56 bytes */
3393                 memset(p, 0, count-8);
3394         }
3395         byteReverse(ctx->in, 14);
3396 
3397         /* Append length in bits and transform */
3398         memcpy(ctx->in + 14*4, ctx->bits, 8);
3399 
3400         MD5Transform(ctx->buf, (uint32 *)ctx->in);
3401         byteReverse((unsigned char *)ctx->buf, 4);
3402         memcpy(digest, ctx->buf, 16);
3403 }
3404 
3405 /*
3406 ** Convert a 128-bit MD5 digest into a 32-digit base-16 number.
3407 */
3408 static void MD5DigestToBase16(unsigned char *digest, char *zBuf){
3409   static char const zEncode[] = "0123456789abcdef";
3410   int i, j;
3411 
3412   for(j=i=0; i<16; i++){
3413     int a = digest[i];
3414     zBuf[j++] = zEncode[(a>>4)&0xf];
3415     zBuf[j++] = zEncode[a & 0xf];
3416   }
3417   zBuf[j] = 0;
3418 }
3419 
3420 
3421 /*
3422 ** Convert a 128-bit MD5 digest into sequency of eight 5-digit integers
3423 ** each representing 16 bits of the digest and separated from each
3424 ** other by a "-" character.
3425 */
3426 static void MD5DigestToBase10x8(unsigned char digest[16], char zDigest[50]){
3427   int i, j;
3428   unsigned int x;
3429   for(i=j=0; i<16; i+=2){
3430     x = digest[i]*256 + digest[i+1];
3431     if( i>0 ) zDigest[j++] = '-';
3432     sqlite3_snprintf(50-j, &zDigest[j], "%05u", x);
3433     j += 5;
3434   }
3435   zDigest[j] = 0;
3436 }
3437 
3438 /*
3439 ** A TCL command for md5.  The argument is the text to be hashed.  The
3440 ** Result is the hash in base64.
3441 */
3442 static int md5_cmd(void*cd, Tcl_Interp *interp, int argc, const char **argv){
3443   MD5Context ctx;
3444   unsigned char digest[16];
3445   char zBuf[50];
3446   void (*converter)(unsigned char*, char*);
3447 
3448   if( argc!=2 ){
3449     Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
3450         " TEXT\"", (char*)0);
3451     return TCL_ERROR;
3452   }
3453   MD5Init(&ctx);
3454   MD5Update(&ctx, (unsigned char*)argv[1], (unsigned)strlen(argv[1]));
3455   MD5Final(digest, &ctx);
3456   converter = (void(*)(unsigned char*,char*))cd;
3457   converter(digest, zBuf);
3458   Tcl_AppendResult(interp, zBuf, (char*)0);
3459   return TCL_OK;
3460 }
3461 
3462 /*
3463 ** A TCL command to take the md5 hash of a file.  The argument is the
3464 ** name of the file.
3465 */
3466 static int md5file_cmd(void*cd, Tcl_Interp*interp, int argc, const char **argv){
3467   FILE *in;
3468   MD5Context ctx;
3469   void (*converter)(unsigned char*, char*);
3470   unsigned char digest[16];
3471   char zBuf[10240];
3472 
3473   if( argc!=2 ){
3474     Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0],
3475         " FILENAME\"", (char*)0);
3476     return TCL_ERROR;
3477   }
3478   in = fopen(argv[1],"rb");
3479   if( in==0 ){
3480     Tcl_AppendResult(interp,"unable to open file \"", argv[1],
3481          "\" for reading", (char*)0);
3482     return TCL_ERROR;
3483   }
3484   MD5Init(&ctx);
3485   for(;;){
3486     int n;
3487     n = (int)fread(zBuf, 1, sizeof(zBuf), in);
3488     if( n<=0 ) break;
3489     MD5Update(&ctx, (unsigned char*)zBuf, (unsigned)n);
3490   }
3491   fclose(in);
3492   MD5Final(digest, &ctx);
3493   converter = (void(*)(unsigned char*,char*))cd;
3494   converter(digest, zBuf);
3495   Tcl_AppendResult(interp, zBuf, (char*)0);
3496   return TCL_OK;
3497 }
3498 
3499 /*
3500 ** Register the four new TCL commands for generating MD5 checksums
3501 ** with the TCL interpreter.
3502 */
3503 int Md5_Init(Tcl_Interp *interp){
3504   Tcl_CreateCommand(interp, "md5", (Tcl_CmdProc*)md5_cmd,
3505                     MD5DigestToBase16, 0);
3506   Tcl_CreateCommand(interp, "md5-10x8", (Tcl_CmdProc*)md5_cmd,
3507                     MD5DigestToBase10x8, 0);
3508   Tcl_CreateCommand(interp, "md5file", (Tcl_CmdProc*)md5file_cmd,
3509                     MD5DigestToBase16, 0);
3510   Tcl_CreateCommand(interp, "md5file-10x8", (Tcl_CmdProc*)md5file_cmd,
3511                     MD5DigestToBase10x8, 0);
3512   return TCL_OK;
3513 }
3514 #endif /* defined(SQLITE_TEST) || defined(SQLITE_TCLMD5) */
3515 
3516 #if defined(SQLITE_TEST)
3517 /*
3518 ** During testing, the special md5sum() aggregate function is available.
3519 ** inside SQLite.  The following routines implement that function.
3520 */
3521 static void md5step(sqlite3_context *context, int argc, sqlite3_value **argv){
3522   MD5Context *p;
3523   int i;
3524   if( argc<1 ) return;
3525   p = sqlite3_aggregate_context(context, sizeof(*p));
3526   if( p==0 ) return;
3527   if( !p->isInit ){
3528     MD5Init(p);
3529   }
3530   for(i=0; i<argc; i++){
3531     const char *zData = (char*)sqlite3_value_text(argv[i]);
3532     if( zData ){
3533       MD5Update(p, (unsigned char*)zData, (int)strlen(zData));
3534     }
3535   }
3536 }
3537 static void md5finalize(sqlite3_context *context){
3538   MD5Context *p;
3539   unsigned char digest[16];
3540   char zBuf[33];
3541   p = sqlite3_aggregate_context(context, sizeof(*p));
3542   MD5Final(digest,p);
3543   MD5DigestToBase16(digest, zBuf);
3544   sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
3545 }
3546 int Md5_Register(sqlite3 *db){
3547   int rc = sqlite3_create_function(db, "md5sum", -1, SQLITE_UTF8, 0, 0,
3548                                  md5step, md5finalize);
3549   sqlite3_overload_function(db, "md5sum", -1);  /* To exercise this API */
3550   return rc;
3551 }
3552 #endif /* defined(SQLITE_TEST) */
3553 
3554 
3555 /*
3556 ** If the macro TCLSH is one, then put in code this for the
3557 ** "main" routine that will initialize Tcl and take input from
3558 ** standard input, or if a file is named on the command line
3559 ** the TCL interpreter reads and evaluates that file.
3560 */
3561 #if TCLSH==1
3562 static const char *tclsh_main_loop(void){
3563   static const char zMainloop[] =
3564     "set line {}\n"
3565     "while {![eof stdin]} {\n"
3566       "if {$line!=\"\"} {\n"
3567         "puts -nonewline \"> \"\n"
3568       "} else {\n"
3569         "puts -nonewline \"% \"\n"
3570       "}\n"
3571       "flush stdout\n"
3572       "append line [gets stdin]\n"
3573       "if {[info complete $line]} {\n"
3574         "if {[catch {uplevel #0 $line} result]} {\n"
3575           "puts stderr \"Error: $result\"\n"
3576         "} elseif {$result!=\"\"} {\n"
3577           "puts $result\n"
3578         "}\n"
3579         "set line {}\n"
3580       "} else {\n"
3581         "append line \\n\n"
3582       "}\n"
3583     "}\n"
3584   ;
3585   return zMainloop;
3586 }
3587 #endif
3588 #if TCLSH==2
3589 static const char *tclsh_main_loop(void);
3590 #endif
3591 
3592 #ifdef SQLITE_TEST
3593 static void init_all(Tcl_Interp *);
3594 static int init_all_cmd(
3595   ClientData cd,
3596   Tcl_Interp *interp,
3597   int objc,
3598   Tcl_Obj *CONST objv[]
3599 ){
3600 
3601   Tcl_Interp *slave;
3602   if( objc!=2 ){
3603     Tcl_WrongNumArgs(interp, 1, objv, "SLAVE");
3604     return TCL_ERROR;
3605   }
3606 
3607   slave = Tcl_GetSlave(interp, Tcl_GetString(objv[1]));
3608   if( !slave ){
3609     return TCL_ERROR;
3610   }
3611 
3612   init_all(slave);
3613   return TCL_OK;
3614 }
3615 
3616 /*
3617 ** Tclcmd: db_use_legacy_prepare DB BOOLEAN
3618 **
3619 **   The first argument to this command must be a database command created by
3620 **   [sqlite3]. If the second argument is true, then the handle is configured
3621 **   to use the sqlite3_prepare_v2() function to prepare statements. If it
3622 **   is false, sqlite3_prepare().
3623 */
3624 static int db_use_legacy_prepare_cmd(
3625   ClientData cd,
3626   Tcl_Interp *interp,
3627   int objc,
3628   Tcl_Obj *CONST objv[]
3629 ){
3630   Tcl_CmdInfo cmdInfo;
3631   SqliteDb *pDb;
3632   int bPrepare;
3633 
3634   if( objc!=3 ){
3635     Tcl_WrongNumArgs(interp, 1, objv, "DB BOOLEAN");
3636     return TCL_ERROR;
3637   }
3638 
3639   if( !Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &cmdInfo) ){
3640     Tcl_AppendResult(interp, "no such db: ", Tcl_GetString(objv[1]), (char*)0);
3641     return TCL_ERROR;
3642   }
3643   pDb = (SqliteDb*)cmdInfo.objClientData;
3644   if( Tcl_GetBooleanFromObj(interp, objv[2], &bPrepare) ){
3645     return TCL_ERROR;
3646   }
3647 
3648   pDb->bLegacyPrepare = bPrepare;
3649 
3650   Tcl_ResetResult(interp);
3651   return TCL_OK;
3652 }
3653 
3654 /*
3655 ** Tclcmd: db_last_stmt_ptr DB
3656 **
3657 **   If the statement cache associated with database DB is not empty,
3658 **   return the text representation of the most recently used statement
3659 **   handle.
3660 */
3661 static int db_last_stmt_ptr(
3662   ClientData cd,
3663   Tcl_Interp *interp,
3664   int objc,
3665   Tcl_Obj *CONST objv[]
3666 ){
3667   extern int sqlite3TestMakePointerStr(Tcl_Interp*, char*, void*);
3668   Tcl_CmdInfo cmdInfo;
3669   SqliteDb *pDb;
3670   sqlite3_stmt *pStmt = 0;
3671   char zBuf[100];
3672 
3673   if( objc!=2 ){
3674     Tcl_WrongNumArgs(interp, 1, objv, "DB");
3675     return TCL_ERROR;
3676   }
3677 
3678   if( !Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &cmdInfo) ){
3679     Tcl_AppendResult(interp, "no such db: ", Tcl_GetString(objv[1]), (char*)0);
3680     return TCL_ERROR;
3681   }
3682   pDb = (SqliteDb*)cmdInfo.objClientData;
3683 
3684   if( pDb->stmtList ) pStmt = pDb->stmtList->pStmt;
3685   if( sqlite3TestMakePointerStr(interp, zBuf, pStmt) ){
3686     return TCL_ERROR;
3687   }
3688   Tcl_SetResult(interp, zBuf, TCL_VOLATILE);
3689 
3690   return TCL_OK;
3691 }
3692 #endif
3693 
3694 /*
3695 ** Configure the interpreter passed as the first argument to have access
3696 ** to the commands and linked variables that make up:
3697 **
3698 **   * the [sqlite3] extension itself,
3699 **
3700 **   * If SQLITE_TCLMD5 or SQLITE_TEST is defined, the Md5 commands, and
3701 **
3702 **   * If SQLITE_TEST is set, the various test interfaces used by the Tcl
3703 **     test suite.
3704 */
3705 static void init_all(Tcl_Interp *interp){
3706   Sqlite3_Init(interp);
3707 
3708 #if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5)
3709   Md5_Init(interp);
3710 #endif
3711 
3712   /* Install the [register_dbstat_vtab] command to access the implementation
3713   ** of virtual table dbstat (source file test_stat.c). This command is
3714   ** required for testfixture and sqlite3_analyzer, but not by the production
3715   ** Tcl extension.  */
3716 #if defined(SQLITE_TEST) || TCLSH==2
3717   {
3718     extern int SqlitetestStat_Init(Tcl_Interp*);
3719     SqlitetestStat_Init(interp);
3720   }
3721 #endif
3722 
3723 #ifdef SQLITE_TEST
3724   {
3725     extern int Sqliteconfig_Init(Tcl_Interp*);
3726     extern int Sqlitetest1_Init(Tcl_Interp*);
3727     extern int Sqlitetest2_Init(Tcl_Interp*);
3728     extern int Sqlitetest3_Init(Tcl_Interp*);
3729     extern int Sqlitetest4_Init(Tcl_Interp*);
3730     extern int Sqlitetest5_Init(Tcl_Interp*);
3731     extern int Sqlitetest6_Init(Tcl_Interp*);
3732     extern int Sqlitetest7_Init(Tcl_Interp*);
3733     extern int Sqlitetest8_Init(Tcl_Interp*);
3734     extern int Sqlitetest9_Init(Tcl_Interp*);
3735     extern int Sqlitetestasync_Init(Tcl_Interp*);
3736     extern int Sqlitetest_autoext_Init(Tcl_Interp*);
3737     extern int Sqlitetest_blob_Init(Tcl_Interp*);
3738     extern int Sqlitetest_demovfs_Init(Tcl_Interp *);
3739     extern int Sqlitetest_func_Init(Tcl_Interp*);
3740     extern int Sqlitetest_hexio_Init(Tcl_Interp*);
3741     extern int Sqlitetest_init_Init(Tcl_Interp*);
3742     extern int Sqlitetest_malloc_Init(Tcl_Interp*);
3743     extern int Sqlitetest_mutex_Init(Tcl_Interp*);
3744     extern int Sqlitetestschema_Init(Tcl_Interp*);
3745     extern int Sqlitetestsse_Init(Tcl_Interp*);
3746     extern int Sqlitetesttclvar_Init(Tcl_Interp*);
3747     extern int Sqlitetestfs_Init(Tcl_Interp*);
3748     extern int SqlitetestThread_Init(Tcl_Interp*);
3749     extern int SqlitetestOnefile_Init();
3750     extern int SqlitetestOsinst_Init(Tcl_Interp*);
3751     extern int Sqlitetestbackup_Init(Tcl_Interp*);
3752     extern int Sqlitetestintarray_Init(Tcl_Interp*);
3753     extern int Sqlitetestvfs_Init(Tcl_Interp *);
3754     extern int Sqlitetestrtree_Init(Tcl_Interp*);
3755     extern int Sqlitequota_Init(Tcl_Interp*);
3756     extern int Sqlitemultiplex_Init(Tcl_Interp*);
3757     extern int SqliteSuperlock_Init(Tcl_Interp*);
3758     extern int SqlitetestSyscall_Init(Tcl_Interp*);
3759 
3760 #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
3761     extern int Sqlitetestfts3_Init(Tcl_Interp *interp);
3762 #endif
3763 
3764 #ifdef SQLITE_ENABLE_ZIPVFS
3765     extern int Zipvfs_Init(Tcl_Interp*);
3766     Zipvfs_Init(interp);
3767 #endif
3768 
3769     Sqliteconfig_Init(interp);
3770     Sqlitetest1_Init(interp);
3771     Sqlitetest2_Init(interp);
3772     Sqlitetest3_Init(interp);
3773     Sqlitetest4_Init(interp);
3774     Sqlitetest5_Init(interp);
3775     Sqlitetest6_Init(interp);
3776     Sqlitetest7_Init(interp);
3777     Sqlitetest8_Init(interp);
3778     Sqlitetest9_Init(interp);
3779     Sqlitetestasync_Init(interp);
3780     Sqlitetest_autoext_Init(interp);
3781     Sqlitetest_blob_Init(interp);
3782     Sqlitetest_demovfs_Init(interp);
3783     Sqlitetest_func_Init(interp);
3784     Sqlitetest_hexio_Init(interp);
3785     Sqlitetest_init_Init(interp);
3786     Sqlitetest_malloc_Init(interp);
3787     Sqlitetest_mutex_Init(interp);
3788     Sqlitetestschema_Init(interp);
3789     Sqlitetesttclvar_Init(interp);
3790     Sqlitetestfs_Init(interp);
3791     SqlitetestThread_Init(interp);
3792     SqlitetestOnefile_Init(interp);
3793     SqlitetestOsinst_Init(interp);
3794     Sqlitetestbackup_Init(interp);
3795     Sqlitetestintarray_Init(interp);
3796     Sqlitetestvfs_Init(interp);
3797     Sqlitetestrtree_Init(interp);
3798     Sqlitequota_Init(interp);
3799     Sqlitemultiplex_Init(interp);
3800     SqliteSuperlock_Init(interp);
3801     SqlitetestSyscall_Init(interp);
3802 
3803 #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
3804     Sqlitetestfts3_Init(interp);
3805 #endif
3806 
3807     Tcl_CreateObjCommand(
3808         interp, "load_testfixture_extensions", init_all_cmd, 0, 0
3809     );
3810     Tcl_CreateObjCommand(
3811         interp, "db_use_legacy_prepare", db_use_legacy_prepare_cmd, 0, 0
3812     );
3813     Tcl_CreateObjCommand(
3814         interp, "db_last_stmt_ptr", db_last_stmt_ptr, 0, 0
3815     );
3816 
3817 #ifdef SQLITE_SSE
3818     Sqlitetestsse_Init(interp);
3819 #endif
3820   }
3821 #endif
3822 }
3823 
3824 /* Needed for the setrlimit() system call on unix */
3825 #if defined(unix)
3826 #include <sys/resource.h>
3827 #endif
3828 
3829 #define TCLSH_MAIN main   /* Needed to fake out mktclapp */
3830 int TCLSH_MAIN(int argc, char **argv){
3831   Tcl_Interp *interp;
3832 
3833 #if !defined(_WIN32_WCE)
3834   if( getenv("BREAK") ){
3835     fprintf(stderr,
3836         "attach debugger to process %d and press any key to continue.\n",
3837         GETPID());
3838     fgetc(stdin);
3839   }
3840 #endif
3841 
3842   /* Since the primary use case for this binary is testing of SQLite,
3843   ** be sure to generate core files if we crash */
3844 #if defined(SQLITE_TEST) && defined(unix)
3845   { struct rlimit x;
3846     getrlimit(RLIMIT_CORE, &x);
3847     x.rlim_cur = x.rlim_max;
3848     setrlimit(RLIMIT_CORE, &x);
3849   }
3850 #endif /* SQLITE_TEST && unix */
3851 
3852 
3853   /* Call sqlite3_shutdown() once before doing anything else. This is to
3854   ** test that sqlite3_shutdown() can be safely called by a process before
3855   ** sqlite3_initialize() is. */
3856   sqlite3_shutdown();
3857 
3858   Tcl_FindExecutable(argv[0]);
3859   Tcl_SetSystemEncoding(NULL, "utf-8");
3860   interp = Tcl_CreateInterp();
3861 
3862 #if TCLSH==2
3863   sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);
3864 #endif
3865 
3866   init_all(interp);
3867   if( argc>=2 ){
3868     int i;
3869     char zArgc[32];
3870     sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-(3-TCLSH));
3871     Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY);
3872     Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY);
3873     Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY);
3874     for(i=3-TCLSH; i<argc; i++){
3875       Tcl_SetVar(interp, "argv", argv[i],
3876           TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE);
3877     }
3878     if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){
3879       const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
3880       if( zInfo==0 ) zInfo = Tcl_GetStringResult(interp);
3881       fprintf(stderr,"%s: %s\n", *argv, zInfo);
3882       return 1;
3883     }
3884   }
3885   if( TCLSH==2 || argc<=1 ){
3886     Tcl_GlobalEval(interp, tclsh_main_loop());
3887   }
3888   return 0;
3889 }
3890 #endif /* TCLSH */
3891