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