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