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