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