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