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