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


asr_psm
Author(s): Braun Kai, Gehrung Joachim, Heizmann Heinrich, Meißner Pascal
autogenerated on Fri Nov 15 2019 04:00:08