4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
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.
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.
16 #include "sqliteInt.h"
21 #ifndef SQLITE_OMIT_VIRTUALTABLE
23 typedef struct echo_vtab echo_vtab
;
24 typedef struct echo_cursor echo_cursor
;
27 ** The test module defined in this file uses four global Tcl variables to
28 ** commicate with test-scripts:
31 ** $::echo_module_sync_fail
32 ** $::echo_module_begin_fail
33 ** $::echo_module_cost
35 ** The variable ::echo_module is a list. Each time one of the following
36 ** methods is called, one or more elements are appended to the list.
37 ** This is used for automated testing of virtual table modules.
39 ** The ::echo_module_sync_fail variable is set by test scripts and read
40 ** by code in this file. If it is set to the name of a real table in the
41 ** the database, then all xSync operations on echo virtual tables that
42 ** use the named table as a backing store will fail.
46 ** Errors can be provoked within the following echo virtual table methods:
48 ** xBestIndex xOpen xFilter xNext
49 ** xColumn xRowid xUpdate xSync
52 ** This is done by setting the global tcl variable:
54 ** echo_module_fail($method,$tbl)
56 ** where $method is set to the name of the virtual table method to fail
57 ** (i.e. "xBestIndex") and $tbl is the name of the table being echoed (not
58 ** the name of the virtual table, the name of the underlying real table).
62 ** An echo virtual-table object.
64 ** echo.vtab.aIndex is an array of booleans. The nth entry is true if
65 ** the nth column of the real table is the left-most column of an index
66 ** (implicit or otherwise). In other words, if SQLite can optimize
67 ** a query like "SELECT * FROM real_table WHERE col = ?".
69 ** Member variable aCol[] contains copies of the column names of the real
74 Tcl_Interp
*interp
; /* Tcl interpreter containing debug variables */
75 sqlite3
*db
; /* Database connection */
78 int inTransaction
; /* True if within a transaction */
79 char *zThis
; /* Name of the echo table */
80 char *zTableName
; /* Name of the real table */
81 char *zLogName
; /* Name of the log table */
82 int nCol
; /* Number of columns in the real table */
83 int *aIndex
; /* Array of size nCol. True if column has an index */
84 char **aCol
; /* Array of size nCol. Column names */
87 /* An echo cursor object */
89 sqlite3_vtab_cursor base
;
93 static int simulateVtabError(echo_vtab
*p
, const char *zMethod
){
97 sqlite3_snprintf(127, zVarname
, "echo_module_fail(%s,%s)", zMethod
, p
->zTableName
);
98 zErr
= Tcl_GetVar(p
->interp
, zVarname
, TCL_GLOBAL_ONLY
);
100 p
->base
.zErrMsg
= sqlite3_mprintf("echo-vtab-error: %s", zErr
);
106 ** Convert an SQL-style quoted string into a normal string by removing
107 ** the quote characters. The conversion is done in-place. If the
108 ** input does not begin with a quote character, then this routine
118 static void dequoteString(char *z
){
126 case '`': break; /* For MySQL compatibility */
127 case '[': quote
= ']'; break; /* For MS SqlServer compatibility */
130 for(i
=1, j
=0; z
[i
]; i
++){
146 ** Retrieve the column names for the table named zTab via database
147 ** connection db. SQLITE_OK is returned on success, or an sqlite error
150 ** If successful, the number of columns is written to *pnCol. *paCol is
151 ** set to point at sqlite3_malloc()'d space containing the array of
152 ** nCol column names. The caller is responsible for calling sqlite3_free
155 static int getColumnNames(
163 sqlite3_stmt
*pStmt
= 0;
167 /* Prepare the statement "SELECT * FROM <tbl>". The column names
168 ** of the result set of the compiled SELECT will be the same as
169 ** the column names of table <tbl>.
171 zSql
= sqlite3_mprintf("SELECT * FROM %Q", zTab
);
176 rc
= sqlite3_prepare(db
, zSql
, -1, &pStmt
, 0);
183 nCol
= sqlite3_column_count(pStmt
);
185 /* Figure out how much space to allocate for the array of column names
186 ** (including space for the strings themselves). Then allocate it.
188 nBytes
= sizeof(char *) * nCol
;
189 for(ii
=0; ii
<nCol
; ii
++){
190 const char *zName
= sqlite3_column_name(pStmt
, ii
);
195 nBytes
+= (int)strlen(zName
)+1;
197 aCol
= (char **)sqlite3MallocZero(nBytes
);
203 /* Copy the column names into the allocated space and set up the
204 ** pointers in the aCol[] array.
206 zSpace
= (char *)(&aCol
[nCol
]);
207 for(ii
=0; ii
<nCol
; ii
++){
209 zSpace
+= sprintf(zSpace
, "%s", sqlite3_column_name(pStmt
, ii
));
212 assert( (zSpace
-nBytes
)==(char *)aCol
);
219 sqlite3_finalize(pStmt
);
224 ** Parameter zTab is the name of a table in database db with nCol
225 ** columns. This function allocates an array of integers nCol in
226 ** size and populates it according to any implicit or explicit
227 ** indices on table zTab.
229 ** If successful, SQLITE_OK is returned and *paIndex set to point
230 ** at the allocated array. Otherwise, an error code is returned.
232 ** See comments associated with the member variable aIndex above
233 ** "struct echo_vtab" for details of the contents of the array.
235 static int getIndexArray(
236 sqlite3
*db
, /* Database connection */
237 const char *zTab
, /* Name of table in database db */
241 sqlite3_stmt
*pStmt
= 0;
246 /* Allocate space for the index array */
247 aIndex
= (int *)sqlite3MallocZero(sizeof(int) * nCol
);
250 goto get_index_array_out
;
253 /* Compile an sqlite pragma to loop through all indices on table zTab */
254 zSql
= sqlite3_mprintf("PRAGMA index_list(%s)", zTab
);
257 goto get_index_array_out
;
259 rc
= sqlite3_prepare(db
, zSql
, -1, &pStmt
, 0);
262 /* For each index, figure out the left-most column and set the
263 ** corresponding entry in aIndex[] to 1.
265 while( pStmt
&& sqlite3_step(pStmt
)==SQLITE_ROW
){
266 const char *zIdx
= (const char *)sqlite3_column_text(pStmt
, 1);
267 sqlite3_stmt
*pStmt2
= 0;
268 if( zIdx
==0 ) continue;
269 zSql
= sqlite3_mprintf("PRAGMA index_info(%s)", zIdx
);
272 goto get_index_array_out
;
274 rc
= sqlite3_prepare(db
, zSql
, -1, &pStmt2
, 0);
276 if( pStmt2
&& sqlite3_step(pStmt2
)==SQLITE_ROW
){
277 int cid
= sqlite3_column_int(pStmt2
, 1);
278 assert( cid
>=0 && cid
<nCol
);
282 rc
= sqlite3_finalize(pStmt2
);
285 goto get_index_array_out
;
292 int rc2
= sqlite3_finalize(pStmt
);
298 sqlite3_free(aIndex
);
306 ** Global Tcl variable $echo_module is a list. This routine appends
307 ** the string element zArg to that list in interpreter interp.
309 static void appendToEchoModule(Tcl_Interp
*interp
, const char *zArg
){
310 int flags
= (TCL_APPEND_VALUE
| TCL_LIST_ELEMENT
| TCL_GLOBAL_ONLY
);
311 Tcl_SetVar(interp
, "echo_module", (zArg
?zArg
:""), flags
);
315 ** This function is called from within the echo-modules xCreate and
316 ** xConnect methods. The argc and argv arguments are copies of those
317 ** passed to the calling method. This function is responsible for
318 ** calling sqlite3_declare_vtab() to declare the schema of the virtual
319 ** table being created or connected.
321 ** If the constructor was passed just one argument, i.e.:
323 ** CREATE TABLE t1 AS echo(t2);
325 ** Then t2 is assumed to be the name of a *real* database table. The
326 ** schema of the virtual table is declared by passing a copy of the
327 ** CREATE TABLE statement for the real table to sqlite3_declare_vtab().
328 ** Hence, the virtual table should have exactly the same column names and
329 ** types as the real table.
331 static int echoDeclareVtab(
337 if( pVtab
->zTableName
){
338 sqlite3_stmt
*pStmt
= 0;
339 rc
= sqlite3_prepare(db
,
340 "SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?",
343 sqlite3_bind_text(pStmt
, 1, pVtab
->zTableName
, -1, 0);
344 if( sqlite3_step(pStmt
)==SQLITE_ROW
){
346 const char *zCreateTable
= (const char *)sqlite3_column_text(pStmt
, 0);
347 rc
= sqlite3_declare_vtab(db
, zCreateTable
);
348 rc2
= sqlite3_finalize(pStmt
);
353 rc
= sqlite3_finalize(pStmt
);
359 rc
= getColumnNames(db
, pVtab
->zTableName
, &pVtab
->aCol
, &pVtab
->nCol
);
362 rc
= getIndexArray(db
, pVtab
->zTableName
, pVtab
->nCol
, &pVtab
->aIndex
);
371 ** This function frees all runtime structures associated with the virtual
374 static int echoDestructor(sqlite3_vtab
*pVtab
){
375 echo_vtab
*p
= (echo_vtab
*)pVtab
;
376 sqlite3_free(p
->aIndex
);
377 sqlite3_free(p
->aCol
);
378 sqlite3_free(p
->zThis
);
379 sqlite3_free(p
->zTableName
);
380 sqlite3_free(p
->zLogName
);
385 typedef struct EchoModule EchoModule
;
391 ** This function is called to do the work of the xConnect() method -
392 ** to allocate the required in-memory structures for a newly connected
395 static int echoConstructor(
398 int argc
, const char *const*argv
,
399 sqlite3_vtab
**ppVtab
,
406 /* Allocate the sqlite3_vtab/echo_vtab structure itself */
407 pVtab
= sqlite3MallocZero( sizeof(*pVtab
) );
411 pVtab
->interp
= ((EchoModule
*)pAux
)->interp
;
414 /* Allocate echo_vtab.zThis */
415 pVtab
->zThis
= sqlite3_mprintf("%s", argv
[2]);
417 echoDestructor((sqlite3_vtab
*)pVtab
);
421 /* Allocate echo_vtab.zTableName */
423 pVtab
->zTableName
= sqlite3_mprintf("%s", argv
[3]);
424 dequoteString(pVtab
->zTableName
);
425 if( pVtab
->zTableName
&& pVtab
->zTableName
[0]=='*' ){
426 char *z
= sqlite3_mprintf("%s%s", argv
[2], &(pVtab
->zTableName
[1]));
427 sqlite3_free(pVtab
->zTableName
);
428 pVtab
->zTableName
= z
;
429 pVtab
->isPattern
= 1;
431 if( !pVtab
->zTableName
){
432 echoDestructor((sqlite3_vtab
*)pVtab
);
437 /* Log the arguments to this function to Tcl var ::echo_module */
438 for(i
=0; i
<argc
; i
++){
439 appendToEchoModule(pVtab
->interp
, argv
[i
]);
442 /* Invoke sqlite3_declare_vtab and set up other members of the echo_vtab
443 ** structure. If an error occurs, delete the sqlite3_vtab structure and
444 ** return an error code.
446 rc
= echoDeclareVtab(pVtab
, db
);
448 echoDestructor((sqlite3_vtab
*)pVtab
);
452 /* Success. Set *ppVtab and return */
453 *ppVtab
= &pVtab
->base
;
458 ** Echo virtual table module xCreate method.
460 static int echoCreate(
463 int argc
, const char *const*argv
,
464 sqlite3_vtab
**ppVtab
,
468 appendToEchoModule(((EchoModule
*)pAux
)->interp
, "xCreate");
469 rc
= echoConstructor(db
, pAux
, argc
, argv
, ppVtab
, pzErr
);
471 /* If there were two arguments passed to the module at the SQL level
472 ** (i.e. "CREATE VIRTUAL TABLE tbl USING echo(arg1, arg2)"), then
473 ** the second argument is used as a table name. Attempt to create
474 ** such a table with a single column, "logmsg". This table will
475 ** be used to log calls to the xUpdate method. It will be deleted
476 ** when the virtual table is DROPed.
478 ** Note: The main point of this is to test that we can drop tables
479 ** from within an xDestroy method call.
481 if( rc
==SQLITE_OK
&& argc
==5 ){
483 echo_vtab
*pVtab
= *(echo_vtab
**)ppVtab
;
484 pVtab
->zLogName
= sqlite3_mprintf("%s", argv
[4]);
485 zSql
= sqlite3_mprintf("CREATE TABLE %Q(logmsg)", pVtab
->zLogName
);
486 rc
= sqlite3_exec(db
, zSql
, 0, 0, 0);
489 *pzErr
= sqlite3_mprintf("%s", sqlite3_errmsg(db
));
493 if( *ppVtab
&& rc
!=SQLITE_OK
){
494 echoDestructor(*ppVtab
);
499 (*(echo_vtab
**)ppVtab
)->inTransaction
= 1;
506 ** Echo virtual table module xConnect method.
508 static int echoConnect(
511 int argc
, const char *const*argv
,
512 sqlite3_vtab
**ppVtab
,
515 appendToEchoModule(((EchoModule
*)pAux
)->interp
, "xConnect");
516 return echoConstructor(db
, pAux
, argc
, argv
, ppVtab
, pzErr
);
520 ** Echo virtual table module xDisconnect method.
522 static int echoDisconnect(sqlite3_vtab
*pVtab
){
523 appendToEchoModule(((echo_vtab
*)pVtab
)->interp
, "xDisconnect");
524 return echoDestructor(pVtab
);
528 ** Echo virtual table module xDestroy method.
530 static int echoDestroy(sqlite3_vtab
*pVtab
){
532 echo_vtab
*p
= (echo_vtab
*)pVtab
;
533 appendToEchoModule(((echo_vtab
*)pVtab
)->interp
, "xDestroy");
535 /* Drop the "log" table, if one exists (see echoCreate() for details) */
536 if( p
&& p
->zLogName
){
538 zSql
= sqlite3_mprintf("DROP TABLE %Q", p
->zLogName
);
539 rc
= sqlite3_exec(p
->db
, zSql
, 0, 0, 0);
544 rc
= echoDestructor(pVtab
);
550 ** Echo virtual table module xOpen method.
552 static int echoOpen(sqlite3_vtab
*pVTab
, sqlite3_vtab_cursor
**ppCursor
){
554 if( simulateVtabError((echo_vtab
*)pVTab
, "xOpen") ){
557 pCur
= sqlite3MallocZero(sizeof(echo_cursor
));
558 *ppCursor
= (sqlite3_vtab_cursor
*)pCur
;
559 return (pCur
? SQLITE_OK
: SQLITE_NOMEM
);
563 ** Echo virtual table module xClose method.
565 static int echoClose(sqlite3_vtab_cursor
*cur
){
567 echo_cursor
*pCur
= (echo_cursor
*)cur
;
568 sqlite3_stmt
*pStmt
= pCur
->pStmt
;
571 rc
= sqlite3_finalize(pStmt
);
576 ** Return non-zero if the cursor does not currently point to a valid record
577 ** (i.e if the scan has finished), or zero otherwise.
579 static int echoEof(sqlite3_vtab_cursor
*cur
){
580 return (((echo_cursor
*)cur
)->pStmt
? 0 : 1);
584 ** Echo virtual table module xNext method.
586 static int echoNext(sqlite3_vtab_cursor
*cur
){
588 echo_cursor
*pCur
= (echo_cursor
*)cur
;
590 if( simulateVtabError((echo_vtab
*)(cur
->pVtab
), "xNext") ){
595 rc
= sqlite3_step(pCur
->pStmt
);
596 if( rc
==SQLITE_ROW
){
599 rc
= sqlite3_finalize(pCur
->pStmt
);
608 ** Echo virtual table module xColumn method.
610 static int echoColumn(sqlite3_vtab_cursor
*cur
, sqlite3_context
*ctx
, int i
){
612 sqlite3_stmt
*pStmt
= ((echo_cursor
*)cur
)->pStmt
;
614 if( simulateVtabError((echo_vtab
*)(cur
->pVtab
), "xColumn") ){
619 sqlite3_result_null(ctx
);
621 assert( sqlite3_data_count(pStmt
)>iCol
);
622 sqlite3_result_value(ctx
, sqlite3_column_value(pStmt
, iCol
));
628 ** Echo virtual table module xRowid method.
630 static int echoRowid(sqlite3_vtab_cursor
*cur
, sqlite_int64
*pRowid
){
631 sqlite3_stmt
*pStmt
= ((echo_cursor
*)cur
)->pStmt
;
633 if( simulateVtabError((echo_vtab
*)(cur
->pVtab
), "xRowid") ){
637 *pRowid
= sqlite3_column_int64(pStmt
, 0);
642 ** Compute a simple hash of the null terminated string zString.
644 ** This module uses only sqlite3_index_info.idxStr, not
645 ** sqlite3_index_info.idxNum. So to test idxNum, when idxStr is set
646 ** in echoBestIndex(), idxNum is set to the corresponding hash value.
647 ** In echoFilter(), code assert()s that the supplied idxNum value is
648 ** indeed the hash of the supplied idxStr.
650 static int hashString(const char *zString
){
653 for(ii
=0; zString
[ii
]; ii
++){
654 val
= (val
<< 3) + (int)zString
[ii
];
660 ** Echo virtual table module xFilter method.
662 static int echoFilter(
663 sqlite3_vtab_cursor
*pVtabCursor
,
664 int idxNum
, const char *idxStr
,
665 int argc
, sqlite3_value
**argv
670 echo_cursor
*pCur
= (echo_cursor
*)pVtabCursor
;
671 echo_vtab
*pVtab
= (echo_vtab
*)pVtabCursor
->pVtab
;
672 sqlite3
*db
= pVtab
->db
;
674 if( simulateVtabError(pVtab
, "xFilter") ){
678 /* Check that idxNum matches idxStr */
679 assert( idxNum
==hashString(idxStr
) );
681 /* Log arguments to the ::echo_module Tcl variable */
682 appendToEchoModule(pVtab
->interp
, "xFilter");
683 appendToEchoModule(pVtab
->interp
, idxStr
);
684 for(i
=0; i
<argc
; i
++){
685 appendToEchoModule(pVtab
->interp
, (const char*)sqlite3_value_text(argv
[i
]));
688 sqlite3_finalize(pCur
->pStmt
);
691 /* Prepare the SQL statement created by echoBestIndex and bind the
692 ** runtime parameters passed to this function to it.
694 rc
= sqlite3_prepare(db
, idxStr
, -1, &pCur
->pStmt
, 0);
695 assert( pCur
->pStmt
|| rc
!=SQLITE_OK
);
696 for(i
=0; rc
==SQLITE_OK
&& i
<argc
; i
++){
697 rc
= sqlite3_bind_value(pCur
->pStmt
, i
+1, argv
[i
]);
700 /* If everything was successful, advance to the first row of the scan */
702 rc
= echoNext(pVtabCursor
);
710 ** A helper function used by echoUpdate() and echoBestIndex() for
711 ** manipulating strings in concert with the sqlite3_mprintf() function.
713 ** Parameter pzStr points to a pointer to a string allocated with
714 ** sqlite3_mprintf. The second parameter, zAppend, points to another
715 ** string. The two strings are concatenated together and *pzStr
716 ** set to point at the result. The initial buffer pointed to by *pzStr
717 ** is deallocated via sqlite3_free().
719 ** If the third argument, doFree, is true, then sqlite3_free() is
720 ** also called to free the buffer pointed to by zAppend.
722 static void string_concat(char **pzStr
, char *zAppend
, int doFree
, int *pRc
){
724 if( !zAppend
&& doFree
&& *pRc
==SQLITE_OK
){
727 if( *pRc
!=SQLITE_OK
){
733 zIn
= sqlite3_mprintf("%s%s", zIn
, zAppend
);
736 zIn
= sqlite3_mprintf("%s", zAppend
);
744 sqlite3_free(zAppend
);
749 ** The echo module implements the subset of query constraints and sort
750 ** orders that may take advantage of SQLite indices on the underlying
751 ** real table. For example, if the real table is declared as:
753 ** CREATE TABLE real(a, b, c);
754 ** CREATE INDEX real_index ON real(b);
756 ** then the echo module handles WHERE or ORDER BY clauses that refer
757 ** to the column "b", but not "a" or "c". If a multi-column index is
758 ** present, only its left most column is considered.
760 ** This xBestIndex method encodes the proposed search strategy as
761 ** an SQL query on the real table underlying the virtual echo module
762 ** table and stores the query in sqlite3_index_info.idxStr. The SQL
763 ** statement is of the form:
765 ** SELECT rowid, * FROM <real-table> ?<where-clause>? ?<order-by-clause>?
767 ** where the <where-clause> and <order-by-clause> are determined
768 ** by the contents of the structure pointed to by the pIdxInfo argument.
770 static int echoBestIndex(sqlite3_vtab
*tab
, sqlite3_index_info
*pIdxInfo
){
775 const char *zSep
= "WHERE";
776 echo_vtab
*pVtab
= (echo_vtab
*)tab
;
777 sqlite3_stmt
*pStmt
= 0;
778 Tcl_Interp
*interp
= pVtab
->interp
;
785 int isIgnoreUsable
= 0;
786 if( Tcl_GetVar(interp
, "echo_module_ignore_usable", TCL_GLOBAL_ONLY
) ){
790 if( simulateVtabError(pVtab
, "xBestIndex") ){
794 /* Determine the number of rows in the table and store this value in local
795 ** variable nRow. The 'estimated-cost' of the scan will be the number of
796 ** rows in the table for a linear scan, or the log (base 2) of the
797 ** number of rows if the proposed scan uses an index.
799 if( Tcl_GetVar(interp
, "echo_module_cost", TCL_GLOBAL_ONLY
) ){
800 cost
= atof(Tcl_GetVar(interp
, "echo_module_cost", TCL_GLOBAL_ONLY
));
803 zQuery
= sqlite3_mprintf("SELECT count(*) FROM %Q", pVtab
->zTableName
);
807 rc
= sqlite3_prepare(pVtab
->db
, zQuery
, -1, &pStmt
, 0);
808 sqlite3_free(zQuery
);
813 nRow
= sqlite3_column_int(pStmt
, 0);
814 rc
= sqlite3_finalize(pStmt
);
820 zQuery
= sqlite3_mprintf("SELECT rowid, * FROM %Q", pVtab
->zTableName
);
824 for(ii
=0; ii
<pIdxInfo
->nConstraint
; ii
++){
825 const struct sqlite3_index_constraint
*pConstraint
;
826 struct sqlite3_index_constraint_usage
*pUsage
;
829 pConstraint
= &pIdxInfo
->aConstraint
[ii
];
830 pUsage
= &pIdxInfo
->aConstraintUsage
[ii
];
832 if( !isIgnoreUsable
&& !pConstraint
->usable
) continue;
834 iCol
= pConstraint
->iColumn
;
835 if( iCol
<0 || pVtab
->aIndex
[iCol
] ){
836 char *zCol
= iCol
>=0 ? pVtab
->aCol
[iCol
] : "rowid";
839 switch( pConstraint
->op
){
840 case SQLITE_INDEX_CONSTRAINT_EQ
:
842 case SQLITE_INDEX_CONSTRAINT_LT
:
844 case SQLITE_INDEX_CONSTRAINT_GT
:
846 case SQLITE_INDEX_CONSTRAINT_LE
:
848 case SQLITE_INDEX_CONSTRAINT_GE
:
850 case SQLITE_INDEX_CONSTRAINT_MATCH
:
854 zNew
= sqlite3_mprintf(" %s %s LIKE (SELECT '%%'||?||'%%')",
857 zNew
= sqlite3_mprintf(" %s %s %s ?", zSep
, zCol
, zOp
);
859 string_concat(&zQuery
, zNew
, 1, &rc
);
862 pUsage
->argvIndex
= ++nArg
;
867 /* If there is only one term in the ORDER BY clause, and it is
868 ** on a column that this virtual table has an index for, then consume
869 ** the ORDER BY clause.
871 if( pIdxInfo
->nOrderBy
==1 && (
872 pIdxInfo
->aOrderBy
->iColumn
<0 ||
873 pVtab
->aIndex
[pIdxInfo
->aOrderBy
->iColumn
]) ){
874 int iCol
= pIdxInfo
->aOrderBy
->iColumn
;
875 char *zCol
= iCol
>=0 ? pVtab
->aCol
[iCol
] : "rowid";
876 char *zDir
= pIdxInfo
->aOrderBy
->desc
?"DESC":"ASC";
877 zNew
= sqlite3_mprintf(" ORDER BY %s %s", zCol
, zDir
);
878 string_concat(&zQuery
, zNew
, 1, &rc
);
879 pIdxInfo
->orderByConsumed
= 1;
882 appendToEchoModule(pVtab
->interp
, "xBestIndex");;
883 appendToEchoModule(pVtab
->interp
, zQuery
);
888 pIdxInfo
->idxNum
= hashString(zQuery
);
889 pIdxInfo
->idxStr
= zQuery
;
890 pIdxInfo
->needToFreeIdxStr
= 1;
892 pIdxInfo
->estimatedCost
= cost
;
894 /* Approximation of log2(nRow). */
895 for( ii
=0; ii
<(sizeof(int)*8)-1; ii
++ ){
896 if( nRow
& (1<<ii
) ){
897 pIdxInfo
->estimatedCost
= (double)ii
;
901 pIdxInfo
->estimatedCost
= (double)nRow
;
907 ** The xUpdate method for echo module virtual tables.
909 ** apData[0] apData[1] apData[2..]
913 ** INTEGER NULL (nCol args) UPDATE (do not set rowid)
914 ** INTEGER INTEGER (nCol args) UPDATE (with SET rowid = <arg1>)
916 ** NULL NULL (nCol args) INSERT INTO (automatic rowid value)
917 ** NULL INTEGER (nCol args) INSERT (incl. rowid value)
923 sqlite3_value
**apData
,
926 echo_vtab
*pVtab
= (echo_vtab
*)tab
;
927 sqlite3
*db
= pVtab
->db
;
931 char *z
= 0; /* SQL statement to execute */
932 int bindArgZero
= 0; /* True to bind apData[0] to sql var no. nData */
933 int bindArgOne
= 0; /* True to bind apData[1] to sql var no. 1 */
934 int i
; /* Counter variable used by for loops */
936 assert( nData
==pVtab
->nCol
+2 || nData
==1 );
938 /* Ticket #3083 - make sure we always start a transaction prior to
939 ** making any changes to a virtual table */
940 assert( pVtab
->inTransaction
);
942 if( simulateVtabError(pVtab
, "xUpdate") ){
946 /* If apData[0] is an integer and nData>1 then do an UPDATE */
947 if( nData
>1 && sqlite3_value_type(apData
[0])==SQLITE_INTEGER
){
949 z
= sqlite3_mprintf("UPDATE %Q", pVtab
->zTableName
);
954 bindArgOne
= (apData
[1] && sqlite3_value_type(apData
[1])==SQLITE_INTEGER
);
958 string_concat(&z
, " SET rowid=?1 ", 0, &rc
);
961 for(i
=2; i
<nData
; i
++){
962 if( apData
[i
]==0 ) continue;
963 string_concat(&z
, sqlite3_mprintf(
964 "%s %Q=?%d", zSep
, pVtab
->aCol
[i
-2], i
), 1, &rc
);
967 string_concat(&z
, sqlite3_mprintf(" WHERE rowid=?%d", nData
), 1, &rc
);
970 /* If apData[0] is an integer and nData==1 then do a DELETE */
971 else if( nData
==1 && sqlite3_value_type(apData
[0])==SQLITE_INTEGER
){
972 z
= sqlite3_mprintf("DELETE FROM %Q WHERE rowid = ?1", pVtab
->zTableName
);
979 /* If the first argument is NULL and there are more than two args, INSERT */
980 else if( nData
>2 && sqlite3_value_type(apData
[0])==SQLITE_NULL
){
985 zInsert
= sqlite3_mprintf("INSERT INTO %Q (", pVtab
->zTableName
);
989 if( sqlite3_value_type(apData
[1])==SQLITE_INTEGER
){
991 zValues
= sqlite3_mprintf("?");
992 string_concat(&zInsert
, "rowid", 0, &rc
);
995 assert((pVtab
->nCol
+2)==nData
);
996 for(ii
=2; ii
<nData
; ii
++){
997 string_concat(&zInsert
,
998 sqlite3_mprintf("%s%Q", zValues
?", ":"", pVtab
->aCol
[ii
-2]), 1, &rc
);
999 string_concat(&zValues
,
1000 sqlite3_mprintf("%s?%d", zValues
?", ":"", ii
), 1, &rc
);
1003 string_concat(&z
, zInsert
, 1, &rc
);
1004 string_concat(&z
, ") VALUES(", 0, &rc
);
1005 string_concat(&z
, zValues
, 1, &rc
);
1006 string_concat(&z
, ")", 0, &rc
);
1009 /* Anything else is an error */
1012 return SQLITE_ERROR
;
1015 if( rc
==SQLITE_OK
){
1016 rc
= sqlite3_prepare(db
, z
, -1, &pStmt
, 0);
1018 assert( rc
!=SQLITE_OK
|| pStmt
);
1020 if( rc
==SQLITE_OK
) {
1022 sqlite3_bind_value(pStmt
, nData
, apData
[0]);
1025 sqlite3_bind_value(pStmt
, 1, apData
[1]);
1027 for(i
=2; i
<nData
&& rc
==SQLITE_OK
; i
++){
1028 if( apData
[i
] ) rc
= sqlite3_bind_value(pStmt
, i
, apData
[i
]);
1030 if( rc
==SQLITE_OK
){
1031 sqlite3_step(pStmt
);
1032 rc
= sqlite3_finalize(pStmt
);
1034 sqlite3_finalize(pStmt
);
1038 if( pRowid
&& rc
==SQLITE_OK
){
1039 *pRowid
= sqlite3_last_insert_rowid(db
);
1041 if( rc
!=SQLITE_OK
){
1042 tab
->zErrMsg
= sqlite3_mprintf("echo-vtab-error: %s", sqlite3_errmsg(db
));
1049 ** xBegin, xSync, xCommit and xRollback callbacks for echo module
1050 ** virtual tables. Do nothing other than add the name of the callback
1051 ** to the $::echo_module Tcl variable.
1053 static int echoTransactionCall(sqlite3_vtab
*tab
, const char *zCall
){
1055 echo_vtab
*pVtab
= (echo_vtab
*)tab
;
1056 z
= sqlite3_mprintf("echo(%s)", pVtab
->zTableName
);
1057 if( z
==0 ) return SQLITE_NOMEM
;
1058 appendToEchoModule(pVtab
->interp
, zCall
);
1059 appendToEchoModule(pVtab
->interp
, z
);
1063 static int echoBegin(sqlite3_vtab
*tab
){
1065 echo_vtab
*pVtab
= (echo_vtab
*)tab
;
1066 Tcl_Interp
*interp
= pVtab
->interp
;
1069 /* Ticket #3083 - do not start a transaction if we are already in
1071 assert( !pVtab
->inTransaction
);
1073 if( simulateVtabError(pVtab
, "xBegin") ){
1074 return SQLITE_ERROR
;
1077 rc
= echoTransactionCall(tab
, "xBegin");
1079 if( rc
==SQLITE_OK
){
1080 /* Check if the $::echo_module_begin_fail variable is defined. If it is,
1081 ** and it is set to the name of the real table underlying this virtual
1082 ** echo module table, then cause this xSync operation to fail.
1084 zVal
= Tcl_GetVar(interp
, "echo_module_begin_fail", TCL_GLOBAL_ONLY
);
1085 if( zVal
&& 0==strcmp(zVal
, pVtab
->zTableName
) ){
1089 if( rc
==SQLITE_OK
){
1090 pVtab
->inTransaction
= 1;
1094 static int echoSync(sqlite3_vtab
*tab
){
1096 echo_vtab
*pVtab
= (echo_vtab
*)tab
;
1097 Tcl_Interp
*interp
= pVtab
->interp
;
1100 /* Ticket #3083 - Only call xSync if we have previously started a
1102 assert( pVtab
->inTransaction
);
1104 if( simulateVtabError(pVtab
, "xSync") ){
1105 return SQLITE_ERROR
;
1108 rc
= echoTransactionCall(tab
, "xSync");
1110 if( rc
==SQLITE_OK
){
1111 /* Check if the $::echo_module_sync_fail variable is defined. If it is,
1112 ** and it is set to the name of the real table underlying this virtual
1113 ** echo module table, then cause this xSync operation to fail.
1115 zVal
= Tcl_GetVar(interp
, "echo_module_sync_fail", TCL_GLOBAL_ONLY
);
1116 if( zVal
&& 0==strcmp(zVal
, pVtab
->zTableName
) ){
1122 static int echoCommit(sqlite3_vtab
*tab
){
1123 echo_vtab
*pVtab
= (echo_vtab
*)tab
;
1126 /* Ticket #3083 - Only call xCommit if we have previously started
1128 assert( pVtab
->inTransaction
);
1130 if( simulateVtabError(pVtab
, "xCommit") ){
1131 return SQLITE_ERROR
;
1134 sqlite3BeginBenignMalloc();
1135 rc
= echoTransactionCall(tab
, "xCommit");
1136 sqlite3EndBenignMalloc();
1137 pVtab
->inTransaction
= 0;
1140 static int echoRollback(sqlite3_vtab
*tab
){
1142 echo_vtab
*pVtab
= (echo_vtab
*)tab
;
1144 /* Ticket #3083 - Only call xRollback if we have previously started
1146 assert( pVtab
->inTransaction
);
1148 rc
= echoTransactionCall(tab
, "xRollback");
1149 pVtab
->inTransaction
= 0;
1154 ** Implementation of "GLOB" function on the echo module. Pass
1155 ** all arguments to the ::echo_glob_overload procedure of TCL
1156 ** and return the result of that procedure as a string.
1158 static void overloadedGlobFunction(
1159 sqlite3_context
*pContext
,
1161 sqlite3_value
**apArg
1163 Tcl_Interp
*interp
= sqlite3_user_data(pContext
);
1167 Tcl_DStringInit(&str
);
1168 Tcl_DStringAppendElement(&str
, "::echo_glob_overload");
1169 for(i
=0; i
<nArg
; i
++){
1170 Tcl_DStringAppendElement(&str
, (char*)sqlite3_value_text(apArg
[i
]));
1172 rc
= Tcl_Eval(interp
, Tcl_DStringValue(&str
));
1173 Tcl_DStringFree(&str
);
1175 sqlite3_result_error(pContext
, Tcl_GetStringResult(interp
), -1);
1177 sqlite3_result_text(pContext
, Tcl_GetStringResult(interp
),
1178 -1, SQLITE_TRANSIENT
);
1180 Tcl_ResetResult(interp
);
1184 ** This is the xFindFunction implementation for the echo module.
1185 ** SQLite calls this routine when the first argument of a function
1186 ** is a column of an echo virtual table. This routine can optionally
1187 ** override the implementation of that function. It will choose to
1188 ** do so if the function is named "glob", and a TCL command named
1189 ** ::echo_glob_overload exists.
1191 static int echoFindFunction(
1194 const char *zFuncName
,
1195 void (**pxFunc
)(sqlite3_context
*,int,sqlite3_value
**),
1198 echo_vtab
*pVtab
= (echo_vtab
*)vtab
;
1199 Tcl_Interp
*interp
= pVtab
->interp
;
1201 if( strcmp(zFuncName
,"glob")!=0 ){
1204 if( Tcl_GetCommandInfo(interp
, "::echo_glob_overload", &info
)==0 ){
1207 *pxFunc
= overloadedGlobFunction
;
1212 static int echoRename(sqlite3_vtab
*vtab
, const char *zNewName
){
1214 echo_vtab
*p
= (echo_vtab
*)vtab
;
1216 if( simulateVtabError(p
, "xRename") ){
1217 return SQLITE_ERROR
;
1221 int nThis
= (int)strlen(p
->zThis
);
1222 char *zSql
= sqlite3_mprintf("ALTER TABLE %s RENAME TO %s%s",
1223 p
->zTableName
, zNewName
, &p
->zTableName
[nThis
]
1225 rc
= sqlite3_exec(p
->db
, zSql
, 0, 0, 0);
1232 static int echoSavepoint(sqlite3_vtab
*pVTab
, int iSavepoint
){
1237 static int echoRelease(sqlite3_vtab
*pVTab
, int iSavepoint
){
1242 static int echoRollbackTo(sqlite3_vtab
*pVTab
, int iSavepoint
){
1248 ** A virtual table module that merely "echos" the contents of another
1249 ** table (like an SQL VIEW).
1251 static sqlite3_module echoModule
= {
1258 echoOpen
, /* xOpen - open a cursor */
1259 echoClose
, /* xClose - close a cursor */
1260 echoFilter
, /* xFilter - configure scan constraints */
1261 echoNext
, /* xNext - advance a cursor */
1263 echoColumn
, /* xColumn - read data */
1264 echoRowid
, /* xRowid - read data */
1265 echoUpdate
, /* xUpdate - write data */
1266 echoBegin
, /* xBegin - begin transaction */
1267 echoSync
, /* xSync - sync transaction */
1268 echoCommit
, /* xCommit - commit transaction */
1269 echoRollback
, /* xRollback - rollback transaction */
1270 echoFindFunction
, /* xFindFunction - function overloading */
1271 echoRename
/* xRename - rename the table */
1274 static sqlite3_module echoModuleV2
= {
1281 echoOpen
, /* xOpen - open a cursor */
1282 echoClose
, /* xClose - close a cursor */
1283 echoFilter
, /* xFilter - configure scan constraints */
1284 echoNext
, /* xNext - advance a cursor */
1286 echoColumn
, /* xColumn - read data */
1287 echoRowid
, /* xRowid - read data */
1288 echoUpdate
, /* xUpdate - write data */
1289 echoBegin
, /* xBegin - begin transaction */
1290 echoSync
, /* xSync - sync transaction */
1291 echoCommit
, /* xCommit - commit transaction */
1292 echoRollback
, /* xRollback - rollback transaction */
1293 echoFindFunction
, /* xFindFunction - function overloading */
1294 echoRename
, /* xRename - rename the table */
1301 ** Decode a pointer to an sqlite3 object.
1303 extern int getDbPointer(Tcl_Interp
*interp
, const char *zA
, sqlite3
**ppDb
);
1304 extern const char *sqlite3ErrName(int);
1306 static void moduleDestroy(void *p
){
1311 ** Register the echo virtual table module.
1313 static int register_echo_module(
1314 ClientData clientData
, /* Pointer to sqlite3_enable_XXX function */
1315 Tcl_Interp
*interp
, /* The TCL interpreter that invoked this command */
1316 int objc
, /* Number of arguments */
1317 Tcl_Obj
*CONST objv
[] /* Command arguments */
1323 Tcl_WrongNumArgs(interp
, 1, objv
, "DB");
1326 if( getDbPointer(interp
, Tcl_GetString(objv
[1]), &db
) ) return TCL_ERROR
;
1328 /* Virtual table module "echo" */
1329 pMod
= sqlite3_malloc(sizeof(EchoModule
));
1330 pMod
->interp
= interp
;
1331 rc
= sqlite3_create_module_v2(
1332 db
, "echo", &echoModule
, (void*)pMod
, moduleDestroy
1335 /* Virtual table module "echo_v2" */
1336 if( rc
==SQLITE_OK
){
1337 pMod
= sqlite3_malloc(sizeof(EchoModule
));
1338 pMod
->interp
= interp
;
1339 rc
= sqlite3_create_module_v2(db
, "echo_v2",
1340 &echoModuleV2
, (void*)pMod
, moduleDestroy
1344 Tcl_SetResult(interp
, (char *)sqlite3ErrName(rc
), TCL_STATIC
);
1349 ** Tcl interface to sqlite3_declare_vtab, invoked as follows from Tcl:
1351 ** sqlite3_declare_vtab DB SQL
1353 static int declare_vtab(
1354 ClientData clientData
, /* Pointer to sqlite3_enable_XXX function */
1355 Tcl_Interp
*interp
, /* The TCL interpreter that invoked this command */
1356 int objc
, /* Number of arguments */
1357 Tcl_Obj
*CONST objv
[] /* Command arguments */
1362 Tcl_WrongNumArgs(interp
, 1, objv
, "DB SQL");
1365 if( getDbPointer(interp
, Tcl_GetString(objv
[1]), &db
) ) return TCL_ERROR
;
1366 rc
= sqlite3_declare_vtab(db
, Tcl_GetString(objv
[2]));
1367 if( rc
!=SQLITE_OK
){
1368 Tcl_SetResult(interp
, (char *)sqlite3_errmsg(db
), TCL_VOLATILE
);
1374 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
1377 ** Register commands with the TCL interpreter.
1379 int Sqlitetest8_Init(Tcl_Interp
*interp
){
1380 #ifndef SQLITE_OMIT_VIRTUALTABLE
1383 Tcl_ObjCmdProc
*xProc
;
1386 { "register_echo_module", register_echo_module
, 0 },
1387 { "sqlite3_declare_vtab", declare_vtab
, 0 },
1390 for(i
=0; i
<sizeof(aObjCmd
)/sizeof(aObjCmd
[0]); i
++){
1391 Tcl_CreateObjCommand(interp
, aObjCmd
[i
].zName
,
1392 aObjCmd
[i
].xProc
, aObjCmd
[i
].clientData
, 0);