test8.c 39 KB

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