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