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