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