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