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