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