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