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