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