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