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