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