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