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