xref: /sqlite-3.40.0/src/vtab.c (revision 5368f29a)
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 ** This file contains code used to help implement virtual tables.
13 **
14 ** $Id: vtab.c,v 1.92 2009/07/01 18:04:21 danielk1977 Exp $
15 */
16 #ifndef SQLITE_OMIT_VIRTUALTABLE
17 #include "sqliteInt.h"
18 
19 /*
20 ** The actual function that does the work of creating a new module.
21 ** This function implements the sqlite3_create_module() and
22 ** sqlite3_create_module_v2() interfaces.
23 */
24 static int createModule(
25   sqlite3 *db,                    /* Database in which module is registered */
26   const char *zName,              /* Name assigned to this module */
27   const sqlite3_module *pModule,  /* The definition of the module */
28   void *pAux,                     /* Context pointer for xCreate/xConnect */
29   void (*xDestroy)(void *)        /* Module destructor function */
30 ) {
31   int rc, nName;
32   Module *pMod;
33 
34   sqlite3_mutex_enter(db->mutex);
35   nName = sqlite3Strlen30(zName);
36   pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
37   if( pMod ){
38     Module *pDel;
39     char *zCopy = (char *)(&pMod[1]);
40     memcpy(zCopy, zName, nName+1);
41     pMod->zName = zCopy;
42     pMod->pModule = pModule;
43     pMod->pAux = pAux;
44     pMod->xDestroy = xDestroy;
45     pDel = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
46     if( pDel && pDel->xDestroy ){
47       pDel->xDestroy(pDel->pAux);
48     }
49     sqlite3DbFree(db, pDel);
50     if( pDel==pMod ){
51       db->mallocFailed = 1;
52     }
53     sqlite3ResetInternalSchema(db, 0);
54   }else if( xDestroy ){
55     xDestroy(pAux);
56   }
57   rc = sqlite3ApiExit(db, SQLITE_OK);
58   sqlite3_mutex_leave(db->mutex);
59   return rc;
60 }
61 
62 
63 /*
64 ** External API function used to create a new virtual-table module.
65 */
66 int sqlite3_create_module(
67   sqlite3 *db,                    /* Database in which module is registered */
68   const char *zName,              /* Name assigned to this module */
69   const sqlite3_module *pModule,  /* The definition of the module */
70   void *pAux                      /* Context pointer for xCreate/xConnect */
71 ){
72   return createModule(db, zName, pModule, pAux, 0);
73 }
74 
75 /*
76 ** External API function used to create a new virtual-table module.
77 */
78 int sqlite3_create_module_v2(
79   sqlite3 *db,                    /* Database in which module is registered */
80   const char *zName,              /* Name assigned to this module */
81   const sqlite3_module *pModule,  /* The definition of the module */
82   void *pAux,                     /* Context pointer for xCreate/xConnect */
83   void (*xDestroy)(void *)        /* Module destructor function */
84 ){
85   return createModule(db, zName, pModule, pAux, xDestroy);
86 }
87 
88 /*
89 ** Lock the virtual table so that it cannot be disconnected.
90 ** Locks nest.  Every lock should have a corresponding unlock.
91 ** If an unlock is omitted, resources leaks will occur.
92 **
93 ** If a disconnect is attempted while a virtual table is locked,
94 ** the disconnect is deferred until all locks have been removed.
95 */
96 void sqlite3VtabLock(sqlite3_vtab *pVtab){
97   pVtab->nRef++;
98 }
99 
100 /*
101 ** Unlock a virtual table.  When the last lock is removed,
102 ** disconnect the virtual table.
103 */
104 void sqlite3VtabUnlock(sqlite3 *db, sqlite3_vtab *pVtab){
105 #ifndef SQLITE_DEBUG
106   UNUSED_PARAMETER(db);
107 #endif
108   assert( pVtab->nRef>0 );
109   pVtab->nRef--;
110   assert(db);
111   assert( sqlite3SafetyCheckOk(db) );
112   if( pVtab->nRef==0 ){
113 #ifdef SQLITE_DEBUG
114     if( db->magic==SQLITE_MAGIC_BUSY ){
115       (void)sqlite3SafetyOff(db);
116       pVtab->pModule->xDisconnect(pVtab);
117       (void)sqlite3SafetyOn(db);
118     } else
119 #endif
120     {
121       pVtab->pModule->xDisconnect(pVtab);
122     }
123   }
124 }
125 
126 /*
127 ** Clear any and all virtual-table information from the Table record.
128 ** This routine is called, for example, just before deleting the Table
129 ** record.
130 */
131 void sqlite3VtabClear(Table *p){
132   sqlite3_vtab *pVtab = p->pVtab;
133   Schema *pSchema = p->pSchema;
134   sqlite3 *db = pSchema ? pSchema->db : 0;
135   if( pVtab ){
136     assert( p->pMod && p->pMod->pModule );
137     sqlite3VtabUnlock(db, pVtab);
138     p->pVtab = 0;
139   }
140   if( p->azModuleArg ){
141     int i;
142     for(i=0; i<p->nModuleArg; i++){
143       sqlite3DbFree(db, p->azModuleArg[i]);
144     }
145     sqlite3DbFree(db, p->azModuleArg);
146   }
147 }
148 
149 /*
150 ** Add a new module argument to pTable->azModuleArg[].
151 ** The string is not copied - the pointer is stored.  The
152 ** string will be freed automatically when the table is
153 ** deleted.
154 */
155 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
156   int i = pTable->nModuleArg++;
157   int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
158   char **azModuleArg;
159   azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
160   if( azModuleArg==0 ){
161     int j;
162     for(j=0; j<i; j++){
163       sqlite3DbFree(db, pTable->azModuleArg[j]);
164     }
165     sqlite3DbFree(db, zArg);
166     sqlite3DbFree(db, pTable->azModuleArg);
167     pTable->nModuleArg = 0;
168   }else{
169     azModuleArg[i] = zArg;
170     azModuleArg[i+1] = 0;
171   }
172   pTable->azModuleArg = azModuleArg;
173 }
174 
175 /*
176 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
177 ** statement.  The module name has been parsed, but the optional list
178 ** of parameters that follow the module name are still pending.
179 */
180 void sqlite3VtabBeginParse(
181   Parse *pParse,        /* Parsing context */
182   Token *pName1,        /* Name of new table, or database name */
183   Token *pName2,        /* Name of new table or NULL */
184   Token *pModuleName    /* Name of the module for the virtual table */
185 ){
186   int iDb;              /* The database the table is being created in */
187   Table *pTable;        /* The new virtual table */
188   sqlite3 *db;          /* Database connection */
189 
190   if( pParse->db->flags & SQLITE_SharedCache ){
191     sqlite3ErrorMsg(pParse, "Cannot use virtual tables in shared-cache mode");
192     return;
193   }
194 
195   sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, 0);
196   pTable = pParse->pNewTable;
197   if( pTable==0 ) return;
198   assert( 0==pTable->pIndex );
199 
200   db = pParse->db;
201   iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
202   assert( iDb>=0 );
203 
204   pTable->tabFlags |= TF_Virtual;
205   pTable->nModuleArg = 0;
206   addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
207   addModuleArgument(db, pTable, sqlite3DbStrDup(db, db->aDb[iDb].zName));
208   addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
209   pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
210 
211 #ifndef SQLITE_OMIT_AUTHORIZATION
212   /* Creating a virtual table invokes the authorization callback twice.
213   ** The first invocation, to obtain permission to INSERT a row into the
214   ** sqlite_master table, has already been made by sqlite3StartTable().
215   ** The second call, to obtain permission to create the table, is made now.
216   */
217   if( pTable->azModuleArg ){
218     sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
219             pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
220   }
221 #endif
222 }
223 
224 /*
225 ** This routine takes the module argument that has been accumulating
226 ** in pParse->zArg[] and appends it to the list of arguments on the
227 ** virtual table currently under construction in pParse->pTable.
228 */
229 static void addArgumentToVtab(Parse *pParse){
230   if( pParse->sArg.z && ALWAYS(pParse->pNewTable) ){
231     const char *z = (const char*)pParse->sArg.z;
232     int n = pParse->sArg.n;
233     sqlite3 *db = pParse->db;
234     addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
235   }
236 }
237 
238 /*
239 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
240 ** has been completely parsed.
241 */
242 void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
243   Table *pTab;        /* The table being constructed */
244   sqlite3 *db;        /* The database connection */
245   char *zModule;      /* The module name of the table: USING modulename */
246   Module *pMod = 0;
247 
248   addArgumentToVtab(pParse);
249   pParse->sArg.z = 0;
250 
251   /* Lookup the module name. */
252   pTab = pParse->pNewTable;
253   if( pTab==0 ) return;
254   db = pParse->db;
255   if( pTab->nModuleArg<1 ) return;
256   zModule = pTab->azModuleArg[0];
257   pMod = (Module*)sqlite3HashFind(&db->aModule, zModule,
258                                   sqlite3Strlen30(zModule));
259   pTab->pMod = pMod;
260 
261   /* If the CREATE VIRTUAL TABLE statement is being entered for the
262   ** first time (in other words if the virtual table is actually being
263   ** created now instead of just being read out of sqlite_master) then
264   ** do additional initialization work and store the statement text
265   ** in the sqlite_master table.
266   */
267   if( !db->init.busy ){
268     char *zStmt;
269     char *zWhere;
270     int iDb;
271     Vdbe *v;
272 
273     /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
274     if( pEnd ){
275       pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
276     }
277     zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
278 
279     /* A slot for the record has already been allocated in the
280     ** SQLITE_MASTER table.  We just need to update that slot with all
281     ** the information we've collected.
282     **
283     ** The VM register number pParse->regRowid holds the rowid of an
284     ** entry in the sqlite_master table tht was created for this vtab
285     ** by sqlite3StartTable().
286     */
287     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
288     sqlite3NestedParse(pParse,
289       "UPDATE %Q.%s "
290          "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
291        "WHERE rowid=#%d",
292       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
293       pTab->zName,
294       pTab->zName,
295       zStmt,
296       pParse->regRowid
297     );
298     sqlite3DbFree(db, zStmt);
299     v = sqlite3GetVdbe(pParse);
300     sqlite3ChangeCookie(pParse, iDb);
301 
302     sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
303     zWhere = sqlite3MPrintf(db, "name='%q'", pTab->zName);
304     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 1, 0, zWhere, P4_DYNAMIC);
305     sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0,
306                          pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
307   }
308 
309   /* If we are rereading the sqlite_master table create the in-memory
310   ** record of the table. If the module has already been registered,
311   ** also call the xConnect method here.
312   */
313   else {
314     Table *pOld;
315     Schema *pSchema = pTab->pSchema;
316     const char *zName = pTab->zName;
317     int nName = sqlite3Strlen30(zName);
318     pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
319     if( pOld ){
320       db->mallocFailed = 1;
321       assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
322       return;
323     }
324     pSchema->db = pParse->db;
325     pParse->pNewTable = 0;
326   }
327 }
328 
329 /*
330 ** The parser calls this routine when it sees the first token
331 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
332 */
333 void sqlite3VtabArgInit(Parse *pParse){
334   addArgumentToVtab(pParse);
335   pParse->sArg.z = 0;
336   pParse->sArg.n = 0;
337 }
338 
339 /*
340 ** The parser calls this routine for each token after the first token
341 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
342 */
343 void sqlite3VtabArgExtend(Parse *pParse, Token *p){
344   Token *pArg = &pParse->sArg;
345   if( pArg->z==0 ){
346     pArg->z = p->z;
347     pArg->n = p->n;
348   }else{
349     assert(pArg->z < p->z);
350     pArg->n = (int)(&p->z[p->n] - pArg->z);
351   }
352 }
353 
354 /*
355 ** Invoke a virtual table constructor (either xCreate or xConnect). The
356 ** pointer to the function to invoke is passed as the fourth parameter
357 ** to this procedure.
358 */
359 static int vtabCallConstructor(
360   sqlite3 *db,
361   Table *pTab,
362   Module *pMod,
363   int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
364   char **pzErr
365 ){
366   int rc;
367   int rc2;
368   sqlite3_vtab *pVtab = 0;
369   const char *const*azArg = (const char *const*)pTab->azModuleArg;
370   int nArg = pTab->nModuleArg;
371   char *zErr = 0;
372   char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
373 
374   if( !zModuleName ){
375     return SQLITE_NOMEM;
376   }
377 
378   assert( !db->pVTab );
379   assert( xConstruct );
380 
381   db->pVTab = pTab;
382   rc = sqlite3SafetyOff(db);
383   assert( rc==SQLITE_OK );
384   rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVtab, &zErr);
385   rc2 = sqlite3SafetyOn(db);
386   if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
387   /* Justification of ALWAYS():  A correct vtab constructor must allocate
388   ** the sqlite3_vtab object if successful. */
389   if( rc==SQLITE_OK && ALWAYS(pVtab) ){
390     pVtab->pModule = pMod->pModule;
391     pVtab->nRef = 1;
392     pTab->pVtab = pVtab;
393   }
394 
395   if( SQLITE_OK!=rc ){
396     if( zErr==0 ){
397       *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
398     }else {
399       *pzErr = sqlite3MPrintf(db, "%s", zErr);
400       sqlite3DbFree(db, zErr);
401     }
402   }else if( db->pVTab ){
403     const char *zFormat = "vtable constructor did not declare schema: %s";
404     *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
405     rc = SQLITE_ERROR;
406   }
407   if( rc==SQLITE_OK ){
408     rc = rc2;
409   }
410   db->pVTab = 0;
411   sqlite3DbFree(db, zModuleName);
412 
413   /* If everything went according to plan, loop through the columns
414   ** of the table to see if any of them contain the token "hidden".
415   ** If so, set the Column.isHidden flag and remove the token from
416   ** the type string.
417   */
418   if( rc==SQLITE_OK ){
419     int iCol;
420     for(iCol=0; iCol<pTab->nCol; iCol++){
421       char *zType = pTab->aCol[iCol].zType;
422       int nType;
423       int i = 0;
424       if( !zType ) continue;
425       nType = sqlite3Strlen30(zType);
426       if( sqlite3StrNICmp("hidden", zType, 6) || (zType[6] && zType[6]!=' ') ){
427         for(i=0; i<nType; i++){
428           if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
429            && (zType[i+7]=='\0' || zType[i+7]==' ')
430           ){
431             i++;
432             break;
433           }
434         }
435       }
436       if( i<nType ){
437         int j;
438         int nDel = 6 + (zType[i+6] ? 1 : 0);
439         for(j=i; (j+nDel)<=nType; j++){
440           zType[j] = zType[j+nDel];
441         }
442         if( zType[i]=='\0' && i>0 ){
443           assert(zType[i-1]==' ');
444           zType[i-1] = '\0';
445         }
446         pTab->aCol[iCol].isHidden = 1;
447       }
448     }
449   }
450   return rc;
451 }
452 
453 /*
454 ** This function is invoked by the parser to call the xConnect() method
455 ** of the virtual table pTab. If an error occurs, an error code is returned
456 ** and an error left in pParse.
457 **
458 ** This call is a no-op if table pTab is not a virtual table.
459 */
460 int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
461   Module *pMod;
462   int rc = SQLITE_OK;
463 
464   assert( pTab );
465   if( (pTab->tabFlags & TF_Virtual)==0 || pTab->pVtab ){
466     return SQLITE_OK;
467   }
468 
469   pMod = pTab->pMod;
470   if( !pMod ){
471     const char *zModule = pTab->azModuleArg[0];
472     sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
473     rc = SQLITE_ERROR;
474   } else {
475     char *zErr = 0;
476     sqlite3 *db = pParse->db;
477     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
478     if( rc!=SQLITE_OK ){
479       sqlite3ErrorMsg(pParse, "%s", zErr);
480     }
481     sqlite3DbFree(db, zErr);
482   }
483 
484   return rc;
485 }
486 
487 /*
488 ** Add the virtual table pVtab to the array sqlite3.aVTrans[].
489 */
490 static int addToVTrans(sqlite3 *db, sqlite3_vtab *pVtab){
491   const int ARRAY_INCR = 5;
492 
493   /* Grow the sqlite3.aVTrans array if required */
494   if( (db->nVTrans%ARRAY_INCR)==0 ){
495     sqlite3_vtab **aVTrans;
496     int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
497     aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
498     if( !aVTrans ){
499       return SQLITE_NOMEM;
500     }
501     memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
502     db->aVTrans = aVTrans;
503   }
504 
505   /* Add pVtab to the end of sqlite3.aVTrans */
506   db->aVTrans[db->nVTrans++] = pVtab;
507   sqlite3VtabLock(pVtab);
508   return SQLITE_OK;
509 }
510 
511 /*
512 ** This function is invoked by the vdbe to call the xCreate method
513 ** of the virtual table named zTab in database iDb.
514 **
515 ** If an error occurs, *pzErr is set to point an an English language
516 ** description of the error and an SQLITE_XXX error code is returned.
517 ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
518 */
519 int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
520   int rc = SQLITE_OK;
521   Table *pTab;
522   Module *pMod;
523   const char *zModule;
524 
525   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
526   assert(pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVtab);
527   pMod = pTab->pMod;
528   zModule = pTab->azModuleArg[0];
529 
530   /* If the module has been registered and includes a Create method,
531   ** invoke it now. If the module has not been registered, return an
532   ** error. Otherwise, do nothing.
533   */
534   if( !pMod ){
535     *pzErr = sqlite3MPrintf(db, "no such module: %s", zModule);
536     rc = SQLITE_ERROR;
537   }else{
538     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
539   }
540 
541   /* Justification of ALWAYS():  The xConstructor method is required to
542   ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
543   if( rc==SQLITE_OK && ALWAYS(pTab->pVtab) ){
544       rc = addToVTrans(db, pTab->pVtab);
545   }
546 
547   return rc;
548 }
549 
550 /*
551 ** This function is used to set the schema of a virtual table.  It is only
552 ** valid to call this function from within the xCreate() or xConnect() of a
553 ** virtual table module.
554 */
555 int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
556   Parse *pParse;
557 
558   int rc = SQLITE_OK;
559   Table *pTab;
560   char *zErr = 0;
561 
562   sqlite3_mutex_enter(db->mutex);
563   pTab = db->pVTab;
564   if( !pTab ){
565     sqlite3Error(db, SQLITE_MISUSE, 0);
566     sqlite3_mutex_leave(db->mutex);
567     return SQLITE_MISUSE;
568   }
569   assert((pTab->tabFlags & TF_Virtual)!=0 && pTab->nCol==0 && pTab->aCol==0);
570 
571   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
572   if( pParse==0 ){
573     rc = SQLITE_NOMEM;
574   }else{
575     pParse->declareVtab = 1;
576     pParse->db = db;
577 
578     if(
579         SQLITE_OK == sqlite3RunParser(pParse, zCreateTable, &zErr) &&
580         pParse->pNewTable &&
581         !pParse->pNewTable->pSelect &&
582         (pParse->pNewTable->tabFlags & TF_Virtual)==0
583     ){
584       pTab->aCol = pParse->pNewTable->aCol;
585       pTab->nCol = pParse->pNewTable->nCol;
586       pParse->pNewTable->nCol = 0;
587       pParse->pNewTable->aCol = 0;
588       db->pVTab = 0;
589     } else {
590       sqlite3Error(db, SQLITE_ERROR, zErr);
591       sqlite3DbFree(db, zErr);
592       rc = SQLITE_ERROR;
593     }
594     pParse->declareVtab = 0;
595 
596     if( pParse->pVdbe ){
597       sqlite3VdbeFinalize(pParse->pVdbe);
598     }
599     sqlite3DeleteTable(pParse->pNewTable);
600     sqlite3StackFree(db, pParse);
601   }
602 
603   assert( (rc&0xff)==rc );
604   rc = sqlite3ApiExit(db, rc);
605   sqlite3_mutex_leave(db->mutex);
606   return rc;
607 }
608 
609 /*
610 ** This function is invoked by the vdbe to call the xDestroy method
611 ** of the virtual table named zTab in database iDb. This occurs
612 ** when a DROP TABLE is mentioned.
613 **
614 ** This call is a no-op if zTab is not a virtual table.
615 */
616 int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
617   int rc = SQLITE_OK;
618   Table *pTab;
619 
620   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
621   if( ALWAYS(pTab!=0 && pTab->pVtab!=0) ){
622     int (*xDestroy)(sqlite3_vtab *pVTab) = pTab->pMod->pModule->xDestroy;
623     rc = sqlite3SafetyOff(db);
624     assert( rc==SQLITE_OK );
625     rc = xDestroy(pTab->pVtab);
626     (void)sqlite3SafetyOn(db);
627     if( rc==SQLITE_OK ){
628       int i;
629       for(i=0; i<db->nVTrans; i++){
630         if( db->aVTrans[i]==pTab->pVtab ){
631           db->aVTrans[i] = db->aVTrans[--db->nVTrans];
632           break;
633         }
634       }
635       pTab->pVtab = 0;
636     }
637   }
638 
639   return rc;
640 }
641 
642 /*
643 ** This function invokes either the xRollback or xCommit method
644 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
645 ** called is identified by the second argument, "offset", which is
646 ** the offset of the method to call in the sqlite3_module structure.
647 **
648 ** The array is cleared after invoking the callbacks.
649 */
650 static void callFinaliser(sqlite3 *db, int offset){
651   int i;
652   if( db->aVTrans ){
653     for(i=0; i<db->nVTrans; i++){
654       sqlite3_vtab *pVtab = db->aVTrans[i];
655       int (*x)(sqlite3_vtab *);
656 
657       assert( pVtab!=0 );
658       x = *(int (**)(sqlite3_vtab *))((char *)pVtab->pModule + offset);
659       if( x ) x(pVtab);
660       sqlite3VtabUnlock(db, pVtab);
661     }
662     sqlite3DbFree(db, db->aVTrans);
663     db->nVTrans = 0;
664     db->aVTrans = 0;
665   }
666 }
667 
668 /*
669 ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
670 ** array. Return the error code for the first error that occurs, or
671 ** SQLITE_OK if all xSync operations are successful.
672 **
673 ** Set *pzErrmsg to point to a buffer that should be released using
674 ** sqlite3DbFree() containing an error message, if one is available.
675 */
676 int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
677   int i;
678   int rc = SQLITE_OK;
679   int rcsafety;
680   sqlite3_vtab **aVTrans = db->aVTrans;
681 
682   rc = sqlite3SafetyOff(db);
683   db->aVTrans = 0;
684   for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
685     sqlite3_vtab *pVtab = aVTrans[i];
686     int (*x)(sqlite3_vtab *);
687     assert( pVtab!=0 );
688     x = pVtab->pModule->xSync;
689     if( x ){
690       rc = x(pVtab);
691       sqlite3DbFree(db, *pzErrmsg);
692       *pzErrmsg = pVtab->zErrMsg;
693       pVtab->zErrMsg = 0;
694     }
695   }
696   db->aVTrans = aVTrans;
697   rcsafety = sqlite3SafetyOn(db);
698 
699   if( rc==SQLITE_OK ){
700     rc = rcsafety;
701   }
702   return rc;
703 }
704 
705 /*
706 ** Invoke the xRollback method of all virtual tables in the
707 ** sqlite3.aVTrans array. Then clear the array itself.
708 */
709 int sqlite3VtabRollback(sqlite3 *db){
710   callFinaliser(db, offsetof(sqlite3_module,xRollback));
711   return SQLITE_OK;
712 }
713 
714 /*
715 ** Invoke the xCommit method of all virtual tables in the
716 ** sqlite3.aVTrans array. Then clear the array itself.
717 */
718 int sqlite3VtabCommit(sqlite3 *db){
719   callFinaliser(db, offsetof(sqlite3_module,xCommit));
720   return SQLITE_OK;
721 }
722 
723 /*
724 ** If the virtual table pVtab supports the transaction interface
725 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
726 ** not currently open, invoke the xBegin method now.
727 **
728 ** If the xBegin call is successful, place the sqlite3_vtab pointer
729 ** in the sqlite3.aVTrans array.
730 */
731 int sqlite3VtabBegin(sqlite3 *db, sqlite3_vtab *pVtab){
732   int rc = SQLITE_OK;
733   const sqlite3_module *pModule;
734 
735   /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
736   ** than zero, then this function is being called from within a
737   ** virtual module xSync() callback. It is illegal to write to
738   ** virtual module tables in this case, so return SQLITE_LOCKED.
739   */
740   if( sqlite3VtabInSync(db) ){
741     return SQLITE_LOCKED;
742   }
743   if( !pVtab ){
744     return SQLITE_OK;
745   }
746   pModule = pVtab->pModule;
747 
748   if( pModule->xBegin ){
749     int i;
750 
751 
752     /* If pVtab is already in the aVTrans array, return early */
753     for(i=0; i<db->nVTrans; i++){
754       if( db->aVTrans[i]==pVtab ){
755         return SQLITE_OK;
756       }
757     }
758 
759     /* Invoke the xBegin method */
760     rc = pModule->xBegin(pVtab);
761     if( rc==SQLITE_OK ){
762       rc = addToVTrans(db, pVtab);
763     }
764   }
765   return rc;
766 }
767 
768 /*
769 ** The first parameter (pDef) is a function implementation.  The
770 ** second parameter (pExpr) is the first argument to this function.
771 ** If pExpr is a column in a virtual table, then let the virtual
772 ** table implementation have an opportunity to overload the function.
773 **
774 ** This routine is used to allow virtual table implementations to
775 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
776 **
777 ** Return either the pDef argument (indicating no change) or a
778 ** new FuncDef structure that is marked as ephemeral using the
779 ** SQLITE_FUNC_EPHEM flag.
780 */
781 FuncDef *sqlite3VtabOverloadFunction(
782   sqlite3 *db,    /* Database connection for reporting malloc problems */
783   FuncDef *pDef,  /* Function to possibly overload */
784   int nArg,       /* Number of arguments to the function */
785   Expr *pExpr     /* First argument to the function */
786 ){
787   Table *pTab;
788   sqlite3_vtab *pVtab;
789   sqlite3_module *pMod;
790   void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
791   void *pArg = 0;
792   FuncDef *pNew;
793   int rc = 0;
794   char *zLowerName;
795   unsigned char *z;
796 
797 
798   /* Check to see the left operand is a column in a virtual table */
799   if( NEVER(pExpr==0) ) return pDef;
800   if( pExpr->op!=TK_COLUMN ) return pDef;
801   pTab = pExpr->pTab;
802   if( NEVER(pTab==0) ) return pDef;
803   if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
804   pVtab = pTab->pVtab;
805   assert( pVtab!=0 );
806   assert( pVtab->pModule!=0 );
807   pMod = (sqlite3_module *)pVtab->pModule;
808   if( pMod->xFindFunction==0 ) return pDef;
809 
810   /* Call the xFindFunction method on the virtual table implementation
811   ** to see if the implementation wants to overload this function
812   */
813   zLowerName = sqlite3DbStrDup(db, pDef->zName);
814   if( zLowerName ){
815     for(z=(unsigned char*)zLowerName; *z; z++){
816       *z = sqlite3UpperToLower[*z];
817     }
818     rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
819     sqlite3DbFree(db, zLowerName);
820   }
821   if( rc==0 ){
822     return pDef;
823   }
824 
825   /* Create a new ephemeral function definition for the overloaded
826   ** function */
827   pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
828                              + sqlite3Strlen30(pDef->zName) + 1);
829   if( pNew==0 ){
830     return pDef;
831   }
832   *pNew = *pDef;
833   pNew->zName = (char *)&pNew[1];
834   memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
835   pNew->xFunc = xFunc;
836   pNew->pUserData = pArg;
837   pNew->flags |= SQLITE_FUNC_EPHEM;
838   return pNew;
839 }
840 
841 /*
842 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
843 ** array so that an OP_VBegin will get generated for it.  Add pTab to the
844 ** array if it is missing.  If pTab is already in the array, this routine
845 ** is a no-op.
846 */
847 void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
848   int i, n;
849   Table **apVtabLock;
850 
851   assert( IsVirtual(pTab) );
852   for(i=0; i<pParse->nVtabLock; i++){
853     if( pTab==pParse->apVtabLock[i] ) return;
854   }
855   n = (pParse->nVtabLock+1)*sizeof(pParse->apVtabLock[0]);
856   apVtabLock = sqlite3_realloc(pParse->apVtabLock, n);
857   if( apVtabLock ){
858     pParse->apVtabLock = apVtabLock;
859     pParse->apVtabLock[pParse->nVtabLock++] = pTab;
860   }else{
861     pParse->db->mallocFailed = 1;
862   }
863 }
864 
865 #endif /* SQLITE_OMIT_VIRTUALTABLE */
866