Home | History | Annotate | Download | only in src
      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 += 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( pVtab->aIndex[iCol] || iCol<0 ){
    835       char *zCol = pVtab->aCol[iCol];
    836       char *zOp = 0;
    837       useIdx = 1;
    838       if( iCol<0 ){
    839         zCol = "rowid";
    840       }
    841       switch( pConstraint->op ){
    842         case SQLITE_INDEX_CONSTRAINT_EQ:
    843           zOp = "="; break;
    844         case SQLITE_INDEX_CONSTRAINT_LT:
    845           zOp = "<"; break;
    846         case SQLITE_INDEX_CONSTRAINT_GT:
    847           zOp = ">"; break;
    848         case SQLITE_INDEX_CONSTRAINT_LE:
    849           zOp = "<="; break;
    850         case SQLITE_INDEX_CONSTRAINT_GE:
    851           zOp = ">="; break;
    852         case SQLITE_INDEX_CONSTRAINT_MATCH:
    853           zOp = "LIKE"; break;
    854       }
    855       if( zOp[0]=='L' ){
    856         zNew = sqlite3_mprintf(" %s %s LIKE (SELECT '%%'||?||'%%')",
    857                                zSep, zCol);
    858       } else {
    859         zNew = sqlite3_mprintf(" %s %s %s ?", zSep, zCol, zOp);
    860       }
    861       string_concat(&zQuery, zNew, 1, &rc);
    862 
    863       zSep = "AND";
    864       pUsage->argvIndex = ++nArg;
    865       pUsage->omit = 1;
    866     }
    867   }
    868 
    869   /* If there is only one term in the ORDER BY clause, and it is
    870   ** on a column that this virtual table has an index for, then consume
    871   ** the ORDER BY clause.
    872   */
    873   if( pIdxInfo->nOrderBy==1 && pVtab->aIndex[pIdxInfo->aOrderBy->iColumn] ){
    874     int iCol = pIdxInfo->aOrderBy->iColumn;
    875     char *zCol = pVtab->aCol[iCol];
    876     char *zDir = pIdxInfo->aOrderBy->desc?"DESC":"ASC";
    877     if( iCol<0 ){
    878       zCol = "rowid";
    879     }
    880     zNew = sqlite3_mprintf(" ORDER BY %s %s", zCol, zDir);
    881     string_concat(&zQuery, zNew, 1, &rc);
    882     pIdxInfo->orderByConsumed = 1;
    883   }
    884 
    885   appendToEchoModule(pVtab->interp, "xBestIndex");;
    886   appendToEchoModule(pVtab->interp, zQuery);
    887 
    888   if( !zQuery ){
    889     return rc;
    890   }
    891   pIdxInfo->idxNum = hashString(zQuery);
    892   pIdxInfo->idxStr = zQuery;
    893   pIdxInfo->needToFreeIdxStr = 1;
    894   if( useCost ){
    895     pIdxInfo->estimatedCost = cost;
    896   }else if( useIdx ){
    897     /* Approximation of log2(nRow). */
    898     for( ii=0; ii<(sizeof(int)*8); ii++ ){
    899       if( nRow & (1<<ii) ){
    900         pIdxInfo->estimatedCost = (double)ii;
    901       }
    902     }
    903   }else{
    904     pIdxInfo->estimatedCost = (double)nRow;
    905   }
    906   return rc;
    907 }
    908 
    909 /*
    910 ** The xUpdate method for echo module virtual tables.
    911 **
    912 **    apData[0]  apData[1]  apData[2..]
    913 **
    914 **    INTEGER                              DELETE
    915 **
    916 **    INTEGER    NULL       (nCol args)    UPDATE (do not set rowid)
    917 **    INTEGER    INTEGER    (nCol args)    UPDATE (with SET rowid = <arg1>)
    918 **
    919 **    NULL       NULL       (nCol args)    INSERT INTO (automatic rowid value)
    920 **    NULL       INTEGER    (nCol args)    INSERT (incl. rowid value)
    921 **
    922 */
    923 int echoUpdate(
    924   sqlite3_vtab *tab,
    925   int nData,
    926   sqlite3_value **apData,
    927   sqlite_int64 *pRowid
    928 ){
    929   echo_vtab *pVtab = (echo_vtab *)tab;
    930   sqlite3 *db = pVtab->db;
    931   int rc = SQLITE_OK;
    932 
    933   sqlite3_stmt *pStmt;
    934   char *z = 0;               /* SQL statement to execute */
    935   int bindArgZero = 0;       /* True to bind apData[0] to sql var no. nData */
    936   int bindArgOne = 0;        /* True to bind apData[1] to sql var no. 1 */
    937   int i;                     /* Counter variable used by for loops */
    938 
    939   assert( nData==pVtab->nCol+2 || nData==1 );
    940 
    941   /* Ticket #3083 - make sure we always start a transaction prior to
    942   ** making any changes to a virtual table */
    943   assert( pVtab->inTransaction );
    944 
    945   if( simulateVtabError(pVtab, "xUpdate") ){
    946     return SQLITE_ERROR;
    947   }
    948 
    949   /* If apData[0] is an integer and nData>1 then do an UPDATE */
    950   if( nData>1 && sqlite3_value_type(apData[0])==SQLITE_INTEGER ){
    951     char *zSep = " SET";
    952     z = sqlite3_mprintf("UPDATE %Q", pVtab->zTableName);
    953     if( !z ){
    954       rc = SQLITE_NOMEM;
    955     }
    956 
    957     bindArgOne = (apData[1] && sqlite3_value_type(apData[1])==SQLITE_INTEGER);
    958     bindArgZero = 1;
    959 
    960     if( bindArgOne ){
    961        string_concat(&z, " SET rowid=?1 ", 0, &rc);
    962        zSep = ",";
    963     }
    964     for(i=2; i<nData; i++){
    965       if( apData[i]==0 ) continue;
    966       string_concat(&z, sqlite3_mprintf(
    967           "%s %Q=?%d", zSep, pVtab->aCol[i-2], i), 1, &rc);
    968       zSep = ",";
    969     }
    970     string_concat(&z, sqlite3_mprintf(" WHERE rowid=?%d", nData), 1, &rc);
    971   }
    972 
    973   /* If apData[0] is an integer and nData==1 then do a DELETE */
    974   else if( nData==1 && sqlite3_value_type(apData[0])==SQLITE_INTEGER ){
    975     z = sqlite3_mprintf("DELETE FROM %Q WHERE rowid = ?1", pVtab->zTableName);
    976     if( !z ){
    977       rc = SQLITE_NOMEM;
    978     }
    979     bindArgZero = 1;
    980   }
    981 
    982   /* If the first argument is NULL and there are more than two args, INSERT */
    983   else if( nData>2 && sqlite3_value_type(apData[0])==SQLITE_NULL ){
    984     int ii;
    985     char *zInsert = 0;
    986     char *zValues = 0;
    987 
    988     zInsert = sqlite3_mprintf("INSERT INTO %Q (", pVtab->zTableName);
    989     if( !zInsert ){
    990       rc = SQLITE_NOMEM;
    991     }
    992     if( sqlite3_value_type(apData[1])==SQLITE_INTEGER ){
    993       bindArgOne = 1;
    994       zValues = sqlite3_mprintf("?");
    995       string_concat(&zInsert, "rowid", 0, &rc);
    996     }
    997 
    998     assert((pVtab->nCol+2)==nData);
    999     for(ii=2; ii<nData; ii++){
   1000       string_concat(&zInsert,
   1001           sqlite3_mprintf("%s%Q", zValues?", ":"", pVtab->aCol[ii-2]), 1, &rc);
   1002       string_concat(&zValues,
   1003           sqlite3_mprintf("%s?%d", zValues?", ":"", ii), 1, &rc);
   1004     }
   1005 
   1006     string_concat(&z, zInsert, 1, &rc);
   1007     string_concat(&z, ") VALUES(", 0, &rc);
   1008     string_concat(&z, zValues, 1, &rc);
   1009     string_concat(&z, ")", 0, &rc);
   1010   }
   1011 
   1012   /* Anything else is an error */
   1013   else{
   1014     assert(0);
   1015     return SQLITE_ERROR;
   1016   }
   1017 
   1018   if( rc==SQLITE_OK ){
   1019     rc = sqlite3_prepare(db, z, -1, &pStmt, 0);
   1020   }
   1021   assert( rc!=SQLITE_OK || pStmt );
   1022   sqlite3_free(z);
   1023   if( rc==SQLITE_OK ) {
   1024     if( bindArgZero ){
   1025       sqlite3_bind_value(pStmt, nData, apData[0]);
   1026     }
   1027     if( bindArgOne ){
   1028       sqlite3_bind_value(pStmt, 1, apData[1]);
   1029     }
   1030     for(i=2; i<nData && rc==SQLITE_OK; i++){
   1031       if( apData[i] ) rc = sqlite3_bind_value(pStmt, i, apData[i]);
   1032     }
   1033     if( rc==SQLITE_OK ){
   1034       sqlite3_step(pStmt);
   1035       rc = sqlite3_finalize(pStmt);
   1036     }else{
   1037       sqlite3_finalize(pStmt);
   1038     }
   1039   }
   1040 
   1041   if( pRowid && rc==SQLITE_OK ){
   1042     *pRowid = sqlite3_last_insert_rowid(db);
   1043   }
   1044   if( rc!=SQLITE_OK ){
   1045     tab->zErrMsg = sqlite3_mprintf("echo-vtab-error: %s", sqlite3_errmsg(db));
   1046   }
   1047 
   1048   return rc;
   1049 }
   1050 
   1051 /*
   1052 ** xBegin, xSync, xCommit and xRollback callbacks for echo module
   1053 ** virtual tables. Do nothing other than add the name of the callback
   1054 ** to the $::echo_module Tcl variable.
   1055 */
   1056 static int echoTransactionCall(sqlite3_vtab *tab, const char *zCall){
   1057   char *z;
   1058   echo_vtab *pVtab = (echo_vtab *)tab;
   1059   z = sqlite3_mprintf("echo(%s)", pVtab->zTableName);
   1060   if( z==0 ) return SQLITE_NOMEM;
   1061   appendToEchoModule(pVtab->interp, zCall);
   1062   appendToEchoModule(pVtab->interp, z);
   1063   sqlite3_free(z);
   1064   return SQLITE_OK;
   1065 }
   1066 static int echoBegin(sqlite3_vtab *tab){
   1067   int rc;
   1068   echo_vtab *pVtab = (echo_vtab *)tab;
   1069   Tcl_Interp *interp = pVtab->interp;
   1070   const char *zVal;
   1071 
   1072   /* Ticket #3083 - do not start a transaction if we are already in
   1073   ** a transaction */
   1074   assert( !pVtab->inTransaction );
   1075 
   1076   if( simulateVtabError(pVtab, "xBegin") ){
   1077     return SQLITE_ERROR;
   1078   }
   1079 
   1080   rc = echoTransactionCall(tab, "xBegin");
   1081 
   1082   if( rc==SQLITE_OK ){
   1083     /* Check if the $::echo_module_begin_fail variable is defined. If it is,
   1084     ** and it is set to the name of the real table underlying this virtual
   1085     ** echo module table, then cause this xSync operation to fail.
   1086     */
   1087     zVal = Tcl_GetVar(interp, "echo_module_begin_fail", TCL_GLOBAL_ONLY);
   1088     if( zVal && 0==strcmp(zVal, pVtab->zTableName) ){
   1089       rc = SQLITE_ERROR;
   1090     }
   1091   }
   1092   if( rc==SQLITE_OK ){
   1093     pVtab->inTransaction = 1;
   1094   }
   1095   return rc;
   1096 }
   1097 static int echoSync(sqlite3_vtab *tab){
   1098   int rc;
   1099   echo_vtab *pVtab = (echo_vtab *)tab;
   1100   Tcl_Interp *interp = pVtab->interp;
   1101   const char *zVal;
   1102 
   1103   /* Ticket #3083 - Only call xSync if we have previously started a
   1104   ** transaction */
   1105   assert( pVtab->inTransaction );
   1106 
   1107   if( simulateVtabError(pVtab, "xSync") ){
   1108     return SQLITE_ERROR;
   1109   }
   1110 
   1111   rc = echoTransactionCall(tab, "xSync");
   1112 
   1113   if( rc==SQLITE_OK ){
   1114     /* Check if the $::echo_module_sync_fail variable is defined. If it is,
   1115     ** and it is set to the name of the real table underlying this virtual
   1116     ** echo module table, then cause this xSync operation to fail.
   1117     */
   1118     zVal = Tcl_GetVar(interp, "echo_module_sync_fail", TCL_GLOBAL_ONLY);
   1119     if( zVal && 0==strcmp(zVal, pVtab->zTableName) ){
   1120       rc = -1;
   1121     }
   1122   }
   1123   return rc;
   1124 }
   1125 static int echoCommit(sqlite3_vtab *tab){
   1126   echo_vtab *pVtab = (echo_vtab*)tab;
   1127   int rc;
   1128 
   1129   /* Ticket #3083 - Only call xCommit if we have previously started
   1130   ** a transaction */
   1131   assert( pVtab->inTransaction );
   1132 
   1133   if( simulateVtabError(pVtab, "xCommit") ){
   1134     return SQLITE_ERROR;
   1135   }
   1136 
   1137   sqlite3BeginBenignMalloc();
   1138   rc = echoTransactionCall(tab, "xCommit");
   1139   sqlite3EndBenignMalloc();
   1140   pVtab->inTransaction = 0;
   1141   return rc;
   1142 }
   1143 static int echoRollback(sqlite3_vtab *tab){
   1144   int rc;
   1145   echo_vtab *pVtab = (echo_vtab*)tab;
   1146 
   1147   /* Ticket #3083 - Only call xRollback if we have previously started
   1148   ** a transaction */
   1149   assert( pVtab->inTransaction );
   1150 
   1151   rc = echoTransactionCall(tab, "xRollback");
   1152   pVtab->inTransaction = 0;
   1153   return rc;
   1154 }
   1155 
   1156 /*
   1157 ** Implementation of "GLOB" function on the echo module.  Pass
   1158 ** all arguments to the ::echo_glob_overload procedure of TCL
   1159 ** and return the result of that procedure as a string.
   1160 */
   1161 static void overloadedGlobFunction(
   1162   sqlite3_context *pContext,
   1163   int nArg,
   1164   sqlite3_value **apArg
   1165 ){
   1166   Tcl_Interp *interp = sqlite3_user_data(pContext);
   1167   Tcl_DString str;
   1168   int i;
   1169   int rc;
   1170   Tcl_DStringInit(&str);
   1171   Tcl_DStringAppendElement(&str, "::echo_glob_overload");
   1172   for(i=0; i<nArg; i++){
   1173     Tcl_DStringAppendElement(&str, (char*)sqlite3_value_text(apArg[i]));
   1174   }
   1175   rc = Tcl_Eval(interp, Tcl_DStringValue(&str));
   1176   Tcl_DStringFree(&str);
   1177   if( rc ){
   1178     sqlite3_result_error(pContext, Tcl_GetStringResult(interp), -1);
   1179   }else{
   1180     sqlite3_result_text(pContext, Tcl_GetStringResult(interp),
   1181                         -1, SQLITE_TRANSIENT);
   1182   }
   1183   Tcl_ResetResult(interp);
   1184 }
   1185 
   1186 /*
   1187 ** This is the xFindFunction implementation for the echo module.
   1188 ** SQLite calls this routine when the first argument of a function
   1189 ** is a column of an echo virtual table.  This routine can optionally
   1190 ** override the implementation of that function.  It will choose to
   1191 ** do so if the function is named "glob", and a TCL command named
   1192 ** ::echo_glob_overload exists.
   1193 */
   1194 static int echoFindFunction(
   1195   sqlite3_vtab *vtab,
   1196   int nArg,
   1197   const char *zFuncName,
   1198   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
   1199   void **ppArg
   1200 ){
   1201   echo_vtab *pVtab = (echo_vtab *)vtab;
   1202   Tcl_Interp *interp = pVtab->interp;
   1203   Tcl_CmdInfo info;
   1204   if( strcmp(zFuncName,"glob")!=0 ){
   1205     return 0;
   1206   }
   1207   if( Tcl_GetCommandInfo(interp, "::echo_glob_overload", &info)==0 ){
   1208     return 0;
   1209   }
   1210   *pxFunc = overloadedGlobFunction;
   1211   *ppArg = interp;
   1212   return 1;
   1213 }
   1214 
   1215 static int echoRename(sqlite3_vtab *vtab, const char *zNewName){
   1216   int rc = SQLITE_OK;
   1217   echo_vtab *p = (echo_vtab *)vtab;
   1218 
   1219   if( simulateVtabError(p, "xRename") ){
   1220     return SQLITE_ERROR;
   1221   }
   1222 
   1223   if( p->isPattern ){
   1224     int nThis = strlen(p->zThis);
   1225     char *zSql = sqlite3_mprintf("ALTER TABLE %s RENAME TO %s%s",
   1226         p->zTableName, zNewName, &p->zTableName[nThis]
   1227     );
   1228     rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
   1229     sqlite3_free(zSql);
   1230   }
   1231 
   1232   return rc;
   1233 }
   1234 
   1235 /*
   1236 ** A virtual table module that merely "echos" the contents of another
   1237 ** table (like an SQL VIEW).
   1238 */
   1239 static sqlite3_module echoModule = {
   1240   0,                         /* iVersion */
   1241   echoCreate,
   1242   echoConnect,
   1243   echoBestIndex,
   1244   echoDisconnect,
   1245   echoDestroy,
   1246   echoOpen,                  /* xOpen - open a cursor */
   1247   echoClose,                 /* xClose - close a cursor */
   1248   echoFilter,                /* xFilter - configure scan constraints */
   1249   echoNext,                  /* xNext - advance a cursor */
   1250   echoEof,                   /* xEof */
   1251   echoColumn,                /* xColumn - read data */
   1252   echoRowid,                 /* xRowid - read data */
   1253   echoUpdate,                /* xUpdate - write data */
   1254   echoBegin,                 /* xBegin - begin transaction */
   1255   echoSync,                  /* xSync - sync transaction */
   1256   echoCommit,                /* xCommit - commit transaction */
   1257   echoRollback,              /* xRollback - rollback transaction */
   1258   echoFindFunction,          /* xFindFunction - function overloading */
   1259   echoRename,                /* xRename - rename the table */
   1260 };
   1261 
   1262 /*
   1263 ** Decode a pointer to an sqlite3 object.
   1264 */
   1265 extern int getDbPointer(Tcl_Interp *interp, const char *zA, sqlite3 **ppDb);
   1266 
   1267 static void moduleDestroy(void *p){
   1268   sqlite3_free(p);
   1269 }
   1270 
   1271 /*
   1272 ** Register the echo virtual table module.
   1273 */
   1274 static int register_echo_module(
   1275   ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
   1276   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
   1277   int objc,              /* Number of arguments */
   1278   Tcl_Obj *CONST objv[]  /* Command arguments */
   1279 ){
   1280   sqlite3 *db;
   1281   EchoModule *pMod;
   1282   if( objc!=2 ){
   1283     Tcl_WrongNumArgs(interp, 1, objv, "DB");
   1284     return TCL_ERROR;
   1285   }
   1286   if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
   1287   pMod = sqlite3_malloc(sizeof(EchoModule));
   1288   pMod->interp = interp;
   1289   sqlite3_create_module_v2(db, "echo", &echoModule, (void*)pMod, moduleDestroy);
   1290   return TCL_OK;
   1291 }
   1292 
   1293 /*
   1294 ** Tcl interface to sqlite3_declare_vtab, invoked as follows from Tcl:
   1295 **
   1296 ** sqlite3_declare_vtab DB SQL
   1297 */
   1298 static int declare_vtab(
   1299   ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
   1300   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
   1301   int objc,              /* Number of arguments */
   1302   Tcl_Obj *CONST objv[]  /* Command arguments */
   1303 ){
   1304   sqlite3 *db;
   1305   int rc;
   1306   if( objc!=3 ){
   1307     Tcl_WrongNumArgs(interp, 1, objv, "DB SQL");
   1308     return TCL_ERROR;
   1309   }
   1310   if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
   1311   rc = sqlite3_declare_vtab(db, Tcl_GetString(objv[2]));
   1312   if( rc!=SQLITE_OK ){
   1313     Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
   1314     return TCL_ERROR;
   1315   }
   1316   return TCL_OK;
   1317 }
   1318 
   1319 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
   1320 
   1321 /*
   1322 ** Register commands with the TCL interpreter.
   1323 */
   1324 int Sqlitetest8_Init(Tcl_Interp *interp){
   1325 #ifndef SQLITE_OMIT_VIRTUALTABLE
   1326   static struct {
   1327      char *zName;
   1328      Tcl_ObjCmdProc *xProc;
   1329      void *clientData;
   1330   } aObjCmd[] = {
   1331      { "register_echo_module",   register_echo_module, 0 },
   1332      { "sqlite3_declare_vtab",   declare_vtab, 0 },
   1333   };
   1334   int i;
   1335   for(i=0; i<sizeof(aObjCmd)/sizeof(aObjCmd[0]); i++){
   1336     Tcl_CreateObjCommand(interp, aObjCmd[i].zName,
   1337         aObjCmd[i].xProc, aObjCmd[i].clientData, 0);
   1338   }
   1339 #endif
   1340   return TCL_OK;
   1341 }
   1342