xref: /sqlite-3.40.0/src/test1.c (revision 48864df9)
1 /*
2 ** 2001 September 15
3 **
4 ** The author disclaims copyright to this source code.  In place of
5 ** a legal notice, here is a blessing:
6 **
7 **    May you do good and not evil.
8 **    May you find forgiveness for yourself and forgive others.
9 **    May you share freely, never taking more than you give.
10 **
11 *************************************************************************
12 ** Code for testing all sorts of SQLite interfaces.  This code
13 ** is not included in the SQLite library.  It is used for automated
14 ** testing of the SQLite library.
15 */
16 #include "sqliteInt.h"
17 #include "vdbeInt.h"
18 #include "tcl.h"
19 #include <stdlib.h>
20 #include <string.h>
21 
22 /*
23 ** This is a copy of the first part of the SqliteDb structure in
24 ** tclsqlite.c.  We need it here so that the get_sqlite_pointer routine
25 ** can extract the sqlite3* pointer from an existing Tcl SQLite
26 ** connection.
27 */
28 struct SqliteDb {
29   sqlite3 *db;
30 };
31 
32 /*
33 ** Convert text generated by the "%p" conversion format back into
34 ** a pointer.
35 */
36 static int testHexToInt(int h){
37   if( h>='0' && h<='9' ){
38     return h - '0';
39   }else if( h>='a' && h<='f' ){
40     return h - 'a' + 10;
41   }else{
42     assert( h>='A' && h<='F' );
43     return h - 'A' + 10;
44   }
45 }
46 void *sqlite3TestTextToPtr(const char *z){
47   void *p;
48   u64 v;
49   u32 v2;
50   if( z[0]=='0' && z[1]=='x' ){
51     z += 2;
52   }
53   v = 0;
54   while( *z ){
55     v = (v<<4) + testHexToInt(*z);
56     z++;
57   }
58   if( sizeof(p)==sizeof(v) ){
59     memcpy(&p, &v, sizeof(p));
60   }else{
61     assert( sizeof(p)==sizeof(v2) );
62     v2 = (u32)v;
63     memcpy(&p, &v2, sizeof(p));
64   }
65   return p;
66 }
67 
68 
69 /*
70 ** A TCL command that returns the address of the sqlite* pointer
71 ** for an sqlite connection instance.  Bad things happen if the
72 ** input is not an sqlite connection.
73 */
74 static int get_sqlite_pointer(
75   void * clientData,
76   Tcl_Interp *interp,
77   int objc,
78   Tcl_Obj *CONST objv[]
79 ){
80   struct SqliteDb *p;
81   Tcl_CmdInfo cmdInfo;
82   char zBuf[100];
83   if( objc!=2 ){
84     Tcl_WrongNumArgs(interp, 1, objv, "SQLITE-CONNECTION");
85     return TCL_ERROR;
86   }
87   if( !Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &cmdInfo) ){
88     Tcl_AppendResult(interp, "command not found: ",
89            Tcl_GetString(objv[1]), (char*)0);
90     return TCL_ERROR;
91   }
92   p = (struct SqliteDb*)cmdInfo.objClientData;
93   sprintf(zBuf, "%p", p->db);
94   if( strncmp(zBuf,"0x",2) ){
95     sprintf(zBuf, "0x%p", p->db);
96   }
97   Tcl_AppendResult(interp, zBuf, 0);
98   return TCL_OK;
99 }
100 
101 /*
102 ** Decode a pointer to an sqlite3 object.
103 */
104 int getDbPointer(Tcl_Interp *interp, const char *zA, sqlite3 **ppDb){
105   struct SqliteDb *p;
106   Tcl_CmdInfo cmdInfo;
107   if( Tcl_GetCommandInfo(interp, zA, &cmdInfo) ){
108     p = (struct SqliteDb*)cmdInfo.objClientData;
109     *ppDb = p->db;
110   }else{
111     *ppDb = (sqlite3*)sqlite3TestTextToPtr(zA);
112   }
113   return TCL_OK;
114 }
115 
116 
117 const char *sqlite3TestErrorName(int rc){
118   const char *zName = 0;
119   switch( rc ){
120     case SQLITE_OK:                  zName = "SQLITE_OK";                break;
121     case SQLITE_ERROR:               zName = "SQLITE_ERROR";             break;
122     case SQLITE_INTERNAL:            zName = "SQLITE_INTERNAL";          break;
123     case SQLITE_PERM:                zName = "SQLITE_PERM";              break;
124     case SQLITE_ABORT:               zName = "SQLITE_ABORT";             break;
125     case SQLITE_BUSY:                zName = "SQLITE_BUSY";              break;
126     case SQLITE_LOCKED:              zName = "SQLITE_LOCKED";            break;
127     case SQLITE_LOCKED_SHAREDCACHE:  zName = "SQLITE_LOCKED_SHAREDCACHE";break;
128     case SQLITE_NOMEM:               zName = "SQLITE_NOMEM";             break;
129     case SQLITE_READONLY:            zName = "SQLITE_READONLY";          break;
130     case SQLITE_INTERRUPT:           zName = "SQLITE_INTERRUPT";         break;
131     case SQLITE_IOERR:               zName = "SQLITE_IOERR";             break;
132     case SQLITE_CORRUPT:             zName = "SQLITE_CORRUPT";           break;
133     case SQLITE_NOTFOUND:            zName = "SQLITE_NOTFOUND";          break;
134     case SQLITE_FULL:                zName = "SQLITE_FULL";              break;
135     case SQLITE_CANTOPEN:            zName = "SQLITE_CANTOPEN";          break;
136     case SQLITE_PROTOCOL:            zName = "SQLITE_PROTOCOL";          break;
137     case SQLITE_EMPTY:               zName = "SQLITE_EMPTY";             break;
138     case SQLITE_SCHEMA:              zName = "SQLITE_SCHEMA";            break;
139     case SQLITE_TOOBIG:              zName = "SQLITE_TOOBIG";            break;
140     case SQLITE_CONSTRAINT:          zName = "SQLITE_CONSTRAINT";        break;
141     case SQLITE_CONSTRAINT_UNIQUE:   zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
142     case SQLITE_CONSTRAINT_TRIGGER:  zName = "SQLITE_CONSTRAINT_TRIGGER";break;
143     case SQLITE_CONSTRAINT_FOREIGNKEY:
144                                  zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break;
145     case SQLITE_CONSTRAINT_CHECK:    zName = "SQLITE_CONSTRAINT_CHECK";  break;
146     case SQLITE_CONSTRAINT_PRIMARYKEY:
147                                  zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break;
148     case SQLITE_CONSTRAINT_NOTNULL:  zName = "SQLITE_CONSTRAINT_NOTNULL";break;
149     case SQLITE_CONSTRAINT_COMMITHOOK:
150                                  zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break;
151     case SQLITE_CONSTRAINT_VTAB:     zName = "SQLITE_CONSTRAINT_VTAB";   break;
152     case SQLITE_CONSTRAINT_FUNCTION: zName = "SQLITE_CONSTRAINT_FUNCTION";break;
153     case SQLITE_MISMATCH:            zName = "SQLITE_MISMATCH";          break;
154     case SQLITE_MISUSE:              zName = "SQLITE_MISUSE";            break;
155     case SQLITE_NOLFS:               zName = "SQLITE_NOLFS";             break;
156     case SQLITE_AUTH:                zName = "SQLITE_AUTH";              break;
157     case SQLITE_FORMAT:              zName = "SQLITE_FORMAT";            break;
158     case SQLITE_RANGE:               zName = "SQLITE_RANGE";             break;
159     case SQLITE_NOTADB:              zName = "SQLITE_NOTADB";            break;
160     case SQLITE_ROW:                 zName = "SQLITE_ROW";               break;
161     case SQLITE_DONE:                zName = "SQLITE_DONE";              break;
162     case SQLITE_IOERR_READ:          zName = "SQLITE_IOERR_READ";        break;
163     case SQLITE_IOERR_SHORT_READ:    zName = "SQLITE_IOERR_SHORT_READ";  break;
164     case SQLITE_IOERR_WRITE:         zName = "SQLITE_IOERR_WRITE";       break;
165     case SQLITE_IOERR_FSYNC:         zName = "SQLITE_IOERR_FSYNC";       break;
166     case SQLITE_IOERR_DIR_FSYNC:     zName = "SQLITE_IOERR_DIR_FSYNC";   break;
167     case SQLITE_IOERR_TRUNCATE:      zName = "SQLITE_IOERR_TRUNCATE";    break;
168     case SQLITE_IOERR_FSTAT:         zName = "SQLITE_IOERR_FSTAT";       break;
169     case SQLITE_IOERR_UNLOCK:        zName = "SQLITE_IOERR_UNLOCK";      break;
170     case SQLITE_IOERR_RDLOCK:        zName = "SQLITE_IOERR_RDLOCK";      break;
171     case SQLITE_IOERR_DELETE:        zName = "SQLITE_IOERR_DELETE";      break;
172     case SQLITE_IOERR_BLOCKED:       zName = "SQLITE_IOERR_BLOCKED";     break;
173     case SQLITE_IOERR_NOMEM:         zName = "SQLITE_IOERR_NOMEM";       break;
174     case SQLITE_IOERR_ACCESS:        zName = "SQLITE_IOERR_ACCESS";      break;
175     case SQLITE_IOERR_CHECKRESERVEDLOCK:
176                                zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
177     case SQLITE_IOERR_LOCK:          zName = "SQLITE_IOERR_LOCK";        break;
178     case SQLITE_CORRUPT_VTAB:        zName = "SQLITE_CORRUPT_VTAB";      break;
179     case SQLITE_READONLY_RECOVERY:   zName = "SQLITE_READONLY_RECOVERY"; break;
180     case SQLITE_READONLY_CANTLOCK:   zName = "SQLITE_READONLY_CANTLOCK"; break;
181     case SQLITE_READONLY_ROLLBACK:   zName = "SQLITE_READONLY_ROLLBACK"; break;
182     default:                         zName = "SQLITE_Unknown";           break;
183   }
184   return zName;
185 }
186 #define t1ErrorName sqlite3TestErrorName
187 
188 /*
189 ** Convert an sqlite3_stmt* into an sqlite3*.  This depends on the
190 ** fact that the sqlite3* is the first field in the Vdbe structure.
191 */
192 #define StmtToDb(X)   sqlite3_db_handle(X)
193 
194 /*
195 ** Check a return value to make sure it agrees with the results
196 ** from sqlite3_errcode.
197 */
198 int sqlite3TestErrCode(Tcl_Interp *interp, sqlite3 *db, int rc){
199   if( sqlite3_threadsafe()==0 && rc!=SQLITE_MISUSE && rc!=SQLITE_OK
200    && sqlite3_errcode(db)!=rc ){
201     char zBuf[200];
202     int r2 = sqlite3_errcode(db);
203     sprintf(zBuf, "error code %s (%d) does not match sqlite3_errcode %s (%d)",
204        t1ErrorName(rc), rc, t1ErrorName(r2), r2);
205     Tcl_ResetResult(interp);
206     Tcl_AppendResult(interp, zBuf, 0);
207     return 1;
208   }
209   return 0;
210 }
211 
212 /*
213 ** Decode a pointer to an sqlite3_stmt object.
214 */
215 static int getStmtPointer(
216   Tcl_Interp *interp,
217   const char *zArg,
218   sqlite3_stmt **ppStmt
219 ){
220   *ppStmt = (sqlite3_stmt*)sqlite3TestTextToPtr(zArg);
221   return TCL_OK;
222 }
223 
224 /*
225 ** Generate a text representation of a pointer that can be understood
226 ** by the getDbPointer and getVmPointer routines above.
227 **
228 ** The problem is, on some machines (Solaris) if you do a printf with
229 ** "%p" you cannot turn around and do a scanf with the same "%p" and
230 ** get your pointer back.  You have to prepend a "0x" before it will
231 ** work.  Or at least that is what is reported to me (drh).  But this
232 ** behavior varies from machine to machine.  The solution used her is
233 ** to test the string right after it is generated to see if it can be
234 ** understood by scanf, and if not, try prepending an "0x" to see if
235 ** that helps.  If nothing works, a fatal error is generated.
236 */
237 int sqlite3TestMakePointerStr(Tcl_Interp *interp, char *zPtr, void *p){
238   sqlite3_snprintf(100, zPtr, "%p", p);
239   return TCL_OK;
240 }
241 
242 /*
243 ** The callback routine for sqlite3_exec_printf().
244 */
245 static int exec_printf_cb(void *pArg, int argc, char **argv, char **name){
246   Tcl_DString *str = (Tcl_DString*)pArg;
247   int i;
248 
249   if( Tcl_DStringLength(str)==0 ){
250     for(i=0; i<argc; i++){
251       Tcl_DStringAppendElement(str, name[i] ? name[i] : "NULL");
252     }
253   }
254   for(i=0; i<argc; i++){
255     Tcl_DStringAppendElement(str, argv[i] ? argv[i] : "NULL");
256   }
257   return 0;
258 }
259 
260 /*
261 ** The I/O tracing callback.
262 */
263 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
264 static FILE *iotrace_file = 0;
265 static void io_trace_callback(const char *zFormat, ...){
266   va_list ap;
267   va_start(ap, zFormat);
268   vfprintf(iotrace_file, zFormat, ap);
269   va_end(ap);
270   fflush(iotrace_file);
271 }
272 #endif
273 
274 /*
275 ** Usage:  io_trace FILENAME
276 **
277 ** Turn I/O tracing on or off.  If FILENAME is not an empty string,
278 ** I/O tracing begins going into FILENAME. If FILENAME is an empty
279 ** string, I/O tracing is turned off.
280 */
281 static int test_io_trace(
282   void *NotUsed,
283   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
284   int argc,              /* Number of arguments */
285   char **argv            /* Text of each argument */
286 ){
287 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
288   if( argc!=2 ){
289     Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
290           " FILENAME\"", 0);
291     return TCL_ERROR;
292   }
293   if( iotrace_file ){
294     if( iotrace_file!=stdout && iotrace_file!=stderr ){
295       fclose(iotrace_file);
296     }
297     iotrace_file = 0;
298     sqlite3IoTrace = 0;
299   }
300   if( argv[1][0] ){
301     if( strcmp(argv[1],"stdout")==0 ){
302       iotrace_file = stdout;
303     }else if( strcmp(argv[1],"stderr")==0 ){
304       iotrace_file = stderr;
305     }else{
306       iotrace_file = fopen(argv[1], "w");
307     }
308     sqlite3IoTrace = io_trace_callback;
309   }
310 #endif
311   return TCL_OK;
312 }
313 
314 
315 /*
316 ** Usage:  sqlite3_exec_printf  DB  FORMAT  STRING
317 **
318 ** Invoke the sqlite3_exec_printf() interface using the open database
319 ** DB.  The SQL is the string FORMAT.  The format string should contain
320 ** one %s or %q.  STRING is the value inserted into %s or %q.
321 */
322 static int test_exec_printf(
323   void *NotUsed,
324   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
325   int argc,              /* Number of arguments */
326   char **argv            /* Text of each argument */
327 ){
328   sqlite3 *db;
329   Tcl_DString str;
330   int rc;
331   char *zErr = 0;
332   char *zSql;
333   char zBuf[30];
334   if( argc!=4 ){
335     Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
336        " DB FORMAT STRING", 0);
337     return TCL_ERROR;
338   }
339   if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
340   Tcl_DStringInit(&str);
341   zSql = sqlite3_mprintf(argv[2], argv[3]);
342   rc = sqlite3_exec(db, zSql, exec_printf_cb, &str, &zErr);
343   sqlite3_free(zSql);
344   sprintf(zBuf, "%d", rc);
345   Tcl_AppendElement(interp, zBuf);
346   Tcl_AppendElement(interp, rc==SQLITE_OK ? Tcl_DStringValue(&str) : zErr);
347   Tcl_DStringFree(&str);
348   if( zErr ) sqlite3_free(zErr);
349   if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR;
350   return TCL_OK;
351 }
352 
353 /*
354 ** Usage:  sqlite3_exec_hex  DB  HEX
355 **
356 ** Invoke the sqlite3_exec() on a string that is obtained by translating
357 ** HEX into ASCII.  Most characters are translated as is.  %HH becomes
358 ** a hex character.
359 */
360 static int test_exec_hex(
361   void *NotUsed,
362   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
363   int argc,              /* Number of arguments */
364   char **argv            /* Text of each argument */
365 ){
366   sqlite3 *db;
367   Tcl_DString str;
368   int rc, i, j;
369   char *zErr = 0;
370   char *zHex;
371   char zSql[500];
372   char zBuf[30];
373   if( argc!=3 ){
374     Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
375        " DB HEX", 0);
376     return TCL_ERROR;
377   }
378   if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
379   zHex = argv[2];
380   for(i=j=0; i<sizeof(zSql) && zHex[j]; i++, j++){
381     if( zHex[j]=='%' && zHex[j+2] && zHex[j+2] ){
382       zSql[i] = (testHexToInt(zHex[j+1])<<4) + testHexToInt(zHex[j+2]);
383       j += 2;
384     }else{
385       zSql[i] = zHex[j];
386     }
387   }
388   zSql[i] = 0;
389   Tcl_DStringInit(&str);
390   rc = sqlite3_exec(db, zSql, exec_printf_cb, &str, &zErr);
391   sprintf(zBuf, "%d", rc);
392   Tcl_AppendElement(interp, zBuf);
393   Tcl_AppendElement(interp, rc==SQLITE_OK ? Tcl_DStringValue(&str) : zErr);
394   Tcl_DStringFree(&str);
395   if( zErr ) sqlite3_free(zErr);
396   if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR;
397   return TCL_OK;
398 }
399 
400 /*
401 ** Usage:  db_enter DB
402 **         db_leave DB
403 **
404 ** Enter or leave the mutex on a database connection.
405 */
406 static int db_enter(
407   void *NotUsed,
408   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
409   int argc,              /* Number of arguments */
410   char **argv            /* Text of each argument */
411 ){
412   sqlite3 *db;
413   if( argc!=2 ){
414     Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
415        " DB", 0);
416     return TCL_ERROR;
417   }
418   if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
419   sqlite3_mutex_enter(db->mutex);
420   return TCL_OK;
421 }
422 static int db_leave(
423   void *NotUsed,
424   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
425   int argc,              /* Number of arguments */
426   char **argv            /* Text of each argument */
427 ){
428   sqlite3 *db;
429   if( argc!=2 ){
430     Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
431        " DB", 0);
432     return TCL_ERROR;
433   }
434   if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
435   sqlite3_mutex_leave(db->mutex);
436   return TCL_OK;
437 }
438 
439 /*
440 ** Usage:  sqlite3_exec  DB  SQL
441 **
442 ** Invoke the sqlite3_exec interface using the open database DB
443 */
444 static int test_exec(
445   void *NotUsed,
446   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
447   int argc,              /* Number of arguments */
448   char **argv            /* Text of each argument */
449 ){
450   sqlite3 *db;
451   Tcl_DString str;
452   int rc;
453   char *zErr = 0;
454   char *zSql;
455   int i, j;
456   char zBuf[30];
457   if( argc!=3 ){
458     Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
459        " DB SQL", 0);
460     return TCL_ERROR;
461   }
462   if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
463   Tcl_DStringInit(&str);
464   zSql = sqlite3_mprintf("%s", argv[2]);
465   for(i=j=0; zSql[i];){
466     if( zSql[i]=='%' ){
467       zSql[j++] = (testHexToInt(zSql[i+1])<<4) + testHexToInt(zSql[i+2]);
468       i += 3;
469     }else{
470       zSql[j++] = zSql[i++];
471     }
472   }
473   zSql[j] = 0;
474   rc = sqlite3_exec(db, zSql, exec_printf_cb, &str, &zErr);
475   sqlite3_free(zSql);
476   sprintf(zBuf, "%d", rc);
477   Tcl_AppendElement(interp, zBuf);
478   Tcl_AppendElement(interp, rc==SQLITE_OK ? Tcl_DStringValue(&str) : zErr);
479   Tcl_DStringFree(&str);
480   if( zErr ) sqlite3_free(zErr);
481   if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR;
482   return TCL_OK;
483 }
484 
485 /*
486 ** Usage:  sqlite3_exec_nr  DB  SQL
487 **
488 ** Invoke the sqlite3_exec interface using the open database DB.  Discard
489 ** all results
490 */
491 static int test_exec_nr(
492   void *NotUsed,
493   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
494   int argc,              /* Number of arguments */
495   char **argv            /* Text of each argument */
496 ){
497   sqlite3 *db;
498   int rc;
499   char *zErr = 0;
500   if( argc!=3 ){
501     Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
502        " DB SQL", 0);
503     return TCL_ERROR;
504   }
505   if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
506   rc = sqlite3_exec(db, argv[2], 0, 0, &zErr);
507   if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR;
508   return TCL_OK;
509 }
510 
511 /*
512 ** Usage:  sqlite3_mprintf_z_test  SEPARATOR  ARG0  ARG1 ...
513 **
514 ** Test the %z format of sqlite_mprintf().  Use multiple mprintf() calls to
515 ** concatenate arg0 through argn using separator as the separator.
516 ** Return the result.
517 */
518 static int test_mprintf_z(
519   void *NotUsed,
520   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
521   int argc,              /* Number of arguments */
522   char **argv            /* Text of each argument */
523 ){
524   char *zResult = 0;
525   int i;
526 
527   for(i=2; i<argc && (i==2 || zResult); i++){
528     zResult = sqlite3_mprintf("%z%s%s", zResult, argv[1], argv[i]);
529   }
530   Tcl_AppendResult(interp, zResult, 0);
531   sqlite3_free(zResult);
532   return TCL_OK;
533 }
534 
535 /*
536 ** Usage:  sqlite3_mprintf_n_test  STRING
537 **
538 ** Test the %n format of sqlite_mprintf().  Return the length of the
539 ** input string.
540 */
541 static int test_mprintf_n(
542   void *NotUsed,
543   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
544   int argc,              /* Number of arguments */
545   char **argv            /* Text of each argument */
546 ){
547   char *zStr;
548   int n = 0;
549   zStr = sqlite3_mprintf("%s%n", argv[1], &n);
550   sqlite3_free(zStr);
551   Tcl_SetObjResult(interp, Tcl_NewIntObj(n));
552   return TCL_OK;
553 }
554 
555 /*
556 ** Usage:  sqlite3_snprintf_int  SIZE FORMAT  INT
557 **
558 ** Test the of sqlite3_snprintf() routine.  SIZE is the size of the
559 ** output buffer in bytes.  The maximum size is 100.  FORMAT is the
560 ** format string.  INT is a single integer argument.  The FORMAT
561 ** string must require no more than this one integer argument.  If
562 ** You pass in a format string that requires more than one argument,
563 ** bad things will happen.
564 */
565 static int test_snprintf_int(
566   void *NotUsed,
567   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
568   int argc,              /* Number of arguments */
569   char **argv            /* Text of each argument */
570 ){
571   char zStr[100];
572   int n = atoi(argv[1]);
573   const char *zFormat = argv[2];
574   int a1 = atoi(argv[3]);
575   if( n>sizeof(zStr) ) n = sizeof(zStr);
576   sqlite3_snprintf(sizeof(zStr), zStr, "abcdefghijklmnopqrstuvwxyz");
577   sqlite3_snprintf(n, zStr, zFormat, a1);
578   Tcl_AppendResult(interp, zStr, 0);
579   return TCL_OK;
580 }
581 
582 #ifndef SQLITE_OMIT_GET_TABLE
583 
584 /*
585 ** Usage:  sqlite3_get_table_printf  DB  FORMAT  STRING  ?--no-counts?
586 **
587 ** Invoke the sqlite3_get_table_printf() interface using the open database
588 ** DB.  The SQL is the string FORMAT.  The format string should contain
589 ** one %s or %q.  STRING is the value inserted into %s or %q.
590 */
591 static int test_get_table_printf(
592   void *NotUsed,
593   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
594   int argc,              /* Number of arguments */
595   char **argv            /* Text of each argument */
596 ){
597   sqlite3 *db;
598   Tcl_DString str;
599   int rc;
600   char *zErr = 0;
601   int nRow, nCol;
602   char **aResult;
603   int i;
604   char zBuf[30];
605   char *zSql;
606   int resCount = -1;
607   if( argc==5 ){
608     if( Tcl_GetInt(interp, argv[4], &resCount) ) return TCL_ERROR;
609   }
610   if( argc!=4 && argc!=5 ){
611     Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
612        " DB FORMAT STRING ?COUNT?", 0);
613     return TCL_ERROR;
614   }
615   if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
616   Tcl_DStringInit(&str);
617   zSql = sqlite3_mprintf(argv[2],argv[3]);
618   if( argc==5 ){
619     rc = sqlite3_get_table(db, zSql, &aResult, 0, 0, &zErr);
620   }else{
621     rc = sqlite3_get_table(db, zSql, &aResult, &nRow, &nCol, &zErr);
622     resCount = (nRow+1)*nCol;
623   }
624   sqlite3_free(zSql);
625   sprintf(zBuf, "%d", rc);
626   Tcl_AppendElement(interp, zBuf);
627   if( rc==SQLITE_OK ){
628     if( argc==4 ){
629       sprintf(zBuf, "%d", nRow);
630       Tcl_AppendElement(interp, zBuf);
631       sprintf(zBuf, "%d", nCol);
632       Tcl_AppendElement(interp, zBuf);
633     }
634     for(i=0; i<resCount; i++){
635       Tcl_AppendElement(interp, aResult[i] ? aResult[i] : "NULL");
636     }
637   }else{
638     Tcl_AppendElement(interp, zErr);
639   }
640   sqlite3_free_table(aResult);
641   if( zErr ) sqlite3_free(zErr);
642   if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR;
643   return TCL_OK;
644 }
645 
646 #endif /* SQLITE_OMIT_GET_TABLE */
647 
648 
649 /*
650 ** Usage:  sqlite3_last_insert_rowid DB
651 **
652 ** Returns the integer ROWID of the most recent insert.
653 */
654 static int test_last_rowid(
655   void *NotUsed,
656   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
657   int argc,              /* Number of arguments */
658   char **argv            /* Text of each argument */
659 ){
660   sqlite3 *db;
661   char zBuf[30];
662 
663   if( argc!=2 ){
664     Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], " DB\"", 0);
665     return TCL_ERROR;
666   }
667   if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
668   sprintf(zBuf, "%lld", sqlite3_last_insert_rowid(db));
669   Tcl_AppendResult(interp, zBuf, 0);
670   return SQLITE_OK;
671 }
672 
673 /*
674 ** Usage:  sqlite3_key DB KEY
675 **
676 ** Set the codec key.
677 */
678 static int test_key(
679   void *NotUsed,
680   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
681   int argc,              /* Number of arguments */
682   char **argv            /* Text of each argument */
683 ){
684 #ifdef SQLITE_HAS_CODEC
685   sqlite3 *db;
686   const char *zKey;
687   int nKey;
688   if( argc!=3 ){
689     Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
690        " FILENAME\"", 0);
691     return TCL_ERROR;
692   }
693   if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
694   zKey = argv[2];
695   nKey = strlen(zKey);
696   sqlite3_key(db, zKey, nKey);
697 #endif
698   return TCL_OK;
699 }
700 
701 /*
702 ** Usage:  sqlite3_rekey DB KEY
703 **
704 ** Change the codec key.
705 */
706 static int test_rekey(
707   void *NotUsed,
708   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
709   int argc,              /* Number of arguments */
710   char **argv            /* Text of each argument */
711 ){
712 #ifdef SQLITE_HAS_CODEC
713   sqlite3 *db;
714   const char *zKey;
715   int nKey;
716   if( argc!=3 ){
717     Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
718        " FILENAME\"", 0);
719     return TCL_ERROR;
720   }
721   if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
722   zKey = argv[2];
723   nKey = strlen(zKey);
724   sqlite3_rekey(db, zKey, nKey);
725 #endif
726   return TCL_OK;
727 }
728 
729 /*
730 ** Usage:  sqlite3_close DB
731 **
732 ** Closes the database opened by sqlite3_open.
733 */
734 static int sqlite_test_close(
735   void *NotUsed,
736   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
737   int argc,              /* Number of arguments */
738   char **argv            /* Text of each argument */
739 ){
740   sqlite3 *db;
741   int rc;
742   if( argc!=2 ){
743     Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
744        " FILENAME\"", 0);
745     return TCL_ERROR;
746   }
747   if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
748   rc = sqlite3_close(db);
749   Tcl_SetResult(interp, (char *)t1ErrorName(rc), TCL_STATIC);
750   return TCL_OK;
751 }
752 
753 /*
754 ** Implementation of the x_coalesce() function.
755 ** Return the first argument non-NULL argument.
756 */
757 static void t1_ifnullFunc(
758   sqlite3_context *context,
759   int argc,
760   sqlite3_value **argv
761 ){
762   int i;
763   for(i=0; i<argc; i++){
764     if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
765       int n = sqlite3_value_bytes(argv[i]);
766       sqlite3_result_text(context, (char*)sqlite3_value_text(argv[i]),
767           n, SQLITE_TRANSIENT);
768       break;
769     }
770   }
771 }
772 
773 /*
774 ** These are test functions.    hex8() interprets its argument as
775 ** UTF8 and returns a hex encoding.  hex16le() interprets its argument
776 ** as UTF16le and returns a hex encoding.
777 */
778 static void hex8Func(sqlite3_context *p, int argc, sqlite3_value **argv){
779   const unsigned char *z;
780   int i;
781   char zBuf[200];
782   z = sqlite3_value_text(argv[0]);
783   for(i=0; i<sizeof(zBuf)/2 - 2 && z[i]; i++){
784     sprintf(&zBuf[i*2], "%02x", z[i]&0xff);
785   }
786   zBuf[i*2] = 0;
787   sqlite3_result_text(p, (char*)zBuf, -1, SQLITE_TRANSIENT);
788 }
789 #ifndef SQLITE_OMIT_UTF16
790 static void hex16Func(sqlite3_context *p, int argc, sqlite3_value **argv){
791   const unsigned short int *z;
792   int i;
793   char zBuf[400];
794   z = sqlite3_value_text16(argv[0]);
795   for(i=0; i<sizeof(zBuf)/4 - 4 && z[i]; i++){
796     sprintf(&zBuf[i*4], "%04x", z[i]&0xff);
797   }
798   zBuf[i*4] = 0;
799   sqlite3_result_text(p, (char*)zBuf, -1, SQLITE_TRANSIENT);
800 }
801 #endif
802 
803 /*
804 ** A structure into which to accumulate text.
805 */
806 struct dstr {
807   int nAlloc;  /* Space allocated */
808   int nUsed;   /* Space used */
809   char *z;     /* The space */
810 };
811 
812 /*
813 ** Append text to a dstr
814 */
815 static void dstrAppend(struct dstr *p, const char *z, int divider){
816   int n = (int)strlen(z);
817   if( p->nUsed + n + 2 > p->nAlloc ){
818     char *zNew;
819     p->nAlloc = p->nAlloc*2 + n + 200;
820     zNew = sqlite3_realloc(p->z, p->nAlloc);
821     if( zNew==0 ){
822       sqlite3_free(p->z);
823       memset(p, 0, sizeof(*p));
824       return;
825     }
826     p->z = zNew;
827   }
828   if( divider && p->nUsed>0 ){
829     p->z[p->nUsed++] = divider;
830   }
831   memcpy(&p->z[p->nUsed], z, n+1);
832   p->nUsed += n;
833 }
834 
835 /*
836 ** Invoked for each callback from sqlite3ExecFunc
837 */
838 static int execFuncCallback(void *pData, int argc, char **argv, char **NotUsed){
839   struct dstr *p = (struct dstr*)pData;
840   int i;
841   for(i=0; i<argc; i++){
842     if( argv[i]==0 ){
843       dstrAppend(p, "NULL", ' ');
844     }else{
845       dstrAppend(p, argv[i], ' ');
846     }
847   }
848   return 0;
849 }
850 
851 /*
852 ** Implementation of the x_sqlite_exec() function.  This function takes
853 ** a single argument and attempts to execute that argument as SQL code.
854 ** This is illegal and should set the SQLITE_MISUSE flag on the database.
855 **
856 ** 2004-Jan-07:  We have changed this to make it legal to call sqlite3_exec()
857 ** from within a function call.
858 **
859 ** This routine simulates the effect of having two threads attempt to
860 ** use the same database at the same time.
861 */
862 static void sqlite3ExecFunc(
863   sqlite3_context *context,
864   int argc,
865   sqlite3_value **argv
866 ){
867   struct dstr x;
868   memset(&x, 0, sizeof(x));
869   (void)sqlite3_exec((sqlite3*)sqlite3_user_data(context),
870       (char*)sqlite3_value_text(argv[0]),
871       execFuncCallback, &x, 0);
872   sqlite3_result_text(context, x.z, x.nUsed, SQLITE_TRANSIENT);
873   sqlite3_free(x.z);
874 }
875 
876 /*
877 ** Implementation of tkt2213func(), a scalar function that takes exactly
878 ** one argument. It has two interesting features:
879 **
880 ** * It calls sqlite3_value_text() 3 times on the argument sqlite3_value*.
881 **   If the three pointers returned are not the same an SQL error is raised.
882 **
883 ** * Otherwise it returns a copy of the text representation of its
884 **   argument in such a way as the VDBE representation is a Mem* cell
885 **   with the MEM_Term flag clear.
886 **
887 ** Ticket #2213 can therefore be tested by evaluating the following
888 ** SQL expression:
889 **
890 **   tkt2213func(tkt2213func('a string'));
891 */
892 static void tkt2213Function(
893   sqlite3_context *context,
894   int argc,
895   sqlite3_value **argv
896 ){
897   int nText;
898   unsigned char const *zText1;
899   unsigned char const *zText2;
900   unsigned char const *zText3;
901 
902   nText = sqlite3_value_bytes(argv[0]);
903   zText1 = sqlite3_value_text(argv[0]);
904   zText2 = sqlite3_value_text(argv[0]);
905   zText3 = sqlite3_value_text(argv[0]);
906 
907   if( zText1!=zText2 || zText2!=zText3 ){
908     sqlite3_result_error(context, "tkt2213 is not fixed", -1);
909   }else{
910     char *zCopy = (char *)sqlite3_malloc(nText);
911     memcpy(zCopy, zText1, nText);
912     sqlite3_result_text(context, zCopy, nText, sqlite3_free);
913   }
914 }
915 
916 /*
917 ** The following SQL function takes 4 arguments.  The 2nd and
918 ** 4th argument must be one of these strings:  'text', 'text16',
919 ** or 'blob' corresponding to API functions
920 **
921 **      sqlite3_value_text()
922 **      sqlite3_value_text16()
923 **      sqlite3_value_blob()
924 **
925 ** The third argument is a string, either 'bytes' or 'bytes16' or 'noop',
926 ** corresponding to APIs:
927 **
928 **      sqlite3_value_bytes()
929 **      sqlite3_value_bytes16()
930 **      noop
931 **
932 ** The APIs designated by the 2nd through 4th arguments are applied
933 ** to the first argument in order.  If the pointers returned by the
934 ** second and fourth are different, this routine returns 1.  Otherwise,
935 ** this routine returns 0.
936 **
937 ** This function is used to test to see when returned pointers from
938 ** the _text(), _text16() and _blob() APIs become invalidated.
939 */
940 static void ptrChngFunction(
941   sqlite3_context *context,
942   int argc,
943   sqlite3_value **argv
944 ){
945   const void *p1, *p2;
946   const char *zCmd;
947   if( argc!=4 ) return;
948   zCmd = (const char*)sqlite3_value_text(argv[1]);
949   if( zCmd==0 ) return;
950   if( strcmp(zCmd,"text")==0 ){
951     p1 = (const void*)sqlite3_value_text(argv[0]);
952 #ifndef SQLITE_OMIT_UTF16
953   }else if( strcmp(zCmd, "text16")==0 ){
954     p1 = (const void*)sqlite3_value_text16(argv[0]);
955 #endif
956   }else if( strcmp(zCmd, "blob")==0 ){
957     p1 = (const void*)sqlite3_value_blob(argv[0]);
958   }else{
959     return;
960   }
961   zCmd = (const char*)sqlite3_value_text(argv[2]);
962   if( zCmd==0 ) return;
963   if( strcmp(zCmd,"bytes")==0 ){
964     sqlite3_value_bytes(argv[0]);
965 #ifndef SQLITE_OMIT_UTF16
966   }else if( strcmp(zCmd, "bytes16")==0 ){
967     sqlite3_value_bytes16(argv[0]);
968 #endif
969   }else if( strcmp(zCmd, "noop")==0 ){
970     /* do nothing */
971   }else{
972     return;
973   }
974   zCmd = (const char*)sqlite3_value_text(argv[3]);
975   if( zCmd==0 ) return;
976   if( strcmp(zCmd,"text")==0 ){
977     p2 = (const void*)sqlite3_value_text(argv[0]);
978 #ifndef SQLITE_OMIT_UTF16
979   }else if( strcmp(zCmd, "text16")==0 ){
980     p2 = (const void*)sqlite3_value_text16(argv[0]);
981 #endif
982   }else if( strcmp(zCmd, "blob")==0 ){
983     p2 = (const void*)sqlite3_value_blob(argv[0]);
984   }else{
985     return;
986   }
987   sqlite3_result_int(context, p1!=p2);
988 }
989 
990 
991 /*
992 ** Usage:  sqlite_test_create_function DB
993 **
994 ** Call the sqlite3_create_function API on the given database in order
995 ** to create a function named "x_coalesce".  This function does the same thing
996 ** as the "coalesce" function.  This function also registers an SQL function
997 ** named "x_sqlite_exec" that invokes sqlite3_exec().  Invoking sqlite3_exec()
998 ** in this way is illegal recursion and should raise an SQLITE_MISUSE error.
999 ** The effect is similar to trying to use the same database connection from
1000 ** two threads at the same time.
1001 **
1002 ** The original motivation for this routine was to be able to call the
1003 ** sqlite3_create_function function while a query is in progress in order
1004 ** to test the SQLITE_MISUSE detection logic.
1005 */
1006 static int test_create_function(
1007   void *NotUsed,
1008   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
1009   int argc,              /* Number of arguments */
1010   char **argv            /* Text of each argument */
1011 ){
1012   int rc;
1013   sqlite3 *db;
1014 
1015   if( argc!=2 ){
1016     Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
1017        " DB\"", 0);
1018     return TCL_ERROR;
1019   }
1020   if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
1021   rc = sqlite3_create_function(db, "x_coalesce", -1, SQLITE_ANY, 0,
1022         t1_ifnullFunc, 0, 0);
1023   if( rc==SQLITE_OK ){
1024     rc = sqlite3_create_function(db, "hex8", 1, SQLITE_ANY, 0,
1025           hex8Func, 0, 0);
1026   }
1027 #ifndef SQLITE_OMIT_UTF16
1028   if( rc==SQLITE_OK ){
1029     rc = sqlite3_create_function(db, "hex16", 1, SQLITE_ANY, 0,
1030           hex16Func, 0, 0);
1031   }
1032 #endif
1033   if( rc==SQLITE_OK ){
1034     rc = sqlite3_create_function(db, "tkt2213func", 1, SQLITE_ANY, 0,
1035           tkt2213Function, 0, 0);
1036   }
1037   if( rc==SQLITE_OK ){
1038     rc = sqlite3_create_function(db, "pointer_change", 4, SQLITE_ANY, 0,
1039           ptrChngFunction, 0, 0);
1040   }
1041 
1042 #ifndef SQLITE_OMIT_UTF16
1043   /* Use the sqlite3_create_function16() API here. Mainly for fun, but also
1044   ** because it is not tested anywhere else. */
1045   if( rc==SQLITE_OK ){
1046     const void *zUtf16;
1047     sqlite3_value *pVal;
1048     sqlite3_mutex_enter(db->mutex);
1049     pVal = sqlite3ValueNew(db);
1050     sqlite3ValueSetStr(pVal, -1, "x_sqlite_exec", SQLITE_UTF8, SQLITE_STATIC);
1051     zUtf16 = sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
1052     if( db->mallocFailed ){
1053       rc = SQLITE_NOMEM;
1054     }else{
1055       rc = sqlite3_create_function16(db, zUtf16,
1056                 1, SQLITE_UTF16, db, sqlite3ExecFunc, 0, 0);
1057     }
1058     sqlite3ValueFree(pVal);
1059     sqlite3_mutex_leave(db->mutex);
1060   }
1061 #endif
1062 
1063   if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR;
1064   Tcl_SetResult(interp, (char *)t1ErrorName(rc), 0);
1065   return TCL_OK;
1066 }
1067 
1068 /*
1069 ** Routines to implement the x_count() aggregate function.
1070 **
1071 ** x_count() counts the number of non-null arguments.  But there are
1072 ** some twists for testing purposes.
1073 **
1074 ** If the argument to x_count() is 40 then a UTF-8 error is reported
1075 ** on the step function.  If x_count(41) is seen, then a UTF-16 error
1076 ** is reported on the step function.  If the total count is 42, then
1077 ** a UTF-8 error is reported on the finalize function.
1078 */
1079 typedef struct t1CountCtx t1CountCtx;
1080 struct t1CountCtx {
1081   int n;
1082 };
1083 static void t1CountStep(
1084   sqlite3_context *context,
1085   int argc,
1086   sqlite3_value **argv
1087 ){
1088   t1CountCtx *p;
1089   p = sqlite3_aggregate_context(context, sizeof(*p));
1090   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0]) ) && p ){
1091     p->n++;
1092   }
1093   if( argc>0 ){
1094     int v = sqlite3_value_int(argv[0]);
1095     if( v==40 ){
1096       sqlite3_result_error(context, "value of 40 handed to x_count", -1);
1097 #ifndef SQLITE_OMIT_UTF16
1098     }else if( v==41 ){
1099       const char zUtf16ErrMsg[] = { 0, 0x61, 0, 0x62, 0, 0x63, 0, 0, 0};
1100       sqlite3_result_error16(context, &zUtf16ErrMsg[1-SQLITE_BIGENDIAN], -1);
1101 #endif
1102     }
1103   }
1104 }
1105 static void t1CountFinalize(sqlite3_context *context){
1106   t1CountCtx *p;
1107   p = sqlite3_aggregate_context(context, sizeof(*p));
1108   if( p ){
1109     if( p->n==42 ){
1110       sqlite3_result_error(context, "x_count totals to 42", -1);
1111     }else{
1112       sqlite3_result_int(context, p ? p->n : 0);
1113     }
1114   }
1115 }
1116 
1117 #ifndef SQLITE_OMIT_DEPRECATED
1118 static void legacyCountStep(
1119   sqlite3_context *context,
1120   int argc,
1121   sqlite3_value **argv
1122 ){
1123   /* no-op */
1124 }
1125 
1126 static void legacyCountFinalize(sqlite3_context *context){
1127   sqlite3_result_int(context, sqlite3_aggregate_count(context));
1128 }
1129 #endif
1130 
1131 /*
1132 ** Usage:  sqlite3_create_aggregate DB
1133 **
1134 ** Call the sqlite3_create_function API on the given database in order
1135 ** to create a function named "x_count".  This function is similar
1136 ** to the built-in count() function, with a few special quirks
1137 ** for testing the sqlite3_result_error() APIs.
1138 **
1139 ** The original motivation for this routine was to be able to call the
1140 ** sqlite3_create_aggregate function while a query is in progress in order
1141 ** to test the SQLITE_MISUSE detection logic.  See misuse.test.
1142 **
1143 ** This routine was later extended to test the use of sqlite3_result_error()
1144 ** within aggregate functions.
1145 **
1146 ** Later: It is now also extended to register the aggregate function
1147 ** "legacy_count()" with the supplied database handle. This is used
1148 ** to test the deprecated sqlite3_aggregate_count() API.
1149 */
1150 static int test_create_aggregate(
1151   void *NotUsed,
1152   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
1153   int argc,              /* Number of arguments */
1154   char **argv            /* Text of each argument */
1155 ){
1156   sqlite3 *db;
1157   int rc;
1158   if( argc!=2 ){
1159     Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
1160        " FILENAME\"", 0);
1161     return TCL_ERROR;
1162   }
1163   if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
1164   rc = sqlite3_create_function(db, "x_count", 0, SQLITE_UTF8, 0, 0,
1165       t1CountStep,t1CountFinalize);
1166   if( rc==SQLITE_OK ){
1167     rc = sqlite3_create_function(db, "x_count", 1, SQLITE_UTF8, 0, 0,
1168         t1CountStep,t1CountFinalize);
1169   }
1170 #ifndef SQLITE_OMIT_DEPRECATED
1171   if( rc==SQLITE_OK ){
1172     rc = sqlite3_create_function(db, "legacy_count", 0, SQLITE_ANY, 0, 0,
1173         legacyCountStep, legacyCountFinalize
1174     );
1175   }
1176 #endif
1177   if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR;
1178   Tcl_SetResult(interp, (char *)t1ErrorName(rc), 0);
1179   return TCL_OK;
1180 }
1181 
1182 
1183 /*
1184 ** Usage:  printf TEXT
1185 **
1186 ** Send output to printf.  Use this rather than puts to merge the output
1187 ** in the correct sequence with debugging printfs inserted into C code.
1188 ** Puts uses a separate buffer and debugging statements will be out of
1189 ** sequence if it is used.
1190 */
1191 static int test_printf(
1192   void *NotUsed,
1193   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
1194   int argc,              /* Number of arguments */
1195   char **argv            /* Text of each argument */
1196 ){
1197   if( argc!=2 ){
1198     Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
1199        " TEXT\"", 0);
1200     return TCL_ERROR;
1201   }
1202   printf("%s\n", argv[1]);
1203   return TCL_OK;
1204 }
1205 
1206 
1207 
1208 /*
1209 ** Usage:  sqlite3_mprintf_int FORMAT INTEGER INTEGER INTEGER
1210 **
1211 ** Call mprintf with three integer arguments
1212 */
1213 static int sqlite3_mprintf_int(
1214   void *NotUsed,
1215   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
1216   int argc,              /* Number of arguments */
1217   char **argv            /* Text of each argument */
1218 ){
1219   int a[3], i;
1220   char *z;
1221   if( argc!=5 ){
1222     Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
1223        " FORMAT INT INT INT\"", 0);
1224     return TCL_ERROR;
1225   }
1226   for(i=2; i<5; i++){
1227     if( Tcl_GetInt(interp, argv[i], &a[i-2]) ) return TCL_ERROR;
1228   }
1229   z = sqlite3_mprintf(argv[1], a[0], a[1], a[2]);
1230   Tcl_AppendResult(interp, z, 0);
1231   sqlite3_free(z);
1232   return TCL_OK;
1233 }
1234 
1235 /*
1236 ** Usage:  sqlite3_mprintf_int64 FORMAT INTEGER INTEGER INTEGER
1237 **
1238 ** Call mprintf with three 64-bit integer arguments
1239 */
1240 static int sqlite3_mprintf_int64(
1241   void *NotUsed,
1242   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
1243   int argc,              /* Number of arguments */
1244   char **argv            /* Text of each argument */
1245 ){
1246   int i;
1247   sqlite_int64 a[3];
1248   char *z;
1249   if( argc!=5 ){
1250     Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
1251        " FORMAT INT INT INT\"", 0);
1252     return TCL_ERROR;
1253   }
1254   for(i=2; i<5; i++){
1255     if( sqlite3Atoi64(argv[i], &a[i-2], 1000000, SQLITE_UTF8) ){
1256       Tcl_AppendResult(interp, "argument is not a valid 64-bit integer", 0);
1257       return TCL_ERROR;
1258     }
1259   }
1260   z = sqlite3_mprintf(argv[1], a[0], a[1], a[2]);
1261   Tcl_AppendResult(interp, z, 0);
1262   sqlite3_free(z);
1263   return TCL_OK;
1264 }
1265 
1266 /*
1267 ** Usage:  sqlite3_mprintf_long FORMAT INTEGER INTEGER INTEGER
1268 **
1269 ** Call mprintf with three long integer arguments.   This might be the
1270 ** same as sqlite3_mprintf_int or sqlite3_mprintf_int64, depending on
1271 ** platform.
1272 */
1273 static int sqlite3_mprintf_long(
1274   void *NotUsed,
1275   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
1276   int argc,              /* Number of arguments */
1277   char **argv            /* Text of each argument */
1278 ){
1279   int i;
1280   long int a[3];
1281   int b[3];
1282   char *z;
1283   if( argc!=5 ){
1284     Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
1285        " FORMAT INT INT INT\"", 0);
1286     return TCL_ERROR;
1287   }
1288   for(i=2; i<5; i++){
1289     if( Tcl_GetInt(interp, argv[i], &b[i-2]) ) return TCL_ERROR;
1290     a[i-2] = (long int)b[i-2];
1291     a[i-2] &= (((u64)1)<<(sizeof(int)*8))-1;
1292   }
1293   z = sqlite3_mprintf(argv[1], a[0], a[1], a[2]);
1294   Tcl_AppendResult(interp, z, 0);
1295   sqlite3_free(z);
1296   return TCL_OK;
1297 }
1298 
1299 /*
1300 ** Usage:  sqlite3_mprintf_str FORMAT INTEGER INTEGER STRING
1301 **
1302 ** Call mprintf with two integer arguments and one string argument
1303 */
1304 static int sqlite3_mprintf_str(
1305   void *NotUsed,
1306   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
1307   int argc,              /* Number of arguments */
1308   char **argv            /* Text of each argument */
1309 ){
1310   int a[3], i;
1311   char *z;
1312   if( argc<4 || argc>5 ){
1313     Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
1314        " FORMAT INT INT ?STRING?\"", 0);
1315     return TCL_ERROR;
1316   }
1317   for(i=2; i<4; i++){
1318     if( Tcl_GetInt(interp, argv[i], &a[i-2]) ) return TCL_ERROR;
1319   }
1320   z = sqlite3_mprintf(argv[1], a[0], a[1], argc>4 ? argv[4] : NULL);
1321   Tcl_AppendResult(interp, z, 0);
1322   sqlite3_free(z);
1323   return TCL_OK;
1324 }
1325 
1326 /*
1327 ** Usage:  sqlite3_snprintf_str INTEGER FORMAT INTEGER INTEGER STRING
1328 **
1329 ** Call mprintf with two integer arguments and one string argument
1330 */
1331 static int sqlite3_snprintf_str(
1332   void *NotUsed,
1333   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
1334   int argc,              /* Number of arguments */
1335   char **argv            /* Text of each argument */
1336 ){
1337   int a[3], i;
1338   int n;
1339   char *z;
1340   if( argc<5 || argc>6 ){
1341     Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
1342        " INT FORMAT INT INT ?STRING?\"", 0);
1343     return TCL_ERROR;
1344   }
1345   if( Tcl_GetInt(interp, argv[1], &n) ) return TCL_ERROR;
1346   if( n<0 ){
1347     Tcl_AppendResult(interp, "N must be non-negative", 0);
1348     return TCL_ERROR;
1349   }
1350   for(i=3; i<5; i++){
1351     if( Tcl_GetInt(interp, argv[i], &a[i-3]) ) return TCL_ERROR;
1352   }
1353   z = sqlite3_malloc( n+1 );
1354   sqlite3_snprintf(n, z, argv[2], a[0], a[1], argc>4 ? argv[5] : NULL);
1355   Tcl_AppendResult(interp, z, 0);
1356   sqlite3_free(z);
1357   return TCL_OK;
1358 }
1359 
1360 /*
1361 ** Usage:  sqlite3_mprintf_double FORMAT INTEGER INTEGER DOUBLE
1362 **
1363 ** Call mprintf with two integer arguments and one double argument
1364 */
1365 static int sqlite3_mprintf_double(
1366   void *NotUsed,
1367   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
1368   int argc,              /* Number of arguments */
1369   char **argv            /* Text of each argument */
1370 ){
1371   int a[3], i;
1372   double r;
1373   char *z;
1374   if( argc!=5 ){
1375     Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
1376        " FORMAT INT INT DOUBLE\"", 0);
1377     return TCL_ERROR;
1378   }
1379   for(i=2; i<4; i++){
1380     if( Tcl_GetInt(interp, argv[i], &a[i-2]) ) return TCL_ERROR;
1381   }
1382   if( Tcl_GetDouble(interp, argv[4], &r) ) return TCL_ERROR;
1383   z = sqlite3_mprintf(argv[1], a[0], a[1], r);
1384   Tcl_AppendResult(interp, z, 0);
1385   sqlite3_free(z);
1386   return TCL_OK;
1387 }
1388 
1389 /*
1390 ** Usage:  sqlite3_mprintf_scaled FORMAT DOUBLE DOUBLE
1391 **
1392 ** Call mprintf with a single double argument which is the product of the
1393 ** two arguments given above.  This is used to generate overflow and underflow
1394 ** doubles to test that they are converted properly.
1395 */
1396 static int sqlite3_mprintf_scaled(
1397   void *NotUsed,
1398   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
1399   int argc,              /* Number of arguments */
1400   char **argv            /* Text of each argument */
1401 ){
1402   int i;
1403   double r[2];
1404   char *z;
1405   if( argc!=4 ){
1406     Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
1407        " FORMAT DOUBLE DOUBLE\"", 0);
1408     return TCL_ERROR;
1409   }
1410   for(i=2; i<4; i++){
1411     if( Tcl_GetDouble(interp, argv[i], &r[i-2]) ) return TCL_ERROR;
1412   }
1413   z = sqlite3_mprintf(argv[1], r[0]*r[1]);
1414   Tcl_AppendResult(interp, z, 0);
1415   sqlite3_free(z);
1416   return TCL_OK;
1417 }
1418 
1419 /*
1420 ** Usage:  sqlite3_mprintf_stronly FORMAT STRING
1421 **
1422 ** Call mprintf with a single double argument which is the product of the
1423 ** two arguments given above.  This is used to generate overflow and underflow
1424 ** doubles to test that they are converted properly.
1425 */
1426 static int sqlite3_mprintf_stronly(
1427   void *NotUsed,
1428   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
1429   int argc,              /* Number of arguments */
1430   char **argv            /* Text of each argument */
1431 ){
1432   char *z;
1433   if( argc!=3 ){
1434     Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
1435        " FORMAT STRING\"", 0);
1436     return TCL_ERROR;
1437   }
1438   z = sqlite3_mprintf(argv[1], argv[2]);
1439   Tcl_AppendResult(interp, z, 0);
1440   sqlite3_free(z);
1441   return TCL_OK;
1442 }
1443 
1444 /*
1445 ** Usage:  sqlite3_mprintf_hexdouble FORMAT HEX
1446 **
1447 ** Call mprintf with a single double argument which is derived from the
1448 ** hexadecimal encoding of an IEEE double.
1449 */
1450 static int sqlite3_mprintf_hexdouble(
1451   void *NotUsed,
1452   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
1453   int argc,              /* Number of arguments */
1454   char **argv            /* Text of each argument */
1455 ){
1456   char *z;
1457   double r;
1458   unsigned int x1, x2;
1459   sqlite_uint64 d;
1460   if( argc!=3 ){
1461     Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
1462        " FORMAT STRING\"", 0);
1463     return TCL_ERROR;
1464   }
1465   if( sscanf(argv[2], "%08x%08x", &x2, &x1)!=2 ){
1466     Tcl_AppendResult(interp, "2nd argument should be 16-characters of hex", 0);
1467     return TCL_ERROR;
1468   }
1469   d = x2;
1470   d = (d<<32) + x1;
1471   memcpy(&r, &d, sizeof(r));
1472   z = sqlite3_mprintf(argv[1], r);
1473   Tcl_AppendResult(interp, z, 0);
1474   sqlite3_free(z);
1475   return TCL_OK;
1476 }
1477 
1478 /*
1479 ** Usage: sqlite3_enable_shared_cache ?BOOLEAN?
1480 **
1481 */
1482 #if !defined(SQLITE_OMIT_SHARED_CACHE)
1483 static int test_enable_shared(
1484   ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
1485   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
1486   int objc,              /* Number of arguments */
1487   Tcl_Obj *CONST objv[]  /* Command arguments */
1488 ){
1489   int rc;
1490   int enable;
1491   int ret = 0;
1492 
1493   if( objc!=2 && objc!=1 ){
1494     Tcl_WrongNumArgs(interp, 1, objv, "?BOOLEAN?");
1495     return TCL_ERROR;
1496   }
1497   ret = sqlite3GlobalConfig.sharedCacheEnabled;
1498 
1499   if( objc==2 ){
1500     if( Tcl_GetBooleanFromObj(interp, objv[1], &enable) ){
1501       return TCL_ERROR;
1502     }
1503     rc = sqlite3_enable_shared_cache(enable);
1504     if( rc!=SQLITE_OK ){
1505       Tcl_SetResult(interp, (char *)sqlite3ErrStr(rc), TCL_STATIC);
1506       return TCL_ERROR;
1507     }
1508   }
1509   Tcl_SetObjResult(interp, Tcl_NewBooleanObj(ret));
1510   return TCL_OK;
1511 }
1512 #endif
1513 
1514 
1515 
1516 /*
1517 ** Usage: sqlite3_extended_result_codes   DB    BOOLEAN
1518 **
1519 */
1520 static int test_extended_result_codes(
1521   ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
1522   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
1523   int objc,              /* Number of arguments */
1524   Tcl_Obj *CONST objv[]  /* Command arguments */
1525 ){
1526   int enable;
1527   sqlite3 *db;
1528 
1529   if( objc!=3 ){
1530     Tcl_WrongNumArgs(interp, 1, objv, "DB BOOLEAN");
1531     return TCL_ERROR;
1532   }
1533   if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
1534   if( Tcl_GetBooleanFromObj(interp, objv[2], &enable) ) return TCL_ERROR;
1535   sqlite3_extended_result_codes(db, enable);
1536   return TCL_OK;
1537 }
1538 
1539 /*
1540 ** Usage: sqlite3_libversion_number
1541 **
1542 */
1543 static int test_libversion_number(
1544   ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
1545   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
1546   int objc,              /* Number of arguments */
1547   Tcl_Obj *CONST objv[]  /* Command arguments */
1548 ){
1549   Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_libversion_number()));
1550   return TCL_OK;
1551 }
1552 
1553 /*
1554 ** Usage: sqlite3_table_column_metadata DB dbname tblname colname
1555 **
1556 */
1557 #ifdef SQLITE_ENABLE_COLUMN_METADATA
1558 static int test_table_column_metadata(
1559   ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
1560   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
1561   int objc,              /* Number of arguments */
1562   Tcl_Obj *CONST objv[]  /* Command arguments */
1563 ){
1564   sqlite3 *db;
1565   const char *zDb;
1566   const char *zTbl;
1567   const char *zCol;
1568   int rc;
1569   Tcl_Obj *pRet;
1570 
1571   const char *zDatatype;
1572   const char *zCollseq;
1573   int notnull;
1574   int primarykey;
1575   int autoincrement;
1576 
1577   if( objc!=5 ){
1578     Tcl_WrongNumArgs(interp, 1, objv, "DB dbname tblname colname");
1579     return TCL_ERROR;
1580   }
1581   if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
1582   zDb = Tcl_GetString(objv[2]);
1583   zTbl = Tcl_GetString(objv[3]);
1584   zCol = Tcl_GetString(objv[4]);
1585 
1586   if( strlen(zDb)==0 ) zDb = 0;
1587 
1588   rc = sqlite3_table_column_metadata(db, zDb, zTbl, zCol,
1589       &zDatatype, &zCollseq, &notnull, &primarykey, &autoincrement);
1590 
1591   if( rc!=SQLITE_OK ){
1592     Tcl_AppendResult(interp, sqlite3_errmsg(db), 0);
1593     return TCL_ERROR;
1594   }
1595 
1596   pRet = Tcl_NewObj();
1597   Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zDatatype, -1));
1598   Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zCollseq, -1));
1599   Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(notnull));
1600   Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(primarykey));
1601   Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(autoincrement));
1602   Tcl_SetObjResult(interp, pRet);
1603 
1604   return TCL_OK;
1605 }
1606 #endif
1607 
1608 #ifndef SQLITE_OMIT_INCRBLOB
1609 
1610 static int blobHandleFromObj(
1611   Tcl_Interp *interp,
1612   Tcl_Obj *pObj,
1613   sqlite3_blob **ppBlob
1614 ){
1615   char *z;
1616   int n;
1617 
1618   z = Tcl_GetStringFromObj(pObj, &n);
1619   if( n==0 ){
1620     *ppBlob = 0;
1621   }else{
1622     int notUsed;
1623     Tcl_Channel channel;
1624     ClientData instanceData;
1625 
1626     channel = Tcl_GetChannel(interp, z, &notUsed);
1627     if( !channel ) return TCL_ERROR;
1628 
1629     Tcl_Flush(channel);
1630     Tcl_Seek(channel, 0, SEEK_SET);
1631 
1632     instanceData = Tcl_GetChannelInstanceData(channel);
1633     *ppBlob = *((sqlite3_blob **)instanceData);
1634   }
1635 
1636   return TCL_OK;
1637 }
1638 
1639 /*
1640 ** sqlite3_blob_bytes  CHANNEL
1641 */
1642 static int test_blob_bytes(
1643   ClientData clientData, /* Not used */
1644   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
1645   int objc,              /* Number of arguments */
1646   Tcl_Obj *CONST objv[]  /* Command arguments */
1647 ){
1648   sqlite3_blob *pBlob;
1649   int nByte;
1650 
1651   if( objc!=2 ){
1652     Tcl_WrongNumArgs(interp, 1, objv, "CHANNEL");
1653     return TCL_ERROR;
1654   }
1655 
1656   if( blobHandleFromObj(interp, objv[1], &pBlob) ) return TCL_ERROR;
1657   nByte = sqlite3_blob_bytes(pBlob);
1658   Tcl_SetObjResult(interp, Tcl_NewIntObj(nByte));
1659 
1660   return TCL_OK;
1661 }
1662 
1663 /*
1664 ** sqlite3_blob_close  CHANNEL
1665 */
1666 static int test_blob_close(
1667   ClientData clientData, /* Not used */
1668   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
1669   int objc,              /* Number of arguments */
1670   Tcl_Obj *CONST objv[]  /* Command arguments */
1671 ){
1672   sqlite3_blob *pBlob;
1673 
1674   if( objc!=2 ){
1675     Tcl_WrongNumArgs(interp, 1, objv, "CHANNEL");
1676     return TCL_ERROR;
1677   }
1678 
1679   if( blobHandleFromObj(interp, objv[1], &pBlob) ) return TCL_ERROR;
1680   sqlite3_blob_close(pBlob);
1681 
1682   return TCL_OK;
1683 }
1684 
1685 /*
1686 ** sqlite3_blob_read  CHANNEL OFFSET N
1687 **
1688 **   This command is used to test the sqlite3_blob_read() in ways that
1689 **   the Tcl channel interface does not. The first argument should
1690 **   be the name of a valid channel created by the [incrblob] method
1691 **   of a database handle. This function calls sqlite3_blob_read()
1692 **   to read N bytes from offset OFFSET from the underlying SQLite
1693 **   blob handle.
1694 **
1695 **   On success, a byte-array object containing the read data is
1696 **   returned. On failure, the interpreter result is set to the
1697 **   text representation of the returned error code (i.e. "SQLITE_NOMEM")
1698 **   and a Tcl exception is thrown.
1699 */
1700 static int test_blob_read(
1701   ClientData clientData, /* Not used */
1702   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
1703   int objc,              /* Number of arguments */
1704   Tcl_Obj *CONST objv[]  /* Command arguments */
1705 ){
1706   sqlite3_blob *pBlob;
1707   int nByte;
1708   int iOffset;
1709   unsigned char *zBuf = 0;
1710   int rc;
1711 
1712   if( objc!=4 ){
1713     Tcl_WrongNumArgs(interp, 1, objv, "CHANNEL OFFSET N");
1714     return TCL_ERROR;
1715   }
1716 
1717   if( blobHandleFromObj(interp, objv[1], &pBlob) ) return TCL_ERROR;
1718   if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &iOffset)
1719    || TCL_OK!=Tcl_GetIntFromObj(interp, objv[3], &nByte)
1720   ){
1721     return TCL_ERROR;
1722   }
1723 
1724   if( nByte>0 ){
1725     zBuf = (unsigned char *)Tcl_Alloc(nByte);
1726   }
1727   rc = sqlite3_blob_read(pBlob, zBuf, nByte, iOffset);
1728   if( rc==SQLITE_OK ){
1729     Tcl_SetObjResult(interp, Tcl_NewByteArrayObj(zBuf, nByte));
1730   }else{
1731     Tcl_SetResult(interp, (char *)sqlite3TestErrorName(rc), TCL_VOLATILE);
1732   }
1733   Tcl_Free((char *)zBuf);
1734 
1735   return (rc==SQLITE_OK ? TCL_OK : TCL_ERROR);
1736 }
1737 
1738 /*
1739 ** sqlite3_blob_write CHANNEL OFFSET DATA ?NDATA?
1740 **
1741 **   This command is used to test the sqlite3_blob_write() in ways that
1742 **   the Tcl channel interface does not. The first argument should
1743 **   be the name of a valid channel created by the [incrblob] method
1744 **   of a database handle. This function calls sqlite3_blob_write()
1745 **   to write the DATA byte-array to the underlying SQLite blob handle.
1746 **   at offset OFFSET.
1747 **
1748 **   On success, an empty string is returned. On failure, the interpreter
1749 **   result is set to the text representation of the returned error code
1750 **   (i.e. "SQLITE_NOMEM") and a Tcl exception is thrown.
1751 */
1752 static int test_blob_write(
1753   ClientData clientData, /* Not used */
1754   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
1755   int objc,              /* Number of arguments */
1756   Tcl_Obj *CONST objv[]  /* Command arguments */
1757 ){
1758   sqlite3_blob *pBlob;
1759   int iOffset;
1760   int rc;
1761 
1762   unsigned char *zBuf;
1763   int nBuf;
1764 
1765   if( objc!=4 && objc!=5 ){
1766     Tcl_WrongNumArgs(interp, 1, objv, "CHANNEL OFFSET DATA ?NDATA?");
1767     return TCL_ERROR;
1768   }
1769 
1770   if( blobHandleFromObj(interp, objv[1], &pBlob) ) return TCL_ERROR;
1771   if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &iOffset) ){
1772     return TCL_ERROR;
1773   }
1774 
1775   zBuf = Tcl_GetByteArrayFromObj(objv[3], &nBuf);
1776   if( objc==5 && Tcl_GetIntFromObj(interp, objv[4], &nBuf) ){
1777     return TCL_ERROR;
1778   }
1779   rc = sqlite3_blob_write(pBlob, zBuf, nBuf, iOffset);
1780   if( rc!=SQLITE_OK ){
1781     Tcl_SetResult(interp, (char *)sqlite3TestErrorName(rc), TCL_VOLATILE);
1782   }
1783 
1784   return (rc==SQLITE_OK ? TCL_OK : TCL_ERROR);
1785 }
1786 
1787 static int test_blob_reopen(
1788   ClientData clientData, /* Not used */
1789   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
1790   int objc,              /* Number of arguments */
1791   Tcl_Obj *CONST objv[]  /* Command arguments */
1792 ){
1793   Tcl_WideInt iRowid;
1794   sqlite3_blob *pBlob;
1795   int rc;
1796 
1797   if( objc!=3 ){
1798     Tcl_WrongNumArgs(interp, 1, objv, "CHANNEL ROWID");
1799     return TCL_ERROR;
1800   }
1801 
1802   if( blobHandleFromObj(interp, objv[1], &pBlob) ) return TCL_ERROR;
1803   if( Tcl_GetWideIntFromObj(interp, objv[2], &iRowid) ) return TCL_ERROR;
1804 
1805   rc = sqlite3_blob_reopen(pBlob, iRowid);
1806   if( rc!=SQLITE_OK ){
1807     Tcl_SetResult(interp, (char *)sqlite3TestErrorName(rc), TCL_VOLATILE);
1808   }
1809 
1810   return (rc==SQLITE_OK ? TCL_OK : TCL_ERROR);
1811 }
1812 
1813 #endif
1814 
1815 /*
1816 ** Usage: sqlite3_create_collation_v2 DB-HANDLE NAME CMP-PROC DEL-PROC
1817 **
1818 **   This Tcl proc is used for testing the experimental
1819 **   sqlite3_create_collation_v2() interface.
1820 */
1821 struct TestCollationX {
1822   Tcl_Interp *interp;
1823   Tcl_Obj *pCmp;
1824   Tcl_Obj *pDel;
1825 };
1826 typedef struct TestCollationX TestCollationX;
1827 static void testCreateCollationDel(void *pCtx){
1828   TestCollationX *p = (TestCollationX *)pCtx;
1829 
1830   int rc = Tcl_EvalObjEx(p->interp, p->pDel, TCL_EVAL_DIRECT|TCL_EVAL_GLOBAL);
1831   if( rc!=TCL_OK ){
1832     Tcl_BackgroundError(p->interp);
1833   }
1834 
1835   Tcl_DecrRefCount(p->pCmp);
1836   Tcl_DecrRefCount(p->pDel);
1837   sqlite3_free((void *)p);
1838 }
1839 static int testCreateCollationCmp(
1840   void *pCtx,
1841   int nLeft,
1842   const void *zLeft,
1843   int nRight,
1844   const void *zRight
1845 ){
1846   TestCollationX *p = (TestCollationX *)pCtx;
1847   Tcl_Obj *pScript = Tcl_DuplicateObj(p->pCmp);
1848   int iRes = 0;
1849 
1850   Tcl_IncrRefCount(pScript);
1851   Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj((char *)zLeft, nLeft));
1852   Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj((char *)zRight,nRight));
1853 
1854   if( TCL_OK!=Tcl_EvalObjEx(p->interp, pScript, TCL_EVAL_DIRECT|TCL_EVAL_GLOBAL)
1855    || TCL_OK!=Tcl_GetIntFromObj(p->interp, Tcl_GetObjResult(p->interp), &iRes)
1856   ){
1857     Tcl_BackgroundError(p->interp);
1858   }
1859   Tcl_DecrRefCount(pScript);
1860 
1861   return iRes;
1862 }
1863 static int test_create_collation_v2(
1864   ClientData clientData, /* Not used */
1865   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
1866   int objc,              /* Number of arguments */
1867   Tcl_Obj *CONST objv[]  /* Command arguments */
1868 ){
1869   TestCollationX *p;
1870   sqlite3 *db;
1871   int rc;
1872 
1873   if( objc!=5 ){
1874     Tcl_WrongNumArgs(interp, 1, objv, "DB-HANDLE NAME CMP-PROC DEL-PROC");
1875     return TCL_ERROR;
1876   }
1877   if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
1878 
1879   p = (TestCollationX *)sqlite3_malloc(sizeof(TestCollationX));
1880   p->pCmp = objv[3];
1881   p->pDel = objv[4];
1882   p->interp = interp;
1883   Tcl_IncrRefCount(p->pCmp);
1884   Tcl_IncrRefCount(p->pDel);
1885 
1886   rc = sqlite3_create_collation_v2(db, Tcl_GetString(objv[2]), 16,
1887       (void *)p, testCreateCollationCmp, testCreateCollationDel
1888   );
1889   if( rc!=SQLITE_MISUSE ){
1890     Tcl_AppendResult(interp, "sqlite3_create_collate_v2() failed to detect "
1891       "an invalid encoding", (char*)0);
1892     return TCL_ERROR;
1893   }
1894   rc = sqlite3_create_collation_v2(db, Tcl_GetString(objv[2]), SQLITE_UTF8,
1895       (void *)p, testCreateCollationCmp, testCreateCollationDel
1896   );
1897   return TCL_OK;
1898 }
1899 
1900 /*
1901 ** USAGE: sqlite3_create_function_v2 DB NAME NARG ENC ?SWITCHES?
1902 **
1903 ** Available switches are:
1904 **
1905 **   -func    SCRIPT
1906 **   -step    SCRIPT
1907 **   -final   SCRIPT
1908 **   -destroy SCRIPT
1909 */
1910 typedef struct CreateFunctionV2 CreateFunctionV2;
1911 struct CreateFunctionV2 {
1912   Tcl_Interp *interp;
1913   Tcl_Obj *pFunc;                 /* Script for function invocation */
1914   Tcl_Obj *pStep;                 /* Script for agg. step invocation */
1915   Tcl_Obj *pFinal;                /* Script for agg. finalization invocation */
1916   Tcl_Obj *pDestroy;              /* Destructor script */
1917 };
1918 static void cf2Func(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
1919 }
1920 static void cf2Step(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
1921 }
1922 static void cf2Final(sqlite3_context *ctx){
1923 }
1924 static void cf2Destroy(void *pUser){
1925   CreateFunctionV2 *p = (CreateFunctionV2 *)pUser;
1926 
1927   if( p->interp && p->pDestroy ){
1928     int rc = Tcl_EvalObjEx(p->interp, p->pDestroy, 0);
1929     if( rc!=TCL_OK ) Tcl_BackgroundError(p->interp);
1930   }
1931 
1932   if( p->pFunc ) Tcl_DecrRefCount(p->pFunc);
1933   if( p->pStep ) Tcl_DecrRefCount(p->pStep);
1934   if( p->pFinal ) Tcl_DecrRefCount(p->pFinal);
1935   if( p->pDestroy ) Tcl_DecrRefCount(p->pDestroy);
1936   sqlite3_free(p);
1937 }
1938 static int test_create_function_v2(
1939   ClientData clientData,          /* Not used */
1940   Tcl_Interp *interp,             /* The invoking TCL interpreter */
1941   int objc,                       /* Number of arguments */
1942   Tcl_Obj *CONST objv[]           /* Command arguments */
1943 ){
1944   sqlite3 *db;
1945   const char *zFunc;
1946   int nArg;
1947   int enc;
1948   CreateFunctionV2 *p;
1949   int i;
1950   int rc;
1951 
1952   struct EncTable {
1953     const char *zEnc;
1954     int enc;
1955   } aEnc[] = {
1956     {"utf8",    SQLITE_UTF8 },
1957     {"utf16",   SQLITE_UTF16 },
1958     {"utf16le", SQLITE_UTF16LE },
1959     {"utf16be", SQLITE_UTF16BE },
1960     {"any",     SQLITE_ANY },
1961     {"0", 0 }
1962   };
1963 
1964   if( objc<5 || (objc%2)==0 ){
1965     Tcl_WrongNumArgs(interp, 1, objv, "DB NAME NARG ENC SWITCHES...");
1966     return TCL_ERROR;
1967   }
1968 
1969   if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
1970   zFunc = Tcl_GetString(objv[2]);
1971   if( Tcl_GetIntFromObj(interp, objv[3], &nArg) ) return TCL_ERROR;
1972   if( Tcl_GetIndexFromObjStruct(interp, objv[4], aEnc, sizeof(aEnc[0]),
1973           "encoding", 0, &enc)
1974   ){
1975     return TCL_ERROR;
1976   }
1977   enc = aEnc[enc].enc;
1978 
1979   p = sqlite3_malloc(sizeof(CreateFunctionV2));
1980   assert( p );
1981   memset(p, 0, sizeof(CreateFunctionV2));
1982   p->interp = interp;
1983 
1984   for(i=5; i<objc; i+=2){
1985     int iSwitch;
1986     const char *azSwitch[] = {"-func", "-step", "-final", "-destroy", 0};
1987     if( Tcl_GetIndexFromObj(interp, objv[i], azSwitch, "switch", 0, &iSwitch) ){
1988       sqlite3_free(p);
1989       return TCL_ERROR;
1990     }
1991 
1992     switch( iSwitch ){
1993       case 0: p->pFunc = objv[i+1];      break;
1994       case 1: p->pStep = objv[i+1];      break;
1995       case 2: p->pFinal = objv[i+1];     break;
1996       case 3: p->pDestroy = objv[i+1];   break;
1997     }
1998   }
1999   if( p->pFunc ) p->pFunc = Tcl_DuplicateObj(p->pFunc);
2000   if( p->pStep ) p->pStep = Tcl_DuplicateObj(p->pStep);
2001   if( p->pFinal ) p->pFinal = Tcl_DuplicateObj(p->pFinal);
2002   if( p->pDestroy ) p->pDestroy = Tcl_DuplicateObj(p->pDestroy);
2003 
2004   if( p->pFunc ) Tcl_IncrRefCount(p->pFunc);
2005   if( p->pStep ) Tcl_IncrRefCount(p->pStep);
2006   if( p->pFinal ) Tcl_IncrRefCount(p->pFinal);
2007   if( p->pDestroy ) Tcl_IncrRefCount(p->pDestroy);
2008 
2009   rc = sqlite3_create_function_v2(db, zFunc, nArg, enc, (void *)p,
2010       (p->pFunc ? cf2Func : 0),
2011       (p->pStep ? cf2Step : 0),
2012       (p->pFinal ? cf2Final : 0),
2013       cf2Destroy
2014   );
2015   if( rc!=SQLITE_OK ){
2016     Tcl_ResetResult(interp);
2017     Tcl_AppendResult(interp, sqlite3TestErrorName(rc), 0);
2018     return TCL_ERROR;
2019   }
2020   return TCL_OK;
2021 }
2022 
2023 /*
2024 ** Usage: sqlite3_load_extension DB-HANDLE FILE ?PROC?
2025 */
2026 static int test_load_extension(
2027   ClientData clientData, /* Not used */
2028   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
2029   int objc,              /* Number of arguments */
2030   Tcl_Obj *CONST objv[]  /* Command arguments */
2031 ){
2032   Tcl_CmdInfo cmdInfo;
2033   sqlite3 *db;
2034   int rc;
2035   char *zDb;
2036   char *zFile;
2037   char *zProc = 0;
2038   char *zErr = 0;
2039 
2040   if( objc!=4 && objc!=3 ){
2041     Tcl_WrongNumArgs(interp, 1, objv, "DB-HANDLE FILE ?PROC?");
2042     return TCL_ERROR;
2043   }
2044   zDb = Tcl_GetString(objv[1]);
2045   zFile = Tcl_GetString(objv[2]);
2046   if( objc==4 ){
2047     zProc = Tcl_GetString(objv[3]);
2048   }
2049 
2050   /* Extract the C database handle from the Tcl command name */
2051   if( !Tcl_GetCommandInfo(interp, zDb, &cmdInfo) ){
2052     Tcl_AppendResult(interp, "command not found: ", zDb, (char*)0);
2053     return TCL_ERROR;
2054   }
2055   db = ((struct SqliteDb*)cmdInfo.objClientData)->db;
2056   assert(db);
2057 
2058   /* Call the underlying C function. If an error occurs, set rc to
2059   ** TCL_ERROR and load any error string into the interpreter. If no
2060   ** error occurs, set rc to TCL_OK.
2061   */
2062 #ifdef SQLITE_OMIT_LOAD_EXTENSION
2063   rc = SQLITE_ERROR;
2064   zErr = sqlite3_mprintf("this build omits sqlite3_load_extension()");
2065 #else
2066   rc = sqlite3_load_extension(db, zFile, zProc, &zErr);
2067 #endif
2068   if( rc!=SQLITE_OK ){
2069     Tcl_SetResult(interp, zErr ? zErr : "", TCL_VOLATILE);
2070     rc = TCL_ERROR;
2071   }else{
2072     rc = TCL_OK;
2073   }
2074   sqlite3_free(zErr);
2075 
2076   return rc;
2077 }
2078 
2079 /*
2080 ** Usage: sqlite3_enable_load_extension DB-HANDLE ONOFF
2081 */
2082 static int test_enable_load(
2083   ClientData clientData, /* Not used */
2084   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
2085   int objc,              /* Number of arguments */
2086   Tcl_Obj *CONST objv[]  /* Command arguments */
2087 ){
2088   Tcl_CmdInfo cmdInfo;
2089   sqlite3 *db;
2090   char *zDb;
2091   int onoff;
2092 
2093   if( objc!=3 ){
2094     Tcl_WrongNumArgs(interp, 1, objv, "DB-HANDLE ONOFF");
2095     return TCL_ERROR;
2096   }
2097   zDb = Tcl_GetString(objv[1]);
2098 
2099   /* Extract the C database handle from the Tcl command name */
2100   if( !Tcl_GetCommandInfo(interp, zDb, &cmdInfo) ){
2101     Tcl_AppendResult(interp, "command not found: ", zDb, (char*)0);
2102     return TCL_ERROR;
2103   }
2104   db = ((struct SqliteDb*)cmdInfo.objClientData)->db;
2105   assert(db);
2106 
2107   /* Get the onoff parameter */
2108   if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){
2109     return TCL_ERROR;
2110   }
2111 
2112 #ifdef SQLITE_OMIT_LOAD_EXTENSION
2113   Tcl_AppendResult(interp, "this build omits sqlite3_load_extension()");
2114   return TCL_ERROR;
2115 #else
2116   sqlite3_enable_load_extension(db, onoff);
2117   return TCL_OK;
2118 #endif
2119 }
2120 
2121 /*
2122 ** Usage:  sqlite_abort
2123 **
2124 ** Shutdown the process immediately.  This is not a clean shutdown.
2125 ** This command is used to test the recoverability of a database in
2126 ** the event of a program crash.
2127 */
2128 static int sqlite_abort(
2129   void *NotUsed,
2130   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
2131   int argc,              /* Number of arguments */
2132   char **argv            /* Text of each argument */
2133 ){
2134 #if defined(_MSC_VER)
2135   /* We do this, otherwise the test will halt with a popup message
2136    * that we have to click away before the test will continue.
2137    */
2138   _set_abort_behavior( 0, _CALL_REPORTFAULT );
2139 #endif
2140   exit(255);
2141   assert( interp==0 );   /* This will always fail */
2142   return TCL_OK;
2143 }
2144 
2145 /*
2146 ** The following routine is a user-defined SQL function whose purpose
2147 ** is to test the sqlite_set_result() API.
2148 */
2149 static void testFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
2150   while( argc>=2 ){
2151     const char *zArg0 = (char*)sqlite3_value_text(argv[0]);
2152     if( zArg0 ){
2153       if( 0==sqlite3StrICmp(zArg0, "int") ){
2154         sqlite3_result_int(context, sqlite3_value_int(argv[1]));
2155       }else if( sqlite3StrICmp(zArg0,"int64")==0 ){
2156         sqlite3_result_int64(context, sqlite3_value_int64(argv[1]));
2157       }else if( sqlite3StrICmp(zArg0,"string")==0 ){
2158         sqlite3_result_text(context, (char*)sqlite3_value_text(argv[1]), -1,
2159             SQLITE_TRANSIENT);
2160       }else if( sqlite3StrICmp(zArg0,"double")==0 ){
2161         sqlite3_result_double(context, sqlite3_value_double(argv[1]));
2162       }else if( sqlite3StrICmp(zArg0,"null")==0 ){
2163         sqlite3_result_null(context);
2164       }else if( sqlite3StrICmp(zArg0,"value")==0 ){
2165         sqlite3_result_value(context, argv[sqlite3_value_int(argv[1])]);
2166       }else{
2167         goto error_out;
2168       }
2169     }else{
2170       goto error_out;
2171     }
2172     argc -= 2;
2173     argv += 2;
2174   }
2175   return;
2176 
2177 error_out:
2178   sqlite3_result_error(context,"first argument should be one of: "
2179       "int int64 string double null value", -1);
2180 }
2181 
2182 /*
2183 ** Usage:   sqlite_register_test_function  DB  NAME
2184 **
2185 ** Register the test SQL function on the database DB under the name NAME.
2186 */
2187 static int test_register_func(
2188   void *NotUsed,
2189   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
2190   int argc,              /* Number of arguments */
2191   char **argv            /* Text of each argument */
2192 ){
2193   sqlite3 *db;
2194   int rc;
2195   if( argc!=3 ){
2196     Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
2197        " DB FUNCTION-NAME", 0);
2198     return TCL_ERROR;
2199   }
2200   if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
2201   rc = sqlite3_create_function(db, argv[2], -1, SQLITE_UTF8, 0,
2202       testFunc, 0, 0);
2203   if( rc!=0 ){
2204     Tcl_AppendResult(interp, sqlite3ErrStr(rc), 0);
2205     return TCL_ERROR;
2206   }
2207   if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR;
2208   return TCL_OK;
2209 }
2210 
2211 /*
2212 ** Usage:  sqlite3_finalize  STMT
2213 **
2214 ** Finalize a statement handle.
2215 */
2216 static int test_finalize(
2217   void * clientData,
2218   Tcl_Interp *interp,
2219   int objc,
2220   Tcl_Obj *CONST objv[]
2221 ){
2222   sqlite3_stmt *pStmt;
2223   int rc;
2224   sqlite3 *db = 0;
2225 
2226   if( objc!=2 ){
2227     Tcl_AppendResult(interp, "wrong # args: should be \"",
2228         Tcl_GetStringFromObj(objv[0], 0), " <STMT>", 0);
2229     return TCL_ERROR;
2230   }
2231 
2232   if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
2233 
2234   if( pStmt ){
2235     db = StmtToDb(pStmt);
2236   }
2237   rc = sqlite3_finalize(pStmt);
2238   Tcl_SetResult(interp, (char *)t1ErrorName(rc), TCL_STATIC);
2239   if( db && sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR;
2240   return TCL_OK;
2241 }
2242 
2243 /*
2244 ** Usage:  sqlite3_stmt_status  STMT  CODE  RESETFLAG
2245 **
2246 ** Get the value of a status counter from a statement.
2247 */
2248 static int test_stmt_status(
2249   void * clientData,
2250   Tcl_Interp *interp,
2251   int objc,
2252   Tcl_Obj *CONST objv[]
2253 ){
2254   int iValue;
2255   int i, op, resetFlag;
2256   const char *zOpName;
2257   sqlite3_stmt *pStmt;
2258 
2259   static const struct {
2260     const char *zName;
2261     int op;
2262   } aOp[] = {
2263     { "SQLITE_STMTSTATUS_FULLSCAN_STEP",   SQLITE_STMTSTATUS_FULLSCAN_STEP   },
2264     { "SQLITE_STMTSTATUS_SORT",            SQLITE_STMTSTATUS_SORT            },
2265     { "SQLITE_STMTSTATUS_AUTOINDEX",       SQLITE_STMTSTATUS_AUTOINDEX       },
2266   };
2267   if( objc!=4 ){
2268     Tcl_WrongNumArgs(interp, 1, objv, "STMT PARAMETER RESETFLAG");
2269     return TCL_ERROR;
2270   }
2271   if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
2272   zOpName = Tcl_GetString(objv[2]);
2273   for(i=0; i<ArraySize(aOp); i++){
2274     if( strcmp(aOp[i].zName, zOpName)==0 ){
2275       op = aOp[i].op;
2276       break;
2277     }
2278   }
2279   if( i>=ArraySize(aOp) ){
2280     if( Tcl_GetIntFromObj(interp, objv[2], &op) ) return TCL_ERROR;
2281   }
2282   if( Tcl_GetBooleanFromObj(interp, objv[3], &resetFlag) ) return TCL_ERROR;
2283   iValue = sqlite3_stmt_status(pStmt, op, resetFlag);
2284   Tcl_SetObjResult(interp, Tcl_NewIntObj(iValue));
2285   return TCL_OK;
2286 }
2287 
2288 /*
2289 ** Usage:  sqlite3_next_stmt  DB  STMT
2290 **
2291 ** Return the next statment in sequence after STMT.
2292 */
2293 static int test_next_stmt(
2294   void * clientData,
2295   Tcl_Interp *interp,
2296   int objc,
2297   Tcl_Obj *CONST objv[]
2298 ){
2299   sqlite3_stmt *pStmt;
2300   sqlite3 *db = 0;
2301   char zBuf[50];
2302 
2303   if( objc!=3 ){
2304     Tcl_AppendResult(interp, "wrong # args: should be \"",
2305         Tcl_GetStringFromObj(objv[0], 0), " DB STMT", 0);
2306     return TCL_ERROR;
2307   }
2308 
2309   if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
2310   if( getStmtPointer(interp, Tcl_GetString(objv[2]), &pStmt) ) return TCL_ERROR;
2311   pStmt = sqlite3_next_stmt(db, pStmt);
2312   if( pStmt ){
2313     if( sqlite3TestMakePointerStr(interp, zBuf, pStmt) ) return TCL_ERROR;
2314     Tcl_AppendResult(interp, zBuf, 0);
2315   }
2316   return TCL_OK;
2317 }
2318 
2319 /*
2320 ** Usage:  sqlite3_stmt_readonly  STMT
2321 **
2322 ** Return true if STMT is a NULL pointer or a pointer to a statement
2323 ** that is guaranteed to leave the database unmodified.
2324 */
2325 static int test_stmt_readonly(
2326   void * clientData,
2327   Tcl_Interp *interp,
2328   int objc,
2329   Tcl_Obj *CONST objv[]
2330 ){
2331   sqlite3_stmt *pStmt;
2332   int rc;
2333 
2334   if( objc!=2 ){
2335     Tcl_AppendResult(interp, "wrong # args: should be \"",
2336         Tcl_GetStringFromObj(objv[0], 0), " STMT", 0);
2337     return TCL_ERROR;
2338   }
2339 
2340   if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
2341   rc = sqlite3_stmt_readonly(pStmt);
2342   Tcl_SetObjResult(interp, Tcl_NewBooleanObj(rc));
2343   return TCL_OK;
2344 }
2345 
2346 /*
2347 ** Usage:  sqlite3_stmt_busy  STMT
2348 **
2349 ** Return true if STMT is a non-NULL pointer to a statement
2350 ** that has been stepped but not to completion.
2351 */
2352 static int test_stmt_busy(
2353   void * clientData,
2354   Tcl_Interp *interp,
2355   int objc,
2356   Tcl_Obj *CONST objv[]
2357 ){
2358   sqlite3_stmt *pStmt;
2359   int rc;
2360 
2361   if( objc!=2 ){
2362     Tcl_AppendResult(interp, "wrong # args: should be \"",
2363         Tcl_GetStringFromObj(objv[0], 0), " STMT", 0);
2364     return TCL_ERROR;
2365   }
2366 
2367   if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
2368   rc = sqlite3_stmt_busy(pStmt);
2369   Tcl_SetObjResult(interp, Tcl_NewBooleanObj(rc));
2370   return TCL_OK;
2371 }
2372 
2373 /*
2374 ** Usage:  uses_stmt_journal  STMT
2375 **
2376 ** Return true if STMT uses a statement journal.
2377 */
2378 static int uses_stmt_journal(
2379   void * clientData,
2380   Tcl_Interp *interp,
2381   int objc,
2382   Tcl_Obj *CONST objv[]
2383 ){
2384   sqlite3_stmt *pStmt;
2385 
2386   if( objc!=2 ){
2387     Tcl_AppendResult(interp, "wrong # args: should be \"",
2388         Tcl_GetStringFromObj(objv[0], 0), " STMT", 0);
2389     return TCL_ERROR;
2390   }
2391 
2392   if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
2393   sqlite3_stmt_readonly(pStmt);
2394   Tcl_SetObjResult(interp, Tcl_NewBooleanObj(((Vdbe *)pStmt)->usesStmtJournal));
2395   return TCL_OK;
2396 }
2397 
2398 
2399 /*
2400 ** Usage:  sqlite3_reset  STMT
2401 **
2402 ** Reset a statement handle.
2403 */
2404 static int test_reset(
2405   void * clientData,
2406   Tcl_Interp *interp,
2407   int objc,
2408   Tcl_Obj *CONST objv[]
2409 ){
2410   sqlite3_stmt *pStmt;
2411   int rc;
2412 
2413   if( objc!=2 ){
2414     Tcl_AppendResult(interp, "wrong # args: should be \"",
2415         Tcl_GetStringFromObj(objv[0], 0), " <STMT>", 0);
2416     return TCL_ERROR;
2417   }
2418 
2419   if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
2420 
2421   rc = sqlite3_reset(pStmt);
2422   if( pStmt && sqlite3TestErrCode(interp, StmtToDb(pStmt), rc) ){
2423     return TCL_ERROR;
2424   }
2425   Tcl_SetResult(interp, (char *)t1ErrorName(rc), TCL_STATIC);
2426 /*
2427   if( rc ){
2428     return TCL_ERROR;
2429   }
2430 */
2431   return TCL_OK;
2432 }
2433 
2434 /*
2435 ** Usage:  sqlite3_expired STMT
2436 **
2437 ** Return TRUE if a recompilation of the statement is recommended.
2438 */
2439 static int test_expired(
2440   void * clientData,
2441   Tcl_Interp *interp,
2442   int objc,
2443   Tcl_Obj *CONST objv[]
2444 ){
2445 #ifndef SQLITE_OMIT_DEPRECATED
2446   sqlite3_stmt *pStmt;
2447   if( objc!=2 ){
2448     Tcl_AppendResult(interp, "wrong # args: should be \"",
2449         Tcl_GetStringFromObj(objv[0], 0), " <STMT>", 0);
2450     return TCL_ERROR;
2451   }
2452   if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
2453   Tcl_SetObjResult(interp, Tcl_NewBooleanObj(sqlite3_expired(pStmt)));
2454 #endif
2455   return TCL_OK;
2456 }
2457 
2458 /*
2459 ** Usage:  sqlite3_transfer_bindings FROMSTMT TOSTMT
2460 **
2461 ** Transfer all bindings from FROMSTMT over to TOSTMT
2462 */
2463 static int test_transfer_bind(
2464   void * clientData,
2465   Tcl_Interp *interp,
2466   int objc,
2467   Tcl_Obj *CONST objv[]
2468 ){
2469 #ifndef SQLITE_OMIT_DEPRECATED
2470   sqlite3_stmt *pStmt1, *pStmt2;
2471   if( objc!=3 ){
2472     Tcl_AppendResult(interp, "wrong # args: should be \"",
2473         Tcl_GetStringFromObj(objv[0], 0), " FROM-STMT TO-STMT", 0);
2474     return TCL_ERROR;
2475   }
2476   if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt1)) return TCL_ERROR;
2477   if( getStmtPointer(interp, Tcl_GetString(objv[2]), &pStmt2)) return TCL_ERROR;
2478   Tcl_SetObjResult(interp,
2479      Tcl_NewIntObj(sqlite3_transfer_bindings(pStmt1,pStmt2)));
2480 #endif
2481   return TCL_OK;
2482 }
2483 
2484 /*
2485 ** Usage:  sqlite3_changes DB
2486 **
2487 ** Return the number of changes made to the database by the last SQL
2488 ** execution.
2489 */
2490 static int test_changes(
2491   void * clientData,
2492   Tcl_Interp *interp,
2493   int objc,
2494   Tcl_Obj *CONST objv[]
2495 ){
2496   sqlite3 *db;
2497   if( objc!=2 ){
2498     Tcl_AppendResult(interp, "wrong # args: should be \"",
2499        Tcl_GetString(objv[0]), " DB", 0);
2500     return TCL_ERROR;
2501   }
2502   if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
2503   Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_changes(db)));
2504   return TCL_OK;
2505 }
2506 
2507 /*
2508 ** This is the "static_bind_value" that variables are bound to when
2509 ** the FLAG option of sqlite3_bind is "static"
2510 */
2511 static char *sqlite_static_bind_value = 0;
2512 static int sqlite_static_bind_nbyte = 0;
2513 
2514 /*
2515 ** Usage:  sqlite3_bind  VM  IDX  VALUE  FLAGS
2516 **
2517 ** Sets the value of the IDX-th occurance of "?" in the original SQL
2518 ** string.  VALUE is the new value.  If FLAGS=="null" then VALUE is
2519 ** ignored and the value is set to NULL.  If FLAGS=="static" then
2520 ** the value is set to the value of a static variable named
2521 ** "sqlite_static_bind_value".  If FLAGS=="normal" then a copy
2522 ** of the VALUE is made.  If FLAGS=="blob10" then a VALUE is ignored
2523 ** an a 10-byte blob "abc\000xyz\000pq" is inserted.
2524 */
2525 static int test_bind(
2526   void *NotUsed,
2527   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
2528   int argc,              /* Number of arguments */
2529   char **argv            /* Text of each argument */
2530 ){
2531   sqlite3_stmt *pStmt;
2532   int rc;
2533   int idx;
2534   if( argc!=5 ){
2535     Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
2536        " VM IDX VALUE (null|static|normal)\"", 0);
2537     return TCL_ERROR;
2538   }
2539   if( getStmtPointer(interp, argv[1], &pStmt) ) return TCL_ERROR;
2540   if( Tcl_GetInt(interp, argv[2], &idx) ) return TCL_ERROR;
2541   if( strcmp(argv[4],"null")==0 ){
2542     rc = sqlite3_bind_null(pStmt, idx);
2543   }else if( strcmp(argv[4],"static")==0 ){
2544     rc = sqlite3_bind_text(pStmt, idx, sqlite_static_bind_value, -1, 0);
2545   }else if( strcmp(argv[4],"static-nbytes")==0 ){
2546     rc = sqlite3_bind_text(pStmt, idx, sqlite_static_bind_value,
2547                                        sqlite_static_bind_nbyte, 0);
2548   }else if( strcmp(argv[4],"normal")==0 ){
2549     rc = sqlite3_bind_text(pStmt, idx, argv[3], -1, SQLITE_TRANSIENT);
2550   }else if( strcmp(argv[4],"blob10")==0 ){
2551     rc = sqlite3_bind_text(pStmt, idx, "abc\000xyz\000pq", 10, SQLITE_STATIC);
2552   }else{
2553     Tcl_AppendResult(interp, "4th argument should be "
2554         "\"null\" or \"static\" or \"normal\"", 0);
2555     return TCL_ERROR;
2556   }
2557   if( sqlite3TestErrCode(interp, StmtToDb(pStmt), rc) ) return TCL_ERROR;
2558   if( rc ){
2559     char zBuf[50];
2560     sprintf(zBuf, "(%d) ", rc);
2561     Tcl_AppendResult(interp, zBuf, sqlite3ErrStr(rc), 0);
2562     return TCL_ERROR;
2563   }
2564   return TCL_OK;
2565 }
2566 
2567 #ifndef SQLITE_OMIT_UTF16
2568 /*
2569 ** Usage: add_test_collate <db ptr> <utf8> <utf16le> <utf16be>
2570 **
2571 ** This function is used to test that SQLite selects the correct collation
2572 ** sequence callback when multiple versions (for different text encodings)
2573 ** are available.
2574 **
2575 ** Calling this routine registers the collation sequence "test_collate"
2576 ** with database handle <db>. The second argument must be a list of three
2577 ** boolean values. If the first is true, then a version of test_collate is
2578 ** registered for UTF-8, if the second is true, a version is registered for
2579 ** UTF-16le, if the third is true, a UTF-16be version is available.
2580 ** Previous versions of test_collate are deleted.
2581 **
2582 ** The collation sequence test_collate is implemented by calling the
2583 ** following TCL script:
2584 **
2585 **   "test_collate <enc> <lhs> <rhs>"
2586 **
2587 ** The <lhs> and <rhs> are the two values being compared, encoded in UTF-8.
2588 ** The <enc> parameter is the encoding of the collation function that
2589 ** SQLite selected to call. The TCL test script implements the
2590 ** "test_collate" proc.
2591 **
2592 ** Note that this will only work with one intepreter at a time, as the
2593 ** interp pointer to use when evaluating the TCL script is stored in
2594 ** pTestCollateInterp.
2595 */
2596 static Tcl_Interp* pTestCollateInterp;
2597 static int test_collate_func(
2598   void *pCtx,
2599   int nA, const void *zA,
2600   int nB, const void *zB
2601 ){
2602   Tcl_Interp *i = pTestCollateInterp;
2603   int encin = SQLITE_PTR_TO_INT(pCtx);
2604   int res;
2605   int n;
2606 
2607   sqlite3_value *pVal;
2608   Tcl_Obj *pX;
2609 
2610   pX = Tcl_NewStringObj("test_collate", -1);
2611   Tcl_IncrRefCount(pX);
2612 
2613   switch( encin ){
2614     case SQLITE_UTF8:
2615       Tcl_ListObjAppendElement(i,pX,Tcl_NewStringObj("UTF-8",-1));
2616       break;
2617     case SQLITE_UTF16LE:
2618       Tcl_ListObjAppendElement(i,pX,Tcl_NewStringObj("UTF-16LE",-1));
2619       break;
2620     case SQLITE_UTF16BE:
2621       Tcl_ListObjAppendElement(i,pX,Tcl_NewStringObj("UTF-16BE",-1));
2622       break;
2623     default:
2624       assert(0);
2625   }
2626 
2627   sqlite3BeginBenignMalloc();
2628   pVal = sqlite3ValueNew(0);
2629   if( pVal ){
2630     sqlite3ValueSetStr(pVal, nA, zA, encin, SQLITE_STATIC);
2631     n = sqlite3_value_bytes(pVal);
2632     Tcl_ListObjAppendElement(i,pX,
2633         Tcl_NewStringObj((char*)sqlite3_value_text(pVal),n));
2634     sqlite3ValueSetStr(pVal, nB, zB, encin, SQLITE_STATIC);
2635     n = sqlite3_value_bytes(pVal);
2636     Tcl_ListObjAppendElement(i,pX,
2637         Tcl_NewStringObj((char*)sqlite3_value_text(pVal),n));
2638     sqlite3ValueFree(pVal);
2639   }
2640   sqlite3EndBenignMalloc();
2641 
2642   Tcl_EvalObjEx(i, pX, 0);
2643   Tcl_DecrRefCount(pX);
2644   Tcl_GetIntFromObj(i, Tcl_GetObjResult(i), &res);
2645   return res;
2646 }
2647 static int test_collate(
2648   void * clientData,
2649   Tcl_Interp *interp,
2650   int objc,
2651   Tcl_Obj *CONST objv[]
2652 ){
2653   sqlite3 *db;
2654   int val;
2655   sqlite3_value *pVal;
2656   int rc;
2657 
2658   if( objc!=5 ) goto bad_args;
2659   pTestCollateInterp = interp;
2660   if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
2661 
2662   if( TCL_OK!=Tcl_GetBooleanFromObj(interp, objv[2], &val) ) return TCL_ERROR;
2663   rc = sqlite3_create_collation(db, "test_collate", SQLITE_UTF8,
2664           (void *)SQLITE_UTF8, val?test_collate_func:0);
2665   if( rc==SQLITE_OK ){
2666     const void *zUtf16;
2667     if( TCL_OK!=Tcl_GetBooleanFromObj(interp, objv[3], &val) ) return TCL_ERROR;
2668     rc = sqlite3_create_collation(db, "test_collate", SQLITE_UTF16LE,
2669             (void *)SQLITE_UTF16LE, val?test_collate_func:0);
2670     if( TCL_OK!=Tcl_GetBooleanFromObj(interp, objv[4], &val) ) return TCL_ERROR;
2671 
2672 #if 0
2673     if( sqlite3_iMallocFail>0 ){
2674       sqlite3_iMallocFail++;
2675     }
2676 #endif
2677     sqlite3_mutex_enter(db->mutex);
2678     pVal = sqlite3ValueNew(db);
2679     sqlite3ValueSetStr(pVal, -1, "test_collate", SQLITE_UTF8, SQLITE_STATIC);
2680     zUtf16 = sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
2681     if( db->mallocFailed ){
2682       rc = SQLITE_NOMEM;
2683     }else{
2684       rc = sqlite3_create_collation16(db, zUtf16, SQLITE_UTF16BE,
2685           (void *)SQLITE_UTF16BE, val?test_collate_func:0);
2686     }
2687     sqlite3ValueFree(pVal);
2688     sqlite3_mutex_leave(db->mutex);
2689   }
2690   if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR;
2691 
2692   if( rc!=SQLITE_OK ){
2693     Tcl_AppendResult(interp, sqlite3TestErrorName(rc), 0);
2694     return TCL_ERROR;
2695   }
2696   return TCL_OK;
2697 
2698 bad_args:
2699   Tcl_AppendResult(interp, "wrong # args: should be \"",
2700       Tcl_GetStringFromObj(objv[0], 0), " <DB> <utf8> <utf16le> <utf16be>", 0);
2701   return TCL_ERROR;
2702 }
2703 
2704 /*
2705 ** When the collation needed callback is invoked, record the name of
2706 ** the requested collating function here.  The recorded name is linked
2707 ** to a TCL variable and used to make sure that the requested collation
2708 ** name is correct.
2709 */
2710 static char zNeededCollation[200];
2711 static char *pzNeededCollation = zNeededCollation;
2712 
2713 
2714 /*
2715 ** Called when a collating sequence is needed.  Registered using
2716 ** sqlite3_collation_needed16().
2717 */
2718 static void test_collate_needed_cb(
2719   void *pCtx,
2720   sqlite3 *db,
2721   int eTextRep,
2722   const void *pName
2723 ){
2724   int enc = ENC(db);
2725   int i;
2726   char *z;
2727   for(z = (char*)pName, i=0; *z || z[1]; z++){
2728     if( *z ) zNeededCollation[i++] = *z;
2729   }
2730   zNeededCollation[i] = 0;
2731   sqlite3_create_collation(
2732       db, "test_collate", ENC(db), SQLITE_INT_TO_PTR(enc), test_collate_func);
2733 }
2734 
2735 /*
2736 ** Usage: add_test_collate_needed DB
2737 */
2738 static int test_collate_needed(
2739   void * clientData,
2740   Tcl_Interp *interp,
2741   int objc,
2742   Tcl_Obj *CONST objv[]
2743 ){
2744   sqlite3 *db;
2745   int rc;
2746 
2747   if( objc!=2 ) goto bad_args;
2748   if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
2749   rc = sqlite3_collation_needed16(db, 0, test_collate_needed_cb);
2750   zNeededCollation[0] = 0;
2751   if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR;
2752   return TCL_OK;
2753 
2754 bad_args:
2755   Tcl_WrongNumArgs(interp, 1, objv, "DB");
2756   return TCL_ERROR;
2757 }
2758 
2759 /*
2760 ** tclcmd:   add_alignment_test_collations  DB
2761 **
2762 ** Add two new collating sequences to the database DB
2763 **
2764 **     utf16_aligned
2765 **     utf16_unaligned
2766 **
2767 ** Both collating sequences use the same sort order as BINARY.
2768 ** The only difference is that the utf16_aligned collating
2769 ** sequence is declared with the SQLITE_UTF16_ALIGNED flag.
2770 ** Both collating functions increment the unaligned utf16 counter
2771 ** whenever they see a string that begins on an odd byte boundary.
2772 */
2773 static int unaligned_string_counter = 0;
2774 static int alignmentCollFunc(
2775   void *NotUsed,
2776   int nKey1, const void *pKey1,
2777   int nKey2, const void *pKey2
2778 ){
2779   int rc, n;
2780   n = nKey1<nKey2 ? nKey1 : nKey2;
2781   if( nKey1>0 && 1==(1&(SQLITE_PTR_TO_INT(pKey1))) ) unaligned_string_counter++;
2782   if( nKey2>0 && 1==(1&(SQLITE_PTR_TO_INT(pKey2))) ) unaligned_string_counter++;
2783   rc = memcmp(pKey1, pKey2, n);
2784   if( rc==0 ){
2785     rc = nKey1 - nKey2;
2786   }
2787   return rc;
2788 }
2789 static int add_alignment_test_collations(
2790   void * clientData,
2791   Tcl_Interp *interp,
2792   int objc,
2793   Tcl_Obj *CONST objv[]
2794 ){
2795   sqlite3 *db;
2796   if( objc>=2 ){
2797     if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
2798     sqlite3_create_collation(db, "utf16_unaligned", SQLITE_UTF16,
2799         0, alignmentCollFunc);
2800     sqlite3_create_collation(db, "utf16_aligned", SQLITE_UTF16_ALIGNED,
2801         0, alignmentCollFunc);
2802   }
2803   return SQLITE_OK;
2804 }
2805 #endif /* !defined(SQLITE_OMIT_UTF16) */
2806 
2807 /*
2808 ** Usage: add_test_function <db ptr> <utf8> <utf16le> <utf16be>
2809 **
2810 ** This function is used to test that SQLite selects the correct user
2811 ** function callback when multiple versions (for different text encodings)
2812 ** are available.
2813 **
2814 ** Calling this routine registers up to three versions of the user function
2815 ** "test_function" with database handle <db>.  If the second argument is
2816 ** true, then a version of test_function is registered for UTF-8, if the
2817 ** third is true, a version is registered for UTF-16le, if the fourth is
2818 ** true, a UTF-16be version is available.  Previous versions of
2819 ** test_function are deleted.
2820 **
2821 ** The user function is implemented by calling the following TCL script:
2822 **
2823 **   "test_function <enc> <arg>"
2824 **
2825 ** Where <enc> is one of UTF-8, UTF-16LE or UTF16BE, and <arg> is the
2826 ** single argument passed to the SQL function. The value returned by
2827 ** the TCL script is used as the return value of the SQL function. It
2828 ** is passed to SQLite using UTF-16BE for a UTF-8 test_function(), UTF-8
2829 ** for a UTF-16LE test_function(), and UTF-16LE for an implementation that
2830 ** prefers UTF-16BE.
2831 */
2832 #ifndef SQLITE_OMIT_UTF16
2833 static void test_function_utf8(
2834   sqlite3_context *pCtx,
2835   int nArg,
2836   sqlite3_value **argv
2837 ){
2838   Tcl_Interp *interp;
2839   Tcl_Obj *pX;
2840   sqlite3_value *pVal;
2841   interp = (Tcl_Interp *)sqlite3_user_data(pCtx);
2842   pX = Tcl_NewStringObj("test_function", -1);
2843   Tcl_IncrRefCount(pX);
2844   Tcl_ListObjAppendElement(interp, pX, Tcl_NewStringObj("UTF-8", -1));
2845   Tcl_ListObjAppendElement(interp, pX,
2846       Tcl_NewStringObj((char*)sqlite3_value_text(argv[0]), -1));
2847   Tcl_EvalObjEx(interp, pX, 0);
2848   Tcl_DecrRefCount(pX);
2849   sqlite3_result_text(pCtx, Tcl_GetStringResult(interp), -1, SQLITE_TRANSIENT);
2850   pVal = sqlite3ValueNew(0);
2851   sqlite3ValueSetStr(pVal, -1, Tcl_GetStringResult(interp),
2852       SQLITE_UTF8, SQLITE_STATIC);
2853   sqlite3_result_text16be(pCtx, sqlite3_value_text16be(pVal),
2854       -1, SQLITE_TRANSIENT);
2855   sqlite3ValueFree(pVal);
2856 }
2857 static void test_function_utf16le(
2858   sqlite3_context *pCtx,
2859   int nArg,
2860   sqlite3_value **argv
2861 ){
2862   Tcl_Interp *interp;
2863   Tcl_Obj *pX;
2864   sqlite3_value *pVal;
2865   interp = (Tcl_Interp *)sqlite3_user_data(pCtx);
2866   pX = Tcl_NewStringObj("test_function", -1);
2867   Tcl_IncrRefCount(pX);
2868   Tcl_ListObjAppendElement(interp, pX, Tcl_NewStringObj("UTF-16LE", -1));
2869   Tcl_ListObjAppendElement(interp, pX,
2870       Tcl_NewStringObj((char*)sqlite3_value_text(argv[0]), -1));
2871   Tcl_EvalObjEx(interp, pX, 0);
2872   Tcl_DecrRefCount(pX);
2873   pVal = sqlite3ValueNew(0);
2874   sqlite3ValueSetStr(pVal, -1, Tcl_GetStringResult(interp),
2875       SQLITE_UTF8, SQLITE_STATIC);
2876   sqlite3_result_text(pCtx,(char*)sqlite3_value_text(pVal),-1,SQLITE_TRANSIENT);
2877   sqlite3ValueFree(pVal);
2878 }
2879 static void test_function_utf16be(
2880   sqlite3_context *pCtx,
2881   int nArg,
2882   sqlite3_value **argv
2883 ){
2884   Tcl_Interp *interp;
2885   Tcl_Obj *pX;
2886   sqlite3_value *pVal;
2887   interp = (Tcl_Interp *)sqlite3_user_data(pCtx);
2888   pX = Tcl_NewStringObj("test_function", -1);
2889   Tcl_IncrRefCount(pX);
2890   Tcl_ListObjAppendElement(interp, pX, Tcl_NewStringObj("UTF-16BE", -1));
2891   Tcl_ListObjAppendElement(interp, pX,
2892       Tcl_NewStringObj((char*)sqlite3_value_text(argv[0]), -1));
2893   Tcl_EvalObjEx(interp, pX, 0);
2894   Tcl_DecrRefCount(pX);
2895   pVal = sqlite3ValueNew(0);
2896   sqlite3ValueSetStr(pVal, -1, Tcl_GetStringResult(interp),
2897       SQLITE_UTF8, SQLITE_STATIC);
2898   sqlite3_result_text16(pCtx, sqlite3_value_text16le(pVal),
2899       -1, SQLITE_TRANSIENT);
2900   sqlite3_result_text16be(pCtx, sqlite3_value_text16le(pVal),
2901       -1, SQLITE_TRANSIENT);
2902   sqlite3_result_text16le(pCtx, sqlite3_value_text16le(pVal),
2903       -1, SQLITE_TRANSIENT);
2904   sqlite3ValueFree(pVal);
2905 }
2906 #endif /* SQLITE_OMIT_UTF16 */
2907 static int test_function(
2908   void * clientData,
2909   Tcl_Interp *interp,
2910   int objc,
2911   Tcl_Obj *CONST objv[]
2912 ){
2913 #ifndef SQLITE_OMIT_UTF16
2914   sqlite3 *db;
2915   int val;
2916 
2917   if( objc!=5 ) goto bad_args;
2918   if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
2919 
2920   if( TCL_OK!=Tcl_GetBooleanFromObj(interp, objv[2], &val) ) return TCL_ERROR;
2921   if( val ){
2922     sqlite3_create_function(db, "test_function", 1, SQLITE_UTF8,
2923         interp, test_function_utf8, 0, 0);
2924   }
2925   if( TCL_OK!=Tcl_GetBooleanFromObj(interp, objv[3], &val) ) return TCL_ERROR;
2926   if( val ){
2927     sqlite3_create_function(db, "test_function", 1, SQLITE_UTF16LE,
2928         interp, test_function_utf16le, 0, 0);
2929   }
2930   if( TCL_OK!=Tcl_GetBooleanFromObj(interp, objv[4], &val) ) return TCL_ERROR;
2931   if( val ){
2932     sqlite3_create_function(db, "test_function", 1, SQLITE_UTF16BE,
2933         interp, test_function_utf16be, 0, 0);
2934   }
2935 
2936   return TCL_OK;
2937 bad_args:
2938   Tcl_AppendResult(interp, "wrong # args: should be \"",
2939       Tcl_GetStringFromObj(objv[0], 0), " <DB> <utf8> <utf16le> <utf16be>", 0);
2940 #endif /* SQLITE_OMIT_UTF16 */
2941   return TCL_ERROR;
2942 }
2943 
2944 /*
2945 ** Usage:         sqlite3_test_errstr <err code>
2946 **
2947 ** Test that the english language string equivalents for sqlite error codes
2948 ** are sane. The parameter is an integer representing an sqlite error code.
2949 ** The result is a list of two elements, the string representation of the
2950 ** error code and the english language explanation.
2951 */
2952 static int test_errstr(
2953   void * clientData,
2954   Tcl_Interp *interp,
2955   int objc,
2956   Tcl_Obj *CONST objv[]
2957 ){
2958   char *zCode;
2959   int i;
2960   if( objc!=1 ){
2961     Tcl_WrongNumArgs(interp, 1, objv, "<error code>");
2962   }
2963 
2964   zCode = Tcl_GetString(objv[1]);
2965   for(i=0; i<200; i++){
2966     if( 0==strcmp(t1ErrorName(i), zCode) ) break;
2967   }
2968   Tcl_SetResult(interp, (char *)sqlite3ErrStr(i), 0);
2969   return TCL_OK;
2970 }
2971 
2972 /*
2973 ** Usage:    breakpoint
2974 **
2975 ** This routine exists for one purpose - to provide a place to put a
2976 ** breakpoint with GDB that can be triggered using TCL code.  The use
2977 ** for this is when a particular test fails on (say) the 1485th iteration.
2978 ** In the TCL test script, we can add code like this:
2979 **
2980 **     if {$i==1485} breakpoint
2981 **
2982 ** Then run testfixture in the debugger and wait for the breakpoint to
2983 ** fire.  Then additional breakpoints can be set to trace down the bug.
2984 */
2985 static int test_breakpoint(
2986   void *NotUsed,
2987   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
2988   int argc,              /* Number of arguments */
2989   char **argv            /* Text of each argument */
2990 ){
2991   return TCL_OK;         /* Do nothing */
2992 }
2993 
2994 /*
2995 ** Usage:   sqlite3_bind_zeroblob  STMT IDX N
2996 **
2997 ** Test the sqlite3_bind_zeroblob interface.  STMT is a prepared statement.
2998 ** IDX is the index of a wildcard in the prepared statement.  This command
2999 ** binds a N-byte zero-filled BLOB to the wildcard.
3000 */
3001 static int test_bind_zeroblob(
3002   void * clientData,
3003   Tcl_Interp *interp,
3004   int objc,
3005   Tcl_Obj *CONST objv[]
3006 ){
3007   sqlite3_stmt *pStmt;
3008   int idx;
3009   int n;
3010   int rc;
3011 
3012   if( objc!=4 ){
3013     Tcl_WrongNumArgs(interp, 1, objv, "STMT IDX N");
3014     return TCL_ERROR;
3015   }
3016 
3017   if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
3018   if( Tcl_GetIntFromObj(interp, objv[2], &idx) ) return TCL_ERROR;
3019   if( Tcl_GetIntFromObj(interp, objv[3], &n) ) return TCL_ERROR;
3020 
3021   rc = sqlite3_bind_zeroblob(pStmt, idx, n);
3022   if( sqlite3TestErrCode(interp, StmtToDb(pStmt), rc) ) return TCL_ERROR;
3023   if( rc!=SQLITE_OK ){
3024     return TCL_ERROR;
3025   }
3026 
3027   return TCL_OK;
3028 }
3029 
3030 /*
3031 ** Usage:   sqlite3_bind_int  STMT N VALUE
3032 **
3033 ** Test the sqlite3_bind_int interface.  STMT is a prepared statement.
3034 ** N is the index of a wildcard in the prepared statement.  This command
3035 ** binds a 32-bit integer VALUE to that wildcard.
3036 */
3037 static int test_bind_int(
3038   void * clientData,
3039   Tcl_Interp *interp,
3040   int objc,
3041   Tcl_Obj *CONST objv[]
3042 ){
3043   sqlite3_stmt *pStmt;
3044   int idx;
3045   int value;
3046   int rc;
3047 
3048   if( objc!=4 ){
3049     Tcl_AppendResult(interp, "wrong # args: should be \"",
3050         Tcl_GetStringFromObj(objv[0], 0), " STMT N VALUE", 0);
3051     return TCL_ERROR;
3052   }
3053 
3054   if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
3055   if( Tcl_GetIntFromObj(interp, objv[2], &idx) ) return TCL_ERROR;
3056   if( Tcl_GetIntFromObj(interp, objv[3], &value) ) return TCL_ERROR;
3057 
3058   rc = sqlite3_bind_int(pStmt, idx, value);
3059   if( sqlite3TestErrCode(interp, StmtToDb(pStmt), rc) ) return TCL_ERROR;
3060   if( rc!=SQLITE_OK ){
3061     return TCL_ERROR;
3062   }
3063 
3064   return TCL_OK;
3065 }
3066 
3067 
3068 /*
3069 ** Usage:   sqlite3_bind_int64  STMT N VALUE
3070 **
3071 ** Test the sqlite3_bind_int64 interface.  STMT is a prepared statement.
3072 ** N is the index of a wildcard in the prepared statement.  This command
3073 ** binds a 64-bit integer VALUE to that wildcard.
3074 */
3075 static int test_bind_int64(
3076   void * clientData,
3077   Tcl_Interp *interp,
3078   int objc,
3079   Tcl_Obj *CONST objv[]
3080 ){
3081   sqlite3_stmt *pStmt;
3082   int idx;
3083   Tcl_WideInt value;
3084   int rc;
3085 
3086   if( objc!=4 ){
3087     Tcl_AppendResult(interp, "wrong # args: should be \"",
3088         Tcl_GetStringFromObj(objv[0], 0), " STMT N VALUE", 0);
3089     return TCL_ERROR;
3090   }
3091 
3092   if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
3093   if( Tcl_GetIntFromObj(interp, objv[2], &idx) ) return TCL_ERROR;
3094   if( Tcl_GetWideIntFromObj(interp, objv[3], &value) ) return TCL_ERROR;
3095 
3096   rc = sqlite3_bind_int64(pStmt, idx, value);
3097   if( sqlite3TestErrCode(interp, StmtToDb(pStmt), rc) ) return TCL_ERROR;
3098   if( rc!=SQLITE_OK ){
3099     return TCL_ERROR;
3100   }
3101 
3102   return TCL_OK;
3103 }
3104 
3105 
3106 /*
3107 ** Usage:   sqlite3_bind_double  STMT N VALUE
3108 **
3109 ** Test the sqlite3_bind_double interface.  STMT is a prepared statement.
3110 ** N is the index of a wildcard in the prepared statement.  This command
3111 ** binds a 64-bit integer VALUE to that wildcard.
3112 */
3113 static int test_bind_double(
3114   void * clientData,
3115   Tcl_Interp *interp,
3116   int objc,
3117   Tcl_Obj *CONST objv[]
3118 ){
3119   sqlite3_stmt *pStmt;
3120   int idx;
3121   double value;
3122   int rc;
3123   const char *zVal;
3124   int i;
3125   static const struct {
3126     const char *zName;     /* Name of the special floating point value */
3127     unsigned int iUpper;   /* Upper 32 bits */
3128     unsigned int iLower;   /* Lower 32 bits */
3129   } aSpecialFp[] = {
3130     {  "NaN",      0x7fffffff, 0xffffffff },
3131     {  "SNaN",     0x7ff7ffff, 0xffffffff },
3132     {  "-NaN",     0xffffffff, 0xffffffff },
3133     {  "-SNaN",    0xfff7ffff, 0xffffffff },
3134     {  "+Inf",     0x7ff00000, 0x00000000 },
3135     {  "-Inf",     0xfff00000, 0x00000000 },
3136     {  "Epsilon",  0x00000000, 0x00000001 },
3137     {  "-Epsilon", 0x80000000, 0x00000001 },
3138     {  "NaN0",     0x7ff80000, 0x00000000 },
3139     {  "-NaN0",    0xfff80000, 0x00000000 },
3140   };
3141 
3142   if( objc!=4 ){
3143     Tcl_AppendResult(interp, "wrong # args: should be \"",
3144         Tcl_GetStringFromObj(objv[0], 0), " STMT N VALUE", 0);
3145     return TCL_ERROR;
3146   }
3147 
3148   if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
3149   if( Tcl_GetIntFromObj(interp, objv[2], &idx) ) return TCL_ERROR;
3150 
3151   /* Intercept the string "NaN" and generate a NaN value for it.
3152   ** All other strings are passed through to Tcl_GetDoubleFromObj().
3153   ** Tcl_GetDoubleFromObj() should understand "NaN" but some versions
3154   ** contain a bug.
3155   */
3156   zVal = Tcl_GetString(objv[3]);
3157   for(i=0; i<sizeof(aSpecialFp)/sizeof(aSpecialFp[0]); i++){
3158     if( strcmp(aSpecialFp[i].zName, zVal)==0 ){
3159       sqlite3_uint64 x;
3160       x = aSpecialFp[i].iUpper;
3161       x <<= 32;
3162       x |= aSpecialFp[i].iLower;
3163       assert( sizeof(value)==8 );
3164       assert( sizeof(x)==8 );
3165       memcpy(&value, &x, 8);
3166       break;
3167     }
3168   }
3169   if( i>=sizeof(aSpecialFp)/sizeof(aSpecialFp[0]) &&
3170          Tcl_GetDoubleFromObj(interp, objv[3], &value) ){
3171     return TCL_ERROR;
3172   }
3173   rc = sqlite3_bind_double(pStmt, idx, value);
3174   if( sqlite3TestErrCode(interp, StmtToDb(pStmt), rc) ) return TCL_ERROR;
3175   if( rc!=SQLITE_OK ){
3176     return TCL_ERROR;
3177   }
3178 
3179   return TCL_OK;
3180 }
3181 
3182 /*
3183 ** Usage:   sqlite3_bind_null  STMT N
3184 **
3185 ** Test the sqlite3_bind_null interface.  STMT is a prepared statement.
3186 ** N is the index of a wildcard in the prepared statement.  This command
3187 ** binds a NULL to the wildcard.
3188 */
3189 static int test_bind_null(
3190   void * clientData,
3191   Tcl_Interp *interp,
3192   int objc,
3193   Tcl_Obj *CONST objv[]
3194 ){
3195   sqlite3_stmt *pStmt;
3196   int idx;
3197   int rc;
3198 
3199   if( objc!=3 ){
3200     Tcl_AppendResult(interp, "wrong # args: should be \"",
3201         Tcl_GetStringFromObj(objv[0], 0), " STMT N", 0);
3202     return TCL_ERROR;
3203   }
3204 
3205   if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
3206   if( Tcl_GetIntFromObj(interp, objv[2], &idx) ) return TCL_ERROR;
3207 
3208   rc = sqlite3_bind_null(pStmt, idx);
3209   if( sqlite3TestErrCode(interp, StmtToDb(pStmt), rc) ) return TCL_ERROR;
3210   if( rc!=SQLITE_OK ){
3211     return TCL_ERROR;
3212   }
3213 
3214   return TCL_OK;
3215 }
3216 
3217 /*
3218 ** Usage:   sqlite3_bind_text  STMT N STRING BYTES
3219 **
3220 ** Test the sqlite3_bind_text interface.  STMT is a prepared statement.
3221 ** N is the index of a wildcard in the prepared statement.  This command
3222 ** binds a UTF-8 string STRING to the wildcard.  The string is BYTES bytes
3223 ** long.
3224 */
3225 static int test_bind_text(
3226   void * clientData,
3227   Tcl_Interp *interp,
3228   int objc,
3229   Tcl_Obj *CONST objv[]
3230 ){
3231   sqlite3_stmt *pStmt;
3232   int idx;
3233   int bytes;
3234   char *value;
3235   int rc;
3236 
3237   if( objc!=5 ){
3238     Tcl_AppendResult(interp, "wrong # args: should be \"",
3239         Tcl_GetStringFromObj(objv[0], 0), " STMT N VALUE BYTES", 0);
3240     return TCL_ERROR;
3241   }
3242 
3243   if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
3244   if( Tcl_GetIntFromObj(interp, objv[2], &idx) ) return TCL_ERROR;
3245   value = (char*)Tcl_GetByteArrayFromObj(objv[3], &bytes);
3246   if( Tcl_GetIntFromObj(interp, objv[4], &bytes) ) return TCL_ERROR;
3247 
3248   rc = sqlite3_bind_text(pStmt, idx, value, bytes, SQLITE_TRANSIENT);
3249   if( sqlite3TestErrCode(interp, StmtToDb(pStmt), rc) ) return TCL_ERROR;
3250   if( rc!=SQLITE_OK ){
3251     Tcl_AppendResult(interp, sqlite3TestErrorName(rc), 0);
3252     return TCL_ERROR;
3253   }
3254 
3255   return TCL_OK;
3256 }
3257 
3258 /*
3259 ** Usage:   sqlite3_bind_text16 ?-static? STMT N STRING BYTES
3260 **
3261 ** Test the sqlite3_bind_text16 interface.  STMT is a prepared statement.
3262 ** N is the index of a wildcard in the prepared statement.  This command
3263 ** binds a UTF-16 string STRING to the wildcard.  The string is BYTES bytes
3264 ** long.
3265 */
3266 static int test_bind_text16(
3267   void * clientData,
3268   Tcl_Interp *interp,
3269   int objc,
3270   Tcl_Obj *CONST objv[]
3271 ){
3272 #ifndef SQLITE_OMIT_UTF16
3273   sqlite3_stmt *pStmt;
3274   int idx;
3275   int bytes;
3276   char *value;
3277   int rc;
3278 
3279   void (*xDel)(void*) = (objc==6?SQLITE_STATIC:SQLITE_TRANSIENT);
3280   Tcl_Obj *oStmt    = objv[objc-4];
3281   Tcl_Obj *oN       = objv[objc-3];
3282   Tcl_Obj *oString  = objv[objc-2];
3283   Tcl_Obj *oBytes   = objv[objc-1];
3284 
3285   if( objc!=5 && objc!=6){
3286     Tcl_AppendResult(interp, "wrong # args: should be \"",
3287         Tcl_GetStringFromObj(objv[0], 0), " STMT N VALUE BYTES", 0);
3288     return TCL_ERROR;
3289   }
3290 
3291   if( getStmtPointer(interp, Tcl_GetString(oStmt), &pStmt) ) return TCL_ERROR;
3292   if( Tcl_GetIntFromObj(interp, oN, &idx) ) return TCL_ERROR;
3293   value = (char*)Tcl_GetByteArrayFromObj(oString, 0);
3294   if( Tcl_GetIntFromObj(interp, oBytes, &bytes) ) return TCL_ERROR;
3295 
3296   rc = sqlite3_bind_text16(pStmt, idx, (void *)value, bytes, xDel);
3297   if( sqlite3TestErrCode(interp, StmtToDb(pStmt), rc) ) return TCL_ERROR;
3298   if( rc!=SQLITE_OK ){
3299     Tcl_AppendResult(interp, sqlite3TestErrorName(rc), 0);
3300     return TCL_ERROR;
3301   }
3302 
3303 #endif /* SQLITE_OMIT_UTF16 */
3304   return TCL_OK;
3305 }
3306 
3307 /*
3308 ** Usage:   sqlite3_bind_blob ?-static? STMT N DATA BYTES
3309 **
3310 ** Test the sqlite3_bind_blob interface.  STMT is a prepared statement.
3311 ** N is the index of a wildcard in the prepared statement.  This command
3312 ** binds a BLOB to the wildcard.  The BLOB is BYTES bytes in size.
3313 */
3314 static int test_bind_blob(
3315   void * clientData,
3316   Tcl_Interp *interp,
3317   int objc,
3318   Tcl_Obj *CONST objv[]
3319 ){
3320   sqlite3_stmt *pStmt;
3321   int idx;
3322   int bytes;
3323   char *value;
3324   int rc;
3325   sqlite3_destructor_type xDestructor = SQLITE_TRANSIENT;
3326 
3327   if( objc!=5 && objc!=6 ){
3328     Tcl_AppendResult(interp, "wrong # args: should be \"",
3329         Tcl_GetStringFromObj(objv[0], 0), " STMT N DATA BYTES", 0);
3330     return TCL_ERROR;
3331   }
3332 
3333   if( objc==6 ){
3334     xDestructor = SQLITE_STATIC;
3335     objv++;
3336   }
3337 
3338   if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
3339   if( Tcl_GetIntFromObj(interp, objv[2], &idx) ) return TCL_ERROR;
3340   value = Tcl_GetString(objv[3]);
3341   if( Tcl_GetIntFromObj(interp, objv[4], &bytes) ) return TCL_ERROR;
3342 
3343   rc = sqlite3_bind_blob(pStmt, idx, value, bytes, xDestructor);
3344   if( sqlite3TestErrCode(interp, StmtToDb(pStmt), rc) ) return TCL_ERROR;
3345   if( rc!=SQLITE_OK ){
3346     return TCL_ERROR;
3347   }
3348 
3349   return TCL_OK;
3350 }
3351 
3352 /*
3353 ** Usage:   sqlite3_bind_parameter_count  STMT
3354 **
3355 ** Return the number of wildcards in the given statement.
3356 */
3357 static int test_bind_parameter_count(
3358   void * clientData,
3359   Tcl_Interp *interp,
3360   int objc,
3361   Tcl_Obj *CONST objv[]
3362 ){
3363   sqlite3_stmt *pStmt;
3364 
3365   if( objc!=2 ){
3366     Tcl_WrongNumArgs(interp, 1, objv, "STMT");
3367     return TCL_ERROR;
3368   }
3369   if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
3370   Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_bind_parameter_count(pStmt)));
3371   return TCL_OK;
3372 }
3373 
3374 /*
3375 ** Usage:   sqlite3_bind_parameter_name  STMT  N
3376 **
3377 ** Return the name of the Nth wildcard.  The first wildcard is 1.
3378 ** An empty string is returned if N is out of range or if the wildcard
3379 ** is nameless.
3380 */
3381 static int test_bind_parameter_name(
3382   void * clientData,
3383   Tcl_Interp *interp,
3384   int objc,
3385   Tcl_Obj *CONST objv[]
3386 ){
3387   sqlite3_stmt *pStmt;
3388   int i;
3389 
3390   if( objc!=3 ){
3391     Tcl_WrongNumArgs(interp, 1, objv, "STMT N");
3392     return TCL_ERROR;
3393   }
3394   if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
3395   if( Tcl_GetIntFromObj(interp, objv[2], &i) ) return TCL_ERROR;
3396   Tcl_SetObjResult(interp,
3397      Tcl_NewStringObj(sqlite3_bind_parameter_name(pStmt,i),-1)
3398   );
3399   return TCL_OK;
3400 }
3401 
3402 /*
3403 ** Usage:   sqlite3_bind_parameter_index  STMT  NAME
3404 **
3405 ** Return the index of the wildcard called NAME.  Return 0 if there is
3406 ** no such wildcard.
3407 */
3408 static int test_bind_parameter_index(
3409   void * clientData,
3410   Tcl_Interp *interp,
3411   int objc,
3412   Tcl_Obj *CONST objv[]
3413 ){
3414   sqlite3_stmt *pStmt;
3415 
3416   if( objc!=3 ){
3417     Tcl_WrongNumArgs(interp, 1, objv, "STMT NAME");
3418     return TCL_ERROR;
3419   }
3420   if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
3421   Tcl_SetObjResult(interp,
3422      Tcl_NewIntObj(
3423        sqlite3_bind_parameter_index(pStmt,Tcl_GetString(objv[2]))
3424      )
3425   );
3426   return TCL_OK;
3427 }
3428 
3429 /*
3430 ** Usage:   sqlite3_clear_bindings STMT
3431 **
3432 */
3433 static int test_clear_bindings(
3434   void * clientData,
3435   Tcl_Interp *interp,
3436   int objc,
3437   Tcl_Obj *CONST objv[]
3438 ){
3439   sqlite3_stmt *pStmt;
3440 
3441   if( objc!=2 ){
3442     Tcl_WrongNumArgs(interp, 1, objv, "STMT");
3443     return TCL_ERROR;
3444   }
3445   if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
3446   Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_clear_bindings(pStmt)));
3447   return TCL_OK;
3448 }
3449 
3450 /*
3451 ** Usage:   sqlite3_sleep MILLISECONDS
3452 */
3453 static int test_sleep(
3454   void * clientData,
3455   Tcl_Interp *interp,
3456   int objc,
3457   Tcl_Obj *CONST objv[]
3458 ){
3459   int ms;
3460 
3461   if( objc!=2 ){
3462     Tcl_WrongNumArgs(interp, 1, objv, "MILLISECONDS");
3463     return TCL_ERROR;
3464   }
3465   if( Tcl_GetIntFromObj(interp, objv[1], &ms) ){
3466     return TCL_ERROR;
3467   }
3468   Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_sleep(ms)));
3469   return TCL_OK;
3470 }
3471 
3472 /*
3473 ** Usage: sqlite3_extended_errcode DB
3474 **
3475 ** Return the string representation of the most recent sqlite3_* API
3476 ** error code. e.g. "SQLITE_ERROR".
3477 */
3478 static int test_ex_errcode(
3479   void * clientData,
3480   Tcl_Interp *interp,
3481   int objc,
3482   Tcl_Obj *CONST objv[]
3483 ){
3484   sqlite3 *db;
3485   int rc;
3486 
3487   if( objc!=2 ){
3488     Tcl_AppendResult(interp, "wrong # args: should be \"",
3489        Tcl_GetString(objv[0]), " DB", 0);
3490     return TCL_ERROR;
3491   }
3492   if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
3493   rc = sqlite3_extended_errcode(db);
3494   Tcl_AppendResult(interp, (char *)t1ErrorName(rc), 0);
3495   return TCL_OK;
3496 }
3497 
3498 
3499 /*
3500 ** Usage: sqlite3_errcode DB
3501 **
3502 ** Return the string representation of the most recent sqlite3_* API
3503 ** error code. e.g. "SQLITE_ERROR".
3504 */
3505 static int test_errcode(
3506   void * clientData,
3507   Tcl_Interp *interp,
3508   int objc,
3509   Tcl_Obj *CONST objv[]
3510 ){
3511   sqlite3 *db;
3512   int rc;
3513 
3514   if( objc!=2 ){
3515     Tcl_AppendResult(interp, "wrong # args: should be \"",
3516        Tcl_GetString(objv[0]), " DB", 0);
3517     return TCL_ERROR;
3518   }
3519   if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
3520   rc = sqlite3_errcode(db);
3521   Tcl_AppendResult(interp, (char *)t1ErrorName(rc), 0);
3522   return TCL_OK;
3523 }
3524 
3525 /*
3526 ** Usage:   sqlite3_errmsg DB
3527 **
3528 ** Returns the UTF-8 representation of the error message string for the
3529 ** most recent sqlite3_* API call.
3530 */
3531 static int test_errmsg(
3532   void * clientData,
3533   Tcl_Interp *interp,
3534   int objc,
3535   Tcl_Obj *CONST objv[]
3536 ){
3537   sqlite3 *db;
3538   const char *zErr;
3539 
3540   if( objc!=2 ){
3541     Tcl_AppendResult(interp, "wrong # args: should be \"",
3542        Tcl_GetString(objv[0]), " DB", 0);
3543     return TCL_ERROR;
3544   }
3545   if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
3546 
3547   zErr = sqlite3_errmsg(db);
3548   Tcl_SetObjResult(interp, Tcl_NewStringObj(zErr, -1));
3549   return TCL_OK;
3550 }
3551 
3552 /*
3553 ** Usage:   test_errmsg16 DB
3554 **
3555 ** Returns the UTF-16 representation of the error message string for the
3556 ** most recent sqlite3_* API call. This is a byte array object at the TCL
3557 ** level, and it includes the 0x00 0x00 terminator bytes at the end of the
3558 ** UTF-16 string.
3559 */
3560 static int test_errmsg16(
3561   void * clientData,
3562   Tcl_Interp *interp,
3563   int objc,
3564   Tcl_Obj *CONST objv[]
3565 ){
3566 #ifndef SQLITE_OMIT_UTF16
3567   sqlite3 *db;
3568   const void *zErr;
3569   const char *z;
3570   int bytes = 0;
3571 
3572   if( objc!=2 ){
3573     Tcl_AppendResult(interp, "wrong # args: should be \"",
3574        Tcl_GetString(objv[0]), " DB", 0);
3575     return TCL_ERROR;
3576   }
3577   if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
3578 
3579   zErr = sqlite3_errmsg16(db);
3580   if( zErr ){
3581     z = zErr;
3582     for(bytes=0; z[bytes] || z[bytes+1]; bytes+=2){}
3583   }
3584   Tcl_SetObjResult(interp, Tcl_NewByteArrayObj(zErr, bytes));
3585 #endif /* SQLITE_OMIT_UTF16 */
3586   return TCL_OK;
3587 }
3588 
3589 /*
3590 ** Usage: sqlite3_prepare DB sql bytes ?tailvar?
3591 **
3592 ** Compile up to <bytes> bytes of the supplied SQL string <sql> using
3593 ** database handle <DB>. The parameter <tailval> is the name of a global
3594 ** variable that is set to the unused portion of <sql> (if any). A
3595 ** STMT handle is returned.
3596 */
3597 static int test_prepare(
3598   void * clientData,
3599   Tcl_Interp *interp,
3600   int objc,
3601   Tcl_Obj *CONST objv[]
3602 ){
3603   sqlite3 *db;
3604   const char *zSql;
3605   int bytes;
3606   const char *zTail = 0;
3607   sqlite3_stmt *pStmt = 0;
3608   char zBuf[50];
3609   int rc;
3610 
3611   if( objc!=5 && objc!=4 ){
3612     Tcl_AppendResult(interp, "wrong # args: should be \"",
3613        Tcl_GetString(objv[0]), " DB sql bytes ?tailvar?", 0);
3614     return TCL_ERROR;
3615   }
3616   if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
3617   zSql = Tcl_GetString(objv[2]);
3618   if( Tcl_GetIntFromObj(interp, objv[3], &bytes) ) return TCL_ERROR;
3619 
3620   rc = sqlite3_prepare(db, zSql, bytes, &pStmt, objc>=5 ? &zTail : 0);
3621   Tcl_ResetResult(interp);
3622   if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR;
3623   if( zTail && objc>=5 ){
3624     if( bytes>=0 ){
3625       bytes = bytes - (int)(zTail-zSql);
3626     }
3627     if( (int)strlen(zTail)<bytes ){
3628       bytes = (int)strlen(zTail);
3629     }
3630     Tcl_ObjSetVar2(interp, objv[4], 0, Tcl_NewStringObj(zTail, bytes), 0);
3631   }
3632   if( rc!=SQLITE_OK ){
3633     assert( pStmt==0 );
3634     sprintf(zBuf, "(%d) ", rc);
3635     Tcl_AppendResult(interp, zBuf, sqlite3_errmsg(db), 0);
3636     return TCL_ERROR;
3637   }
3638 
3639   if( pStmt ){
3640     if( sqlite3TestMakePointerStr(interp, zBuf, pStmt) ) return TCL_ERROR;
3641     Tcl_AppendResult(interp, zBuf, 0);
3642   }
3643   return TCL_OK;
3644 }
3645 
3646 /*
3647 ** Usage: sqlite3_prepare_v2 DB sql bytes ?tailvar?
3648 **
3649 ** Compile up to <bytes> bytes of the supplied SQL string <sql> using
3650 ** database handle <DB>. The parameter <tailval> is the name of a global
3651 ** variable that is set to the unused portion of <sql> (if any). A
3652 ** STMT handle is returned.
3653 */
3654 static int test_prepare_v2(
3655   void * clientData,
3656   Tcl_Interp *interp,
3657   int objc,
3658   Tcl_Obj *CONST objv[]
3659 ){
3660   sqlite3 *db;
3661   const char *zSql;
3662   int bytes;
3663   const char *zTail = 0;
3664   sqlite3_stmt *pStmt = 0;
3665   char zBuf[50];
3666   int rc;
3667 
3668   if( objc!=5 && objc!=4 ){
3669     Tcl_AppendResult(interp, "wrong # args: should be \"",
3670        Tcl_GetString(objv[0]), " DB sql bytes tailvar", 0);
3671     return TCL_ERROR;
3672   }
3673   if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
3674   zSql = Tcl_GetString(objv[2]);
3675   if( Tcl_GetIntFromObj(interp, objv[3], &bytes) ) return TCL_ERROR;
3676 
3677   rc = sqlite3_prepare_v2(db, zSql, bytes, &pStmt, objc>=5 ? &zTail : 0);
3678   assert(rc==SQLITE_OK || pStmt==0);
3679   Tcl_ResetResult(interp);
3680   if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR;
3681   if( zTail && objc>=5 ){
3682     if( bytes>=0 ){
3683       bytes = bytes - (int)(zTail-zSql);
3684     }
3685     Tcl_ObjSetVar2(interp, objv[4], 0, Tcl_NewStringObj(zTail, bytes), 0);
3686   }
3687   if( rc!=SQLITE_OK ){
3688     assert( pStmt==0 );
3689     sprintf(zBuf, "(%d) ", rc);
3690     Tcl_AppendResult(interp, zBuf, sqlite3_errmsg(db), 0);
3691     return TCL_ERROR;
3692   }
3693 
3694   if( pStmt ){
3695     if( sqlite3TestMakePointerStr(interp, zBuf, pStmt) ) return TCL_ERROR;
3696     Tcl_AppendResult(interp, zBuf, 0);
3697   }
3698   return TCL_OK;
3699 }
3700 
3701 /*
3702 ** Usage: sqlite3_prepare_tkt3134 DB
3703 **
3704 ** Generate a prepared statement for a zero-byte string as a test
3705 ** for ticket #3134.  The string should be preceeded by a zero byte.
3706 */
3707 static int test_prepare_tkt3134(
3708   void * clientData,
3709   Tcl_Interp *interp,
3710   int objc,
3711   Tcl_Obj *CONST objv[]
3712 ){
3713   sqlite3 *db;
3714   static const char zSql[] = "\000SELECT 1";
3715   sqlite3_stmt *pStmt = 0;
3716   char zBuf[50];
3717   int rc;
3718 
3719   if( objc!=2 ){
3720     Tcl_AppendResult(interp, "wrong # args: should be \"",
3721        Tcl_GetString(objv[0]), " DB sql bytes tailvar", 0);
3722     return TCL_ERROR;
3723   }
3724   if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
3725   rc = sqlite3_prepare_v2(db, &zSql[1], 0, &pStmt, 0);
3726   assert(rc==SQLITE_OK || pStmt==0);
3727   if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR;
3728   if( rc!=SQLITE_OK ){
3729     assert( pStmt==0 );
3730     sprintf(zBuf, "(%d) ", rc);
3731     Tcl_AppendResult(interp, zBuf, sqlite3_errmsg(db), 0);
3732     return TCL_ERROR;
3733   }
3734 
3735   if( pStmt ){
3736     if( sqlite3TestMakePointerStr(interp, zBuf, pStmt) ) return TCL_ERROR;
3737     Tcl_AppendResult(interp, zBuf, 0);
3738   }
3739   return TCL_OK;
3740 }
3741 
3742 /*
3743 ** Usage: sqlite3_prepare16 DB sql bytes tailvar
3744 **
3745 ** Compile up to <bytes> bytes of the supplied SQL string <sql> using
3746 ** database handle <DB>. The parameter <tailval> is the name of a global
3747 ** variable that is set to the unused portion of <sql> (if any). A
3748 ** STMT handle is returned.
3749 */
3750 static int test_prepare16(
3751   void * clientData,
3752   Tcl_Interp *interp,
3753   int objc,
3754   Tcl_Obj *CONST objv[]
3755 ){
3756 #ifndef SQLITE_OMIT_UTF16
3757   sqlite3 *db;
3758   const void *zSql;
3759   const void *zTail = 0;
3760   Tcl_Obj *pTail = 0;
3761   sqlite3_stmt *pStmt = 0;
3762   char zBuf[50];
3763   int rc;
3764   int bytes;                /* The integer specified as arg 3 */
3765   int objlen;               /* The byte-array length of arg 2 */
3766 
3767   if( objc!=5 && objc!=4 ){
3768     Tcl_AppendResult(interp, "wrong # args: should be \"",
3769        Tcl_GetString(objv[0]), " DB sql bytes ?tailvar?", 0);
3770     return TCL_ERROR;
3771   }
3772   if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
3773   zSql = Tcl_GetByteArrayFromObj(objv[2], &objlen);
3774   if( Tcl_GetIntFromObj(interp, objv[3], &bytes) ) return TCL_ERROR;
3775 
3776   rc = sqlite3_prepare16(db, zSql, bytes, &pStmt, objc>=5 ? &zTail : 0);
3777   if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR;
3778   if( rc ){
3779     return TCL_ERROR;
3780   }
3781 
3782   if( objc>=5 ){
3783     if( zTail ){
3784       objlen = objlen - (int)((u8 *)zTail-(u8 *)zSql);
3785     }else{
3786       objlen = 0;
3787     }
3788     pTail = Tcl_NewByteArrayObj((u8 *)zTail, objlen);
3789     Tcl_IncrRefCount(pTail);
3790     Tcl_ObjSetVar2(interp, objv[4], 0, pTail, 0);
3791     Tcl_DecrRefCount(pTail);
3792   }
3793 
3794   if( pStmt ){
3795     if( sqlite3TestMakePointerStr(interp, zBuf, pStmt) ) return TCL_ERROR;
3796   }
3797   Tcl_AppendResult(interp, zBuf, 0);
3798 #endif /* SQLITE_OMIT_UTF16 */
3799   return TCL_OK;
3800 }
3801 
3802 /*
3803 ** Usage: sqlite3_prepare16_v2 DB sql bytes ?tailvar?
3804 **
3805 ** Compile up to <bytes> bytes of the supplied SQL string <sql> using
3806 ** database handle <DB>. The parameter <tailval> is the name of a global
3807 ** variable that is set to the unused portion of <sql> (if any). A
3808 ** STMT handle is returned.
3809 */
3810 static int test_prepare16_v2(
3811   void * clientData,
3812   Tcl_Interp *interp,
3813   int objc,
3814   Tcl_Obj *CONST objv[]
3815 ){
3816 #ifndef SQLITE_OMIT_UTF16
3817   sqlite3 *db;
3818   const void *zSql;
3819   const void *zTail = 0;
3820   Tcl_Obj *pTail = 0;
3821   sqlite3_stmt *pStmt = 0;
3822   char zBuf[50];
3823   int rc;
3824   int bytes;                /* The integer specified as arg 3 */
3825   int objlen;               /* The byte-array length of arg 2 */
3826 
3827   if( objc!=5 && objc!=4 ){
3828     Tcl_AppendResult(interp, "wrong # args: should be \"",
3829        Tcl_GetString(objv[0]), " DB sql bytes ?tailvar?", 0);
3830     return TCL_ERROR;
3831   }
3832   if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
3833   zSql = Tcl_GetByteArrayFromObj(objv[2], &objlen);
3834   if( Tcl_GetIntFromObj(interp, objv[3], &bytes) ) return TCL_ERROR;
3835 
3836   rc = sqlite3_prepare16_v2(db, zSql, bytes, &pStmt, objc>=5 ? &zTail : 0);
3837   if( sqlite3TestErrCode(interp, db, rc) ) return TCL_ERROR;
3838   if( rc ){
3839     return TCL_ERROR;
3840   }
3841 
3842   if( objc>=5 ){
3843     if( zTail ){
3844       objlen = objlen - (int)((u8 *)zTail-(u8 *)zSql);
3845     }else{
3846       objlen = 0;
3847     }
3848     pTail = Tcl_NewByteArrayObj((u8 *)zTail, objlen);
3849     Tcl_IncrRefCount(pTail);
3850     Tcl_ObjSetVar2(interp, objv[4], 0, pTail, 0);
3851     Tcl_DecrRefCount(pTail);
3852   }
3853 
3854   if( pStmt ){
3855     if( sqlite3TestMakePointerStr(interp, zBuf, pStmt) ) return TCL_ERROR;
3856   }
3857   Tcl_AppendResult(interp, zBuf, 0);
3858 #endif /* SQLITE_OMIT_UTF16 */
3859   return TCL_OK;
3860 }
3861 
3862 /*
3863 ** Usage: sqlite3_open filename ?options-list?
3864 */
3865 static int test_open(
3866   void * clientData,
3867   Tcl_Interp *interp,
3868   int objc,
3869   Tcl_Obj *CONST objv[]
3870 ){
3871   const char *zFilename;
3872   sqlite3 *db;
3873   char zBuf[100];
3874 
3875   if( objc!=3 && objc!=2 && objc!=1 ){
3876     Tcl_AppendResult(interp, "wrong # args: should be \"",
3877        Tcl_GetString(objv[0]), " filename options-list", 0);
3878     return TCL_ERROR;
3879   }
3880 
3881   zFilename = objc>1 ? Tcl_GetString(objv[1]) : 0;
3882   sqlite3_open(zFilename, &db);
3883 
3884   if( sqlite3TestMakePointerStr(interp, zBuf, db) ) return TCL_ERROR;
3885   Tcl_AppendResult(interp, zBuf, 0);
3886   return TCL_OK;
3887 }
3888 
3889 /*
3890 ** Usage: sqlite3_open_v2 FILENAME FLAGS VFS
3891 */
3892 static int test_open_v2(
3893   void * clientData,
3894   Tcl_Interp *interp,
3895   int objc,
3896   Tcl_Obj *CONST objv[]
3897 ){
3898   const char *zFilename;
3899   const char *zVfs;
3900   int flags = 0;
3901   sqlite3 *db;
3902   int rc;
3903   char zBuf[100];
3904 
3905   int nFlag;
3906   Tcl_Obj **apFlag;
3907   int i;
3908 
3909   if( objc!=4 ){
3910     Tcl_WrongNumArgs(interp, 1, objv, "FILENAME FLAGS VFS");
3911     return TCL_ERROR;
3912   }
3913   zFilename = Tcl_GetString(objv[1]);
3914   zVfs = Tcl_GetString(objv[3]);
3915   if( zVfs[0]==0x00 ) zVfs = 0;
3916 
3917   rc = Tcl_ListObjGetElements(interp, objv[2], &nFlag, &apFlag);
3918   if( rc!=TCL_OK ) return rc;
3919   for(i=0; i<nFlag; i++){
3920     int iFlag;
3921     struct OpenFlag {
3922       const char *zFlag;
3923       int flag;
3924     } aFlag[] = {
3925       { "SQLITE_OPEN_READONLY", SQLITE_OPEN_READONLY },
3926       { "SQLITE_OPEN_READWRITE", SQLITE_OPEN_READWRITE },
3927       { "SQLITE_OPEN_CREATE", SQLITE_OPEN_CREATE },
3928       { "SQLITE_OPEN_DELETEONCLOSE", SQLITE_OPEN_DELETEONCLOSE },
3929       { "SQLITE_OPEN_EXCLUSIVE", SQLITE_OPEN_EXCLUSIVE },
3930       { "SQLITE_OPEN_AUTOPROXY", SQLITE_OPEN_AUTOPROXY },
3931       { "SQLITE_OPEN_MAIN_DB", SQLITE_OPEN_MAIN_DB },
3932       { "SQLITE_OPEN_TEMP_DB", SQLITE_OPEN_TEMP_DB },
3933       { "SQLITE_OPEN_TRANSIENT_DB", SQLITE_OPEN_TRANSIENT_DB },
3934       { "SQLITE_OPEN_MAIN_JOURNAL", SQLITE_OPEN_MAIN_JOURNAL },
3935       { "SQLITE_OPEN_TEMP_JOURNAL", SQLITE_OPEN_TEMP_JOURNAL },
3936       { "SQLITE_OPEN_SUBJOURNAL", SQLITE_OPEN_SUBJOURNAL },
3937       { "SQLITE_OPEN_MASTER_JOURNAL", SQLITE_OPEN_MASTER_JOURNAL },
3938       { "SQLITE_OPEN_NOMUTEX", SQLITE_OPEN_NOMUTEX },
3939       { "SQLITE_OPEN_FULLMUTEX", SQLITE_OPEN_FULLMUTEX },
3940       { "SQLITE_OPEN_SHAREDCACHE", SQLITE_OPEN_SHAREDCACHE },
3941       { "SQLITE_OPEN_PRIVATECACHE", SQLITE_OPEN_PRIVATECACHE },
3942       { "SQLITE_OPEN_WAL", SQLITE_OPEN_WAL },
3943       { "SQLITE_OPEN_URI", SQLITE_OPEN_URI },
3944       { 0, 0 }
3945     };
3946     rc = Tcl_GetIndexFromObjStruct(interp, apFlag[i], aFlag, sizeof(aFlag[0]),
3947         "flag", 0, &iFlag
3948     );
3949     if( rc!=TCL_OK ) return rc;
3950     flags |= aFlag[iFlag].flag;
3951   }
3952 
3953   rc = sqlite3_open_v2(zFilename, &db, flags, zVfs);
3954   if( sqlite3TestMakePointerStr(interp, zBuf, db) ) return TCL_ERROR;
3955   Tcl_AppendResult(interp, zBuf, 0);
3956   return TCL_OK;
3957 }
3958 
3959 /*
3960 ** Usage: sqlite3_open16 filename options
3961 */
3962 static int test_open16(
3963   void * clientData,
3964   Tcl_Interp *interp,
3965   int objc,
3966   Tcl_Obj *CONST objv[]
3967 ){
3968 #ifndef SQLITE_OMIT_UTF16
3969   const void *zFilename;
3970   sqlite3 *db;
3971   char zBuf[100];
3972 
3973   if( objc!=3 ){
3974     Tcl_AppendResult(interp, "wrong # args: should be \"",
3975        Tcl_GetString(objv[0]), " filename options-list", 0);
3976     return TCL_ERROR;
3977   }
3978 
3979   zFilename = Tcl_GetByteArrayFromObj(objv[1], 0);
3980   sqlite3_open16(zFilename, &db);
3981 
3982   if( sqlite3TestMakePointerStr(interp, zBuf, db) ) return TCL_ERROR;
3983   Tcl_AppendResult(interp, zBuf, 0);
3984 #endif /* SQLITE_OMIT_UTF16 */
3985   return TCL_OK;
3986 }
3987 
3988 /*
3989 ** Usage: sqlite3_complete16 <UTF-16 string>
3990 **
3991 ** Return 1 if the supplied argument is a complete SQL statement, or zero
3992 ** otherwise.
3993 */
3994 static int test_complete16(
3995   void * clientData,
3996   Tcl_Interp *interp,
3997   int objc,
3998   Tcl_Obj *CONST objv[]
3999 ){
4000 #if !defined(SQLITE_OMIT_COMPLETE) && !defined(SQLITE_OMIT_UTF16)
4001   char *zBuf;
4002 
4003   if( objc!=2 ){
4004     Tcl_WrongNumArgs(interp, 1, objv, "<utf-16 sql>");
4005     return TCL_ERROR;
4006   }
4007 
4008   zBuf = (char*)Tcl_GetByteArrayFromObj(objv[1], 0);
4009   Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_complete16(zBuf)));
4010 #endif /* SQLITE_OMIT_COMPLETE && SQLITE_OMIT_UTF16 */
4011   return TCL_OK;
4012 }
4013 
4014 /*
4015 ** Usage: sqlite3_step STMT
4016 **
4017 ** Advance the statement to the next row.
4018 */
4019 static int test_step(
4020   void * clientData,
4021   Tcl_Interp *interp,
4022   int objc,
4023   Tcl_Obj *CONST objv[]
4024 ){
4025   sqlite3_stmt *pStmt;
4026   int rc;
4027 
4028   if( objc!=2 ){
4029     Tcl_AppendResult(interp, "wrong # args: should be \"",
4030        Tcl_GetString(objv[0]), " STMT", 0);
4031     return TCL_ERROR;
4032   }
4033 
4034   if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
4035   rc = sqlite3_step(pStmt);
4036 
4037   /* if( rc!=SQLITE_DONE && rc!=SQLITE_ROW ) return TCL_ERROR; */
4038   Tcl_SetResult(interp, (char *)t1ErrorName(rc), 0);
4039   return TCL_OK;
4040 }
4041 
4042 static int test_sql(
4043   void * clientData,
4044   Tcl_Interp *interp,
4045   int objc,
4046   Tcl_Obj *CONST objv[]
4047 ){
4048   sqlite3_stmt *pStmt;
4049 
4050   if( objc!=2 ){
4051     Tcl_WrongNumArgs(interp, 1, objv, "STMT");
4052     return TCL_ERROR;
4053   }
4054 
4055   if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
4056   Tcl_SetResult(interp, (char *)sqlite3_sql(pStmt), TCL_VOLATILE);
4057   return TCL_OK;
4058 }
4059 
4060 /*
4061 ** Usage: sqlite3_column_count STMT
4062 **
4063 ** Return the number of columns returned by the sql statement STMT.
4064 */
4065 static int test_column_count(
4066   void * clientData,
4067   Tcl_Interp *interp,
4068   int objc,
4069   Tcl_Obj *CONST objv[]
4070 ){
4071   sqlite3_stmt *pStmt;
4072 
4073   if( objc!=2 ){
4074     Tcl_AppendResult(interp, "wrong # args: should be \"",
4075        Tcl_GetString(objv[0]), " STMT column", 0);
4076     return TCL_ERROR;
4077   }
4078 
4079   if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
4080 
4081   Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_column_count(pStmt)));
4082   return TCL_OK;
4083 }
4084 
4085 /*
4086 ** Usage: sqlite3_column_type STMT column
4087 **
4088 ** Return the type of the data in column 'column' of the current row.
4089 */
4090 static int test_column_type(
4091   void * clientData,
4092   Tcl_Interp *interp,
4093   int objc,
4094   Tcl_Obj *CONST objv[]
4095 ){
4096   sqlite3_stmt *pStmt;
4097   int col;
4098   int tp;
4099 
4100   if( objc!=3 ){
4101     Tcl_AppendResult(interp, "wrong # args: should be \"",
4102        Tcl_GetString(objv[0]), " STMT column", 0);
4103     return TCL_ERROR;
4104   }
4105 
4106   if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
4107   if( Tcl_GetIntFromObj(interp, objv[2], &col) ) return TCL_ERROR;
4108 
4109   tp = sqlite3_column_type(pStmt, col);
4110   switch( tp ){
4111     case SQLITE_INTEGER:
4112       Tcl_SetResult(interp, "INTEGER", TCL_STATIC);
4113       break;
4114     case SQLITE_NULL:
4115       Tcl_SetResult(interp, "NULL", TCL_STATIC);
4116       break;
4117     case SQLITE_FLOAT:
4118       Tcl_SetResult(interp, "FLOAT", TCL_STATIC);
4119       break;
4120     case SQLITE_TEXT:
4121       Tcl_SetResult(interp, "TEXT", TCL_STATIC);
4122       break;
4123     case SQLITE_BLOB:
4124       Tcl_SetResult(interp, "BLOB", TCL_STATIC);
4125       break;
4126     default:
4127       assert(0);
4128   }
4129 
4130   return TCL_OK;
4131 }
4132 
4133 /*
4134 ** Usage: sqlite3_column_int64 STMT column
4135 **
4136 ** Return the data in column 'column' of the current row cast as an
4137 ** wide (64-bit) integer.
4138 */
4139 static int test_column_int64(
4140   void * clientData,
4141   Tcl_Interp *interp,
4142   int objc,
4143   Tcl_Obj *CONST objv[]
4144 ){
4145   sqlite3_stmt *pStmt;
4146   int col;
4147   i64 iVal;
4148 
4149   if( objc!=3 ){
4150     Tcl_AppendResult(interp, "wrong # args: should be \"",
4151        Tcl_GetString(objv[0]), " STMT column", 0);
4152     return TCL_ERROR;
4153   }
4154 
4155   if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
4156   if( Tcl_GetIntFromObj(interp, objv[2], &col) ) return TCL_ERROR;
4157 
4158   iVal = sqlite3_column_int64(pStmt, col);
4159   Tcl_SetObjResult(interp, Tcl_NewWideIntObj(iVal));
4160   return TCL_OK;
4161 }
4162 
4163 /*
4164 ** Usage: sqlite3_column_blob STMT column
4165 */
4166 static int test_column_blob(
4167   void * clientData,
4168   Tcl_Interp *interp,
4169   int objc,
4170   Tcl_Obj *CONST objv[]
4171 ){
4172   sqlite3_stmt *pStmt;
4173   int col;
4174 
4175   int len;
4176   const void *pBlob;
4177 
4178   if( objc!=3 ){
4179     Tcl_AppendResult(interp, "wrong # args: should be \"",
4180        Tcl_GetString(objv[0]), " STMT column", 0);
4181     return TCL_ERROR;
4182   }
4183 
4184   if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
4185   if( Tcl_GetIntFromObj(interp, objv[2], &col) ) return TCL_ERROR;
4186 
4187   len = sqlite3_column_bytes(pStmt, col);
4188   pBlob = sqlite3_column_blob(pStmt, col);
4189   Tcl_SetObjResult(interp, Tcl_NewByteArrayObj(pBlob, len));
4190   return TCL_OK;
4191 }
4192 
4193 /*
4194 ** Usage: sqlite3_column_double STMT column
4195 **
4196 ** Return the data in column 'column' of the current row cast as a double.
4197 */
4198 static int test_column_double(
4199   void * clientData,
4200   Tcl_Interp *interp,
4201   int objc,
4202   Tcl_Obj *CONST objv[]
4203 ){
4204   sqlite3_stmt *pStmt;
4205   int col;
4206   double rVal;
4207 
4208   if( objc!=3 ){
4209     Tcl_AppendResult(interp, "wrong # args: should be \"",
4210        Tcl_GetString(objv[0]), " STMT column", 0);
4211     return TCL_ERROR;
4212   }
4213 
4214   if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
4215   if( Tcl_GetIntFromObj(interp, objv[2], &col) ) return TCL_ERROR;
4216 
4217   rVal = sqlite3_column_double(pStmt, col);
4218   Tcl_SetObjResult(interp, Tcl_NewDoubleObj(rVal));
4219   return TCL_OK;
4220 }
4221 
4222 /*
4223 ** Usage: sqlite3_data_count STMT
4224 **
4225 ** Return the number of columns returned by the sql statement STMT.
4226 */
4227 static int test_data_count(
4228   void * clientData,
4229   Tcl_Interp *interp,
4230   int objc,
4231   Tcl_Obj *CONST objv[]
4232 ){
4233   sqlite3_stmt *pStmt;
4234 
4235   if( objc!=2 ){
4236     Tcl_AppendResult(interp, "wrong # args: should be \"",
4237        Tcl_GetString(objv[0]), " STMT column", 0);
4238     return TCL_ERROR;
4239   }
4240 
4241   if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
4242 
4243   Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_data_count(pStmt)));
4244   return TCL_OK;
4245 }
4246 
4247 /*
4248 ** Usage: sqlite3_column_text STMT column
4249 **
4250 ** Usage: sqlite3_column_decltype STMT column
4251 **
4252 ** Usage: sqlite3_column_name STMT column
4253 */
4254 static int test_stmt_utf8(
4255   void * clientData,        /* Pointer to SQLite API function to be invoke */
4256   Tcl_Interp *interp,
4257   int objc,
4258   Tcl_Obj *CONST objv[]
4259 ){
4260   sqlite3_stmt *pStmt;
4261   int col;
4262   const char *(*xFunc)(sqlite3_stmt*, int);
4263   const char *zRet;
4264 
4265   xFunc = (const char *(*)(sqlite3_stmt*, int))clientData;
4266   if( objc!=3 ){
4267     Tcl_AppendResult(interp, "wrong # args: should be \"",
4268        Tcl_GetString(objv[0]), " STMT column", 0);
4269     return TCL_ERROR;
4270   }
4271 
4272   if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
4273   if( Tcl_GetIntFromObj(interp, objv[2], &col) ) return TCL_ERROR;
4274   zRet = xFunc(pStmt, col);
4275   if( zRet ){
4276     Tcl_SetResult(interp, (char *)zRet, 0);
4277   }
4278   return TCL_OK;
4279 }
4280 
4281 static int test_global_recover(
4282   void * clientData,
4283   Tcl_Interp *interp,
4284   int objc,
4285   Tcl_Obj *CONST objv[]
4286 ){
4287 #ifndef SQLITE_OMIT_DEPRECATED
4288   int rc;
4289   if( objc!=1 ){
4290     Tcl_WrongNumArgs(interp, 1, objv, "");
4291     return TCL_ERROR;
4292   }
4293   rc = sqlite3_global_recover();
4294   Tcl_SetResult(interp, (char *)t1ErrorName(rc), TCL_STATIC);
4295 #endif
4296   return TCL_OK;
4297 }
4298 
4299 /*
4300 ** Usage: sqlite3_column_text STMT column
4301 **
4302 ** Usage: sqlite3_column_decltype STMT column
4303 **
4304 ** Usage: sqlite3_column_name STMT column
4305 */
4306 static int test_stmt_utf16(
4307   void * clientData,     /* Pointer to SQLite API function to be invoked */
4308   Tcl_Interp *interp,
4309   int objc,
4310   Tcl_Obj *CONST objv[]
4311 ){
4312 #ifndef SQLITE_OMIT_UTF16
4313   sqlite3_stmt *pStmt;
4314   int col;
4315   Tcl_Obj *pRet;
4316   const void *zName16;
4317   const void *(*xFunc)(sqlite3_stmt*, int);
4318 
4319   xFunc = (const void *(*)(sqlite3_stmt*, int))clientData;
4320   if( objc!=3 ){
4321     Tcl_AppendResult(interp, "wrong # args: should be \"",
4322        Tcl_GetString(objv[0]), " STMT column", 0);
4323     return TCL_ERROR;
4324   }
4325 
4326   if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
4327   if( Tcl_GetIntFromObj(interp, objv[2], &col) ) return TCL_ERROR;
4328 
4329   zName16 = xFunc(pStmt, col);
4330   if( zName16 ){
4331     int n;
4332     const char *z = zName16;
4333     for(n=0; z[n] || z[n+1]; n+=2){}
4334     pRet = Tcl_NewByteArrayObj(zName16, n+2);
4335     Tcl_SetObjResult(interp, pRet);
4336   }
4337 #endif /* SQLITE_OMIT_UTF16 */
4338 
4339   return TCL_OK;
4340 }
4341 
4342 /*
4343 ** Usage: sqlite3_column_int STMT column
4344 **
4345 ** Usage: sqlite3_column_bytes STMT column
4346 **
4347 ** Usage: sqlite3_column_bytes16 STMT column
4348 **
4349 */
4350 static int test_stmt_int(
4351   void * clientData,    /* Pointer to SQLite API function to be invoked */
4352   Tcl_Interp *interp,
4353   int objc,
4354   Tcl_Obj *CONST objv[]
4355 ){
4356   sqlite3_stmt *pStmt;
4357   int col;
4358   int (*xFunc)(sqlite3_stmt*, int);
4359 
4360   xFunc = (int (*)(sqlite3_stmt*, int))clientData;
4361   if( objc!=3 ){
4362     Tcl_AppendResult(interp, "wrong # args: should be \"",
4363        Tcl_GetString(objv[0]), " STMT column", 0);
4364     return TCL_ERROR;
4365   }
4366 
4367   if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
4368   if( Tcl_GetIntFromObj(interp, objv[2], &col) ) return TCL_ERROR;
4369 
4370   Tcl_SetObjResult(interp, Tcl_NewIntObj(xFunc(pStmt, col)));
4371   return TCL_OK;
4372 }
4373 
4374 /*
4375 ** Usage:  sqlite_set_magic  DB  MAGIC-NUMBER
4376 **
4377 ** Set the db->magic value.  This is used to test error recovery logic.
4378 */
4379 static int sqlite_set_magic(
4380   void * clientData,
4381   Tcl_Interp *interp,
4382   int argc,
4383   char **argv
4384 ){
4385   sqlite3 *db;
4386   if( argc!=3 ){
4387     Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
4388          " DB MAGIC", 0);
4389     return TCL_ERROR;
4390   }
4391   if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
4392   if( strcmp(argv[2], "SQLITE_MAGIC_OPEN")==0 ){
4393     db->magic = SQLITE_MAGIC_OPEN;
4394   }else if( strcmp(argv[2], "SQLITE_MAGIC_CLOSED")==0 ){
4395     db->magic = SQLITE_MAGIC_CLOSED;
4396   }else if( strcmp(argv[2], "SQLITE_MAGIC_BUSY")==0 ){
4397     db->magic = SQLITE_MAGIC_BUSY;
4398   }else if( strcmp(argv[2], "SQLITE_MAGIC_ERROR")==0 ){
4399     db->magic = SQLITE_MAGIC_ERROR;
4400   }else if( Tcl_GetInt(interp, argv[2], (int*)&db->magic) ){
4401     return TCL_ERROR;
4402   }
4403   return TCL_OK;
4404 }
4405 
4406 /*
4407 ** Usage:  sqlite3_interrupt  DB
4408 **
4409 ** Trigger an interrupt on DB
4410 */
4411 static int test_interrupt(
4412   void * clientData,
4413   Tcl_Interp *interp,
4414   int argc,
4415   char **argv
4416 ){
4417   sqlite3 *db;
4418   if( argc!=2 ){
4419     Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], " DB", 0);
4420     return TCL_ERROR;
4421   }
4422   if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
4423   sqlite3_interrupt(db);
4424   return TCL_OK;
4425 }
4426 
4427 static u8 *sqlite3_stack_baseline = 0;
4428 
4429 /*
4430 ** Fill the stack with a known bitpattern.
4431 */
4432 static void prepStack(void){
4433   int i;
4434   u32 bigBuf[65536];
4435   for(i=0; i<sizeof(bigBuf)/sizeof(bigBuf[0]); i++) bigBuf[i] = 0xdeadbeef;
4436   sqlite3_stack_baseline = (u8*)&bigBuf[65536];
4437 }
4438 
4439 /*
4440 ** Get the current stack depth.  Used for debugging only.
4441 */
4442 u64 sqlite3StackDepth(void){
4443   u8 x;
4444   return (u64)(sqlite3_stack_baseline - &x);
4445 }
4446 
4447 /*
4448 ** Usage:  sqlite3_stack_used DB SQL
4449 **
4450 ** Try to measure the amount of stack space used by a call to sqlite3_exec
4451 */
4452 static int test_stack_used(
4453   void * clientData,
4454   Tcl_Interp *interp,
4455   int argc,
4456   char **argv
4457 ){
4458   sqlite3 *db;
4459   int i;
4460   if( argc!=3 ){
4461     Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
4462         " DB SQL", 0);
4463     return TCL_ERROR;
4464   }
4465   if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
4466   prepStack();
4467   (void)sqlite3_exec(db, argv[2], 0, 0, 0);
4468   for(i=65535; i>=0 && ((u32*)sqlite3_stack_baseline)[-i]==0xdeadbeef; i--){}
4469   Tcl_SetObjResult(interp, Tcl_NewIntObj(i*4));
4470   return TCL_OK;
4471 }
4472 
4473 /*
4474 ** Usage: sqlite_delete_function DB function-name
4475 **
4476 ** Delete the user function 'function-name' from database handle DB. It
4477 ** is assumed that the user function was created as UTF8, any number of
4478 ** arguments (the way the TCL interface does it).
4479 */
4480 static int delete_function(
4481   void * clientData,
4482   Tcl_Interp *interp,
4483   int argc,
4484   char **argv
4485 ){
4486   int rc;
4487   sqlite3 *db;
4488   if( argc!=3 ){
4489     Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
4490         " DB function-name", 0);
4491     return TCL_ERROR;
4492   }
4493   if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
4494   rc = sqlite3_create_function(db, argv[2], -1, SQLITE_UTF8, 0, 0, 0, 0);
4495   Tcl_SetResult(interp, (char *)t1ErrorName(rc), TCL_STATIC);
4496   return TCL_OK;
4497 }
4498 
4499 /*
4500 ** Usage: sqlite_delete_collation DB collation-name
4501 **
4502 ** Delete the collation sequence 'collation-name' from database handle
4503 ** DB. It is assumed that the collation sequence was created as UTF8 (the
4504 ** way the TCL interface does it).
4505 */
4506 static int delete_collation(
4507   void * clientData,
4508   Tcl_Interp *interp,
4509   int argc,
4510   char **argv
4511 ){
4512   int rc;
4513   sqlite3 *db;
4514   if( argc!=3 ){
4515     Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
4516         " DB function-name", 0);
4517     return TCL_ERROR;
4518   }
4519   if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
4520   rc = sqlite3_create_collation(db, argv[2], SQLITE_UTF8, 0, 0);
4521   Tcl_SetResult(interp, (char *)t1ErrorName(rc), TCL_STATIC);
4522   return TCL_OK;
4523 }
4524 
4525 /*
4526 ** Usage: sqlite3_get_autocommit DB
4527 **
4528 ** Return true if the database DB is currently in auto-commit mode.
4529 ** Return false if not.
4530 */
4531 static int get_autocommit(
4532   void * clientData,
4533   Tcl_Interp *interp,
4534   int argc,
4535   char **argv
4536 ){
4537   char zBuf[30];
4538   sqlite3 *db;
4539   if( argc!=2 ){
4540     Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
4541         " DB", 0);
4542     return TCL_ERROR;
4543   }
4544   if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
4545   sprintf(zBuf, "%d", sqlite3_get_autocommit(db));
4546   Tcl_AppendResult(interp, zBuf, 0);
4547   return TCL_OK;
4548 }
4549 
4550 /*
4551 ** Usage: sqlite3_busy_timeout DB MS
4552 **
4553 ** Set the busy timeout.  This is more easily done using the timeout
4554 ** method of the TCL interface.  But we need a way to test the case
4555 ** where it returns SQLITE_MISUSE.
4556 */
4557 static int test_busy_timeout(
4558   void * clientData,
4559   Tcl_Interp *interp,
4560   int argc,
4561   char **argv
4562 ){
4563   int rc, ms;
4564   sqlite3 *db;
4565   if( argc!=3 ){
4566     Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
4567         " DB", 0);
4568     return TCL_ERROR;
4569   }
4570   if( getDbPointer(interp, argv[1], &db) ) return TCL_ERROR;
4571   if( Tcl_GetInt(interp, argv[2], &ms) ) return TCL_ERROR;
4572   rc = sqlite3_busy_timeout(db, ms);
4573   Tcl_AppendResult(interp, sqlite3TestErrorName(rc), 0);
4574   return TCL_OK;
4575 }
4576 
4577 /*
4578 ** Usage:  tcl_variable_type VARIABLENAME
4579 **
4580 ** Return the name of the internal representation for the
4581 ** value of the given variable.
4582 */
4583 static int tcl_variable_type(
4584   void * clientData,
4585   Tcl_Interp *interp,
4586   int objc,
4587   Tcl_Obj *CONST objv[]
4588 ){
4589   Tcl_Obj *pVar;
4590   if( objc!=2 ){
4591     Tcl_WrongNumArgs(interp, 1, objv, "VARIABLE");
4592     return TCL_ERROR;
4593   }
4594   pVar = Tcl_GetVar2Ex(interp, Tcl_GetString(objv[1]), 0, TCL_LEAVE_ERR_MSG);
4595   if( pVar==0 ) return TCL_ERROR;
4596   if( pVar->typePtr ){
4597     Tcl_SetObjResult(interp, Tcl_NewStringObj(pVar->typePtr->name, -1));
4598   }
4599   return TCL_OK;
4600 }
4601 
4602 /*
4603 ** Usage:  sqlite3_release_memory ?N?
4604 **
4605 ** Attempt to release memory currently held but not actually required.
4606 ** The integer N is the number of bytes we are trying to release.  The
4607 ** return value is the amount of memory actually released.
4608 */
4609 static int test_release_memory(
4610   void * clientData,
4611   Tcl_Interp *interp,
4612   int objc,
4613   Tcl_Obj *CONST objv[]
4614 ){
4615 #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) && !defined(SQLITE_OMIT_DISKIO)
4616   int N;
4617   int amt;
4618   if( objc!=1 && objc!=2 ){
4619     Tcl_WrongNumArgs(interp, 1, objv, "?N?");
4620     return TCL_ERROR;
4621   }
4622   if( objc==2 ){
4623     if( Tcl_GetIntFromObj(interp, objv[1], &N) ) return TCL_ERROR;
4624   }else{
4625     N = -1;
4626   }
4627   amt = sqlite3_release_memory(N);
4628   Tcl_SetObjResult(interp, Tcl_NewIntObj(amt));
4629 #endif
4630   return TCL_OK;
4631 }
4632 
4633 
4634 /*
4635 ** Usage:  sqlite3_db_release_memory DB
4636 **
4637 ** Attempt to release memory currently held by database DB.  Return the
4638 ** result code (which in the current implementation is always zero).
4639 */
4640 static int test_db_release_memory(
4641   void * clientData,
4642   Tcl_Interp *interp,
4643   int objc,
4644   Tcl_Obj *CONST objv[]
4645 ){
4646   sqlite3 *db;
4647   int rc;
4648   if( objc!=2 ){
4649     Tcl_WrongNumArgs(interp, 1, objv, "DB");
4650     return TCL_ERROR;
4651   }
4652   if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
4653   rc = sqlite3_db_release_memory(db);
4654   Tcl_SetObjResult(interp, Tcl_NewIntObj(rc));
4655   return TCL_OK;
4656 }
4657 
4658 /*
4659 ** Usage:  sqlite3_db_filename DB DBNAME
4660 **
4661 ** Return the name of a file associated with a database.
4662 */
4663 static int test_db_filename(
4664   void * clientData,
4665   Tcl_Interp *interp,
4666   int objc,
4667   Tcl_Obj *CONST objv[]
4668 ){
4669   sqlite3 *db;
4670   const char *zDbName;
4671   if( objc!=3 ){
4672     Tcl_WrongNumArgs(interp, 1, objv, "DB DBNAME");
4673     return TCL_ERROR;
4674   }
4675   if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
4676   zDbName = Tcl_GetString(objv[2]);
4677   Tcl_AppendResult(interp, sqlite3_db_filename(db, zDbName), (void*)0);
4678   return TCL_OK;
4679 }
4680 
4681 /*
4682 ** Usage:  sqlite3_db_readonly DB DBNAME
4683 **
4684 ** Return 1 or 0 if DBNAME is readonly or not.  Return -1 if DBNAME does
4685 ** not exist.
4686 */
4687 static int test_db_readonly(
4688   void * clientData,
4689   Tcl_Interp *interp,
4690   int objc,
4691   Tcl_Obj *CONST objv[]
4692 ){
4693   sqlite3 *db;
4694   const char *zDbName;
4695   if( objc!=3 ){
4696     Tcl_WrongNumArgs(interp, 1, objv, "DB DBNAME");
4697     return TCL_ERROR;
4698   }
4699   if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
4700   zDbName = Tcl_GetString(objv[2]);
4701   Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_db_readonly(db, zDbName)));
4702   return TCL_OK;
4703 }
4704 
4705 /*
4706 ** Usage:  sqlite3_soft_heap_limit ?N?
4707 **
4708 ** Query or set the soft heap limit for the current thread.  The
4709 ** limit is only changed if the N is present.  The previous limit
4710 ** is returned.
4711 */
4712 static int test_soft_heap_limit(
4713   void * clientData,
4714   Tcl_Interp *interp,
4715   int objc,
4716   Tcl_Obj *CONST objv[]
4717 ){
4718   sqlite3_int64 amt;
4719   Tcl_WideInt N = -1;
4720   if( objc!=1 && objc!=2 ){
4721     Tcl_WrongNumArgs(interp, 1, objv, "?N?");
4722     return TCL_ERROR;
4723   }
4724   if( objc==2 ){
4725     if( Tcl_GetWideIntFromObj(interp, objv[1], &N) ) return TCL_ERROR;
4726   }
4727   amt = sqlite3_soft_heap_limit64(N);
4728   Tcl_SetObjResult(interp, Tcl_NewWideIntObj(amt));
4729   return TCL_OK;
4730 }
4731 
4732 /*
4733 ** Usage:   sqlite3_thread_cleanup
4734 **
4735 ** Call the sqlite3_thread_cleanup API.
4736 */
4737 static int test_thread_cleanup(
4738   void * clientData,
4739   Tcl_Interp *interp,
4740   int objc,
4741   Tcl_Obj *CONST objv[]
4742 ){
4743 #ifndef SQLITE_OMIT_DEPRECATED
4744   sqlite3_thread_cleanup();
4745 #endif
4746   return TCL_OK;
4747 }
4748 
4749 /*
4750 ** Usage:   sqlite3_pager_refcounts  DB
4751 **
4752 ** Return a list of numbers which are the PagerRefcount for all
4753 ** pagers on each database connection.
4754 */
4755 static int test_pager_refcounts(
4756   void * clientData,
4757   Tcl_Interp *interp,
4758   int objc,
4759   Tcl_Obj *CONST objv[]
4760 ){
4761   sqlite3 *db;
4762   int i;
4763   int v, *a;
4764   Tcl_Obj *pResult;
4765 
4766   if( objc!=2 ){
4767     Tcl_AppendResult(interp, "wrong # args: should be \"",
4768         Tcl_GetStringFromObj(objv[0], 0), " DB", 0);
4769     return TCL_ERROR;
4770   }
4771   if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
4772   pResult = Tcl_NewObj();
4773   for(i=0; i<db->nDb; i++){
4774     if( db->aDb[i].pBt==0 ){
4775       v = -1;
4776     }else{
4777       sqlite3_mutex_enter(db->mutex);
4778       a = sqlite3PagerStats(sqlite3BtreePager(db->aDb[i].pBt));
4779       v = a[0];
4780       sqlite3_mutex_leave(db->mutex);
4781     }
4782     Tcl_ListObjAppendElement(0, pResult, Tcl_NewIntObj(v));
4783   }
4784   Tcl_SetObjResult(interp, pResult);
4785   return TCL_OK;
4786 }
4787 
4788 
4789 /*
4790 ** tclcmd:   working_64bit_int
4791 **
4792 ** Some TCL builds (ex: cygwin) do not support 64-bit integers.  This
4793 ** leads to a number of test failures.  The present command checks the
4794 ** TCL build to see whether or not it supports 64-bit integers.  It
4795 ** returns TRUE if it does and FALSE if not.
4796 **
4797 ** This command is used to warn users that their TCL build is defective
4798 ** and that the errors they are seeing in the test scripts might be
4799 ** a result of their defective TCL rather than problems in SQLite.
4800 */
4801 static int working_64bit_int(
4802   ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
4803   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
4804   int objc,              /* Number of arguments */
4805   Tcl_Obj *CONST objv[]  /* Command arguments */
4806 ){
4807   Tcl_Obj *pTestObj;
4808   int working = 0;
4809 
4810   pTestObj = Tcl_NewWideIntObj(1000000*(i64)1234567890);
4811   working = strcmp(Tcl_GetString(pTestObj), "1234567890000000")==0;
4812   Tcl_DecrRefCount(pTestObj);
4813   Tcl_SetObjResult(interp, Tcl_NewBooleanObj(working));
4814   return TCL_OK;
4815 }
4816 
4817 
4818 /*
4819 ** tclcmd:   vfs_unlink_test
4820 **
4821 ** This TCL command unregisters the primary VFS and then registers
4822 ** it back again.  This is used to test the ability to register a
4823 ** VFS when none are previously registered, and the ability to
4824 ** unregister the only available VFS.  Ticket #2738
4825 */
4826 static int vfs_unlink_test(
4827   ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
4828   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
4829   int objc,              /* Number of arguments */
4830   Tcl_Obj *CONST objv[]  /* Command arguments */
4831 ){
4832   int i;
4833   sqlite3_vfs *pMain;
4834   sqlite3_vfs *apVfs[20];
4835   sqlite3_vfs one, two;
4836 
4837   sqlite3_vfs_unregister(0);   /* Unregister of NULL is harmless */
4838   one.zName = "__one";
4839   two.zName = "__two";
4840 
4841   /* Calling sqlite3_vfs_register with 2nd argument of 0 does not
4842   ** change the default VFS
4843   */
4844   pMain = sqlite3_vfs_find(0);
4845   sqlite3_vfs_register(&one, 0);
4846   assert( pMain==0 || pMain==sqlite3_vfs_find(0) );
4847   sqlite3_vfs_register(&two, 0);
4848   assert( pMain==0 || pMain==sqlite3_vfs_find(0) );
4849 
4850   /* We can find a VFS by its name */
4851   assert( sqlite3_vfs_find("__one")==&one );
4852   assert( sqlite3_vfs_find("__two")==&two );
4853 
4854   /* Calling sqlite_vfs_register with non-zero second parameter changes the
4855   ** default VFS, even if the 1st parameter is an existig VFS that is
4856   ** previously registered as the non-default.
4857   */
4858   sqlite3_vfs_register(&one, 1);
4859   assert( sqlite3_vfs_find("__one")==&one );
4860   assert( sqlite3_vfs_find("__two")==&two );
4861   assert( sqlite3_vfs_find(0)==&one );
4862   sqlite3_vfs_register(&two, 1);
4863   assert( sqlite3_vfs_find("__one")==&one );
4864   assert( sqlite3_vfs_find("__two")==&two );
4865   assert( sqlite3_vfs_find(0)==&two );
4866   if( pMain ){
4867     sqlite3_vfs_register(pMain, 1);
4868     assert( sqlite3_vfs_find("__one")==&one );
4869     assert( sqlite3_vfs_find("__two")==&two );
4870     assert( sqlite3_vfs_find(0)==pMain );
4871   }
4872 
4873   /* Unlink the default VFS.  Repeat until there are no more VFSes
4874   ** registered.
4875   */
4876   for(i=0; i<sizeof(apVfs)/sizeof(apVfs[0]); i++){
4877     apVfs[i] = sqlite3_vfs_find(0);
4878     if( apVfs[i] ){
4879       assert( apVfs[i]==sqlite3_vfs_find(apVfs[i]->zName) );
4880       sqlite3_vfs_unregister(apVfs[i]);
4881       assert( 0==sqlite3_vfs_find(apVfs[i]->zName) );
4882     }
4883   }
4884   assert( 0==sqlite3_vfs_find(0) );
4885 
4886   /* Register the main VFS as non-default (will be made default, since
4887   ** it'll be the only one in existence).
4888   */
4889   sqlite3_vfs_register(pMain, 0);
4890   assert( sqlite3_vfs_find(0)==pMain );
4891 
4892   /* Un-register the main VFS again to restore an empty VFS list */
4893   sqlite3_vfs_unregister(pMain);
4894   assert( 0==sqlite3_vfs_find(0) );
4895 
4896   /* Relink all VFSes in reverse order. */
4897   for(i=sizeof(apVfs)/sizeof(apVfs[0])-1; i>=0; i--){
4898     if( apVfs[i] ){
4899       sqlite3_vfs_register(apVfs[i], 1);
4900       assert( apVfs[i]==sqlite3_vfs_find(0) );
4901       assert( apVfs[i]==sqlite3_vfs_find(apVfs[i]->zName) );
4902     }
4903   }
4904 
4905   /* Unregister out sample VFSes. */
4906   sqlite3_vfs_unregister(&one);
4907   sqlite3_vfs_unregister(&two);
4908 
4909   /* Unregistering a VFS that is not currently registered is harmless */
4910   sqlite3_vfs_unregister(&one);
4911   sqlite3_vfs_unregister(&two);
4912   assert( sqlite3_vfs_find("__one")==0 );
4913   assert( sqlite3_vfs_find("__two")==0 );
4914 
4915   /* We should be left with the original default VFS back as the
4916   ** original */
4917   assert( sqlite3_vfs_find(0)==pMain );
4918 
4919   return TCL_OK;
4920 }
4921 
4922 /*
4923 ** tclcmd:   vfs_initfail_test
4924 **
4925 ** This TCL command attempts to vfs_find and vfs_register when the
4926 ** sqlite3_initialize() interface is failing.  All calls should fail.
4927 */
4928 static int vfs_initfail_test(
4929   ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
4930   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
4931   int objc,              /* Number of arguments */
4932   Tcl_Obj *CONST objv[]  /* Command arguments */
4933 ){
4934   sqlite3_vfs one;
4935   one.zName = "__one";
4936 
4937   if( sqlite3_vfs_find(0) ) return TCL_ERROR;
4938   sqlite3_vfs_register(&one, 0);
4939   if( sqlite3_vfs_find(0) ) return TCL_ERROR;
4940   sqlite3_vfs_register(&one, 1);
4941   if( sqlite3_vfs_find(0) ) return TCL_ERROR;
4942   return TCL_OK;
4943 }
4944 
4945 /*
4946 ** Saved VFSes
4947 */
4948 static sqlite3_vfs *apVfs[20];
4949 static int nVfs = 0;
4950 
4951 /*
4952 ** tclcmd:   vfs_unregister_all
4953 **
4954 ** Unregister all VFSes.
4955 */
4956 static int vfs_unregister_all(
4957   ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
4958   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
4959   int objc,              /* Number of arguments */
4960   Tcl_Obj *CONST objv[]  /* Command arguments */
4961 ){
4962   int i;
4963   for(i=0; i<ArraySize(apVfs); i++){
4964     apVfs[i] = sqlite3_vfs_find(0);
4965     if( apVfs[i]==0 ) break;
4966     sqlite3_vfs_unregister(apVfs[i]);
4967   }
4968   nVfs = i;
4969   return TCL_OK;
4970 }
4971 /*
4972 ** tclcmd:   vfs_reregister_all
4973 **
4974 ** Restore all VFSes that were removed using vfs_unregister_all
4975 */
4976 static int vfs_reregister_all(
4977   ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
4978   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
4979   int objc,              /* Number of arguments */
4980   Tcl_Obj *CONST objv[]  /* Command arguments */
4981 ){
4982   int i;
4983   for(i=0; i<nVfs; i++){
4984     sqlite3_vfs_register(apVfs[i], i==0);
4985   }
4986   return TCL_OK;
4987 }
4988 
4989 
4990 /*
4991 ** tclcmd:   file_control_test DB
4992 **
4993 ** This TCL command runs the sqlite3_file_control interface and
4994 ** verifies correct operation of the same.
4995 */
4996 static int file_control_test(
4997   ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
4998   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
4999   int objc,              /* Number of arguments */
5000   Tcl_Obj *CONST objv[]  /* Command arguments */
5001 ){
5002   int iArg = 0;
5003   sqlite3 *db;
5004   int rc;
5005 
5006   if( objc!=2 ){
5007     Tcl_AppendResult(interp, "wrong # args: should be \"",
5008         Tcl_GetStringFromObj(objv[0], 0), " DB", 0);
5009     return TCL_ERROR;
5010   }
5011   if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
5012   rc = sqlite3_file_control(db, 0, 0, &iArg);
5013   assert( rc==SQLITE_NOTFOUND );
5014   rc = sqlite3_file_control(db, "notadatabase", SQLITE_FCNTL_LOCKSTATE, &iArg);
5015   assert( rc==SQLITE_ERROR );
5016   rc = sqlite3_file_control(db, "main", -1, &iArg);
5017   assert( rc==SQLITE_NOTFOUND );
5018   rc = sqlite3_file_control(db, "temp", -1, &iArg);
5019   assert( rc==SQLITE_NOTFOUND || rc==SQLITE_ERROR );
5020 
5021   return TCL_OK;
5022 }
5023 
5024 
5025 /*
5026 ** tclcmd:   file_control_lasterrno_test DB
5027 **
5028 ** This TCL command runs the sqlite3_file_control interface and
5029 ** verifies correct operation of the SQLITE_LAST_ERRNO verb.
5030 */
5031 static int file_control_lasterrno_test(
5032   ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
5033   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
5034   int objc,              /* Number of arguments */
5035   Tcl_Obj *CONST objv[]  /* Command arguments */
5036 ){
5037   int iArg = 0;
5038   sqlite3 *db;
5039   int rc;
5040 
5041   if( objc!=2 ){
5042     Tcl_AppendResult(interp, "wrong # args: should be \"",
5043         Tcl_GetStringFromObj(objv[0], 0), " DB", 0);
5044     return TCL_ERROR;
5045   }
5046   if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ){
5047     return TCL_ERROR;
5048   }
5049   rc = sqlite3_file_control(db, NULL, SQLITE_LAST_ERRNO, &iArg);
5050   if( rc ){
5051     Tcl_SetObjResult(interp, Tcl_NewIntObj(rc));
5052     return TCL_ERROR;
5053   }
5054   if( iArg!=0 ) {
5055     Tcl_AppendResult(interp, "Unexpected non-zero errno: ",
5056                      Tcl_GetStringFromObj(Tcl_NewIntObj(iArg), 0), " ", 0);
5057     return TCL_ERROR;
5058   }
5059   return TCL_OK;
5060 }
5061 
5062 /*
5063 ** tclcmd:   file_control_chunksize_test DB DBNAME SIZE
5064 **
5065 ** This TCL command runs the sqlite3_file_control interface and
5066 ** verifies correct operation of the SQLITE_GET_LOCKPROXYFILE and
5067 ** SQLITE_SET_LOCKPROXYFILE verbs.
5068 */
5069 static int file_control_chunksize_test(
5070   ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
5071   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
5072   int objc,              /* Number of arguments */
5073   Tcl_Obj *CONST objv[]  /* Command arguments */
5074 ){
5075   int nSize;                      /* New chunk size */
5076   char *zDb;                      /* Db name ("main", "temp" etc.) */
5077   sqlite3 *db;                    /* Database handle */
5078   int rc;                         /* file_control() return code */
5079 
5080   if( objc!=4 ){
5081     Tcl_WrongNumArgs(interp, 1, objv, "DB DBNAME SIZE");
5082     return TCL_ERROR;
5083   }
5084   if( getDbPointer(interp, Tcl_GetString(objv[1]), &db)
5085    || Tcl_GetIntFromObj(interp, objv[3], &nSize)
5086   ){
5087    return TCL_ERROR;
5088   }
5089   zDb = Tcl_GetString(objv[2]);
5090   if( zDb[0]=='\0' ) zDb = NULL;
5091 
5092   rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_CHUNK_SIZE, (void *)&nSize);
5093   if( rc ){
5094     Tcl_SetResult(interp, (char *)sqlite3TestErrorName(rc), TCL_STATIC);
5095     return TCL_ERROR;
5096   }
5097   return TCL_OK;
5098 }
5099 
5100 /*
5101 ** tclcmd:   file_control_sizehint_test DB DBNAME SIZE
5102 **
5103 ** This TCL command runs the sqlite3_file_control interface
5104 ** with SQLITE_FCNTL_SIZE_HINT
5105 */
5106 static int file_control_sizehint_test(
5107   ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
5108   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
5109   int objc,              /* Number of arguments */
5110   Tcl_Obj *CONST objv[]  /* Command arguments */
5111 ){
5112   Tcl_WideInt nSize;              /* Hinted size */
5113   char *zDb;                      /* Db name ("main", "temp" etc.) */
5114   sqlite3 *db;                    /* Database handle */
5115   int rc;                         /* file_control() return code */
5116 
5117   if( objc!=4 ){
5118     Tcl_WrongNumArgs(interp, 1, objv, "DB DBNAME SIZE");
5119     return TCL_ERROR;
5120   }
5121   if( getDbPointer(interp, Tcl_GetString(objv[1]), &db)
5122    || Tcl_GetWideIntFromObj(interp, objv[3], &nSize)
5123   ){
5124    return TCL_ERROR;
5125   }
5126   zDb = Tcl_GetString(objv[2]);
5127   if( zDb[0]=='\0' ) zDb = NULL;
5128 
5129   rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_SIZE_HINT, (void *)&nSize);
5130   if( rc ){
5131     Tcl_SetResult(interp, (char *)sqlite3TestErrorName(rc), TCL_STATIC);
5132     return TCL_ERROR;
5133   }
5134   return TCL_OK;
5135 }
5136 
5137 /*
5138 ** tclcmd:   file_control_lockproxy_test DB PWD
5139 **
5140 ** This TCL command runs the sqlite3_file_control interface and
5141 ** verifies correct operation of the SQLITE_GET_LOCKPROXYFILE and
5142 ** SQLITE_SET_LOCKPROXYFILE verbs.
5143 */
5144 static int file_control_lockproxy_test(
5145   ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
5146   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
5147   int objc,              /* Number of arguments */
5148   Tcl_Obj *CONST objv[]  /* Command arguments */
5149 ){
5150   sqlite3 *db;
5151 
5152   if( objc!=3 ){
5153     Tcl_AppendResult(interp, "wrong # args: should be \"",
5154                      Tcl_GetStringFromObj(objv[0], 0), " DB PWD", 0);
5155     return TCL_ERROR;
5156   }
5157   if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ){
5158    return TCL_ERROR;
5159   }
5160 
5161 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
5162 #  if defined(__APPLE__)
5163 #    define SQLITE_ENABLE_LOCKING_STYLE 1
5164 #  else
5165 #    define SQLITE_ENABLE_LOCKING_STYLE 0
5166 #  endif
5167 #endif
5168 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
5169   {
5170     char *testPath;
5171     int rc;
5172     int nPwd;
5173     const char *zPwd;
5174     char proxyPath[400];
5175 
5176     zPwd = Tcl_GetStringFromObj(objv[2], &nPwd);
5177     if( sizeof(proxyPath)<nPwd+20 ){
5178       Tcl_AppendResult(interp, "PWD too big", (void*)0);
5179       return TCL_ERROR;
5180     }
5181     sprintf(proxyPath, "%s/test.proxy", zPwd);
5182     rc = sqlite3_file_control(db, NULL, SQLITE_SET_LOCKPROXYFILE, proxyPath);
5183     if( rc ){
5184       Tcl_SetObjResult(interp, Tcl_NewIntObj(rc));
5185       return TCL_ERROR;
5186     }
5187     rc = sqlite3_file_control(db, NULL, SQLITE_GET_LOCKPROXYFILE, &testPath);
5188     if( strncmp(proxyPath,testPath,11) ){
5189       Tcl_AppendResult(interp, "Lock proxy file did not match the "
5190                                "previously assigned value", 0);
5191       return TCL_ERROR;
5192     }
5193     if( rc ){
5194       Tcl_SetObjResult(interp, Tcl_NewIntObj(rc));
5195       return TCL_ERROR;
5196     }
5197     rc = sqlite3_file_control(db, NULL, SQLITE_SET_LOCKPROXYFILE, proxyPath);
5198     if( rc ){
5199       Tcl_SetObjResult(interp, Tcl_NewIntObj(rc));
5200       return TCL_ERROR;
5201     }
5202   }
5203 #endif
5204   return TCL_OK;
5205 }
5206 
5207 /*
5208 ** tclcmd:   file_control_win32_av_retry DB  NRETRY  DELAY
5209 **
5210 ** This TCL command runs the sqlite3_file_control interface with
5211 ** the SQLITE_FCNTL_WIN32_AV_RETRY opcode.
5212 */
5213 static int file_control_win32_av_retry(
5214   ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
5215   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
5216   int objc,              /* Number of arguments */
5217   Tcl_Obj *CONST objv[]  /* Command arguments */
5218 ){
5219   sqlite3 *db;
5220   int rc;
5221   int a[2];
5222   char z[100];
5223 
5224   if( objc!=4 ){
5225     Tcl_AppendResult(interp, "wrong # args: should be \"",
5226         Tcl_GetStringFromObj(objv[0], 0), " DB NRETRY DELAY", 0);
5227     return TCL_ERROR;
5228   }
5229   if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ){
5230     return TCL_ERROR;
5231   }
5232   if( Tcl_GetIntFromObj(interp, objv[2], &a[0]) ) return TCL_ERROR;
5233   if( Tcl_GetIntFromObj(interp, objv[3], &a[1]) ) return TCL_ERROR;
5234   rc = sqlite3_file_control(db, NULL, SQLITE_FCNTL_WIN32_AV_RETRY, (void*)a);
5235   sqlite3_snprintf(sizeof(z), z, "%d %d %d", rc, a[0], a[1]);
5236   Tcl_AppendResult(interp, z, (char*)0);
5237   return TCL_OK;
5238 }
5239 
5240 /*
5241 ** tclcmd:   file_control_persist_wal DB PERSIST-FLAG
5242 **
5243 ** This TCL command runs the sqlite3_file_control interface with
5244 ** the SQLITE_FCNTL_PERSIST_WAL opcode.
5245 */
5246 static int file_control_persist_wal(
5247   ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
5248   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
5249   int objc,              /* Number of arguments */
5250   Tcl_Obj *CONST objv[]  /* Command arguments */
5251 ){
5252   sqlite3 *db;
5253   int rc;
5254   int bPersist;
5255   char z[100];
5256 
5257   if( objc!=3 ){
5258     Tcl_AppendResult(interp, "wrong # args: should be \"",
5259         Tcl_GetStringFromObj(objv[0], 0), " DB FLAG", 0);
5260     return TCL_ERROR;
5261   }
5262   if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ){
5263     return TCL_ERROR;
5264   }
5265   if( Tcl_GetIntFromObj(interp, objv[2], &bPersist) ) return TCL_ERROR;
5266   rc = sqlite3_file_control(db, NULL, SQLITE_FCNTL_PERSIST_WAL, (void*)&bPersist);
5267   sqlite3_snprintf(sizeof(z), z, "%d %d", rc, bPersist);
5268   Tcl_AppendResult(interp, z, (char*)0);
5269   return TCL_OK;
5270 }
5271 
5272 /*
5273 ** tclcmd:   file_control_powersafe_overwrite DB PSOW-FLAG
5274 **
5275 ** This TCL command runs the sqlite3_file_control interface with
5276 ** the SQLITE_FCNTL_POWERSAFE_OVERWRITE opcode.
5277 */
5278 static int file_control_powersafe_overwrite(
5279   ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
5280   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
5281   int objc,              /* Number of arguments */
5282   Tcl_Obj *CONST objv[]  /* Command arguments */
5283 ){
5284   sqlite3 *db;
5285   int rc;
5286   int b;
5287   char z[100];
5288 
5289   if( objc!=3 ){
5290     Tcl_AppendResult(interp, "wrong # args: should be \"",
5291         Tcl_GetStringFromObj(objv[0], 0), " DB FLAG", 0);
5292     return TCL_ERROR;
5293   }
5294   if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ){
5295     return TCL_ERROR;
5296   }
5297   if( Tcl_GetIntFromObj(interp, objv[2], &b) ) return TCL_ERROR;
5298   rc = sqlite3_file_control(db,NULL,SQLITE_FCNTL_POWERSAFE_OVERWRITE,(void*)&b);
5299   sqlite3_snprintf(sizeof(z), z, "%d %d", rc, b);
5300   Tcl_AppendResult(interp, z, (char*)0);
5301   return TCL_OK;
5302 }
5303 
5304 
5305 /*
5306 ** tclcmd:   file_control_vfsname DB ?AUXDB?
5307 **
5308 ** Return a string that describes the stack of VFSes.
5309 */
5310 static int file_control_vfsname(
5311   ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
5312   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
5313   int objc,              /* Number of arguments */
5314   Tcl_Obj *CONST objv[]  /* Command arguments */
5315 ){
5316   sqlite3 *db;
5317   const char *zDbName = "main";
5318   char *zVfsName = 0;
5319 
5320   if( objc!=2 && objc!=3 ){
5321     Tcl_AppendResult(interp, "wrong # args: should be \"",
5322         Tcl_GetStringFromObj(objv[0], 0), " DB ?AUXDB?", 0);
5323     return TCL_ERROR;
5324   }
5325   if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ){
5326     return TCL_ERROR;
5327   }
5328   if( objc==3 ){
5329     zDbName = Tcl_GetString(objv[2]);
5330   }
5331   sqlite3_file_control(db, zDbName, SQLITE_FCNTL_VFSNAME,(void*)&zVfsName);
5332   Tcl_AppendResult(interp, zVfsName, (char*)0);
5333   sqlite3_free(zVfsName);
5334   return TCL_OK;
5335 }
5336 
5337 /*
5338 ** tclcmd:   file_control_tempfilename DB ?AUXDB?
5339 **
5340 ** Return a string that is a temporary filename
5341 */
5342 static int file_control_tempfilename(
5343   ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
5344   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
5345   int objc,              /* Number of arguments */
5346   Tcl_Obj *CONST objv[]  /* Command arguments */
5347 ){
5348   sqlite3 *db;
5349   const char *zDbName = "main";
5350   char *zTName = 0;
5351 
5352   if( objc!=2 && objc!=3 ){
5353     Tcl_AppendResult(interp, "wrong # args: should be \"",
5354         Tcl_GetStringFromObj(objv[0], 0), " DB ?AUXDB?", 0);
5355     return TCL_ERROR;
5356   }
5357   if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ){
5358     return TCL_ERROR;
5359   }
5360   if( objc==3 ){
5361     zDbName = Tcl_GetString(objv[2]);
5362   }
5363   sqlite3_file_control(db, zDbName, SQLITE_FCNTL_TEMPFILENAME, (void*)&zTName);
5364   Tcl_AppendResult(interp, zTName, (char*)0);
5365   sqlite3_free(zTName);
5366   return TCL_OK;
5367 }
5368 
5369 
5370 /*
5371 ** tclcmd:   sqlite3_vfs_list
5372 **
5373 **   Return a tcl list containing the names of all registered vfs's.
5374 */
5375 static int vfs_list(
5376   ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
5377   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
5378   int objc,              /* Number of arguments */
5379   Tcl_Obj *CONST objv[]  /* Command arguments */
5380 ){
5381   sqlite3_vfs *pVfs;
5382   Tcl_Obj *pRet = Tcl_NewObj();
5383   if( objc!=1 ){
5384     Tcl_WrongNumArgs(interp, 1, objv, "");
5385     return TCL_ERROR;
5386   }
5387   for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
5388     Tcl_ListObjAppendElement(interp, pRet, Tcl_NewStringObj(pVfs->zName, -1));
5389   }
5390   Tcl_SetObjResult(interp, pRet);
5391   return TCL_OK;
5392 }
5393 
5394 /*
5395 ** tclcmd:   sqlite3_limit DB ID VALUE
5396 **
5397 ** This TCL command runs the sqlite3_limit interface and
5398 ** verifies correct operation of the same.
5399 */
5400 static int test_limit(
5401   ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
5402   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
5403   int objc,              /* Number of arguments */
5404   Tcl_Obj *CONST objv[]  /* Command arguments */
5405 ){
5406   sqlite3 *db;
5407   int rc;
5408   static const struct {
5409      char *zName;
5410      int id;
5411   } aId[] = {
5412     { "SQLITE_LIMIT_LENGTH",              SQLITE_LIMIT_LENGTH               },
5413     { "SQLITE_LIMIT_SQL_LENGTH",          SQLITE_LIMIT_SQL_LENGTH           },
5414     { "SQLITE_LIMIT_COLUMN",              SQLITE_LIMIT_COLUMN               },
5415     { "SQLITE_LIMIT_EXPR_DEPTH",          SQLITE_LIMIT_EXPR_DEPTH           },
5416     { "SQLITE_LIMIT_COMPOUND_SELECT",     SQLITE_LIMIT_COMPOUND_SELECT      },
5417     { "SQLITE_LIMIT_VDBE_OP",             SQLITE_LIMIT_VDBE_OP              },
5418     { "SQLITE_LIMIT_FUNCTION_ARG",        SQLITE_LIMIT_FUNCTION_ARG         },
5419     { "SQLITE_LIMIT_ATTACHED",            SQLITE_LIMIT_ATTACHED             },
5420     { "SQLITE_LIMIT_LIKE_PATTERN_LENGTH", SQLITE_LIMIT_LIKE_PATTERN_LENGTH  },
5421     { "SQLITE_LIMIT_VARIABLE_NUMBER",     SQLITE_LIMIT_VARIABLE_NUMBER      },
5422     { "SQLITE_LIMIT_TRIGGER_DEPTH",       SQLITE_LIMIT_TRIGGER_DEPTH        },
5423 
5424     /* Out of range test cases */
5425     { "SQLITE_LIMIT_TOOSMALL",            -1,                               },
5426     { "SQLITE_LIMIT_TOOBIG",              SQLITE_LIMIT_TRIGGER_DEPTH+1      },
5427   };
5428   int i, id;
5429   int val;
5430   const char *zId;
5431 
5432   if( objc!=4 ){
5433     Tcl_AppendResult(interp, "wrong # args: should be \"",
5434         Tcl_GetStringFromObj(objv[0], 0), " DB ID VALUE", 0);
5435     return TCL_ERROR;
5436   }
5437   if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
5438   zId = Tcl_GetString(objv[2]);
5439   for(i=0; i<sizeof(aId)/sizeof(aId[0]); i++){
5440     if( strcmp(zId, aId[i].zName)==0 ){
5441       id = aId[i].id;
5442       break;
5443     }
5444   }
5445   if( i>=sizeof(aId)/sizeof(aId[0]) ){
5446     Tcl_AppendResult(interp, "unknown limit type: ", zId, (char*)0);
5447     return TCL_ERROR;
5448   }
5449   if( Tcl_GetIntFromObj(interp, objv[3], &val) ) return TCL_ERROR;
5450   rc = sqlite3_limit(db, id, val);
5451   Tcl_SetObjResult(interp, Tcl_NewIntObj(rc));
5452   return TCL_OK;
5453 }
5454 
5455 /*
5456 ** tclcmd:  save_prng_state
5457 **
5458 ** Save the state of the pseudo-random number generator.
5459 ** At the same time, verify that sqlite3_test_control works even when
5460 ** called with an out-of-range opcode.
5461 */
5462 static int save_prng_state(
5463   ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
5464   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
5465   int objc,              /* Number of arguments */
5466   Tcl_Obj *CONST objv[]  /* Command arguments */
5467 ){
5468   int rc = sqlite3_test_control(9999);
5469   assert( rc==0 );
5470   rc = sqlite3_test_control(-1);
5471   assert( rc==0 );
5472   sqlite3_test_control(SQLITE_TESTCTRL_PRNG_SAVE);
5473   return TCL_OK;
5474 }
5475 /*
5476 ** tclcmd:  restore_prng_state
5477 */
5478 static int restore_prng_state(
5479   ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
5480   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
5481   int objc,              /* Number of arguments */
5482   Tcl_Obj *CONST objv[]  /* Command arguments */
5483 ){
5484   sqlite3_test_control(SQLITE_TESTCTRL_PRNG_RESTORE);
5485   return TCL_OK;
5486 }
5487 /*
5488 ** tclcmd:  reset_prng_state
5489 */
5490 static int reset_prng_state(
5491   ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
5492   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
5493   int objc,              /* Number of arguments */
5494   Tcl_Obj *CONST objv[]  /* Command arguments */
5495 ){
5496   sqlite3_test_control(SQLITE_TESTCTRL_PRNG_RESET);
5497   return TCL_OK;
5498 }
5499 
5500 /*
5501 ** tclcmd:  pcache_stats
5502 */
5503 static int test_pcache_stats(
5504   ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
5505   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
5506   int objc,              /* Number of arguments */
5507   Tcl_Obj *CONST objv[]  /* Command arguments */
5508 ){
5509   int nMin;
5510   int nMax;
5511   int nCurrent;
5512   int nRecyclable;
5513   Tcl_Obj *pRet;
5514 
5515   sqlite3PcacheStats(&nCurrent, &nMax, &nMin, &nRecyclable);
5516 
5517   pRet = Tcl_NewObj();
5518   Tcl_ListObjAppendElement(interp, pRet, Tcl_NewStringObj("current", -1));
5519   Tcl_ListObjAppendElement(interp, pRet, Tcl_NewIntObj(nCurrent));
5520   Tcl_ListObjAppendElement(interp, pRet, Tcl_NewStringObj("max", -1));
5521   Tcl_ListObjAppendElement(interp, pRet, Tcl_NewIntObj(nMax));
5522   Tcl_ListObjAppendElement(interp, pRet, Tcl_NewStringObj("min", -1));
5523   Tcl_ListObjAppendElement(interp, pRet, Tcl_NewIntObj(nMin));
5524   Tcl_ListObjAppendElement(interp, pRet, Tcl_NewStringObj("recyclable", -1));
5525   Tcl_ListObjAppendElement(interp, pRet, Tcl_NewIntObj(nRecyclable));
5526 
5527   Tcl_SetObjResult(interp, pRet);
5528 
5529   return TCL_OK;
5530 }
5531 
5532 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
5533 static void test_unlock_notify_cb(void **aArg, int nArg){
5534   int ii;
5535   for(ii=0; ii<nArg; ii++){
5536     Tcl_EvalEx((Tcl_Interp *)aArg[ii], "unlock_notify", -1, TCL_EVAL_GLOBAL);
5537   }
5538 }
5539 #endif /* SQLITE_ENABLE_UNLOCK_NOTIFY */
5540 
5541 /*
5542 ** tclcmd:  sqlite3_unlock_notify db
5543 */
5544 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
5545 static int test_unlock_notify(
5546   ClientData clientData, /* Unused */
5547   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
5548   int objc,              /* Number of arguments */
5549   Tcl_Obj *CONST objv[]  /* Command arguments */
5550 ){
5551   sqlite3 *db;
5552   int rc;
5553 
5554   if( objc!=2 ){
5555     Tcl_WrongNumArgs(interp, 1, objv, "DB");
5556     return TCL_ERROR;
5557   }
5558 
5559   if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ){
5560     return TCL_ERROR;
5561   }
5562   rc = sqlite3_unlock_notify(db, test_unlock_notify_cb, (void *)interp);
5563   Tcl_SetResult(interp, (char *)t1ErrorName(rc), TCL_STATIC);
5564   return TCL_OK;
5565 }
5566 #endif
5567 
5568 /*
5569 ** tclcmd:  sqlite3_wal_checkpoint db ?NAME?
5570 */
5571 static int test_wal_checkpoint(
5572   ClientData clientData, /* Unused */
5573   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
5574   int objc,              /* Number of arguments */
5575   Tcl_Obj *CONST objv[]  /* Command arguments */
5576 ){
5577   char *zDb = 0;
5578   sqlite3 *db;
5579   int rc;
5580 
5581   if( objc!=3 && objc!=2 ){
5582     Tcl_WrongNumArgs(interp, 1, objv, "DB ?NAME?");
5583     return TCL_ERROR;
5584   }
5585 
5586   if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ){
5587     return TCL_ERROR;
5588   }
5589   if( objc==3 ){
5590     zDb = Tcl_GetString(objv[2]);
5591   }
5592   rc = sqlite3_wal_checkpoint(db, zDb);
5593   Tcl_SetResult(interp, (char *)t1ErrorName(rc), TCL_STATIC);
5594   return TCL_OK;
5595 }
5596 
5597 /*
5598 ** tclcmd:  sqlite3_wal_checkpoint_v2 db MODE ?NAME?
5599 **
5600 ** This command calls the wal_checkpoint_v2() function with the specified
5601 ** mode argument (passive, full or restart). If present, the database name
5602 ** NAME is passed as the second argument to wal_checkpoint_v2(). If it the
5603 ** NAME argument is not present, a NULL pointer is passed instead.
5604 **
5605 ** If wal_checkpoint_v2() returns any value other than SQLITE_BUSY or
5606 ** SQLITE_OK, then this command returns TCL_ERROR. The Tcl result is set
5607 ** to the error message obtained from sqlite3_errmsg().
5608 **
5609 ** Otherwise, this command returns a list of three integers. The first integer
5610 ** is 1 if SQLITE_BUSY was returned, or 0 otherwise. The following two integers
5611 ** are the values returned via the output paramaters by wal_checkpoint_v2() -
5612 ** the number of frames in the log and the number of frames in the log
5613 ** that have been checkpointed.
5614 */
5615 static int test_wal_checkpoint_v2(
5616   ClientData clientData, /* Unused */
5617   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
5618   int objc,              /* Number of arguments */
5619   Tcl_Obj *CONST objv[]  /* Command arguments */
5620 ){
5621   char *zDb = 0;
5622   sqlite3 *db;
5623   int rc;
5624 
5625   int eMode;
5626   int nLog = -555;
5627   int nCkpt = -555;
5628   Tcl_Obj *pRet;
5629 
5630   const char * aMode[] = { "passive", "full", "restart", 0 };
5631   assert( SQLITE_CHECKPOINT_PASSIVE==0 );
5632   assert( SQLITE_CHECKPOINT_FULL==1 );
5633   assert( SQLITE_CHECKPOINT_RESTART==2 );
5634 
5635   if( objc!=3 && objc!=4 ){
5636     Tcl_WrongNumArgs(interp, 1, objv, "DB MODE ?NAME?");
5637     return TCL_ERROR;
5638   }
5639 
5640   if( objc==4 ){
5641     zDb = Tcl_GetString(objv[3]);
5642   }
5643   if( getDbPointer(interp, Tcl_GetString(objv[1]), &db)
5644    || Tcl_GetIndexFromObj(interp, objv[2], aMode, "mode", 0, &eMode)
5645   ){
5646     return TCL_ERROR;
5647   }
5648 
5649   rc = sqlite3_wal_checkpoint_v2(db, zDb, eMode, &nLog, &nCkpt);
5650   if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
5651     Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
5652     return TCL_ERROR;
5653   }
5654 
5655   pRet = Tcl_NewObj();
5656   Tcl_ListObjAppendElement(interp, pRet, Tcl_NewIntObj(rc==SQLITE_BUSY?1:0));
5657   Tcl_ListObjAppendElement(interp, pRet, Tcl_NewIntObj(nLog));
5658   Tcl_ListObjAppendElement(interp, pRet, Tcl_NewIntObj(nCkpt));
5659   Tcl_SetObjResult(interp, pRet);
5660 
5661   return TCL_OK;
5662 }
5663 
5664 /*
5665 ** tclcmd:  test_sqlite3_log ?SCRIPT?
5666 */
5667 static struct LogCallback {
5668   Tcl_Interp *pInterp;
5669   Tcl_Obj *pObj;
5670 } logcallback = {0, 0};
5671 static void xLogcallback(void *unused, int err, char *zMsg){
5672   Tcl_Obj *pNew = Tcl_DuplicateObj(logcallback.pObj);
5673   Tcl_IncrRefCount(pNew);
5674   Tcl_ListObjAppendElement(
5675       0, pNew, Tcl_NewStringObj(sqlite3TestErrorName(err), -1)
5676   );
5677   Tcl_ListObjAppendElement(0, pNew, Tcl_NewStringObj(zMsg, -1));
5678   Tcl_EvalObjEx(logcallback.pInterp, pNew, TCL_EVAL_GLOBAL|TCL_EVAL_DIRECT);
5679   Tcl_DecrRefCount(pNew);
5680 }
5681 static int test_sqlite3_log(
5682   ClientData clientData,
5683   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
5684   int objc,              /* Number of arguments */
5685   Tcl_Obj *CONST objv[]  /* Command arguments */
5686 ){
5687   if( objc>2 ){
5688     Tcl_WrongNumArgs(interp, 1, objv, "SCRIPT");
5689     return TCL_ERROR;
5690   }
5691   if( logcallback.pObj ){
5692     Tcl_DecrRefCount(logcallback.pObj);
5693     logcallback.pObj = 0;
5694     logcallback.pInterp = 0;
5695     sqlite3_config(SQLITE_CONFIG_LOG, 0, 0);
5696   }
5697   if( objc>1 ){
5698     logcallback.pObj = objv[1];
5699     Tcl_IncrRefCount(logcallback.pObj);
5700     logcallback.pInterp = interp;
5701     sqlite3_config(SQLITE_CONFIG_LOG, xLogcallback, 0);
5702   }
5703   return TCL_OK;
5704 }
5705 
5706 /*
5707 **     tcl_objproc COMMANDNAME ARGS...
5708 **
5709 ** Run a TCL command using its objProc interface.  Throw an error if
5710 ** the command has no objProc interface.
5711 */
5712 static int runAsObjProc(
5713   void * clientData,
5714   Tcl_Interp *interp,
5715   int objc,
5716   Tcl_Obj *CONST objv[]
5717 ){
5718   Tcl_CmdInfo cmdInfo;
5719   if( objc<2 ){
5720     Tcl_WrongNumArgs(interp, 1, objv, "COMMAND ...");
5721     return TCL_ERROR;
5722   }
5723   if( !Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &cmdInfo) ){
5724     Tcl_AppendResult(interp, "command not found: ",
5725            Tcl_GetString(objv[1]), (char*)0);
5726     return TCL_ERROR;
5727   }
5728   if( cmdInfo.objProc==0 ){
5729     Tcl_AppendResult(interp, "command has no objProc: ",
5730            Tcl_GetString(objv[1]), (char*)0);
5731     return TCL_ERROR;
5732   }
5733   return cmdInfo.objProc(cmdInfo.objClientData, interp, objc-1, objv+1);
5734 }
5735 
5736 #ifndef SQLITE_OMIT_EXPLAIN
5737 /*
5738 ** WARNING: The following function, printExplainQueryPlan() is an exact
5739 ** copy of example code from eqp.in (eqp.html). If this code is modified,
5740 ** then the documentation copy needs to be modified as well.
5741 */
5742 /*
5743 ** Argument pStmt is a prepared SQL statement. This function compiles
5744 ** an EXPLAIN QUERY PLAN command to report on the prepared statement,
5745 ** and prints the report to stdout using printf().
5746 */
5747 int printExplainQueryPlan(sqlite3_stmt *pStmt){
5748   const char *zSql;               /* Input SQL */
5749   char *zExplain;                 /* SQL with EXPLAIN QUERY PLAN prepended */
5750   sqlite3_stmt *pExplain;         /* Compiled EXPLAIN QUERY PLAN command */
5751   int rc;                         /* Return code from sqlite3_prepare_v2() */
5752 
5753   zSql = sqlite3_sql(pStmt);
5754   if( zSql==0 ) return SQLITE_ERROR;
5755 
5756   zExplain = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zSql);
5757   if( zExplain==0 ) return SQLITE_NOMEM;
5758 
5759   rc = sqlite3_prepare_v2(sqlite3_db_handle(pStmt), zExplain, -1, &pExplain, 0);
5760   sqlite3_free(zExplain);
5761   if( rc!=SQLITE_OK ) return rc;
5762 
5763   while( SQLITE_ROW==sqlite3_step(pExplain) ){
5764     int iSelectid = sqlite3_column_int(pExplain, 0);
5765     int iOrder = sqlite3_column_int(pExplain, 1);
5766     int iFrom = sqlite3_column_int(pExplain, 2);
5767     const char *zDetail = (const char *)sqlite3_column_text(pExplain, 3);
5768 
5769     printf("%d %d %d %s\n", iSelectid, iOrder, iFrom, zDetail);
5770   }
5771 
5772   return sqlite3_finalize(pExplain);
5773 }
5774 
5775 static int test_print_eqp(
5776   void * clientData,
5777   Tcl_Interp *interp,
5778   int objc,
5779   Tcl_Obj *CONST objv[]
5780 ){
5781   int rc;
5782   sqlite3_stmt *pStmt;
5783 
5784   if( objc!=2 ){
5785     Tcl_WrongNumArgs(interp, 1, objv, "STMT");
5786     return TCL_ERROR;
5787   }
5788   if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
5789   rc = printExplainQueryPlan(pStmt);
5790   /* This is needed on Windows so that a test case using this
5791   ** function can open a read pipe and get the output of
5792   ** printExplainQueryPlan() immediately.
5793   */
5794   fflush(stdout);
5795   Tcl_SetResult(interp, (char *)t1ErrorName(rc), 0);
5796   return TCL_OK;
5797 }
5798 #endif /* SQLITE_OMIT_EXPLAIN */
5799 
5800 /*
5801 ** sqlite3_test_control VERB ARGS...
5802 */
5803 static int test_test_control(
5804   void * clientData,
5805   Tcl_Interp *interp,
5806   int objc,
5807   Tcl_Obj *CONST objv[]
5808 ){
5809   struct Verb {
5810     const char *zName;
5811     int i;
5812   } aVerb[] = {
5813     { "SQLITE_TESTCTRL_LOCALTIME_FAULT", SQLITE_TESTCTRL_LOCALTIME_FAULT },
5814   };
5815   int iVerb;
5816   int iFlag;
5817   int rc;
5818 
5819   if( objc<2 ){
5820     Tcl_WrongNumArgs(interp, 1, objv, "VERB ARGS...");
5821     return TCL_ERROR;
5822   }
5823 
5824   rc = Tcl_GetIndexFromObjStruct(
5825       interp, objv[1], aVerb, sizeof(aVerb[0]), "VERB", 0, &iVerb
5826   );
5827   if( rc!=TCL_OK ) return rc;
5828 
5829   iFlag = aVerb[iVerb].i;
5830   switch( iFlag ){
5831     case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
5832       int val;
5833       if( objc!=3 ){
5834         Tcl_WrongNumArgs(interp, 2, objv, "ONOFF");
5835         return TCL_ERROR;
5836       }
5837       if( Tcl_GetBooleanFromObj(interp, objv[2], &val) ) return TCL_ERROR;
5838       sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, val);
5839       break;
5840     }
5841   }
5842 
5843   Tcl_ResetResult(interp);
5844   return TCL_OK;
5845 }
5846 
5847 #if SQLITE_OS_WIN
5848 /*
5849 ** Information passed from the main thread into the windows file locker
5850 ** background thread.
5851 */
5852 struct win32FileLocker {
5853   char *evName;       /* Name of event to signal thread startup */
5854   HANDLE h;           /* Handle of the file to be locked */
5855   int delay1;         /* Delay before locking */
5856   int delay2;         /* Delay before unlocking */
5857   int ok;             /* Finished ok */
5858   int err;            /* True if an error occurs */
5859 };
5860 #endif
5861 
5862 
5863 #if SQLITE_OS_WIN
5864 #include <process.h>
5865 /*
5866 ** The background thread that does file locking.
5867 */
5868 static void win32_file_locker(void *pAppData){
5869   struct win32FileLocker *p = (struct win32FileLocker*)pAppData;
5870   if( p->evName ){
5871     HANDLE ev = OpenEvent(EVENT_MODIFY_STATE, FALSE, p->evName);
5872     if ( ev ){
5873       SetEvent(ev);
5874       CloseHandle(ev);
5875     }
5876   }
5877   if( p->delay1 ) Sleep(p->delay1);
5878   if( LockFile(p->h, 0, 0, 100000000, 0) ){
5879     Sleep(p->delay2);
5880     UnlockFile(p->h, 0, 0, 100000000, 0);
5881     p->ok = 1;
5882   }else{
5883     p->err = 1;
5884   }
5885   CloseHandle(p->h);
5886   p->h = 0;
5887   p->delay1 = 0;
5888   p->delay2 = 0;
5889 }
5890 #endif
5891 
5892 #if SQLITE_OS_WIN
5893 /*
5894 **      lock_win32_file FILENAME DELAY1 DELAY2
5895 **
5896 ** Get an exclusive manditory lock on file for DELAY2 milliseconds.
5897 ** Wait DELAY1 milliseconds before acquiring the lock.
5898 */
5899 static int win32_file_lock(
5900   void * clientData,
5901   Tcl_Interp *interp,
5902   int objc,
5903   Tcl_Obj *CONST objv[]
5904 ){
5905   static struct win32FileLocker x = { "win32_file_lock", 0, 0, 0, 0, 0 };
5906   const char *zFilename;
5907   char zBuf[200];
5908   int retry = 0;
5909   HANDLE ev;
5910   DWORD wResult;
5911 
5912   if( objc!=4 && objc!=1 ){
5913     Tcl_WrongNumArgs(interp, 1, objv, "FILENAME DELAY1 DELAY2");
5914     return TCL_ERROR;
5915   }
5916   if( objc==1 ){
5917     sqlite3_snprintf(sizeof(zBuf), zBuf, "%d %d %d %d %d",
5918                      x.ok, x.err, x.delay1, x.delay2, x.h);
5919     Tcl_AppendResult(interp, zBuf, (char*)0);
5920     return TCL_OK;
5921   }
5922   while( x.h && retry<30 ){
5923     retry++;
5924     Sleep(100);
5925   }
5926   if( x.h ){
5927     Tcl_AppendResult(interp, "busy", (char*)0);
5928     return TCL_ERROR;
5929   }
5930   if( Tcl_GetIntFromObj(interp, objv[2], &x.delay1) ) return TCL_ERROR;
5931   if( Tcl_GetIntFromObj(interp, objv[3], &x.delay2) ) return TCL_ERROR;
5932   zFilename = Tcl_GetString(objv[1]);
5933   x.h = CreateFile(zFilename, GENERIC_READ|GENERIC_WRITE,
5934               FILE_SHARE_READ|FILE_SHARE_WRITE, 0, OPEN_ALWAYS,
5935               FILE_ATTRIBUTE_NORMAL, 0);
5936   if( !x.h ){
5937     Tcl_AppendResult(interp, "cannot open file: ", zFilename, (char*)0);
5938     return TCL_ERROR;
5939   }
5940   ev = CreateEvent(NULL, TRUE, FALSE, x.evName);
5941   if ( !ev ){
5942     Tcl_AppendResult(interp, "cannot create event: ", x.evName, (char*)0);
5943     return TCL_ERROR;
5944   }
5945   _beginthread(win32_file_locker, 0, (void*)&x);
5946   Sleep(0);
5947   if ( (wResult = WaitForSingleObject(ev, 10000))!=WAIT_OBJECT_0 ){
5948     sqlite3_snprintf(sizeof(zBuf), zBuf, "0x%x", wResult);
5949     Tcl_AppendResult(interp, "wait failed: ", zBuf, (char*)0);
5950     CloseHandle(ev);
5951     return TCL_ERROR;
5952   }
5953   CloseHandle(ev);
5954   return TCL_OK;
5955 }
5956 #endif
5957 
5958 
5959 /*
5960 **      optimization_control DB OPT BOOLEAN
5961 **
5962 ** Enable or disable query optimizations using the sqlite3_test_control()
5963 ** interface.  Disable if BOOLEAN is false and enable if BOOLEAN is true.
5964 ** OPT is the name of the optimization to be disabled.
5965 */
5966 static int optimization_control(
5967   void * clientData,
5968   Tcl_Interp *interp,
5969   int objc,
5970   Tcl_Obj *CONST objv[]
5971 ){
5972   int i;
5973   sqlite3 *db;
5974   const char *zOpt;
5975   int onoff;
5976   int mask = 0;
5977   static const struct {
5978     const char *zOptName;
5979     int mask;
5980   } aOpt[] = {
5981     { "all",              SQLITE_AllOpts        },
5982     { "query-flattener",  SQLITE_QueryFlattener },
5983     { "column-cache",     SQLITE_ColumnCache    },
5984     { "groupby-order",    SQLITE_GroupByOrder   },
5985     { "factor-constants", SQLITE_FactorOutConst },
5986     { "real-as-int",      SQLITE_IdxRealAsInt   },
5987     { "distinct-opt",     SQLITE_DistinctOpt    },
5988     { "cover-idx-scan",   SQLITE_CoverIdxScan   },
5989     { "order-by-idx-join",SQLITE_OrderByIdxJoin },
5990   };
5991 
5992   if( objc!=4 ){
5993     Tcl_WrongNumArgs(interp, 1, objv, "DB OPT BOOLEAN");
5994     return TCL_ERROR;
5995   }
5996   if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
5997   if( Tcl_GetBooleanFromObj(interp, objv[3], &onoff) ) return TCL_ERROR;
5998   zOpt = Tcl_GetString(objv[2]);
5999   for(i=0; i<sizeof(aOpt)/sizeof(aOpt[0]); i++){
6000     if( strcmp(zOpt, aOpt[i].zOptName)==0 ){
6001       mask = aOpt[i].mask;
6002       break;
6003     }
6004   }
6005   if( onoff ) mask = ~mask;
6006   if( i>=sizeof(aOpt)/sizeof(aOpt[0]) ){
6007     Tcl_AppendResult(interp, "unknown optimization - should be one of:",
6008                      (char*)0);
6009     for(i=0; i<sizeof(aOpt)/sizeof(aOpt[0]); i++){
6010       Tcl_AppendResult(interp, " ", aOpt[i].zOptName);
6011     }
6012     return TCL_ERROR;
6013   }
6014   sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, db, mask);
6015   return TCL_OK;
6016 }
6017 
6018 /*
6019 ** Register commands with the TCL interpreter.
6020 */
6021 int Sqlitetest1_Init(Tcl_Interp *interp){
6022   extern int sqlite3_search_count;
6023   extern int sqlite3_found_count;
6024   extern int sqlite3_interrupt_count;
6025   extern int sqlite3_open_file_count;
6026   extern int sqlite3_sort_count;
6027   extern int sqlite3_current_time;
6028 #if SQLITE_OS_UNIX && defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
6029   extern int sqlite3_hostid_num;
6030 #endif
6031   extern int sqlite3_max_blobsize;
6032   extern int sqlite3BtreeSharedCacheReport(void*,
6033                                           Tcl_Interp*,int,Tcl_Obj*CONST*);
6034   static struct {
6035      char *zName;
6036      Tcl_CmdProc *xProc;
6037   } aCmd[] = {
6038      { "db_enter",                      (Tcl_CmdProc*)db_enter               },
6039      { "db_leave",                      (Tcl_CmdProc*)db_leave               },
6040      { "sqlite3_mprintf_int",           (Tcl_CmdProc*)sqlite3_mprintf_int    },
6041      { "sqlite3_mprintf_int64",         (Tcl_CmdProc*)sqlite3_mprintf_int64  },
6042      { "sqlite3_mprintf_long",          (Tcl_CmdProc*)sqlite3_mprintf_long   },
6043      { "sqlite3_mprintf_str",           (Tcl_CmdProc*)sqlite3_mprintf_str    },
6044      { "sqlite3_snprintf_str",          (Tcl_CmdProc*)sqlite3_snprintf_str   },
6045      { "sqlite3_mprintf_stronly",       (Tcl_CmdProc*)sqlite3_mprintf_stronly},
6046      { "sqlite3_mprintf_double",        (Tcl_CmdProc*)sqlite3_mprintf_double },
6047      { "sqlite3_mprintf_scaled",        (Tcl_CmdProc*)sqlite3_mprintf_scaled },
6048      { "sqlite3_mprintf_hexdouble",   (Tcl_CmdProc*)sqlite3_mprintf_hexdouble},
6049      { "sqlite3_mprintf_z_test",        (Tcl_CmdProc*)test_mprintf_z        },
6050      { "sqlite3_mprintf_n_test",        (Tcl_CmdProc*)test_mprintf_n        },
6051      { "sqlite3_snprintf_int",          (Tcl_CmdProc*)test_snprintf_int     },
6052      { "sqlite3_last_insert_rowid",     (Tcl_CmdProc*)test_last_rowid       },
6053      { "sqlite3_exec_printf",           (Tcl_CmdProc*)test_exec_printf      },
6054      { "sqlite3_exec_hex",              (Tcl_CmdProc*)test_exec_hex         },
6055      { "sqlite3_exec",                  (Tcl_CmdProc*)test_exec             },
6056      { "sqlite3_exec_nr",               (Tcl_CmdProc*)test_exec_nr          },
6057 #ifndef SQLITE_OMIT_GET_TABLE
6058      { "sqlite3_get_table_printf",      (Tcl_CmdProc*)test_get_table_printf },
6059 #endif
6060      { "sqlite3_close",                 (Tcl_CmdProc*)sqlite_test_close     },
6061      { "sqlite3_create_function",       (Tcl_CmdProc*)test_create_function  },
6062      { "sqlite3_create_aggregate",      (Tcl_CmdProc*)test_create_aggregate },
6063      { "sqlite_register_test_function", (Tcl_CmdProc*)test_register_func    },
6064      { "sqlite_abort",                  (Tcl_CmdProc*)sqlite_abort          },
6065      { "sqlite_bind",                   (Tcl_CmdProc*)test_bind             },
6066      { "breakpoint",                    (Tcl_CmdProc*)test_breakpoint       },
6067      { "sqlite3_key",                   (Tcl_CmdProc*)test_key              },
6068      { "sqlite3_rekey",                 (Tcl_CmdProc*)test_rekey            },
6069      { "sqlite_set_magic",              (Tcl_CmdProc*)sqlite_set_magic      },
6070      { "sqlite3_interrupt",             (Tcl_CmdProc*)test_interrupt        },
6071      { "sqlite_delete_function",        (Tcl_CmdProc*)delete_function       },
6072      { "sqlite_delete_collation",       (Tcl_CmdProc*)delete_collation      },
6073      { "sqlite3_get_autocommit",        (Tcl_CmdProc*)get_autocommit        },
6074      { "sqlite3_stack_used",            (Tcl_CmdProc*)test_stack_used       },
6075      { "sqlite3_busy_timeout",          (Tcl_CmdProc*)test_busy_timeout     },
6076      { "printf",                        (Tcl_CmdProc*)test_printf           },
6077      { "sqlite3IoTrace",              (Tcl_CmdProc*)test_io_trace         },
6078   };
6079   static struct {
6080      char *zName;
6081      Tcl_ObjCmdProc *xProc;
6082      void *clientData;
6083   } aObjCmd[] = {
6084      { "sqlite3_connection_pointer",    get_sqlite_pointer, 0 },
6085      { "sqlite3_bind_int",              test_bind_int,      0 },
6086      { "sqlite3_bind_zeroblob",         test_bind_zeroblob, 0 },
6087      { "sqlite3_bind_int64",            test_bind_int64,    0 },
6088      { "sqlite3_bind_double",           test_bind_double,   0 },
6089      { "sqlite3_bind_null",             test_bind_null     ,0 },
6090      { "sqlite3_bind_text",             test_bind_text     ,0 },
6091      { "sqlite3_bind_text16",           test_bind_text16   ,0 },
6092      { "sqlite3_bind_blob",             test_bind_blob     ,0 },
6093      { "sqlite3_bind_parameter_count",  test_bind_parameter_count, 0},
6094      { "sqlite3_bind_parameter_name",   test_bind_parameter_name,  0},
6095      { "sqlite3_bind_parameter_index",  test_bind_parameter_index, 0},
6096      { "sqlite3_clear_bindings",        test_clear_bindings, 0},
6097      { "sqlite3_sleep",                 test_sleep,          0},
6098      { "sqlite3_errcode",               test_errcode       ,0 },
6099      { "sqlite3_extended_errcode",      test_ex_errcode    ,0 },
6100      { "sqlite3_errmsg",                test_errmsg        ,0 },
6101      { "sqlite3_errmsg16",              test_errmsg16      ,0 },
6102      { "sqlite3_open",                  test_open          ,0 },
6103      { "sqlite3_open16",                test_open16        ,0 },
6104      { "sqlite3_open_v2",               test_open_v2       ,0 },
6105      { "sqlite3_complete16",            test_complete16    ,0 },
6106 
6107      { "sqlite3_prepare",               test_prepare       ,0 },
6108      { "sqlite3_prepare16",             test_prepare16     ,0 },
6109      { "sqlite3_prepare_v2",            test_prepare_v2    ,0 },
6110      { "sqlite3_prepare_tkt3134",       test_prepare_tkt3134, 0},
6111      { "sqlite3_prepare16_v2",          test_prepare16_v2  ,0 },
6112      { "sqlite3_finalize",              test_finalize      ,0 },
6113      { "sqlite3_stmt_status",           test_stmt_status   ,0 },
6114      { "sqlite3_reset",                 test_reset         ,0 },
6115      { "sqlite3_expired",               test_expired       ,0 },
6116      { "sqlite3_transfer_bindings",     test_transfer_bind ,0 },
6117      { "sqlite3_changes",               test_changes       ,0 },
6118      { "sqlite3_step",                  test_step          ,0 },
6119      { "sqlite3_sql",                   test_sql           ,0 },
6120      { "sqlite3_next_stmt",             test_next_stmt     ,0 },
6121      { "sqlite3_stmt_readonly",         test_stmt_readonly ,0 },
6122      { "sqlite3_stmt_busy",             test_stmt_busy     ,0 },
6123      { "uses_stmt_journal",             uses_stmt_journal ,0 },
6124 
6125      { "sqlite3_release_memory",        test_release_memory,     0},
6126      { "sqlite3_db_release_memory",     test_db_release_memory,  0},
6127      { "sqlite3_db_filename",           test_db_filename,        0},
6128      { "sqlite3_db_readonly",           test_db_readonly,        0},
6129      { "sqlite3_soft_heap_limit",       test_soft_heap_limit,    0},
6130      { "sqlite3_thread_cleanup",        test_thread_cleanup,     0},
6131      { "sqlite3_pager_refcounts",       test_pager_refcounts,    0},
6132 
6133      { "sqlite3_load_extension",        test_load_extension,     0},
6134      { "sqlite3_enable_load_extension", test_enable_load,        0},
6135      { "sqlite3_extended_result_codes", test_extended_result_codes, 0},
6136      { "sqlite3_limit",                 test_limit,                 0},
6137 
6138      { "save_prng_state",               save_prng_state,    0 },
6139      { "restore_prng_state",            restore_prng_state, 0 },
6140      { "reset_prng_state",              reset_prng_state,   0 },
6141      { "optimization_control",          optimization_control,0},
6142 #if SQLITE_OS_WIN
6143      { "lock_win32_file",               win32_file_lock,    0 },
6144 #endif
6145      { "tcl_objproc",                   runAsObjProc,       0 },
6146 
6147      /* sqlite3_column_*() API */
6148      { "sqlite3_column_count",          test_column_count  ,0 },
6149      { "sqlite3_data_count",            test_data_count    ,0 },
6150      { "sqlite3_column_type",           test_column_type   ,0 },
6151      { "sqlite3_column_blob",           test_column_blob   ,0 },
6152      { "sqlite3_column_double",         test_column_double ,0 },
6153      { "sqlite3_column_int64",          test_column_int64  ,0 },
6154      { "sqlite3_column_text",   test_stmt_utf8,  (void*)sqlite3_column_text },
6155      { "sqlite3_column_name",   test_stmt_utf8,  (void*)sqlite3_column_name },
6156      { "sqlite3_column_int",    test_stmt_int,   (void*)sqlite3_column_int  },
6157      { "sqlite3_column_bytes",  test_stmt_int,   (void*)sqlite3_column_bytes},
6158 #ifndef SQLITE_OMIT_DECLTYPE
6159      { "sqlite3_column_decltype",test_stmt_utf8,(void*)sqlite3_column_decltype},
6160 #endif
6161 #ifdef SQLITE_ENABLE_COLUMN_METADATA
6162 { "sqlite3_column_database_name",test_stmt_utf8,(void*)sqlite3_column_database_name},
6163 { "sqlite3_column_table_name",test_stmt_utf8,(void*)sqlite3_column_table_name},
6164 { "sqlite3_column_origin_name",test_stmt_utf8,(void*)sqlite3_column_origin_name},
6165 #endif
6166 
6167 #ifndef SQLITE_OMIT_UTF16
6168      { "sqlite3_column_bytes16", test_stmt_int, (void*)sqlite3_column_bytes16 },
6169      { "sqlite3_column_text16",  test_stmt_utf16, (void*)sqlite3_column_text16},
6170      { "sqlite3_column_name16",  test_stmt_utf16, (void*)sqlite3_column_name16},
6171      { "add_alignment_test_collations", add_alignment_test_collations, 0      },
6172 #ifndef SQLITE_OMIT_DECLTYPE
6173      { "sqlite3_column_decltype16",test_stmt_utf16,(void*)sqlite3_column_decltype16},
6174 #endif
6175 #ifdef SQLITE_ENABLE_COLUMN_METADATA
6176 {"sqlite3_column_database_name16",
6177   test_stmt_utf16, (void*)sqlite3_column_database_name16},
6178 {"sqlite3_column_table_name16", test_stmt_utf16, (void*)sqlite3_column_table_name16},
6179 {"sqlite3_column_origin_name16", test_stmt_utf16, (void*)sqlite3_column_origin_name16},
6180 #endif
6181 #endif
6182      { "sqlite3_create_collation_v2", test_create_collation_v2, 0 },
6183      { "sqlite3_global_recover",     test_global_recover, 0   },
6184      { "working_64bit_int",          working_64bit_int,   0   },
6185      { "vfs_unlink_test",            vfs_unlink_test,     0   },
6186      { "vfs_initfail_test",          vfs_initfail_test,   0   },
6187      { "vfs_unregister_all",         vfs_unregister_all,  0   },
6188      { "vfs_reregister_all",         vfs_reregister_all,  0   },
6189      { "file_control_test",          file_control_test,   0   },
6190      { "file_control_lasterrno_test", file_control_lasterrno_test,  0   },
6191      { "file_control_lockproxy_test", file_control_lockproxy_test,  0   },
6192      { "file_control_chunksize_test", file_control_chunksize_test,  0   },
6193      { "file_control_sizehint_test",  file_control_sizehint_test,   0   },
6194      { "file_control_win32_av_retry", file_control_win32_av_retry,  0   },
6195      { "file_control_persist_wal",    file_control_persist_wal,     0   },
6196      { "file_control_powersafe_overwrite",file_control_powersafe_overwrite,0},
6197      { "file_control_vfsname",        file_control_vfsname,         0   },
6198      { "file_control_tempfilename",   file_control_tempfilename,    0   },
6199      { "sqlite3_vfs_list",           vfs_list,     0   },
6200      { "sqlite3_create_function_v2", test_create_function_v2, 0 },
6201 
6202      /* Functions from os.h */
6203 #ifndef SQLITE_OMIT_UTF16
6204      { "add_test_collate",        test_collate, 0            },
6205      { "add_test_collate_needed", test_collate_needed, 0     },
6206      { "add_test_function",       test_function, 0           },
6207 #endif
6208      { "sqlite3_test_errstr",     test_errstr, 0             },
6209      { "tcl_variable_type",       tcl_variable_type, 0       },
6210 #ifndef SQLITE_OMIT_SHARED_CACHE
6211      { "sqlite3_enable_shared_cache", test_enable_shared, 0  },
6212      { "sqlite3_shared_cache_report", sqlite3BtreeSharedCacheReport, 0},
6213 #endif
6214      { "sqlite3_libversion_number", test_libversion_number, 0  },
6215 #ifdef SQLITE_ENABLE_COLUMN_METADATA
6216      { "sqlite3_table_column_metadata", test_table_column_metadata, 0  },
6217 #endif
6218 #ifndef SQLITE_OMIT_INCRBLOB
6219      { "sqlite3_blob_read",   test_blob_read, 0  },
6220      { "sqlite3_blob_write",  test_blob_write, 0  },
6221      { "sqlite3_blob_reopen", test_blob_reopen, 0  },
6222      { "sqlite3_blob_bytes",  test_blob_bytes, 0  },
6223      { "sqlite3_blob_close",  test_blob_close, 0  },
6224 #endif
6225      { "pcache_stats",       test_pcache_stats, 0  },
6226 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
6227      { "sqlite3_unlock_notify", test_unlock_notify, 0  },
6228 #endif
6229      { "sqlite3_wal_checkpoint",   test_wal_checkpoint, 0  },
6230      { "sqlite3_wal_checkpoint_v2",test_wal_checkpoint_v2, 0  },
6231      { "test_sqlite3_log",         test_sqlite3_log, 0  },
6232 #ifndef SQLITE_OMIT_EXPLAIN
6233      { "print_explain_query_plan", test_print_eqp, 0  },
6234 #endif
6235      { "sqlite3_test_control", test_test_control },
6236   };
6237   static int bitmask_size = sizeof(Bitmask)*8;
6238   int i;
6239   extern int sqlite3_sync_count, sqlite3_fullsync_count;
6240   extern int sqlite3_opentemp_count;
6241   extern int sqlite3_like_count;
6242   extern int sqlite3_xferopt_count;
6243   extern int sqlite3_pager_readdb_count;
6244   extern int sqlite3_pager_writedb_count;
6245   extern int sqlite3_pager_writej_count;
6246 #if SQLITE_OS_WIN
6247   extern int sqlite3_os_type;
6248 #endif
6249 #ifdef SQLITE_DEBUG
6250   extern int sqlite3WhereTrace;
6251   extern int sqlite3OSTrace;
6252   extern int sqlite3WalTrace;
6253 #endif
6254 #ifdef SQLITE_TEST
6255   extern char sqlite3_query_plan[];
6256   static char *query_plan = sqlite3_query_plan;
6257 #ifdef SQLITE_ENABLE_FTS3
6258   extern int sqlite3_fts3_enable_parentheses;
6259 #endif
6260 #endif
6261 
6262   for(i=0; i<sizeof(aCmd)/sizeof(aCmd[0]); i++){
6263     Tcl_CreateCommand(interp, aCmd[i].zName, aCmd[i].xProc, 0, 0);
6264   }
6265   for(i=0; i<sizeof(aObjCmd)/sizeof(aObjCmd[0]); i++){
6266     Tcl_CreateObjCommand(interp, aObjCmd[i].zName,
6267         aObjCmd[i].xProc, aObjCmd[i].clientData, 0);
6268   }
6269   Tcl_LinkVar(interp, "sqlite_search_count",
6270       (char*)&sqlite3_search_count, TCL_LINK_INT);
6271   Tcl_LinkVar(interp, "sqlite_found_count",
6272       (char*)&sqlite3_found_count, TCL_LINK_INT);
6273   Tcl_LinkVar(interp, "sqlite_sort_count",
6274       (char*)&sqlite3_sort_count, TCL_LINK_INT);
6275   Tcl_LinkVar(interp, "sqlite3_max_blobsize",
6276       (char*)&sqlite3_max_blobsize, TCL_LINK_INT);
6277   Tcl_LinkVar(interp, "sqlite_like_count",
6278       (char*)&sqlite3_like_count, TCL_LINK_INT);
6279   Tcl_LinkVar(interp, "sqlite_interrupt_count",
6280       (char*)&sqlite3_interrupt_count, TCL_LINK_INT);
6281   Tcl_LinkVar(interp, "sqlite_open_file_count",
6282       (char*)&sqlite3_open_file_count, TCL_LINK_INT);
6283   Tcl_LinkVar(interp, "sqlite_current_time",
6284       (char*)&sqlite3_current_time, TCL_LINK_INT);
6285 #if SQLITE_OS_UNIX && defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
6286   Tcl_LinkVar(interp, "sqlite_hostid_num",
6287       (char*)&sqlite3_hostid_num, TCL_LINK_INT);
6288 #endif
6289   Tcl_LinkVar(interp, "sqlite3_xferopt_count",
6290       (char*)&sqlite3_xferopt_count, TCL_LINK_INT);
6291   Tcl_LinkVar(interp, "sqlite3_pager_readdb_count",
6292       (char*)&sqlite3_pager_readdb_count, TCL_LINK_INT);
6293   Tcl_LinkVar(interp, "sqlite3_pager_writedb_count",
6294       (char*)&sqlite3_pager_writedb_count, TCL_LINK_INT);
6295   Tcl_LinkVar(interp, "sqlite3_pager_writej_count",
6296       (char*)&sqlite3_pager_writej_count, TCL_LINK_INT);
6297 #ifndef SQLITE_OMIT_UTF16
6298   Tcl_LinkVar(interp, "unaligned_string_counter",
6299       (char*)&unaligned_string_counter, TCL_LINK_INT);
6300 #endif
6301 #ifndef SQLITE_OMIT_UTF16
6302   Tcl_LinkVar(interp, "sqlite_last_needed_collation",
6303       (char*)&pzNeededCollation, TCL_LINK_STRING|TCL_LINK_READ_ONLY);
6304 #endif
6305 #if SQLITE_OS_WIN
6306   Tcl_LinkVar(interp, "sqlite_os_type",
6307       (char*)&sqlite3_os_type, TCL_LINK_INT);
6308 #endif
6309 #ifdef SQLITE_TEST
6310   Tcl_LinkVar(interp, "sqlite_query_plan",
6311       (char*)&query_plan, TCL_LINK_STRING|TCL_LINK_READ_ONLY);
6312 #endif
6313 #ifdef SQLITE_DEBUG
6314   Tcl_LinkVar(interp, "sqlite_where_trace",
6315       (char*)&sqlite3WhereTrace, TCL_LINK_INT);
6316   Tcl_LinkVar(interp, "sqlite_os_trace",
6317       (char*)&sqlite3OSTrace, TCL_LINK_INT);
6318 #ifndef SQLITE_OMIT_WAL
6319   Tcl_LinkVar(interp, "sqlite_wal_trace",
6320       (char*)&sqlite3WalTrace, TCL_LINK_INT);
6321 #endif
6322 #endif
6323 #ifndef SQLITE_OMIT_DISKIO
6324   Tcl_LinkVar(interp, "sqlite_opentemp_count",
6325       (char*)&sqlite3_opentemp_count, TCL_LINK_INT);
6326 #endif
6327   Tcl_LinkVar(interp, "sqlite_static_bind_value",
6328       (char*)&sqlite_static_bind_value, TCL_LINK_STRING);
6329   Tcl_LinkVar(interp, "sqlite_static_bind_nbyte",
6330       (char*)&sqlite_static_bind_nbyte, TCL_LINK_INT);
6331   Tcl_LinkVar(interp, "sqlite_temp_directory",
6332       (char*)&sqlite3_temp_directory, TCL_LINK_STRING);
6333   Tcl_LinkVar(interp, "sqlite_data_directory",
6334       (char*)&sqlite3_data_directory, TCL_LINK_STRING);
6335   Tcl_LinkVar(interp, "bitmask_size",
6336       (char*)&bitmask_size, TCL_LINK_INT|TCL_LINK_READ_ONLY);
6337   Tcl_LinkVar(interp, "sqlite_sync_count",
6338       (char*)&sqlite3_sync_count, TCL_LINK_INT);
6339   Tcl_LinkVar(interp, "sqlite_fullsync_count",
6340       (char*)&sqlite3_fullsync_count, TCL_LINK_INT);
6341 #if defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_TEST)
6342   Tcl_LinkVar(interp, "sqlite_fts3_enable_parentheses",
6343       (char*)&sqlite3_fts3_enable_parentheses, TCL_LINK_INT);
6344 #endif
6345   return TCL_OK;
6346 }
6347