xref: /sqlite-3.40.0/src/test8.c (revision e3147332)
1 /*
2 ** 2006 June 10
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 the virtual table 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 #ifndef SQLITE_OMIT_VIRTUALTABLE
22 
23 typedef struct echo_vtab echo_vtab;
24 typedef struct echo_cursor echo_cursor;
25 
26 /*
27 ** The test module defined in this file uses four global Tcl variables to
28 ** commicate with test-scripts:
29 **
30 **     $::echo_module
31 **     $::echo_module_sync_fail
32 **     $::echo_module_begin_fail
33 **     $::echo_module_cost
34 **
35 ** The variable ::echo_module is a list. Each time one of the following
36 ** methods is called, one or more elements are appended to the list.
37 ** This is used for automated testing of virtual table modules.
38 **
39 ** The ::echo_module_sync_fail variable is set by test scripts and read
40 ** by code in this file. If it is set to the name of a real table in the
41 ** the database, then all xSync operations on echo virtual tables that
42 ** use the named table as a backing store will fail.
43 */
44 
45 /*
46 ** Errors can be provoked within the following echo virtual table methods:
47 **
48 **   xBestIndex   xOpen     xFilter   xNext
49 **   xColumn      xRowid    xUpdate   xSync
50 **   xBegin       xRename
51 **
52 ** This is done by setting the global tcl variable:
53 **
54 **   echo_module_fail($method,$tbl)
55 **
56 ** where $method is set to the name of the virtual table method to fail
57 ** (i.e. "xBestIndex") and $tbl is the name of the table being echoed (not
58 ** the name of the virtual table, the name of the underlying real table).
59 */
60 
61 /*
62 ** An echo virtual-table object.
63 **
64 ** echo.vtab.aIndex is an array of booleans. The nth entry is true if
65 ** the nth column of the real table is the left-most column of an index
66 ** (implicit or otherwise). In other words, if SQLite can optimize
67 ** a query like "SELECT * FROM real_table WHERE col = ?".
68 **
69 ** Member variable aCol[] contains copies of the column names of the real
70 ** table.
71 */
72 struct echo_vtab {
73   sqlite3_vtab base;
74   Tcl_Interp *interp;     /* Tcl interpreter containing debug variables */
75   sqlite3 *db;            /* Database connection */
76 
77   int isPattern;
78   int inTransaction;      /* True if within a transaction */
79   char *zThis;            /* Name of the echo table */
80   char *zTableName;       /* Name of the real table */
81   char *zLogName;         /* Name of the log table */
82   int nCol;               /* Number of columns in the real table */
83   int *aIndex;            /* Array of size nCol. True if column has an index */
84   char **aCol;            /* Array of size nCol. Column names */
85 };
86 
87 /* An echo cursor object */
88 struct echo_cursor {
89   sqlite3_vtab_cursor base;
90   sqlite3_stmt *pStmt;
91 };
92 
93 static int simulateVtabError(echo_vtab *p, const char *zMethod){
94   const char *zErr;
95   char zVarname[128];
96   zVarname[127] = '\0';
97   sqlite3_snprintf(127, zVarname, "echo_module_fail(%s,%s)", zMethod, p->zTableName);
98   zErr = Tcl_GetVar(p->interp, zVarname, TCL_GLOBAL_ONLY);
99   if( zErr ){
100     p->base.zErrMsg = sqlite3_mprintf("echo-vtab-error: %s", zErr);
101   }
102   return (zErr!=0);
103 }
104 
105 /*
106 ** Convert an SQL-style quoted string into a normal string by removing
107 ** the quote characters.  The conversion is done in-place.  If the
108 ** input does not begin with a quote character, then this routine
109 ** is a no-op.
110 **
111 ** Examples:
112 **
113 **     "abc"   becomes   abc
114 **     'xyz'   becomes   xyz
115 **     [pqr]   becomes   pqr
116 **     `mno`   becomes   mno
117 */
118 static void dequoteString(char *z){
119   int quote;
120   int i, j;
121   if( z==0 ) return;
122   quote = z[0];
123   switch( quote ){
124     case '\'':  break;
125     case '"':   break;
126     case '`':   break;                /* For MySQL compatibility */
127     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
128     default:    return;
129   }
130   for(i=1, j=0; z[i]; i++){
131     if( z[i]==quote ){
132       if( z[i+1]==quote ){
133         z[j++] = quote;
134         i++;
135       }else{
136         z[j++] = 0;
137         break;
138       }
139     }else{
140       z[j++] = z[i];
141     }
142   }
143 }
144 
145 /*
146 ** Retrieve the column names for the table named zTab via database
147 ** connection db. SQLITE_OK is returned on success, or an sqlite error
148 ** code otherwise.
149 **
150 ** If successful, the number of columns is written to *pnCol. *paCol is
151 ** set to point at sqlite3_malloc()'d space containing the array of
152 ** nCol column names. The caller is responsible for calling sqlite3_free
153 ** on *paCol.
154 */
155 static int getColumnNames(
156   sqlite3 *db,
157   const char *zTab,
158   char ***paCol,
159   int *pnCol
160 ){
161   char **aCol = 0;
162   char *zSql;
163   sqlite3_stmt *pStmt = 0;
164   int rc = SQLITE_OK;
165   int nCol = 0;
166 
167   /* Prepare the statement "SELECT * FROM <tbl>". The column names
168   ** of the result set of the compiled SELECT will be the same as
169   ** the column names of table <tbl>.
170   */
171   zSql = sqlite3_mprintf("SELECT * FROM %Q", zTab);
172   if( !zSql ){
173     rc = SQLITE_NOMEM;
174     goto out;
175   }
176   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
177   sqlite3_free(zSql);
178 
179   if( rc==SQLITE_OK ){
180     int ii;
181     int nBytes;
182     char *zSpace;
183     nCol = sqlite3_column_count(pStmt);
184 
185     /* Figure out how much space to allocate for the array of column names
186     ** (including space for the strings themselves). Then allocate it.
187     */
188     nBytes = sizeof(char *) * nCol;
189     for(ii=0; ii<nCol; ii++){
190       const char *zName = sqlite3_column_name(pStmt, ii);
191       if( !zName ){
192         rc = SQLITE_NOMEM;
193         goto out;
194       }
195       nBytes += (int)strlen(zName)+1;
196     }
197     aCol = (char **)sqlite3MallocZero(nBytes);
198     if( !aCol ){
199       rc = SQLITE_NOMEM;
200       goto out;
201     }
202 
203     /* Copy the column names into the allocated space and set up the
204     ** pointers in the aCol[] array.
205     */
206     zSpace = (char *)(&aCol[nCol]);
207     for(ii=0; ii<nCol; ii++){
208       aCol[ii] = zSpace;
209       zSpace += sprintf(zSpace, "%s", sqlite3_column_name(pStmt, ii));
210       zSpace++;
211     }
212     assert( (zSpace-nBytes)==(char *)aCol );
213   }
214 
215   *paCol = aCol;
216   *pnCol = nCol;
217 
218 out:
219   sqlite3_finalize(pStmt);
220   return rc;
221 }
222 
223 /*
224 ** Parameter zTab is the name of a table in database db with nCol
225 ** columns. This function allocates an array of integers nCol in
226 ** size and populates it according to any implicit or explicit
227 ** indices on table zTab.
228 **
229 ** If successful, SQLITE_OK is returned and *paIndex set to point
230 ** at the allocated array. Otherwise, an error code is returned.
231 **
232 ** See comments associated with the member variable aIndex above
233 ** "struct echo_vtab" for details of the contents of the array.
234 */
235 static int getIndexArray(
236   sqlite3 *db,             /* Database connection */
237   const char *zTab,        /* Name of table in database db */
238   int nCol,
239   int **paIndex
240 ){
241   sqlite3_stmt *pStmt = 0;
242   int *aIndex = 0;
243   int rc;
244   char *zSql;
245 
246   /* Allocate space for the index array */
247   aIndex = (int *)sqlite3MallocZero(sizeof(int) * nCol);
248   if( !aIndex ){
249     rc = SQLITE_NOMEM;
250     goto get_index_array_out;
251   }
252 
253   /* Compile an sqlite pragma to loop through all indices on table zTab */
254   zSql = sqlite3_mprintf("PRAGMA index_list(%s)", zTab);
255   if( !zSql ){
256     rc = SQLITE_NOMEM;
257     goto get_index_array_out;
258   }
259   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
260   sqlite3_free(zSql);
261 
262   /* For each index, figure out the left-most column and set the
263   ** corresponding entry in aIndex[] to 1.
264   */
265   while( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
266     const char *zIdx = (const char *)sqlite3_column_text(pStmt, 1);
267     sqlite3_stmt *pStmt2 = 0;
268     zSql = sqlite3_mprintf("PRAGMA index_info(%s)", zIdx);
269     if( !zSql ){
270       rc = SQLITE_NOMEM;
271       goto get_index_array_out;
272     }
273     rc = sqlite3_prepare(db, zSql, -1, &pStmt2, 0);
274     sqlite3_free(zSql);
275     if( pStmt2 && sqlite3_step(pStmt2)==SQLITE_ROW ){
276       int cid = sqlite3_column_int(pStmt2, 1);
277       assert( cid>=0 && cid<nCol );
278       aIndex[cid] = 1;
279     }
280     if( pStmt2 ){
281       rc = sqlite3_finalize(pStmt2);
282     }
283     if( rc!=SQLITE_OK ){
284       goto get_index_array_out;
285     }
286   }
287 
288 
289 get_index_array_out:
290   if( pStmt ){
291     int rc2 = sqlite3_finalize(pStmt);
292     if( rc==SQLITE_OK ){
293       rc = rc2;
294     }
295   }
296   if( rc!=SQLITE_OK ){
297     sqlite3_free(aIndex);
298     aIndex = 0;
299   }
300   *paIndex = aIndex;
301   return rc;
302 }
303 
304 /*
305 ** Global Tcl variable $echo_module is a list. This routine appends
306 ** the string element zArg to that list in interpreter interp.
307 */
308 static void appendToEchoModule(Tcl_Interp *interp, const char *zArg){
309   int flags = (TCL_APPEND_VALUE | TCL_LIST_ELEMENT | TCL_GLOBAL_ONLY);
310   Tcl_SetVar(interp, "echo_module", (zArg?zArg:""), flags);
311 }
312 
313 /*
314 ** This function is called from within the echo-modules xCreate and
315 ** xConnect methods. The argc and argv arguments are copies of those
316 ** passed to the calling method. This function is responsible for
317 ** calling sqlite3_declare_vtab() to declare the schema of the virtual
318 ** table being created or connected.
319 **
320 ** If the constructor was passed just one argument, i.e.:
321 **
322 **   CREATE TABLE t1 AS echo(t2);
323 **
324 ** Then t2 is assumed to be the name of a *real* database table. The
325 ** schema of the virtual table is declared by passing a copy of the
326 ** CREATE TABLE statement for the real table to sqlite3_declare_vtab().
327 ** Hence, the virtual table should have exactly the same column names and
328 ** types as the real table.
329 */
330 static int echoDeclareVtab(
331   echo_vtab *pVtab,
332   sqlite3 *db
333 ){
334   int rc = SQLITE_OK;
335 
336   if( pVtab->zTableName ){
337     sqlite3_stmt *pStmt = 0;
338     rc = sqlite3_prepare(db,
339         "SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?",
340         -1, &pStmt, 0);
341     if( rc==SQLITE_OK ){
342       sqlite3_bind_text(pStmt, 1, pVtab->zTableName, -1, 0);
343       if( sqlite3_step(pStmt)==SQLITE_ROW ){
344         int rc2;
345         const char *zCreateTable = (const char *)sqlite3_column_text(pStmt, 0);
346         rc = sqlite3_declare_vtab(db, zCreateTable);
347         rc2 = sqlite3_finalize(pStmt);
348         if( rc==SQLITE_OK ){
349           rc = rc2;
350         }
351       } else {
352         rc = sqlite3_finalize(pStmt);
353         if( rc==SQLITE_OK ){
354           rc = SQLITE_ERROR;
355         }
356       }
357       if( rc==SQLITE_OK ){
358         rc = getColumnNames(db, pVtab->zTableName, &pVtab->aCol, &pVtab->nCol);
359       }
360       if( rc==SQLITE_OK ){
361         rc = getIndexArray(db, pVtab->zTableName, pVtab->nCol, &pVtab->aIndex);
362       }
363     }
364   }
365 
366   return rc;
367 }
368 
369 /*
370 ** This function frees all runtime structures associated with the virtual
371 ** table pVtab.
372 */
373 static int echoDestructor(sqlite3_vtab *pVtab){
374   echo_vtab *p = (echo_vtab*)pVtab;
375   sqlite3_free(p->aIndex);
376   sqlite3_free(p->aCol);
377   sqlite3_free(p->zThis);
378   sqlite3_free(p->zTableName);
379   sqlite3_free(p->zLogName);
380   sqlite3_free(p);
381   return 0;
382 }
383 
384 typedef struct EchoModule EchoModule;
385 struct EchoModule {
386   Tcl_Interp *interp;
387 };
388 
389 /*
390 ** This function is called to do the work of the xConnect() method -
391 ** to allocate the required in-memory structures for a newly connected
392 ** virtual table.
393 */
394 static int echoConstructor(
395   sqlite3 *db,
396   void *pAux,
397   int argc, const char *const*argv,
398   sqlite3_vtab **ppVtab,
399   char **pzErr
400 ){
401   int rc;
402   int i;
403   echo_vtab *pVtab;
404 
405   /* Allocate the sqlite3_vtab/echo_vtab structure itself */
406   pVtab = sqlite3MallocZero( sizeof(*pVtab) );
407   if( !pVtab ){
408     return SQLITE_NOMEM;
409   }
410   pVtab->interp = ((EchoModule *)pAux)->interp;
411   pVtab->db = db;
412 
413   /* Allocate echo_vtab.zThis */
414   pVtab->zThis = sqlite3_mprintf("%s", argv[2]);
415   if( !pVtab->zThis ){
416     echoDestructor((sqlite3_vtab *)pVtab);
417     return SQLITE_NOMEM;
418   }
419 
420   /* Allocate echo_vtab.zTableName */
421   if( argc>3 ){
422     pVtab->zTableName = sqlite3_mprintf("%s", argv[3]);
423     dequoteString(pVtab->zTableName);
424     if( pVtab->zTableName && pVtab->zTableName[0]=='*' ){
425       char *z = sqlite3_mprintf("%s%s", argv[2], &(pVtab->zTableName[1]));
426       sqlite3_free(pVtab->zTableName);
427       pVtab->zTableName = z;
428       pVtab->isPattern = 1;
429     }
430     if( !pVtab->zTableName ){
431       echoDestructor((sqlite3_vtab *)pVtab);
432       return SQLITE_NOMEM;
433     }
434   }
435 
436   /* Log the arguments to this function to Tcl var ::echo_module */
437   for(i=0; i<argc; i++){
438     appendToEchoModule(pVtab->interp, argv[i]);
439   }
440 
441   /* Invoke sqlite3_declare_vtab and set up other members of the echo_vtab
442   ** structure. If an error occurs, delete the sqlite3_vtab structure and
443   ** return an error code.
444   */
445   rc = echoDeclareVtab(pVtab, db);
446   if( rc!=SQLITE_OK ){
447     echoDestructor((sqlite3_vtab *)pVtab);
448     return rc;
449   }
450 
451   /* Success. Set *ppVtab and return */
452   *ppVtab = &pVtab->base;
453   return SQLITE_OK;
454 }
455 
456 /*
457 ** Echo virtual table module xCreate method.
458 */
459 static int echoCreate(
460   sqlite3 *db,
461   void *pAux,
462   int argc, const char *const*argv,
463   sqlite3_vtab **ppVtab,
464   char **pzErr
465 ){
466   int rc = SQLITE_OK;
467   appendToEchoModule(((EchoModule *)pAux)->interp, "xCreate");
468   rc = echoConstructor(db, pAux, argc, argv, ppVtab, pzErr);
469 
470   /* If there were two arguments passed to the module at the SQL level
471   ** (i.e. "CREATE VIRTUAL TABLE tbl USING echo(arg1, arg2)"), then
472   ** the second argument is used as a table name. Attempt to create
473   ** such a table with a single column, "logmsg". This table will
474   ** be used to log calls to the xUpdate method. It will be deleted
475   ** when the virtual table is DROPed.
476   **
477   ** Note: The main point of this is to test that we can drop tables
478   ** from within an xDestroy method call.
479   */
480   if( rc==SQLITE_OK && argc==5 ){
481     char *zSql;
482     echo_vtab *pVtab = *(echo_vtab **)ppVtab;
483     pVtab->zLogName = sqlite3_mprintf("%s", argv[4]);
484     zSql = sqlite3_mprintf("CREATE TABLE %Q(logmsg)", pVtab->zLogName);
485     rc = sqlite3_exec(db, zSql, 0, 0, 0);
486     sqlite3_free(zSql);
487     if( rc!=SQLITE_OK ){
488       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
489     }
490   }
491 
492   if( *ppVtab && rc!=SQLITE_OK ){
493     echoDestructor(*ppVtab);
494     *ppVtab = 0;
495   }
496 
497   if( rc==SQLITE_OK ){
498     (*(echo_vtab**)ppVtab)->inTransaction = 1;
499   }
500 
501   return rc;
502 }
503 
504 /*
505 ** Echo virtual table module xConnect method.
506 */
507 static int echoConnect(
508   sqlite3 *db,
509   void *pAux,
510   int argc, const char *const*argv,
511   sqlite3_vtab **ppVtab,
512   char **pzErr
513 ){
514   appendToEchoModule(((EchoModule *)pAux)->interp, "xConnect");
515   return echoConstructor(db, pAux, argc, argv, ppVtab, pzErr);
516 }
517 
518 /*
519 ** Echo virtual table module xDisconnect method.
520 */
521 static int echoDisconnect(sqlite3_vtab *pVtab){
522   appendToEchoModule(((echo_vtab *)pVtab)->interp, "xDisconnect");
523   return echoDestructor(pVtab);
524 }
525 
526 /*
527 ** Echo virtual table module xDestroy method.
528 */
529 static int echoDestroy(sqlite3_vtab *pVtab){
530   int rc = SQLITE_OK;
531   echo_vtab *p = (echo_vtab *)pVtab;
532   appendToEchoModule(((echo_vtab *)pVtab)->interp, "xDestroy");
533 
534   /* Drop the "log" table, if one exists (see echoCreate() for details) */
535   if( p && p->zLogName ){
536     char *zSql;
537     zSql = sqlite3_mprintf("DROP TABLE %Q", p->zLogName);
538     rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
539     sqlite3_free(zSql);
540   }
541 
542   if( rc==SQLITE_OK ){
543     rc = echoDestructor(pVtab);
544   }
545   return rc;
546 }
547 
548 /*
549 ** Echo virtual table module xOpen method.
550 */
551 static int echoOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
552   echo_cursor *pCur;
553   if( simulateVtabError((echo_vtab *)pVTab, "xOpen") ){
554     return SQLITE_ERROR;
555   }
556   pCur = sqlite3MallocZero(sizeof(echo_cursor));
557   *ppCursor = (sqlite3_vtab_cursor *)pCur;
558   return (pCur ? SQLITE_OK : SQLITE_NOMEM);
559 }
560 
561 /*
562 ** Echo virtual table module xClose method.
563 */
564 static int echoClose(sqlite3_vtab_cursor *cur){
565   int rc;
566   echo_cursor *pCur = (echo_cursor *)cur;
567   sqlite3_stmt *pStmt = pCur->pStmt;
568   pCur->pStmt = 0;
569   sqlite3_free(pCur);
570   rc = sqlite3_finalize(pStmt);
571   return rc;
572 }
573 
574 /*
575 ** Return non-zero if the cursor does not currently point to a valid record
576 ** (i.e if the scan has finished), or zero otherwise.
577 */
578 static int echoEof(sqlite3_vtab_cursor *cur){
579   return (((echo_cursor *)cur)->pStmt ? 0 : 1);
580 }
581 
582 /*
583 ** Echo virtual table module xNext method.
584 */
585 static int echoNext(sqlite3_vtab_cursor *cur){
586   int rc = SQLITE_OK;
587   echo_cursor *pCur = (echo_cursor *)cur;
588 
589   if( simulateVtabError((echo_vtab *)(cur->pVtab), "xNext") ){
590     return SQLITE_ERROR;
591   }
592 
593   if( pCur->pStmt ){
594     rc = sqlite3_step(pCur->pStmt);
595     if( rc==SQLITE_ROW ){
596       rc = SQLITE_OK;
597     }else{
598       rc = sqlite3_finalize(pCur->pStmt);
599       pCur->pStmt = 0;
600     }
601   }
602 
603   return rc;
604 }
605 
606 /*
607 ** Echo virtual table module xColumn method.
608 */
609 static int echoColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
610   int iCol = i + 1;
611   sqlite3_stmt *pStmt = ((echo_cursor *)cur)->pStmt;
612 
613   if( simulateVtabError((echo_vtab *)(cur->pVtab), "xColumn") ){
614     return SQLITE_ERROR;
615   }
616 
617   if( !pStmt ){
618     sqlite3_result_null(ctx);
619   }else{
620     assert( sqlite3_data_count(pStmt)>iCol );
621     sqlite3_result_value(ctx, sqlite3_column_value(pStmt, iCol));
622   }
623   return SQLITE_OK;
624 }
625 
626 /*
627 ** Echo virtual table module xRowid method.
628 */
629 static int echoRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
630   sqlite3_stmt *pStmt = ((echo_cursor *)cur)->pStmt;
631 
632   if( simulateVtabError((echo_vtab *)(cur->pVtab), "xRowid") ){
633     return SQLITE_ERROR;
634   }
635 
636   *pRowid = sqlite3_column_int64(pStmt, 0);
637   return SQLITE_OK;
638 }
639 
640 /*
641 ** Compute a simple hash of the null terminated string zString.
642 **
643 ** This module uses only sqlite3_index_info.idxStr, not
644 ** sqlite3_index_info.idxNum. So to test idxNum, when idxStr is set
645 ** in echoBestIndex(), idxNum is set to the corresponding hash value.
646 ** In echoFilter(), code assert()s that the supplied idxNum value is
647 ** indeed the hash of the supplied idxStr.
648 */
649 static int hashString(const char *zString){
650   int val = 0;
651   int ii;
652   for(ii=0; zString[ii]; ii++){
653     val = (val << 3) + (int)zString[ii];
654   }
655   return val;
656 }
657 
658 /*
659 ** Echo virtual table module xFilter method.
660 */
661 static int echoFilter(
662   sqlite3_vtab_cursor *pVtabCursor,
663   int idxNum, const char *idxStr,
664   int argc, sqlite3_value **argv
665 ){
666   int rc;
667   int i;
668 
669   echo_cursor *pCur = (echo_cursor *)pVtabCursor;
670   echo_vtab *pVtab = (echo_vtab *)pVtabCursor->pVtab;
671   sqlite3 *db = pVtab->db;
672 
673   if( simulateVtabError(pVtab, "xFilter") ){
674     return SQLITE_ERROR;
675   }
676 
677   /* Check that idxNum matches idxStr */
678   assert( idxNum==hashString(idxStr) );
679 
680   /* Log arguments to the ::echo_module Tcl variable */
681   appendToEchoModule(pVtab->interp, "xFilter");
682   appendToEchoModule(pVtab->interp, idxStr);
683   for(i=0; i<argc; i++){
684     appendToEchoModule(pVtab->interp, (const char*)sqlite3_value_text(argv[i]));
685   }
686 
687   sqlite3_finalize(pCur->pStmt);
688   pCur->pStmt = 0;
689 
690   /* Prepare the SQL statement created by echoBestIndex and bind the
691   ** runtime parameters passed to this function to it.
692   */
693   rc = sqlite3_prepare(db, idxStr, -1, &pCur->pStmt, 0);
694   assert( pCur->pStmt || rc!=SQLITE_OK );
695   for(i=0; rc==SQLITE_OK && i<argc; i++){
696     rc = sqlite3_bind_value(pCur->pStmt, i+1, argv[i]);
697   }
698 
699   /* If everything was successful, advance to the first row of the scan */
700   if( rc==SQLITE_OK ){
701     rc = echoNext(pVtabCursor);
702   }
703 
704   return rc;
705 }
706 
707 
708 /*
709 ** A helper function used by echoUpdate() and echoBestIndex() for
710 ** manipulating strings in concert with the sqlite3_mprintf() function.
711 **
712 ** Parameter pzStr points to a pointer to a string allocated with
713 ** sqlite3_mprintf. The second parameter, zAppend, points to another
714 ** string. The two strings are concatenated together and *pzStr
715 ** set to point at the result. The initial buffer pointed to by *pzStr
716 ** is deallocated via sqlite3_free().
717 **
718 ** If the third argument, doFree, is true, then sqlite3_free() is
719 ** also called to free the buffer pointed to by zAppend.
720 */
721 static void string_concat(char **pzStr, char *zAppend, int doFree, int *pRc){
722   char *zIn = *pzStr;
723   if( !zAppend && doFree && *pRc==SQLITE_OK ){
724     *pRc = SQLITE_NOMEM;
725   }
726   if( *pRc!=SQLITE_OK ){
727     sqlite3_free(zIn);
728     zIn = 0;
729   }else{
730     if( zIn ){
731       char *zTemp = zIn;
732       zIn = sqlite3_mprintf("%s%s", zIn, zAppend);
733       sqlite3_free(zTemp);
734     }else{
735       zIn = sqlite3_mprintf("%s", zAppend);
736     }
737     if( !zIn ){
738       *pRc = SQLITE_NOMEM;
739     }
740   }
741   *pzStr = zIn;
742   if( doFree ){
743     sqlite3_free(zAppend);
744   }
745 }
746 
747 /*
748 ** The echo module implements the subset of query constraints and sort
749 ** orders that may take advantage of SQLite indices on the underlying
750 ** real table. For example, if the real table is declared as:
751 **
752 **     CREATE TABLE real(a, b, c);
753 **     CREATE INDEX real_index ON real(b);
754 **
755 ** then the echo module handles WHERE or ORDER BY clauses that refer
756 ** to the column "b", but not "a" or "c". If a multi-column index is
757 ** present, only its left most column is considered.
758 **
759 ** This xBestIndex method encodes the proposed search strategy as
760 ** an SQL query on the real table underlying the virtual echo module
761 ** table and stores the query in sqlite3_index_info.idxStr. The SQL
762 ** statement is of the form:
763 **
764 **   SELECT rowid, * FROM <real-table> ?<where-clause>? ?<order-by-clause>?
765 **
766 ** where the <where-clause> and <order-by-clause> are determined
767 ** by the contents of the structure pointed to by the pIdxInfo argument.
768 */
769 static int echoBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
770   int ii;
771   char *zQuery = 0;
772   char *zNew;
773   int nArg = 0;
774   const char *zSep = "WHERE";
775   echo_vtab *pVtab = (echo_vtab *)tab;
776   sqlite3_stmt *pStmt = 0;
777   Tcl_Interp *interp = pVtab->interp;
778 
779   int nRow;
780   int useIdx = 0;
781   int rc = SQLITE_OK;
782   int useCost = 0;
783   double cost;
784   int isIgnoreUsable = 0;
785   if( Tcl_GetVar(interp, "echo_module_ignore_usable", TCL_GLOBAL_ONLY) ){
786     isIgnoreUsable = 1;
787   }
788 
789   if( simulateVtabError(pVtab, "xBestIndex") ){
790     return SQLITE_ERROR;
791   }
792 
793   /* Determine the number of rows in the table and store this value in local
794   ** variable nRow. The 'estimated-cost' of the scan will be the number of
795   ** rows in the table for a linear scan, or the log (base 2) of the
796   ** number of rows if the proposed scan uses an index.
797   */
798   if( Tcl_GetVar(interp, "echo_module_cost", TCL_GLOBAL_ONLY) ){
799     cost = atof(Tcl_GetVar(interp, "echo_module_cost", TCL_GLOBAL_ONLY));
800     useCost = 1;
801   } else {
802     zQuery = sqlite3_mprintf("SELECT count(*) FROM %Q", pVtab->zTableName);
803     if( !zQuery ){
804       return SQLITE_NOMEM;
805     }
806     rc = sqlite3_prepare(pVtab->db, zQuery, -1, &pStmt, 0);
807     sqlite3_free(zQuery);
808     if( rc!=SQLITE_OK ){
809       return rc;
810     }
811     sqlite3_step(pStmt);
812     nRow = sqlite3_column_int(pStmt, 0);
813     rc = sqlite3_finalize(pStmt);
814     if( rc!=SQLITE_OK ){
815       return rc;
816     }
817   }
818 
819   zQuery = sqlite3_mprintf("SELECT rowid, * FROM %Q", pVtab->zTableName);
820   if( !zQuery ){
821     return SQLITE_NOMEM;
822   }
823   for(ii=0; ii<pIdxInfo->nConstraint; ii++){
824     const struct sqlite3_index_constraint *pConstraint;
825     struct sqlite3_index_constraint_usage *pUsage;
826     int iCol;
827 
828     pConstraint = &pIdxInfo->aConstraint[ii];
829     pUsage = &pIdxInfo->aConstraintUsage[ii];
830 
831     if( !isIgnoreUsable && !pConstraint->usable ) continue;
832 
833     iCol = pConstraint->iColumn;
834     if( iCol<0 || pVtab->aIndex[iCol] ){
835       char *zCol = iCol>=0 ? pVtab->aCol[iCol] : "rowid";
836       char *zOp = 0;
837       useIdx = 1;
838       switch( pConstraint->op ){
839         case SQLITE_INDEX_CONSTRAINT_EQ:
840           zOp = "="; break;
841         case SQLITE_INDEX_CONSTRAINT_LT:
842           zOp = "<"; break;
843         case SQLITE_INDEX_CONSTRAINT_GT:
844           zOp = ">"; break;
845         case SQLITE_INDEX_CONSTRAINT_LE:
846           zOp = "<="; break;
847         case SQLITE_INDEX_CONSTRAINT_GE:
848           zOp = ">="; break;
849         case SQLITE_INDEX_CONSTRAINT_MATCH:
850           zOp = "LIKE"; break;
851       }
852       if( zOp[0]=='L' ){
853         zNew = sqlite3_mprintf(" %s %s LIKE (SELECT '%%'||?||'%%')",
854                                zSep, zCol);
855       } else {
856         zNew = sqlite3_mprintf(" %s %s %s ?", zSep, zCol, zOp);
857       }
858       string_concat(&zQuery, zNew, 1, &rc);
859 
860       zSep = "AND";
861       pUsage->argvIndex = ++nArg;
862       pUsage->omit = 1;
863     }
864   }
865 
866   /* If there is only one term in the ORDER BY clause, and it is
867   ** on a column that this virtual table has an index for, then consume
868   ** the ORDER BY clause.
869   */
870   if( pIdxInfo->nOrderBy==1 && (
871         pIdxInfo->aOrderBy->iColumn<0 ||
872         pVtab->aIndex[pIdxInfo->aOrderBy->iColumn]) ){
873     int iCol = pIdxInfo->aOrderBy->iColumn;
874     char *zCol = iCol>=0 ? pVtab->aCol[iCol] : "rowid";
875     char *zDir = pIdxInfo->aOrderBy->desc?"DESC":"ASC";
876     zNew = sqlite3_mprintf(" ORDER BY %s %s", zCol, zDir);
877     string_concat(&zQuery, zNew, 1, &rc);
878     pIdxInfo->orderByConsumed = 1;
879   }
880 
881   appendToEchoModule(pVtab->interp, "xBestIndex");;
882   appendToEchoModule(pVtab->interp, zQuery);
883 
884   if( !zQuery ){
885     return rc;
886   }
887   pIdxInfo->idxNum = hashString(zQuery);
888   pIdxInfo->idxStr = zQuery;
889   pIdxInfo->needToFreeIdxStr = 1;
890   if( useCost ){
891     pIdxInfo->estimatedCost = cost;
892   }else if( useIdx ){
893     /* Approximation of log2(nRow). */
894     for( ii=0; ii<(sizeof(int)*8); ii++ ){
895       if( nRow & (1<<ii) ){
896         pIdxInfo->estimatedCost = (double)ii;
897       }
898     }
899   }else{
900     pIdxInfo->estimatedCost = (double)nRow;
901   }
902   return rc;
903 }
904 
905 /*
906 ** The xUpdate method for echo module virtual tables.
907 **
908 **    apData[0]  apData[1]  apData[2..]
909 **
910 **    INTEGER                              DELETE
911 **
912 **    INTEGER    NULL       (nCol args)    UPDATE (do not set rowid)
913 **    INTEGER    INTEGER    (nCol args)    UPDATE (with SET rowid = <arg1>)
914 **
915 **    NULL       NULL       (nCol args)    INSERT INTO (automatic rowid value)
916 **    NULL       INTEGER    (nCol args)    INSERT (incl. rowid value)
917 **
918 */
919 int echoUpdate(
920   sqlite3_vtab *tab,
921   int nData,
922   sqlite3_value **apData,
923   sqlite_int64 *pRowid
924 ){
925   echo_vtab *pVtab = (echo_vtab *)tab;
926   sqlite3 *db = pVtab->db;
927   int rc = SQLITE_OK;
928 
929   sqlite3_stmt *pStmt;
930   char *z = 0;               /* SQL statement to execute */
931   int bindArgZero = 0;       /* True to bind apData[0] to sql var no. nData */
932   int bindArgOne = 0;        /* True to bind apData[1] to sql var no. 1 */
933   int i;                     /* Counter variable used by for loops */
934 
935   assert( nData==pVtab->nCol+2 || nData==1 );
936 
937   /* Ticket #3083 - make sure we always start a transaction prior to
938   ** making any changes to a virtual table */
939   assert( pVtab->inTransaction );
940 
941   if( simulateVtabError(pVtab, "xUpdate") ){
942     return SQLITE_ERROR;
943   }
944 
945   /* If apData[0] is an integer and nData>1 then do an UPDATE */
946   if( nData>1 && sqlite3_value_type(apData[0])==SQLITE_INTEGER ){
947     char *zSep = " SET";
948     z = sqlite3_mprintf("UPDATE %Q", pVtab->zTableName);
949     if( !z ){
950       rc = SQLITE_NOMEM;
951     }
952 
953     bindArgOne = (apData[1] && sqlite3_value_type(apData[1])==SQLITE_INTEGER);
954     bindArgZero = 1;
955 
956     if( bindArgOne ){
957        string_concat(&z, " SET rowid=?1 ", 0, &rc);
958        zSep = ",";
959     }
960     for(i=2; i<nData; i++){
961       if( apData[i]==0 ) continue;
962       string_concat(&z, sqlite3_mprintf(
963           "%s %Q=?%d", zSep, pVtab->aCol[i-2], i), 1, &rc);
964       zSep = ",";
965     }
966     string_concat(&z, sqlite3_mprintf(" WHERE rowid=?%d", nData), 1, &rc);
967   }
968 
969   /* If apData[0] is an integer and nData==1 then do a DELETE */
970   else if( nData==1 && sqlite3_value_type(apData[0])==SQLITE_INTEGER ){
971     z = sqlite3_mprintf("DELETE FROM %Q WHERE rowid = ?1", pVtab->zTableName);
972     if( !z ){
973       rc = SQLITE_NOMEM;
974     }
975     bindArgZero = 1;
976   }
977 
978   /* If the first argument is NULL and there are more than two args, INSERT */
979   else if( nData>2 && sqlite3_value_type(apData[0])==SQLITE_NULL ){
980     int ii;
981     char *zInsert = 0;
982     char *zValues = 0;
983 
984     zInsert = sqlite3_mprintf("INSERT INTO %Q (", pVtab->zTableName);
985     if( !zInsert ){
986       rc = SQLITE_NOMEM;
987     }
988     if( sqlite3_value_type(apData[1])==SQLITE_INTEGER ){
989       bindArgOne = 1;
990       zValues = sqlite3_mprintf("?");
991       string_concat(&zInsert, "rowid", 0, &rc);
992     }
993 
994     assert((pVtab->nCol+2)==nData);
995     for(ii=2; ii<nData; ii++){
996       string_concat(&zInsert,
997           sqlite3_mprintf("%s%Q", zValues?", ":"", pVtab->aCol[ii-2]), 1, &rc);
998       string_concat(&zValues,
999           sqlite3_mprintf("%s?%d", zValues?", ":"", ii), 1, &rc);
1000     }
1001 
1002     string_concat(&z, zInsert, 1, &rc);
1003     string_concat(&z, ") VALUES(", 0, &rc);
1004     string_concat(&z, zValues, 1, &rc);
1005     string_concat(&z, ")", 0, &rc);
1006   }
1007 
1008   /* Anything else is an error */
1009   else{
1010     assert(0);
1011     return SQLITE_ERROR;
1012   }
1013 
1014   if( rc==SQLITE_OK ){
1015     rc = sqlite3_prepare(db, z, -1, &pStmt, 0);
1016   }
1017   assert( rc!=SQLITE_OK || pStmt );
1018   sqlite3_free(z);
1019   if( rc==SQLITE_OK ) {
1020     if( bindArgZero ){
1021       sqlite3_bind_value(pStmt, nData, apData[0]);
1022     }
1023     if( bindArgOne ){
1024       sqlite3_bind_value(pStmt, 1, apData[1]);
1025     }
1026     for(i=2; i<nData && rc==SQLITE_OK; i++){
1027       if( apData[i] ) rc = sqlite3_bind_value(pStmt, i, apData[i]);
1028     }
1029     if( rc==SQLITE_OK ){
1030       sqlite3_step(pStmt);
1031       rc = sqlite3_finalize(pStmt);
1032     }else{
1033       sqlite3_finalize(pStmt);
1034     }
1035   }
1036 
1037   if( pRowid && rc==SQLITE_OK ){
1038     *pRowid = sqlite3_last_insert_rowid(db);
1039   }
1040   if( rc!=SQLITE_OK ){
1041     tab->zErrMsg = sqlite3_mprintf("echo-vtab-error: %s", sqlite3_errmsg(db));
1042   }
1043 
1044   return rc;
1045 }
1046 
1047 /*
1048 ** xBegin, xSync, xCommit and xRollback callbacks for echo module
1049 ** virtual tables. Do nothing other than add the name of the callback
1050 ** to the $::echo_module Tcl variable.
1051 */
1052 static int echoTransactionCall(sqlite3_vtab *tab, const char *zCall){
1053   char *z;
1054   echo_vtab *pVtab = (echo_vtab *)tab;
1055   z = sqlite3_mprintf("echo(%s)", pVtab->zTableName);
1056   if( z==0 ) return SQLITE_NOMEM;
1057   appendToEchoModule(pVtab->interp, zCall);
1058   appendToEchoModule(pVtab->interp, z);
1059   sqlite3_free(z);
1060   return SQLITE_OK;
1061 }
1062 static int echoBegin(sqlite3_vtab *tab){
1063   int rc;
1064   echo_vtab *pVtab = (echo_vtab *)tab;
1065   Tcl_Interp *interp = pVtab->interp;
1066   const char *zVal;
1067 
1068   /* Ticket #3083 - do not start a transaction if we are already in
1069   ** a transaction */
1070   assert( !pVtab->inTransaction );
1071 
1072   if( simulateVtabError(pVtab, "xBegin") ){
1073     return SQLITE_ERROR;
1074   }
1075 
1076   rc = echoTransactionCall(tab, "xBegin");
1077 
1078   if( rc==SQLITE_OK ){
1079     /* Check if the $::echo_module_begin_fail variable is defined. If it is,
1080     ** and it is set to the name of the real table underlying this virtual
1081     ** echo module table, then cause this xSync operation to fail.
1082     */
1083     zVal = Tcl_GetVar(interp, "echo_module_begin_fail", TCL_GLOBAL_ONLY);
1084     if( zVal && 0==strcmp(zVal, pVtab->zTableName) ){
1085       rc = SQLITE_ERROR;
1086     }
1087   }
1088   if( rc==SQLITE_OK ){
1089     pVtab->inTransaction = 1;
1090   }
1091   return rc;
1092 }
1093 static int echoSync(sqlite3_vtab *tab){
1094   int rc;
1095   echo_vtab *pVtab = (echo_vtab *)tab;
1096   Tcl_Interp *interp = pVtab->interp;
1097   const char *zVal;
1098 
1099   /* Ticket #3083 - Only call xSync if we have previously started a
1100   ** transaction */
1101   assert( pVtab->inTransaction );
1102 
1103   if( simulateVtabError(pVtab, "xSync") ){
1104     return SQLITE_ERROR;
1105   }
1106 
1107   rc = echoTransactionCall(tab, "xSync");
1108 
1109   if( rc==SQLITE_OK ){
1110     /* Check if the $::echo_module_sync_fail variable is defined. If it is,
1111     ** and it is set to the name of the real table underlying this virtual
1112     ** echo module table, then cause this xSync operation to fail.
1113     */
1114     zVal = Tcl_GetVar(interp, "echo_module_sync_fail", TCL_GLOBAL_ONLY);
1115     if( zVal && 0==strcmp(zVal, pVtab->zTableName) ){
1116       rc = -1;
1117     }
1118   }
1119   return rc;
1120 }
1121 static int echoCommit(sqlite3_vtab *tab){
1122   echo_vtab *pVtab = (echo_vtab*)tab;
1123   int rc;
1124 
1125   /* Ticket #3083 - Only call xCommit if we have previously started
1126   ** a transaction */
1127   assert( pVtab->inTransaction );
1128 
1129   if( simulateVtabError(pVtab, "xCommit") ){
1130     return SQLITE_ERROR;
1131   }
1132 
1133   sqlite3BeginBenignMalloc();
1134   rc = echoTransactionCall(tab, "xCommit");
1135   sqlite3EndBenignMalloc();
1136   pVtab->inTransaction = 0;
1137   return rc;
1138 }
1139 static int echoRollback(sqlite3_vtab *tab){
1140   int rc;
1141   echo_vtab *pVtab = (echo_vtab*)tab;
1142 
1143   /* Ticket #3083 - Only call xRollback if we have previously started
1144   ** a transaction */
1145   assert( pVtab->inTransaction );
1146 
1147   rc = echoTransactionCall(tab, "xRollback");
1148   pVtab->inTransaction = 0;
1149   return rc;
1150 }
1151 
1152 /*
1153 ** Implementation of "GLOB" function on the echo module.  Pass
1154 ** all arguments to the ::echo_glob_overload procedure of TCL
1155 ** and return the result of that procedure as a string.
1156 */
1157 static void overloadedGlobFunction(
1158   sqlite3_context *pContext,
1159   int nArg,
1160   sqlite3_value **apArg
1161 ){
1162   Tcl_Interp *interp = sqlite3_user_data(pContext);
1163   Tcl_DString str;
1164   int i;
1165   int rc;
1166   Tcl_DStringInit(&str);
1167   Tcl_DStringAppendElement(&str, "::echo_glob_overload");
1168   for(i=0; i<nArg; i++){
1169     Tcl_DStringAppendElement(&str, (char*)sqlite3_value_text(apArg[i]));
1170   }
1171   rc = Tcl_Eval(interp, Tcl_DStringValue(&str));
1172   Tcl_DStringFree(&str);
1173   if( rc ){
1174     sqlite3_result_error(pContext, Tcl_GetStringResult(interp), -1);
1175   }else{
1176     sqlite3_result_text(pContext, Tcl_GetStringResult(interp),
1177                         -1, SQLITE_TRANSIENT);
1178   }
1179   Tcl_ResetResult(interp);
1180 }
1181 
1182 /*
1183 ** This is the xFindFunction implementation for the echo module.
1184 ** SQLite calls this routine when the first argument of a function
1185 ** is a column of an echo virtual table.  This routine can optionally
1186 ** override the implementation of that function.  It will choose to
1187 ** do so if the function is named "glob", and a TCL command named
1188 ** ::echo_glob_overload exists.
1189 */
1190 static int echoFindFunction(
1191   sqlite3_vtab *vtab,
1192   int nArg,
1193   const char *zFuncName,
1194   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
1195   void **ppArg
1196 ){
1197   echo_vtab *pVtab = (echo_vtab *)vtab;
1198   Tcl_Interp *interp = pVtab->interp;
1199   Tcl_CmdInfo info;
1200   if( strcmp(zFuncName,"glob")!=0 ){
1201     return 0;
1202   }
1203   if( Tcl_GetCommandInfo(interp, "::echo_glob_overload", &info)==0 ){
1204     return 0;
1205   }
1206   *pxFunc = overloadedGlobFunction;
1207   *ppArg = interp;
1208   return 1;
1209 }
1210 
1211 static int echoRename(sqlite3_vtab *vtab, const char *zNewName){
1212   int rc = SQLITE_OK;
1213   echo_vtab *p = (echo_vtab *)vtab;
1214 
1215   if( simulateVtabError(p, "xRename") ){
1216     return SQLITE_ERROR;
1217   }
1218 
1219   if( p->isPattern ){
1220     int nThis = (int)strlen(p->zThis);
1221     char *zSql = sqlite3_mprintf("ALTER TABLE %s RENAME TO %s%s",
1222         p->zTableName, zNewName, &p->zTableName[nThis]
1223     );
1224     rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
1225     sqlite3_free(zSql);
1226   }
1227 
1228   return rc;
1229 }
1230 
1231 static int echoSavepoint(sqlite3_vtab *pVTab, int iSavepoint){
1232   assert( pVTab );
1233   return SQLITE_OK;
1234 }
1235 
1236 static int echoRelease(sqlite3_vtab *pVTab, int iSavepoint){
1237   assert( pVTab );
1238   return SQLITE_OK;
1239 }
1240 
1241 static int echoRollbackTo(sqlite3_vtab *pVTab, int iSavepoint){
1242   assert( pVTab );
1243   return SQLITE_OK;
1244 }
1245 
1246 /*
1247 ** A virtual table module that merely "echos" the contents of another
1248 ** table (like an SQL VIEW).
1249 */
1250 static sqlite3_module echoModule = {
1251   1,                         /* iVersion */
1252   echoCreate,
1253   echoConnect,
1254   echoBestIndex,
1255   echoDisconnect,
1256   echoDestroy,
1257   echoOpen,                  /* xOpen - open a cursor */
1258   echoClose,                 /* xClose - close a cursor */
1259   echoFilter,                /* xFilter - configure scan constraints */
1260   echoNext,                  /* xNext - advance a cursor */
1261   echoEof,                   /* xEof */
1262   echoColumn,                /* xColumn - read data */
1263   echoRowid,                 /* xRowid - read data */
1264   echoUpdate,                /* xUpdate - write data */
1265   echoBegin,                 /* xBegin - begin transaction */
1266   echoSync,                  /* xSync - sync transaction */
1267   echoCommit,                /* xCommit - commit transaction */
1268   echoRollback,              /* xRollback - rollback transaction */
1269   echoFindFunction,          /* xFindFunction - function overloading */
1270   echoRename                 /* xRename - rename the table */
1271 };
1272 
1273 static sqlite3_module echoModuleV2 = {
1274   2,                         /* iVersion */
1275   echoCreate,
1276   echoConnect,
1277   echoBestIndex,
1278   echoDisconnect,
1279   echoDestroy,
1280   echoOpen,                  /* xOpen - open a cursor */
1281   echoClose,                 /* xClose - close a cursor */
1282   echoFilter,                /* xFilter - configure scan constraints */
1283   echoNext,                  /* xNext - advance a cursor */
1284   echoEof,                   /* xEof */
1285   echoColumn,                /* xColumn - read data */
1286   echoRowid,                 /* xRowid - read data */
1287   echoUpdate,                /* xUpdate - write data */
1288   echoBegin,                 /* xBegin - begin transaction */
1289   echoSync,                  /* xSync - sync transaction */
1290   echoCommit,                /* xCommit - commit transaction */
1291   echoRollback,              /* xRollback - rollback transaction */
1292   echoFindFunction,          /* xFindFunction - function overloading */
1293   echoRename,                /* xRename - rename the table */
1294   echoSavepoint,
1295   echoRelease,
1296   echoRollbackTo
1297 };
1298 
1299 /*
1300 ** Decode a pointer to an sqlite3 object.
1301 */
1302 extern int getDbPointer(Tcl_Interp *interp, const char *zA, sqlite3 **ppDb);
1303 extern const char *sqlite3ErrName(int);
1304 
1305 static void moduleDestroy(void *p){
1306   sqlite3_free(p);
1307 }
1308 
1309 /*
1310 ** Register the echo virtual table module.
1311 */
1312 static int register_echo_module(
1313   ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
1314   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
1315   int objc,              /* Number of arguments */
1316   Tcl_Obj *CONST objv[]  /* Command arguments */
1317 ){
1318   int rc;
1319   sqlite3 *db;
1320   EchoModule *pMod;
1321   if( objc!=2 ){
1322     Tcl_WrongNumArgs(interp, 1, objv, "DB");
1323     return TCL_ERROR;
1324   }
1325   if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
1326 
1327   /* Virtual table module "echo" */
1328   pMod = sqlite3_malloc(sizeof(EchoModule));
1329   pMod->interp = interp;
1330   rc = sqlite3_create_module_v2(
1331       db, "echo", &echoModule, (void*)pMod, moduleDestroy
1332   );
1333 
1334   /* Virtual table module "echo_v2" */
1335   if( rc==SQLITE_OK ){
1336     pMod = sqlite3_malloc(sizeof(EchoModule));
1337     pMod->interp = interp;
1338     rc = sqlite3_create_module_v2(db, "echo_v2",
1339         &echoModuleV2, (void*)pMod, moduleDestroy
1340     );
1341   }
1342 
1343   Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_STATIC);
1344   return TCL_OK;
1345 }
1346 
1347 /*
1348 ** Tcl interface to sqlite3_declare_vtab, invoked as follows from Tcl:
1349 **
1350 ** sqlite3_declare_vtab DB SQL
1351 */
1352 static int declare_vtab(
1353   ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
1354   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
1355   int objc,              /* Number of arguments */
1356   Tcl_Obj *CONST objv[]  /* Command arguments */
1357 ){
1358   sqlite3 *db;
1359   int rc;
1360   if( objc!=3 ){
1361     Tcl_WrongNumArgs(interp, 1, objv, "DB SQL");
1362     return TCL_ERROR;
1363   }
1364   if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
1365   rc = sqlite3_declare_vtab(db, Tcl_GetString(objv[2]));
1366   if( rc!=SQLITE_OK ){
1367     Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
1368     return TCL_ERROR;
1369   }
1370   return TCL_OK;
1371 }
1372 
1373 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
1374 
1375 /*
1376 ** Register commands with the TCL interpreter.
1377 */
1378 int Sqlitetest8_Init(Tcl_Interp *interp){
1379 #ifndef SQLITE_OMIT_VIRTUALTABLE
1380   static struct {
1381      char *zName;
1382      Tcl_ObjCmdProc *xProc;
1383      void *clientData;
1384   } aObjCmd[] = {
1385      { "register_echo_module",       register_echo_module, 0 },
1386      { "sqlite3_declare_vtab",       declare_vtab, 0 },
1387   };
1388   int i;
1389   for(i=0; i<sizeof(aObjCmd)/sizeof(aObjCmd[0]); i++){
1390     Tcl_CreateObjCommand(interp, aObjCmd[i].zName,
1391         aObjCmd[i].xProc, aObjCmd[i].clientData, 0);
1392   }
1393 #endif
1394   return TCL_OK;
1395 }
1396