| Index: third_party/sqlite/amalgamation/sqlite3.05.c
|
| diff --git a/third_party/sqlite/amalgamation/sqlite3.05.c b/third_party/sqlite/amalgamation/sqlite3.05.c
|
| new file mode 100644
|
| index 0000000000000000000000000000000000000000..563376b65a9f7bcac81b9ffd4920773074a5ced6
|
| --- /dev/null
|
| +++ b/third_party/sqlite/amalgamation/sqlite3.05.c
|
| @@ -0,0 +1,23025 @@
|
| +/************** Begin file trigger.c *****************************************/
|
| +/*
|
| +**
|
| +** The author disclaims copyright to this source code. In place of
|
| +** a legal notice, here is a blessing:
|
| +**
|
| +** May you do good and not evil.
|
| +** May you find forgiveness for yourself and forgive others.
|
| +** May you share freely, never taking more than you give.
|
| +**
|
| +*************************************************************************
|
| +** This file contains the implementation for TRIGGERs
|
| +*/
|
| +/* #include "sqliteInt.h" */
|
| +
|
| +#ifndef SQLITE_OMIT_TRIGGER
|
| +/*
|
| +** Delete a linked list of TriggerStep structures.
|
| +*/
|
| +SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
|
| + while( pTriggerStep ){
|
| + TriggerStep * pTmp = pTriggerStep;
|
| + pTriggerStep = pTriggerStep->pNext;
|
| +
|
| + sqlite3ExprDelete(db, pTmp->pWhere);
|
| + sqlite3ExprListDelete(db, pTmp->pExprList);
|
| + sqlite3SelectDelete(db, pTmp->pSelect);
|
| + sqlite3IdListDelete(db, pTmp->pIdList);
|
| +
|
| + sqlite3DbFree(db, pTmp);
|
| + }
|
| +}
|
| +
|
| +/*
|
| +** Given table pTab, return a list of all the triggers attached to
|
| +** the table. The list is connected by Trigger.pNext pointers.
|
| +**
|
| +** All of the triggers on pTab that are in the same database as pTab
|
| +** are already attached to pTab->pTrigger. But there might be additional
|
| +** triggers on pTab in the TEMP schema. This routine prepends all
|
| +** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
|
| +** and returns the combined list.
|
| +**
|
| +** To state it another way: This routine returns a list of all triggers
|
| +** that fire off of pTab. The list will include any TEMP triggers on
|
| +** pTab as well as the triggers lised in pTab->pTrigger.
|
| +*/
|
| +SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
|
| + Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
|
| + Trigger *pList = 0; /* List of triggers to return */
|
| +
|
| + if( pParse->disableTriggers ){
|
| + return 0;
|
| + }
|
| +
|
| + if( pTmpSchema!=pTab->pSchema ){
|
| + HashElem *p;
|
| + assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
|
| + for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
|
| + Trigger *pTrig = (Trigger *)sqliteHashData(p);
|
| + if( pTrig->pTabSchema==pTab->pSchema
|
| + && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
|
| + ){
|
| + pTrig->pNext = (pList ? pList : pTab->pTrigger);
|
| + pList = pTrig;
|
| + }
|
| + }
|
| + }
|
| +
|
| + return (pList ? pList : pTab->pTrigger);
|
| +}
|
| +
|
| +/*
|
| +** This is called by the parser when it sees a CREATE TRIGGER statement
|
| +** up to the point of the BEGIN before the trigger actions. A Trigger
|
| +** structure is generated based on the information available and stored
|
| +** in pParse->pNewTrigger. After the trigger actions have been parsed, the
|
| +** sqlite3FinishTrigger() function is called to complete the trigger
|
| +** construction process.
|
| +*/
|
| +SQLITE_PRIVATE void sqlite3BeginTrigger(
|
| + Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
|
| + Token *pName1, /* The name of the trigger */
|
| + Token *pName2, /* The name of the trigger */
|
| + int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
|
| + int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
|
| + IdList *pColumns, /* column list if this is an UPDATE OF trigger */
|
| + SrcList *pTableName,/* The name of the table/view the trigger applies to */
|
| + Expr *pWhen, /* WHEN clause */
|
| + int isTemp, /* True if the TEMPORARY keyword is present */
|
| + int noErr /* Suppress errors if the trigger already exists */
|
| +){
|
| + Trigger *pTrigger = 0; /* The new trigger */
|
| + Table *pTab; /* Table that the trigger fires off of */
|
| + char *zName = 0; /* Name of the trigger */
|
| + sqlite3 *db = pParse->db; /* The database connection */
|
| + int iDb; /* The database to store the trigger in */
|
| + Token *pName; /* The unqualified db name */
|
| + DbFixer sFix; /* State vector for the DB fixer */
|
| + int iTabDb; /* Index of the database holding pTab */
|
| +
|
| + assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
|
| + assert( pName2!=0 );
|
| + assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
|
| + assert( op>0 && op<0xff );
|
| + if( isTemp ){
|
| + /* If TEMP was specified, then the trigger name may not be qualified. */
|
| + if( pName2->n>0 ){
|
| + sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
|
| + goto trigger_cleanup;
|
| + }
|
| + iDb = 1;
|
| + pName = pName1;
|
| + }else{
|
| + /* Figure out the db that the trigger will be created in */
|
| + iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
|
| + if( iDb<0 ){
|
| + goto trigger_cleanup;
|
| + }
|
| + }
|
| + if( !pTableName || db->mallocFailed ){
|
| + goto trigger_cleanup;
|
| + }
|
| +
|
| + /* A long-standing parser bug is that this syntax was allowed:
|
| + **
|
| + ** CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
|
| + ** ^^^^^^^^
|
| + **
|
| + ** To maintain backwards compatibility, ignore the database
|
| + ** name on pTableName if we are reparsing out of SQLITE_MASTER.
|
| + */
|
| + if( db->init.busy && iDb!=1 ){
|
| + sqlite3DbFree(db, pTableName->a[0].zDatabase);
|
| + pTableName->a[0].zDatabase = 0;
|
| + }
|
| +
|
| + /* If the trigger name was unqualified, and the table is a temp table,
|
| + ** then set iDb to 1 to create the trigger in the temporary database.
|
| + ** If sqlite3SrcListLookup() returns 0, indicating the table does not
|
| + ** exist, the error is caught by the block below.
|
| + */
|
| + pTab = sqlite3SrcListLookup(pParse, pTableName);
|
| + if( db->init.busy==0 && pName2->n==0 && pTab
|
| + && pTab->pSchema==db->aDb[1].pSchema ){
|
| + iDb = 1;
|
| + }
|
| +
|
| + /* Ensure the table name matches database name and that the table exists */
|
| + if( db->mallocFailed ) goto trigger_cleanup;
|
| + assert( pTableName->nSrc==1 );
|
| + sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
|
| + if( sqlite3FixSrcList(&sFix, pTableName) ){
|
| + goto trigger_cleanup;
|
| + }
|
| + pTab = sqlite3SrcListLookup(pParse, pTableName);
|
| + if( !pTab ){
|
| + /* The table does not exist. */
|
| + if( db->init.iDb==1 ){
|
| + /* Ticket #3810.
|
| + ** Normally, whenever a table is dropped, all associated triggers are
|
| + ** dropped too. But if a TEMP trigger is created on a non-TEMP table
|
| + ** and the table is dropped by a different database connection, the
|
| + ** trigger is not visible to the database connection that does the
|
| + ** drop so the trigger cannot be dropped. This results in an
|
| + ** "orphaned trigger" - a trigger whose associated table is missing.
|
| + */
|
| + db->init.orphanTrigger = 1;
|
| + }
|
| + goto trigger_cleanup;
|
| + }
|
| + if( IsVirtual(pTab) ){
|
| + sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
|
| + goto trigger_cleanup;
|
| + }
|
| +
|
| + /* Check that the trigger name is not reserved and that no trigger of the
|
| + ** specified name exists */
|
| + zName = sqlite3NameFromToken(db, pName);
|
| + if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
|
| + goto trigger_cleanup;
|
| + }
|
| + assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
|
| + if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
|
| + if( !noErr ){
|
| + sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
|
| + }else{
|
| + assert( !db->init.busy );
|
| + sqlite3CodeVerifySchema(pParse, iDb);
|
| + }
|
| + goto trigger_cleanup;
|
| + }
|
| +
|
| + /* Do not create a trigger on a system table */
|
| + if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
|
| + sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
|
| + goto trigger_cleanup;
|
| + }
|
| +
|
| + /* INSTEAD of triggers are only for views and views only support INSTEAD
|
| + ** of triggers.
|
| + */
|
| + if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
|
| + sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
|
| + (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
|
| + goto trigger_cleanup;
|
| + }
|
| + if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
|
| + sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
|
| + " trigger on table: %S", pTableName, 0);
|
| + goto trigger_cleanup;
|
| + }
|
| + iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
|
| +
|
| +#ifndef SQLITE_OMIT_AUTHORIZATION
|
| + {
|
| + int code = SQLITE_CREATE_TRIGGER;
|
| + const char *zDb = db->aDb[iTabDb].zName;
|
| + const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
|
| + if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
|
| + if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
|
| + goto trigger_cleanup;
|
| + }
|
| + if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
|
| + goto trigger_cleanup;
|
| + }
|
| + }
|
| +#endif
|
| +
|
| + /* INSTEAD OF triggers can only appear on views and BEFORE triggers
|
| + ** cannot appear on views. So we might as well translate every
|
| + ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
|
| + ** elsewhere.
|
| + */
|
| + if (tr_tm == TK_INSTEAD){
|
| + tr_tm = TK_BEFORE;
|
| + }
|
| +
|
| + /* Build the Trigger object */
|
| + pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
|
| + if( pTrigger==0 ) goto trigger_cleanup;
|
| + pTrigger->zName = zName;
|
| + zName = 0;
|
| + pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
|
| + pTrigger->pSchema = db->aDb[iDb].pSchema;
|
| + pTrigger->pTabSchema = pTab->pSchema;
|
| + pTrigger->op = (u8)op;
|
| + pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
|
| + pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
|
| + pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
|
| + assert( pParse->pNewTrigger==0 );
|
| + pParse->pNewTrigger = pTrigger;
|
| +
|
| +trigger_cleanup:
|
| + sqlite3DbFree(db, zName);
|
| + sqlite3SrcListDelete(db, pTableName);
|
| + sqlite3IdListDelete(db, pColumns);
|
| + sqlite3ExprDelete(db, pWhen);
|
| + if( !pParse->pNewTrigger ){
|
| + sqlite3DeleteTrigger(db, pTrigger);
|
| + }else{
|
| + assert( pParse->pNewTrigger==pTrigger );
|
| + }
|
| +}
|
| +
|
| +/*
|
| +** This routine is called after all of the trigger actions have been parsed
|
| +** in order to complete the process of building the trigger.
|
| +*/
|
| +SQLITE_PRIVATE void sqlite3FinishTrigger(
|
| + Parse *pParse, /* Parser context */
|
| + TriggerStep *pStepList, /* The triggered program */
|
| + Token *pAll /* Token that describes the complete CREATE TRIGGER */
|
| +){
|
| + Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */
|
| + char *zName; /* Name of trigger */
|
| + sqlite3 *db = pParse->db; /* The database */
|
| + DbFixer sFix; /* Fixer object */
|
| + int iDb; /* Database containing the trigger */
|
| + Token nameToken; /* Trigger name for error reporting */
|
| +
|
| + pParse->pNewTrigger = 0;
|
| + if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
|
| + zName = pTrig->zName;
|
| + iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
|
| + pTrig->step_list = pStepList;
|
| + while( pStepList ){
|
| + pStepList->pTrig = pTrig;
|
| + pStepList = pStepList->pNext;
|
| + }
|
| + nameToken.z = pTrig->zName;
|
| + nameToken.n = sqlite3Strlen30(nameToken.z);
|
| + sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
|
| + if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
|
| + || sqlite3FixExpr(&sFix, pTrig->pWhen)
|
| + ){
|
| + goto triggerfinish_cleanup;
|
| + }
|
| +
|
| + /* if we are not initializing,
|
| + ** build the sqlite_master entry
|
| + */
|
| + if( !db->init.busy ){
|
| + Vdbe *v;
|
| + char *z;
|
| +
|
| + /* Make an entry in the sqlite_master table */
|
| + v = sqlite3GetVdbe(pParse);
|
| + if( v==0 ) goto triggerfinish_cleanup;
|
| + sqlite3BeginWriteOperation(pParse, 0, iDb);
|
| + z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
|
| + sqlite3NestedParse(pParse,
|
| + "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
|
| + db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
|
| + pTrig->table, z);
|
| + sqlite3DbFree(db, z);
|
| + sqlite3ChangeCookie(pParse, iDb);
|
| + sqlite3VdbeAddParseSchemaOp(v, iDb,
|
| + sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
|
| + }
|
| +
|
| + if( db->init.busy ){
|
| + Trigger *pLink = pTrig;
|
| + Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
|
| + assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
|
| + pTrig = sqlite3HashInsert(pHash, zName, pTrig);
|
| + if( pTrig ){
|
| + db->mallocFailed = 1;
|
| + }else if( pLink->pSchema==pLink->pTabSchema ){
|
| + Table *pTab;
|
| + pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table);
|
| + assert( pTab!=0 );
|
| + pLink->pNext = pTab->pTrigger;
|
| + pTab->pTrigger = pLink;
|
| + }
|
| + }
|
| +
|
| +triggerfinish_cleanup:
|
| + sqlite3DeleteTrigger(db, pTrig);
|
| + assert( !pParse->pNewTrigger );
|
| + sqlite3DeleteTriggerStep(db, pStepList);
|
| +}
|
| +
|
| +/*
|
| +** Turn a SELECT statement (that the pSelect parameter points to) into
|
| +** a trigger step. Return a pointer to a TriggerStep structure.
|
| +**
|
| +** The parser calls this routine when it finds a SELECT statement in
|
| +** body of a TRIGGER.
|
| +*/
|
| +SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
|
| + TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
|
| + if( pTriggerStep==0 ) {
|
| + sqlite3SelectDelete(db, pSelect);
|
| + return 0;
|
| + }
|
| + pTriggerStep->op = TK_SELECT;
|
| + pTriggerStep->pSelect = pSelect;
|
| + pTriggerStep->orconf = OE_Default;
|
| + return pTriggerStep;
|
| +}
|
| +
|
| +/*
|
| +** Allocate space to hold a new trigger step. The allocated space
|
| +** holds both the TriggerStep object and the TriggerStep.target.z string.
|
| +**
|
| +** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
|
| +*/
|
| +static TriggerStep *triggerStepAllocate(
|
| + sqlite3 *db, /* Database connection */
|
| + u8 op, /* Trigger opcode */
|
| + Token *pName /* The target name */
|
| +){
|
| + TriggerStep *pTriggerStep;
|
| +
|
| + pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n + 1);
|
| + if( pTriggerStep ){
|
| + char *z = (char*)&pTriggerStep[1];
|
| + memcpy(z, pName->z, pName->n);
|
| + sqlite3Dequote(z);
|
| + pTriggerStep->zTarget = z;
|
| + pTriggerStep->op = op;
|
| + }
|
| + return pTriggerStep;
|
| +}
|
| +
|
| +/*
|
| +** Build a trigger step out of an INSERT statement. Return a pointer
|
| +** to the new trigger step.
|
| +**
|
| +** The parser calls this routine when it sees an INSERT inside the
|
| +** body of a trigger.
|
| +*/
|
| +SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
|
| + sqlite3 *db, /* The database connection */
|
| + Token *pTableName, /* Name of the table into which we insert */
|
| + IdList *pColumn, /* List of columns in pTableName to insert into */
|
| + Select *pSelect, /* A SELECT statement that supplies values */
|
| + u8 orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
|
| +){
|
| + TriggerStep *pTriggerStep;
|
| +
|
| + assert(pSelect != 0 || db->mallocFailed);
|
| +
|
| + pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
|
| + if( pTriggerStep ){
|
| + pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
|
| + pTriggerStep->pIdList = pColumn;
|
| + pTriggerStep->orconf = orconf;
|
| + }else{
|
| + sqlite3IdListDelete(db, pColumn);
|
| + }
|
| + sqlite3SelectDelete(db, pSelect);
|
| +
|
| + return pTriggerStep;
|
| +}
|
| +
|
| +/*
|
| +** Construct a trigger step that implements an UPDATE statement and return
|
| +** a pointer to that trigger step. The parser calls this routine when it
|
| +** sees an UPDATE statement inside the body of a CREATE TRIGGER.
|
| +*/
|
| +SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
|
| + sqlite3 *db, /* The database connection */
|
| + Token *pTableName, /* Name of the table to be updated */
|
| + ExprList *pEList, /* The SET clause: list of column and new values */
|
| + Expr *pWhere, /* The WHERE clause */
|
| + u8 orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
|
| +){
|
| + TriggerStep *pTriggerStep;
|
| +
|
| + pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
|
| + if( pTriggerStep ){
|
| + pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
|
| + pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
|
| + pTriggerStep->orconf = orconf;
|
| + }
|
| + sqlite3ExprListDelete(db, pEList);
|
| + sqlite3ExprDelete(db, pWhere);
|
| + return pTriggerStep;
|
| +}
|
| +
|
| +/*
|
| +** Construct a trigger step that implements a DELETE statement and return
|
| +** a pointer to that trigger step. The parser calls this routine when it
|
| +** sees a DELETE statement inside the body of a CREATE TRIGGER.
|
| +*/
|
| +SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
|
| + sqlite3 *db, /* Database connection */
|
| + Token *pTableName, /* The table from which rows are deleted */
|
| + Expr *pWhere /* The WHERE clause */
|
| +){
|
| + TriggerStep *pTriggerStep;
|
| +
|
| + pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
|
| + if( pTriggerStep ){
|
| + pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
|
| + pTriggerStep->orconf = OE_Default;
|
| + }
|
| + sqlite3ExprDelete(db, pWhere);
|
| + return pTriggerStep;
|
| +}
|
| +
|
| +/*
|
| +** Recursively delete a Trigger structure
|
| +*/
|
| +SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
|
| + if( pTrigger==0 ) return;
|
| + sqlite3DeleteTriggerStep(db, pTrigger->step_list);
|
| + sqlite3DbFree(db, pTrigger->zName);
|
| + sqlite3DbFree(db, pTrigger->table);
|
| + sqlite3ExprDelete(db, pTrigger->pWhen);
|
| + sqlite3IdListDelete(db, pTrigger->pColumns);
|
| + sqlite3DbFree(db, pTrigger);
|
| +}
|
| +
|
| +/*
|
| +** This function is called to drop a trigger from the database schema.
|
| +**
|
| +** This may be called directly from the parser and therefore identifies
|
| +** the trigger by name. The sqlite3DropTriggerPtr() routine does the
|
| +** same job as this routine except it takes a pointer to the trigger
|
| +** instead of the trigger name.
|
| +**/
|
| +SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
|
| + Trigger *pTrigger = 0;
|
| + int i;
|
| + const char *zDb;
|
| + const char *zName;
|
| + sqlite3 *db = pParse->db;
|
| +
|
| + if( db->mallocFailed ) goto drop_trigger_cleanup;
|
| + if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
|
| + goto drop_trigger_cleanup;
|
| + }
|
| +
|
| + assert( pName->nSrc==1 );
|
| + zDb = pName->a[0].zDatabase;
|
| + zName = pName->a[0].zName;
|
| + assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
|
| + for(i=OMIT_TEMPDB; i<db->nDb; i++){
|
| + int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
|
| + if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
|
| + assert( sqlite3SchemaMutexHeld(db, j, 0) );
|
| + pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName);
|
| + if( pTrigger ) break;
|
| + }
|
| + if( !pTrigger ){
|
| + if( !noErr ){
|
| + sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
|
| + }else{
|
| + sqlite3CodeVerifyNamedSchema(pParse, zDb);
|
| + }
|
| + pParse->checkSchema = 1;
|
| + goto drop_trigger_cleanup;
|
| + }
|
| + sqlite3DropTriggerPtr(pParse, pTrigger);
|
| +
|
| +drop_trigger_cleanup:
|
| + sqlite3SrcListDelete(db, pName);
|
| +}
|
| +
|
| +/*
|
| +** Return a pointer to the Table structure for the table that a trigger
|
| +** is set on.
|
| +*/
|
| +static Table *tableOfTrigger(Trigger *pTrigger){
|
| + return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table);
|
| +}
|
| +
|
| +
|
| +/*
|
| +** Drop a trigger given a pointer to that trigger.
|
| +*/
|
| +SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
|
| + Table *pTable;
|
| + Vdbe *v;
|
| + sqlite3 *db = pParse->db;
|
| + int iDb;
|
| +
|
| + iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
|
| + assert( iDb>=0 && iDb<db->nDb );
|
| + pTable = tableOfTrigger(pTrigger);
|
| + assert( pTable );
|
| + assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
|
| +#ifndef SQLITE_OMIT_AUTHORIZATION
|
| + {
|
| + int code = SQLITE_DROP_TRIGGER;
|
| + const char *zDb = db->aDb[iDb].zName;
|
| + const char *zTab = SCHEMA_TABLE(iDb);
|
| + if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
|
| + if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
|
| + sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
|
| + return;
|
| + }
|
| + }
|
| +#endif
|
| +
|
| + /* Generate code to destroy the database record of the trigger.
|
| + */
|
| + assert( pTable!=0 );
|
| + if( (v = sqlite3GetVdbe(pParse))!=0 ){
|
| + sqlite3NestedParse(pParse,
|
| + "DELETE FROM %Q.%s WHERE name=%Q AND type='trigger'",
|
| + db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pTrigger->zName
|
| + );
|
| + sqlite3ChangeCookie(pParse, iDb);
|
| + sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
|
| + }
|
| +}
|
| +
|
| +/*
|
| +** Remove a trigger from the hash tables of the sqlite* pointer.
|
| +*/
|
| +SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
|
| + Trigger *pTrigger;
|
| + Hash *pHash;
|
| +
|
| + assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
|
| + pHash = &(db->aDb[iDb].pSchema->trigHash);
|
| + pTrigger = sqlite3HashInsert(pHash, zName, 0);
|
| + if( ALWAYS(pTrigger) ){
|
| + if( pTrigger->pSchema==pTrigger->pTabSchema ){
|
| + Table *pTab = tableOfTrigger(pTrigger);
|
| + Trigger **pp;
|
| + for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
|
| + *pp = (*pp)->pNext;
|
| + }
|
| + sqlite3DeleteTrigger(db, pTrigger);
|
| + db->flags |= SQLITE_InternChanges;
|
| + }
|
| +}
|
| +
|
| +/*
|
| +** pEList is the SET clause of an UPDATE statement. Each entry
|
| +** in pEList is of the format <id>=<expr>. If any of the entries
|
| +** in pEList have an <id> which matches an identifier in pIdList,
|
| +** then return TRUE. If pIdList==NULL, then it is considered a
|
| +** wildcard that matches anything. Likewise if pEList==NULL then
|
| +** it matches anything so always return true. Return false only
|
| +** if there is no match.
|
| +*/
|
| +static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
|
| + int e;
|
| + if( pIdList==0 || NEVER(pEList==0) ) return 1;
|
| + for(e=0; e<pEList->nExpr; e++){
|
| + if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
|
| + }
|
| + return 0;
|
| +}
|
| +
|
| +/*
|
| +** Return a list of all triggers on table pTab if there exists at least
|
| +** one trigger that must be fired when an operation of type 'op' is
|
| +** performed on the table, and, if that operation is an UPDATE, if at
|
| +** least one of the columns in pChanges is being modified.
|
| +*/
|
| +SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
|
| + Parse *pParse, /* Parse context */
|
| + Table *pTab, /* The table the contains the triggers */
|
| + int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
|
| + ExprList *pChanges, /* Columns that change in an UPDATE statement */
|
| + int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
|
| +){
|
| + int mask = 0;
|
| + Trigger *pList = 0;
|
| + Trigger *p;
|
| +
|
| + if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
|
| + pList = sqlite3TriggerList(pParse, pTab);
|
| + }
|
| + assert( pList==0 || IsVirtual(pTab)==0 );
|
| + for(p=pList; p; p=p->pNext){
|
| + if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
|
| + mask |= p->tr_tm;
|
| + }
|
| + }
|
| + if( pMask ){
|
| + *pMask = mask;
|
| + }
|
| + return (mask ? pList : 0);
|
| +}
|
| +
|
| +/*
|
| +** Convert the pStep->zTarget string into a SrcList and return a pointer
|
| +** to that SrcList.
|
| +**
|
| +** This routine adds a specific database name, if needed, to the target when
|
| +** forming the SrcList. This prevents a trigger in one database from
|
| +** referring to a target in another database. An exception is when the
|
| +** trigger is in TEMP in which case it can refer to any other database it
|
| +** wants.
|
| +*/
|
| +static SrcList *targetSrcList(
|
| + Parse *pParse, /* The parsing context */
|
| + TriggerStep *pStep /* The trigger containing the target token */
|
| +){
|
| + sqlite3 *db = pParse->db;
|
| + int iDb; /* Index of the database to use */
|
| + SrcList *pSrc; /* SrcList to be returned */
|
| +
|
| + pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
|
| + if( pSrc ){
|
| + assert( pSrc->nSrc>0 );
|
| + pSrc->a[pSrc->nSrc-1].zName = sqlite3DbStrDup(db, pStep->zTarget);
|
| + iDb = sqlite3SchemaToIndex(db, pStep->pTrig->pSchema);
|
| + if( iDb==0 || iDb>=2 ){
|
| + assert( iDb<db->nDb );
|
| + pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
|
| + }
|
| + }
|
| + return pSrc;
|
| +}
|
| +
|
| +/*
|
| +** Generate VDBE code for the statements inside the body of a single
|
| +** trigger.
|
| +*/
|
| +static int codeTriggerProgram(
|
| + Parse *pParse, /* The parser context */
|
| + TriggerStep *pStepList, /* List of statements inside the trigger body */
|
| + int orconf /* Conflict algorithm. (OE_Abort, etc) */
|
| +){
|
| + TriggerStep *pStep;
|
| + Vdbe *v = pParse->pVdbe;
|
| + sqlite3 *db = pParse->db;
|
| +
|
| + assert( pParse->pTriggerTab && pParse->pToplevel );
|
| + assert( pStepList );
|
| + assert( v!=0 );
|
| + for(pStep=pStepList; pStep; pStep=pStep->pNext){
|
| + /* Figure out the ON CONFLICT policy that will be used for this step
|
| + ** of the trigger program. If the statement that caused this trigger
|
| + ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
|
| + ** the ON CONFLICT policy that was specified as part of the trigger
|
| + ** step statement. Example:
|
| + **
|
| + ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
|
| + ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
|
| + ** END;
|
| + **
|
| + ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy
|
| + ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy
|
| + */
|
| + pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
|
| + assert( pParse->okConstFactor==0 );
|
| +
|
| + switch( pStep->op ){
|
| + case TK_UPDATE: {
|
| + sqlite3Update(pParse,
|
| + targetSrcList(pParse, pStep),
|
| + sqlite3ExprListDup(db, pStep->pExprList, 0),
|
| + sqlite3ExprDup(db, pStep->pWhere, 0),
|
| + pParse->eOrconf
|
| + );
|
| + break;
|
| + }
|
| + case TK_INSERT: {
|
| + sqlite3Insert(pParse,
|
| + targetSrcList(pParse, pStep),
|
| + sqlite3SelectDup(db, pStep->pSelect, 0),
|
| + sqlite3IdListDup(db, pStep->pIdList),
|
| + pParse->eOrconf
|
| + );
|
| + break;
|
| + }
|
| + case TK_DELETE: {
|
| + sqlite3DeleteFrom(pParse,
|
| + targetSrcList(pParse, pStep),
|
| + sqlite3ExprDup(db, pStep->pWhere, 0)
|
| + );
|
| + break;
|
| + }
|
| + default: assert( pStep->op==TK_SELECT ); {
|
| + SelectDest sDest;
|
| + Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
|
| + sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
|
| + sqlite3Select(pParse, pSelect, &sDest);
|
| + sqlite3SelectDelete(db, pSelect);
|
| + break;
|
| + }
|
| + }
|
| + if( pStep->op!=TK_SELECT ){
|
| + sqlite3VdbeAddOp0(v, OP_ResetCount);
|
| + }
|
| + }
|
| +
|
| + return 0;
|
| +}
|
| +
|
| +#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
|
| +/*
|
| +** This function is used to add VdbeComment() annotations to a VDBE
|
| +** program. It is not used in production code, only for debugging.
|
| +*/
|
| +static const char *onErrorText(int onError){
|
| + switch( onError ){
|
| + case OE_Abort: return "abort";
|
| + case OE_Rollback: return "rollback";
|
| + case OE_Fail: return "fail";
|
| + case OE_Replace: return "replace";
|
| + case OE_Ignore: return "ignore";
|
| + case OE_Default: return "default";
|
| + }
|
| + return "n/a";
|
| +}
|
| +#endif
|
| +
|
| +/*
|
| +** Parse context structure pFrom has just been used to create a sub-vdbe
|
| +** (trigger program). If an error has occurred, transfer error information
|
| +** from pFrom to pTo.
|
| +*/
|
| +static void transferParseError(Parse *pTo, Parse *pFrom){
|
| + assert( pFrom->zErrMsg==0 || pFrom->nErr );
|
| + assert( pTo->zErrMsg==0 || pTo->nErr );
|
| + if( pTo->nErr==0 ){
|
| + pTo->zErrMsg = pFrom->zErrMsg;
|
| + pTo->nErr = pFrom->nErr;
|
| + pTo->rc = pFrom->rc;
|
| + }else{
|
| + sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
|
| + }
|
| +}
|
| +
|
| +/*
|
| +** Create and populate a new TriggerPrg object with a sub-program
|
| +** implementing trigger pTrigger with ON CONFLICT policy orconf.
|
| +*/
|
| +static TriggerPrg *codeRowTrigger(
|
| + Parse *pParse, /* Current parse context */
|
| + Trigger *pTrigger, /* Trigger to code */
|
| + Table *pTab, /* The table pTrigger is attached to */
|
| + int orconf /* ON CONFLICT policy to code trigger program with */
|
| +){
|
| + Parse *pTop = sqlite3ParseToplevel(pParse);
|
| + sqlite3 *db = pParse->db; /* Database handle */
|
| + TriggerPrg *pPrg; /* Value to return */
|
| + Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */
|
| + Vdbe *v; /* Temporary VM */
|
| + NameContext sNC; /* Name context for sub-vdbe */
|
| + SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */
|
| + Parse *pSubParse; /* Parse context for sub-vdbe */
|
| + int iEndTrigger = 0; /* Label to jump to if WHEN is false */
|
| +
|
| + assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
|
| + assert( pTop->pVdbe );
|
| +
|
| + /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
|
| + ** are freed if an error occurs, link them into the Parse.pTriggerPrg
|
| + ** list of the top-level Parse object sooner rather than later. */
|
| + pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
|
| + if( !pPrg ) return 0;
|
| + pPrg->pNext = pTop->pTriggerPrg;
|
| + pTop->pTriggerPrg = pPrg;
|
| + pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
|
| + if( !pProgram ) return 0;
|
| + sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
|
| + pPrg->pTrigger = pTrigger;
|
| + pPrg->orconf = orconf;
|
| + pPrg->aColmask[0] = 0xffffffff;
|
| + pPrg->aColmask[1] = 0xffffffff;
|
| +
|
| + /* Allocate and populate a new Parse context to use for coding the
|
| + ** trigger sub-program. */
|
| + pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
|
| + if( !pSubParse ) return 0;
|
| + memset(&sNC, 0, sizeof(sNC));
|
| + sNC.pParse = pSubParse;
|
| + pSubParse->db = db;
|
| + pSubParse->pTriggerTab = pTab;
|
| + pSubParse->pToplevel = pTop;
|
| + pSubParse->zAuthContext = pTrigger->zName;
|
| + pSubParse->eTriggerOp = pTrigger->op;
|
| + pSubParse->nQueryLoop = pParse->nQueryLoop;
|
| +
|
| + v = sqlite3GetVdbe(pSubParse);
|
| + if( v ){
|
| + VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
|
| + pTrigger->zName, onErrorText(orconf),
|
| + (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
|
| + (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
|
| + (pTrigger->op==TK_INSERT ? "INSERT" : ""),
|
| + (pTrigger->op==TK_DELETE ? "DELETE" : ""),
|
| + pTab->zName
|
| + ));
|
| +#ifndef SQLITE_OMIT_TRACE
|
| + sqlite3VdbeChangeP4(v, -1,
|
| + sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
|
| + );
|
| +#endif
|
| +
|
| + /* If one was specified, code the WHEN clause. If it evaluates to false
|
| + ** (or NULL) the sub-vdbe is immediately halted by jumping to the
|
| + ** OP_Halt inserted at the end of the program. */
|
| + if( pTrigger->pWhen ){
|
| + pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
|
| + if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
|
| + && db->mallocFailed==0
|
| + ){
|
| + iEndTrigger = sqlite3VdbeMakeLabel(v);
|
| + sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
|
| + }
|
| + sqlite3ExprDelete(db, pWhen);
|
| + }
|
| +
|
| + /* Code the trigger program into the sub-vdbe. */
|
| + codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
|
| +
|
| + /* Insert an OP_Halt at the end of the sub-program. */
|
| + if( iEndTrigger ){
|
| + sqlite3VdbeResolveLabel(v, iEndTrigger);
|
| + }
|
| + sqlite3VdbeAddOp0(v, OP_Halt);
|
| + VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
|
| +
|
| + transferParseError(pParse, pSubParse);
|
| + if( db->mallocFailed==0 ){
|
| + pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
|
| + }
|
| + pProgram->nMem = pSubParse->nMem;
|
| + pProgram->nCsr = pSubParse->nTab;
|
| + pProgram->nOnce = pSubParse->nOnce;
|
| + pProgram->token = (void *)pTrigger;
|
| + pPrg->aColmask[0] = pSubParse->oldmask;
|
| + pPrg->aColmask[1] = pSubParse->newmask;
|
| + sqlite3VdbeDelete(v);
|
| + }
|
| +
|
| + assert( !pSubParse->pAinc && !pSubParse->pZombieTab );
|
| + assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
|
| + sqlite3ParserReset(pSubParse);
|
| + sqlite3StackFree(db, pSubParse);
|
| +
|
| + return pPrg;
|
| +}
|
| +
|
| +/*
|
| +** Return a pointer to a TriggerPrg object containing the sub-program for
|
| +** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
|
| +** TriggerPrg object exists, a new object is allocated and populated before
|
| +** being returned.
|
| +*/
|
| +static TriggerPrg *getRowTrigger(
|
| + Parse *pParse, /* Current parse context */
|
| + Trigger *pTrigger, /* Trigger to code */
|
| + Table *pTab, /* The table trigger pTrigger is attached to */
|
| + int orconf /* ON CONFLICT algorithm. */
|
| +){
|
| + Parse *pRoot = sqlite3ParseToplevel(pParse);
|
| + TriggerPrg *pPrg;
|
| +
|
| + assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
|
| +
|
| + /* It may be that this trigger has already been coded (or is in the
|
| + ** process of being coded). If this is the case, then an entry with
|
| + ** a matching TriggerPrg.pTrigger field will be present somewhere
|
| + ** in the Parse.pTriggerPrg list. Search for such an entry. */
|
| + for(pPrg=pRoot->pTriggerPrg;
|
| + pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
|
| + pPrg=pPrg->pNext
|
| + );
|
| +
|
| + /* If an existing TriggerPrg could not be located, create a new one. */
|
| + if( !pPrg ){
|
| + pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
|
| + }
|
| +
|
| + return pPrg;
|
| +}
|
| +
|
| +/*
|
| +** Generate code for the trigger program associated with trigger p on
|
| +** table pTab. The reg, orconf and ignoreJump parameters passed to this
|
| +** function are the same as those described in the header function for
|
| +** sqlite3CodeRowTrigger()
|
| +*/
|
| +SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
|
| + Parse *pParse, /* Parse context */
|
| + Trigger *p, /* Trigger to code */
|
| + Table *pTab, /* The table to code triggers from */
|
| + int reg, /* Reg array containing OLD.* and NEW.* values */
|
| + int orconf, /* ON CONFLICT policy */
|
| + int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
|
| +){
|
| + Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
|
| + TriggerPrg *pPrg;
|
| + pPrg = getRowTrigger(pParse, p, pTab, orconf);
|
| + assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
|
| +
|
| + /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
|
| + ** is a pointer to the sub-vdbe containing the trigger program. */
|
| + if( pPrg ){
|
| + int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
|
| +
|
| + sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
|
| + sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
|
| + VdbeComment(
|
| + (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
|
| +
|
| + /* Set the P5 operand of the OP_Program instruction to non-zero if
|
| + ** recursive invocation of this trigger program is disallowed. Recursive
|
| + ** invocation is disallowed if (a) the sub-program is really a trigger,
|
| + ** not a foreign key action, and (b) the flag to enable recursive triggers
|
| + ** is clear. */
|
| + sqlite3VdbeChangeP5(v, (u8)bRecursive);
|
| + }
|
| +}
|
| +
|
| +/*
|
| +** This is called to code the required FOR EACH ROW triggers for an operation
|
| +** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
|
| +** is given by the op parameter. The tr_tm parameter determines whether the
|
| +** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
|
| +** parameter pChanges is passed the list of columns being modified.
|
| +**
|
| +** If there are no triggers that fire at the specified time for the specified
|
| +** operation on pTab, this function is a no-op.
|
| +**
|
| +** The reg argument is the address of the first in an array of registers
|
| +** that contain the values substituted for the new.* and old.* references
|
| +** in the trigger program. If N is the number of columns in table pTab
|
| +** (a copy of pTab->nCol), then registers are populated as follows:
|
| +**
|
| +** Register Contains
|
| +** ------------------------------------------------------
|
| +** reg+0 OLD.rowid
|
| +** reg+1 OLD.* value of left-most column of pTab
|
| +** ... ...
|
| +** reg+N OLD.* value of right-most column of pTab
|
| +** reg+N+1 NEW.rowid
|
| +** reg+N+2 OLD.* value of left-most column of pTab
|
| +** ... ...
|
| +** reg+N+N+1 NEW.* value of right-most column of pTab
|
| +**
|
| +** For ON DELETE triggers, the registers containing the NEW.* values will
|
| +** never be accessed by the trigger program, so they are not allocated or
|
| +** populated by the caller (there is no data to populate them with anyway).
|
| +** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
|
| +** are never accessed, and so are not allocated by the caller. So, for an
|
| +** ON INSERT trigger, the value passed to this function as parameter reg
|
| +** is not a readable register, although registers (reg+N) through
|
| +** (reg+N+N+1) are.
|
| +**
|
| +** Parameter orconf is the default conflict resolution algorithm for the
|
| +** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
|
| +** is the instruction that control should jump to if a trigger program
|
| +** raises an IGNORE exception.
|
| +*/
|
| +SQLITE_PRIVATE void sqlite3CodeRowTrigger(
|
| + Parse *pParse, /* Parse context */
|
| + Trigger *pTrigger, /* List of triggers on table pTab */
|
| + int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
|
| + ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
|
| + int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
|
| + Table *pTab, /* The table to code triggers from */
|
| + int reg, /* The first in an array of registers (see above) */
|
| + int orconf, /* ON CONFLICT policy */
|
| + int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
|
| +){
|
| + Trigger *p; /* Used to iterate through pTrigger list */
|
| +
|
| + assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
|
| + assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
|
| + assert( (op==TK_UPDATE)==(pChanges!=0) );
|
| +
|
| + for(p=pTrigger; p; p=p->pNext){
|
| +
|
| + /* Sanity checking: The schema for the trigger and for the table are
|
| + ** always defined. The trigger must be in the same schema as the table
|
| + ** or else it must be a TEMP trigger. */
|
| + assert( p->pSchema!=0 );
|
| + assert( p->pTabSchema!=0 );
|
| + assert( p->pSchema==p->pTabSchema
|
| + || p->pSchema==pParse->db->aDb[1].pSchema );
|
| +
|
| + /* Determine whether we should code this trigger */
|
| + if( p->op==op
|
| + && p->tr_tm==tr_tm
|
| + && checkColumnOverlap(p->pColumns, pChanges)
|
| + ){
|
| + sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
|
| + }
|
| + }
|
| +}
|
| +
|
| +/*
|
| +** Triggers may access values stored in the old.* or new.* pseudo-table.
|
| +** This function returns a 32-bit bitmask indicating which columns of the
|
| +** old.* or new.* tables actually are used by triggers. This information
|
| +** may be used by the caller, for example, to avoid having to load the entire
|
| +** old.* record into memory when executing an UPDATE or DELETE command.
|
| +**
|
| +** Bit 0 of the returned mask is set if the left-most column of the
|
| +** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
|
| +** the second leftmost column value is required, and so on. If there
|
| +** are more than 32 columns in the table, and at least one of the columns
|
| +** with an index greater than 32 may be accessed, 0xffffffff is returned.
|
| +**
|
| +** It is not possible to determine if the old.rowid or new.rowid column is
|
| +** accessed by triggers. The caller must always assume that it is.
|
| +**
|
| +** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
|
| +** applies to the old.* table. If 1, the new.* table.
|
| +**
|
| +** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
|
| +** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
|
| +** included in the returned mask if the TRIGGER_BEFORE bit is set in the
|
| +** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
|
| +** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
|
| +*/
|
| +SQLITE_PRIVATE u32 sqlite3TriggerColmask(
|
| + Parse *pParse, /* Parse context */
|
| + Trigger *pTrigger, /* List of triggers on table pTab */
|
| + ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
|
| + int isNew, /* 1 for new.* ref mask, 0 for old.* ref mask */
|
| + int tr_tm, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
|
| + Table *pTab, /* The table to code triggers from */
|
| + int orconf /* Default ON CONFLICT policy for trigger steps */
|
| +){
|
| + const int op = pChanges ? TK_UPDATE : TK_DELETE;
|
| + u32 mask = 0;
|
| + Trigger *p;
|
| +
|
| + assert( isNew==1 || isNew==0 );
|
| + for(p=pTrigger; p; p=p->pNext){
|
| + if( p->op==op && (tr_tm&p->tr_tm)
|
| + && checkColumnOverlap(p->pColumns,pChanges)
|
| + ){
|
| + TriggerPrg *pPrg;
|
| + pPrg = getRowTrigger(pParse, p, pTab, orconf);
|
| + if( pPrg ){
|
| + mask |= pPrg->aColmask[isNew];
|
| + }
|
| + }
|
| + }
|
| +
|
| + return mask;
|
| +}
|
| +
|
| +#endif /* !defined(SQLITE_OMIT_TRIGGER) */
|
| +
|
| +/************** End of trigger.c *********************************************/
|
| +/************** Begin file update.c ******************************************/
|
| +/*
|
| +** 2001 September 15
|
| +**
|
| +** The author disclaims copyright to this source code. In place of
|
| +** a legal notice, here is a blessing:
|
| +**
|
| +** May you do good and not evil.
|
| +** May you find forgiveness for yourself and forgive others.
|
| +** May you share freely, never taking more than you give.
|
| +**
|
| +*************************************************************************
|
| +** This file contains C code routines that are called by the parser
|
| +** to handle UPDATE statements.
|
| +*/
|
| +/* #include "sqliteInt.h" */
|
| +
|
| +#ifndef SQLITE_OMIT_VIRTUALTABLE
|
| +/* Forward declaration */
|
| +static void updateVirtualTable(
|
| + Parse *pParse, /* The parsing context */
|
| + SrcList *pSrc, /* The virtual table to be modified */
|
| + Table *pTab, /* The virtual table */
|
| + ExprList *pChanges, /* The columns to change in the UPDATE statement */
|
| + Expr *pRowidExpr, /* Expression used to recompute the rowid */
|
| + int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
|
| + Expr *pWhere, /* WHERE clause of the UPDATE statement */
|
| + int onError /* ON CONFLICT strategy */
|
| +);
|
| +#endif /* SQLITE_OMIT_VIRTUALTABLE */
|
| +
|
| +/*
|
| +** The most recently coded instruction was an OP_Column to retrieve the
|
| +** i-th column of table pTab. This routine sets the P4 parameter of the
|
| +** OP_Column to the default value, if any.
|
| +**
|
| +** The default value of a column is specified by a DEFAULT clause in the
|
| +** column definition. This was either supplied by the user when the table
|
| +** was created, or added later to the table definition by an ALTER TABLE
|
| +** command. If the latter, then the row-records in the table btree on disk
|
| +** may not contain a value for the column and the default value, taken
|
| +** from the P4 parameter of the OP_Column instruction, is returned instead.
|
| +** If the former, then all row-records are guaranteed to include a value
|
| +** for the column and the P4 value is not required.
|
| +**
|
| +** Column definitions created by an ALTER TABLE command may only have
|
| +** literal default values specified: a number, null or a string. (If a more
|
| +** complicated default expression value was provided, it is evaluated
|
| +** when the ALTER TABLE is executed and one of the literal values written
|
| +** into the sqlite_master table.)
|
| +**
|
| +** Therefore, the P4 parameter is only required if the default value for
|
| +** the column is a literal number, string or null. The sqlite3ValueFromExpr()
|
| +** function is capable of transforming these types of expressions into
|
| +** sqlite3_value objects.
|
| +**
|
| +** If parameter iReg is not negative, code an OP_RealAffinity instruction
|
| +** on register iReg. This is used when an equivalent integer value is
|
| +** stored in place of an 8-byte floating point value in order to save
|
| +** space.
|
| +*/
|
| +SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
|
| + assert( pTab!=0 );
|
| + if( !pTab->pSelect ){
|
| + sqlite3_value *pValue = 0;
|
| + u8 enc = ENC(sqlite3VdbeDb(v));
|
| + Column *pCol = &pTab->aCol[i];
|
| + VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
|
| + assert( i<pTab->nCol );
|
| + sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
|
| + pCol->affinity, &pValue);
|
| + if( pValue ){
|
| + sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
|
| + }
|
| +#ifndef SQLITE_OMIT_FLOATING_POINT
|
| + if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
|
| + sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
|
| + }
|
| +#endif
|
| + }
|
| +}
|
| +
|
| +/*
|
| +** Process an UPDATE statement.
|
| +**
|
| +** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
|
| +** \_______/ \________/ \______/ \________________/
|
| +* onError pTabList pChanges pWhere
|
| +*/
|
| +SQLITE_PRIVATE void sqlite3Update(
|
| + Parse *pParse, /* The parser context */
|
| + SrcList *pTabList, /* The table in which we should change things */
|
| + ExprList *pChanges, /* Things to be changed */
|
| + Expr *pWhere, /* The WHERE clause. May be null */
|
| + int onError /* How to handle constraint errors */
|
| +){
|
| + int i, j; /* Loop counters */
|
| + Table *pTab; /* The table to be updated */
|
| + int addrTop = 0; /* VDBE instruction address of the start of the loop */
|
| + WhereInfo *pWInfo; /* Information about the WHERE clause */
|
| + Vdbe *v; /* The virtual database engine */
|
| + Index *pIdx; /* For looping over indices */
|
| + Index *pPk; /* The PRIMARY KEY index for WITHOUT ROWID tables */
|
| + int nIdx; /* Number of indices that need updating */
|
| + int iBaseCur; /* Base cursor number */
|
| + int iDataCur; /* Cursor for the canonical data btree */
|
| + int iIdxCur; /* Cursor for the first index */
|
| + sqlite3 *db; /* The database structure */
|
| + int *aRegIdx = 0; /* One register assigned to each index to be updated */
|
| + int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
|
| + ** an expression for the i-th column of the table.
|
| + ** aXRef[i]==-1 if the i-th column is not changed. */
|
| + u8 *aToOpen; /* 1 for tables and indices to be opened */
|
| + u8 chngPk; /* PRIMARY KEY changed in a WITHOUT ROWID table */
|
| + u8 chngRowid; /* Rowid changed in a normal table */
|
| + u8 chngKey; /* Either chngPk or chngRowid */
|
| + Expr *pRowidExpr = 0; /* Expression defining the new record number */
|
| + AuthContext sContext; /* The authorization context */
|
| + NameContext sNC; /* The name-context to resolve expressions in */
|
| + int iDb; /* Database containing the table being updated */
|
| + int okOnePass; /* True for one-pass algorithm without the FIFO */
|
| + int hasFK; /* True if foreign key processing is required */
|
| + int labelBreak; /* Jump here to break out of UPDATE loop */
|
| + int labelContinue; /* Jump here to continue next step of UPDATE loop */
|
| +
|
| +#ifndef SQLITE_OMIT_TRIGGER
|
| + int isView; /* True when updating a view (INSTEAD OF trigger) */
|
| + Trigger *pTrigger; /* List of triggers on pTab, if required */
|
| + int tmask; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
|
| +#endif
|
| + int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */
|
| + int iEph = 0; /* Ephemeral table holding all primary key values */
|
| + int nKey = 0; /* Number of elements in regKey for WITHOUT ROWID */
|
| + int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
|
| +
|
| + /* Register Allocations */
|
| + int regRowCount = 0; /* A count of rows changed */
|
| + int regOldRowid = 0; /* The old rowid */
|
| + int regNewRowid = 0; /* The new rowid */
|
| + int regNew = 0; /* Content of the NEW.* table in triggers */
|
| + int regOld = 0; /* Content of OLD.* table in triggers */
|
| + int regRowSet = 0; /* Rowset of rows to be updated */
|
| + int regKey = 0; /* composite PRIMARY KEY value */
|
| +
|
| + memset(&sContext, 0, sizeof(sContext));
|
| + db = pParse->db;
|
| + if( pParse->nErr || db->mallocFailed ){
|
| + goto update_cleanup;
|
| + }
|
| + assert( pTabList->nSrc==1 );
|
| +
|
| + /* Locate the table which we want to update.
|
| + */
|
| + pTab = sqlite3SrcListLookup(pParse, pTabList);
|
| + if( pTab==0 ) goto update_cleanup;
|
| + iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
|
| +
|
| + /* Figure out if we have any triggers and if the table being
|
| + ** updated is a view.
|
| + */
|
| +#ifndef SQLITE_OMIT_TRIGGER
|
| + pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
|
| + isView = pTab->pSelect!=0;
|
| + assert( pTrigger || tmask==0 );
|
| +#else
|
| +# define pTrigger 0
|
| +# define isView 0
|
| +# define tmask 0
|
| +#endif
|
| +#ifdef SQLITE_OMIT_VIEW
|
| +# undef isView
|
| +# define isView 0
|
| +#endif
|
| +
|
| + if( sqlite3ViewGetColumnNames(pParse, pTab) ){
|
| + goto update_cleanup;
|
| + }
|
| + if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
|
| + goto update_cleanup;
|
| + }
|
| +
|
| + /* Allocate a cursors for the main database table and for all indices.
|
| + ** The index cursors might not be used, but if they are used they
|
| + ** need to occur right after the database cursor. So go ahead and
|
| + ** allocate enough space, just in case.
|
| + */
|
| + pTabList->a[0].iCursor = iBaseCur = iDataCur = pParse->nTab++;
|
| + iIdxCur = iDataCur+1;
|
| + pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
|
| + for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
|
| + if( IsPrimaryKeyIndex(pIdx) && pPk!=0 ){
|
| + iDataCur = pParse->nTab;
|
| + pTabList->a[0].iCursor = iDataCur;
|
| + }
|
| + pParse->nTab++;
|
| + }
|
| +
|
| + /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].
|
| + ** Initialize aXRef[] and aToOpen[] to their default values.
|
| + */
|
| + aXRef = sqlite3DbMallocRaw(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 );
|
| + if( aXRef==0 ) goto update_cleanup;
|
| + aRegIdx = aXRef+pTab->nCol;
|
| + aToOpen = (u8*)(aRegIdx+nIdx);
|
| + memset(aToOpen, 1, nIdx+1);
|
| + aToOpen[nIdx+1] = 0;
|
| + for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
|
| +
|
| + /* Initialize the name-context */
|
| + memset(&sNC, 0, sizeof(sNC));
|
| + sNC.pParse = pParse;
|
| + sNC.pSrcList = pTabList;
|
| +
|
| + /* Resolve the column names in all the expressions of the
|
| + ** of the UPDATE statement. Also find the column index
|
| + ** for each column to be updated in the pChanges array. For each
|
| + ** column to be updated, make sure we have authorization to change
|
| + ** that column.
|
| + */
|
| + chngRowid = chngPk = 0;
|
| + for(i=0; i<pChanges->nExpr; i++){
|
| + if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
|
| + goto update_cleanup;
|
| + }
|
| + for(j=0; j<pTab->nCol; j++){
|
| + if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
|
| + if( j==pTab->iPKey ){
|
| + chngRowid = 1;
|
| + pRowidExpr = pChanges->a[i].pExpr;
|
| + }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
|
| + chngPk = 1;
|
| + }
|
| + aXRef[j] = i;
|
| + break;
|
| + }
|
| + }
|
| + if( j>=pTab->nCol ){
|
| + if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){
|
| + j = -1;
|
| + chngRowid = 1;
|
| + pRowidExpr = pChanges->a[i].pExpr;
|
| + }else{
|
| + sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
|
| + pParse->checkSchema = 1;
|
| + goto update_cleanup;
|
| + }
|
| + }
|
| +#ifndef SQLITE_OMIT_AUTHORIZATION
|
| + {
|
| + int rc;
|
| + rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
|
| + j<0 ? "ROWID" : pTab->aCol[j].zName,
|
| + db->aDb[iDb].zName);
|
| + if( rc==SQLITE_DENY ){
|
| + goto update_cleanup;
|
| + }else if( rc==SQLITE_IGNORE ){
|
| + aXRef[j] = -1;
|
| + }
|
| + }
|
| +#endif
|
| + }
|
| + assert( (chngRowid & chngPk)==0 );
|
| + assert( chngRowid==0 || chngRowid==1 );
|
| + assert( chngPk==0 || chngPk==1 );
|
| + chngKey = chngRowid + chngPk;
|
| +
|
| + /* The SET expressions are not actually used inside the WHERE loop.
|
| + ** So reset the colUsed mask. Unless this is a virtual table. In that
|
| + ** case, set all bits of the colUsed mask (to ensure that the virtual
|
| + ** table implementation makes all columns available).
|
| + */
|
| + pTabList->a[0].colUsed = IsVirtual(pTab) ? (Bitmask)-1 : 0;
|
| +
|
| + hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
|
| +
|
| + /* There is one entry in the aRegIdx[] array for each index on the table
|
| + ** being updated. Fill in aRegIdx[] with a register number that will hold
|
| + ** the key for accessing each index.
|
| + **
|
| + ** FIXME: Be smarter about omitting indexes that use expressions.
|
| + */
|
| + for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
|
| + int reg;
|
| + if( chngKey || hasFK || pIdx->pPartIdxWhere || pIdx==pPk ){
|
| + reg = ++pParse->nMem;
|
| + }else{
|
| + reg = 0;
|
| + for(i=0; i<pIdx->nKeyCol; i++){
|
| + i16 iIdxCol = pIdx->aiColumn[i];
|
| + if( iIdxCol<0 || aXRef[iIdxCol]>=0 ){
|
| + reg = ++pParse->nMem;
|
| + break;
|
| + }
|
| + }
|
| + }
|
| + if( reg==0 ) aToOpen[j+1] = 0;
|
| + aRegIdx[j] = reg;
|
| + }
|
| +
|
| + /* Begin generating code. */
|
| + v = sqlite3GetVdbe(pParse);
|
| + if( v==0 ) goto update_cleanup;
|
| + if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
|
| + sqlite3BeginWriteOperation(pParse, 1, iDb);
|
| +
|
| + /* Allocate required registers. */
|
| + if( !IsVirtual(pTab) ){
|
| + regRowSet = ++pParse->nMem;
|
| + regOldRowid = regNewRowid = ++pParse->nMem;
|
| + if( chngPk || pTrigger || hasFK ){
|
| + regOld = pParse->nMem + 1;
|
| + pParse->nMem += pTab->nCol;
|
| + }
|
| + if( chngKey || pTrigger || hasFK ){
|
| + regNewRowid = ++pParse->nMem;
|
| + }
|
| + regNew = pParse->nMem + 1;
|
| + pParse->nMem += pTab->nCol;
|
| + }
|
| +
|
| + /* Start the view context. */
|
| + if( isView ){
|
| + sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
|
| + }
|
| +
|
| + /* If we are trying to update a view, realize that view into
|
| + ** an ephemeral table.
|
| + */
|
| +#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
|
| + if( isView ){
|
| + sqlite3MaterializeView(pParse, pTab, pWhere, iDataCur);
|
| + }
|
| +#endif
|
| +
|
| + /* Resolve the column names in all the expressions in the
|
| + ** WHERE clause.
|
| + */
|
| + if( sqlite3ResolveExprNames(&sNC, pWhere) ){
|
| + goto update_cleanup;
|
| + }
|
| +
|
| +#ifndef SQLITE_OMIT_VIRTUALTABLE
|
| + /* Virtual tables must be handled separately */
|
| + if( IsVirtual(pTab) ){
|
| + updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
|
| + pWhere, onError);
|
| + goto update_cleanup;
|
| + }
|
| +#endif
|
| +
|
| + /* Begin the database scan
|
| + */
|
| + if( HasRowid(pTab) ){
|
| + sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
|
| + pWInfo = sqlite3WhereBegin(
|
| + pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, iIdxCur
|
| + );
|
| + if( pWInfo==0 ) goto update_cleanup;
|
| + okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
|
| +
|
| + /* Remember the rowid of every item to be updated.
|
| + */
|
| + sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
|
| + if( !okOnePass ){
|
| + sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
|
| + }
|
| +
|
| + /* End the database scan loop.
|
| + */
|
| + sqlite3WhereEnd(pWInfo);
|
| + }else{
|
| + int iPk; /* First of nPk memory cells holding PRIMARY KEY value */
|
| + i16 nPk; /* Number of components of the PRIMARY KEY */
|
| + int addrOpen; /* Address of the OpenEphemeral instruction */
|
| +
|
| + assert( pPk!=0 );
|
| + nPk = pPk->nKeyCol;
|
| + iPk = pParse->nMem+1;
|
| + pParse->nMem += nPk;
|
| + regKey = ++pParse->nMem;
|
| + iEph = pParse->nTab++;
|
| + sqlite3VdbeAddOp2(v, OP_Null, 0, iPk);
|
| + addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk);
|
| + sqlite3VdbeSetP4KeyInfo(pParse, pPk);
|
| + pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0,
|
| + WHERE_ONEPASS_DESIRED, iIdxCur);
|
| + if( pWInfo==0 ) goto update_cleanup;
|
| + okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
|
| + for(i=0; i<nPk; i++){
|
| + assert( pPk->aiColumn[i]>=0 );
|
| + sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, pPk->aiColumn[i],
|
| + iPk+i);
|
| + }
|
| + if( okOnePass ){
|
| + sqlite3VdbeChangeToNoop(v, addrOpen);
|
| + nKey = nPk;
|
| + regKey = iPk;
|
| + }else{
|
| + sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
|
| + sqlite3IndexAffinityStr(db, pPk), nPk);
|
| + sqlite3VdbeAddOp2(v, OP_IdxInsert, iEph, regKey);
|
| + }
|
| + sqlite3WhereEnd(pWInfo);
|
| + }
|
| +
|
| + /* Initialize the count of updated rows
|
| + */
|
| + if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
|
| + regRowCount = ++pParse->nMem;
|
| + sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
|
| + }
|
| +
|
| + labelBreak = sqlite3VdbeMakeLabel(v);
|
| + if( !isView ){
|
| + /*
|
| + ** Open every index that needs updating. Note that if any
|
| + ** index could potentially invoke a REPLACE conflict resolution
|
| + ** action, then we need to open all indices because we might need
|
| + ** to be deleting some records.
|
| + */
|
| + if( onError==OE_Replace ){
|
| + memset(aToOpen, 1, nIdx+1);
|
| + }else{
|
| + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
|
| + if( pIdx->onError==OE_Replace ){
|
| + memset(aToOpen, 1, nIdx+1);
|
| + break;
|
| + }
|
| + }
|
| + }
|
| + if( okOnePass ){
|
| + if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
|
| + if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
|
| + }
|
| + sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, iBaseCur, aToOpen,
|
| + 0, 0);
|
| + }
|
| +
|
| + /* Top of the update loop */
|
| + if( okOnePass ){
|
| + if( aToOpen[iDataCur-iBaseCur] && !isView ){
|
| + assert( pPk );
|
| + sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey, nKey);
|
| + VdbeCoverageNeverTaken(v);
|
| + }
|
| + labelContinue = labelBreak;
|
| + sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
|
| + VdbeCoverageIf(v, pPk==0);
|
| + VdbeCoverageIf(v, pPk!=0);
|
| + }else if( pPk ){
|
| + labelContinue = sqlite3VdbeMakeLabel(v);
|
| + sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
|
| + addrTop = sqlite3VdbeAddOp2(v, OP_RowKey, iEph, regKey);
|
| + sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0);
|
| + VdbeCoverage(v);
|
| + }else{
|
| + labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, labelBreak,
|
| + regOldRowid);
|
| + VdbeCoverage(v);
|
| + sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
|
| + VdbeCoverage(v);
|
| + }
|
| +
|
| + /* If the record number will change, set register regNewRowid to
|
| + ** contain the new value. If the record number is not being modified,
|
| + ** then regNewRowid is the same register as regOldRowid, which is
|
| + ** already populated. */
|
| + assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
|
| + if( chngRowid ){
|
| + sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
|
| + sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
|
| + }
|
| +
|
| + /* Compute the old pre-UPDATE content of the row being changed, if that
|
| + ** information is needed */
|
| + if( chngPk || hasFK || pTrigger ){
|
| + u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
|
| + oldmask |= sqlite3TriggerColmask(pParse,
|
| + pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
|
| + );
|
| + for(i=0; i<pTab->nCol; i++){
|
| + if( oldmask==0xffffffff
|
| + || (i<32 && (oldmask & MASKBIT32(i))!=0)
|
| + || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
|
| + ){
|
| + testcase( oldmask!=0xffffffff && i==31 );
|
| + sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i);
|
| + }else{
|
| + sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
|
| + }
|
| + }
|
| + if( chngRowid==0 && pPk==0 ){
|
| + sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
|
| + }
|
| + }
|
| +
|
| + /* Populate the array of registers beginning at regNew with the new
|
| + ** row data. This array is used to check constants, create the new
|
| + ** table and index records, and as the values for any new.* references
|
| + ** made by triggers.
|
| + **
|
| + ** If there are one or more BEFORE triggers, then do not populate the
|
| + ** registers associated with columns that are (a) not modified by
|
| + ** this UPDATE statement and (b) not accessed by new.* references. The
|
| + ** values for registers not modified by the UPDATE must be reloaded from
|
| + ** the database after the BEFORE triggers are fired anyway (as the trigger
|
| + ** may have modified them). So not loading those that are not going to
|
| + ** be used eliminates some redundant opcodes.
|
| + */
|
| + newmask = sqlite3TriggerColmask(
|
| + pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
|
| + );
|
| + for(i=0; i<pTab->nCol; i++){
|
| + if( i==pTab->iPKey ){
|
| + sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
|
| + }else{
|
| + j = aXRef[i];
|
| + if( j>=0 ){
|
| + sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
|
| + }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
|
| + /* This branch loads the value of a column that will not be changed
|
| + ** into a register. This is done if there are no BEFORE triggers, or
|
| + ** if there are one or more BEFORE triggers that use this value via
|
| + ** a new.* reference in a trigger program.
|
| + */
|
| + testcase( i==31 );
|
| + testcase( i==32 );
|
| + sqlite3ExprCodeGetColumnToReg(pParse, pTab, i, iDataCur, regNew+i);
|
| + }else{
|
| + sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
|
| + }
|
| + }
|
| + }
|
| +
|
| + /* Fire any BEFORE UPDATE triggers. This happens before constraints are
|
| + ** verified. One could argue that this is wrong.
|
| + */
|
| + if( tmask&TRIGGER_BEFORE ){
|
| + sqlite3TableAffinity(v, pTab, regNew);
|
| + sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
|
| + TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
|
| +
|
| + /* The row-trigger may have deleted the row being updated. In this
|
| + ** case, jump to the next row. No updates or AFTER triggers are
|
| + ** required. This behavior - what happens when the row being updated
|
| + ** is deleted or renamed by a BEFORE trigger - is left undefined in the
|
| + ** documentation.
|
| + */
|
| + if( pPk ){
|
| + sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey);
|
| + VdbeCoverage(v);
|
| + }else{
|
| + sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
|
| + VdbeCoverage(v);
|
| + }
|
| +
|
| + /* If it did not delete it, the row-trigger may still have modified
|
| + ** some of the columns of the row being updated. Load the values for
|
| + ** all columns not modified by the update statement into their
|
| + ** registers in case this has happened.
|
| + */
|
| + for(i=0; i<pTab->nCol; i++){
|
| + if( aXRef[i]<0 && i!=pTab->iPKey ){
|
| + sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
|
| + }
|
| + }
|
| + }
|
| +
|
| + if( !isView ){
|
| + int addr1 = 0; /* Address of jump instruction */
|
| + int bReplace = 0; /* True if REPLACE conflict resolution might happen */
|
| +
|
| + /* Do constraint checks. */
|
| + assert( regOldRowid>0 );
|
| + sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
|
| + regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace);
|
| +
|
| + /* Do FK constraint checks. */
|
| + if( hasFK ){
|
| + sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
|
| + }
|
| +
|
| + /* Delete the index entries associated with the current record. */
|
| + if( bReplace || chngKey ){
|
| + if( pPk ){
|
| + addr1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey);
|
| + }else{
|
| + addr1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
|
| + }
|
| + VdbeCoverageNeverTaken(v);
|
| + }
|
| + sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1);
|
| +
|
| + /* If changing the record number, delete the old record. */
|
| + if( hasFK || chngKey || pPk!=0 ){
|
| + sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
|
| + }
|
| + if( bReplace || chngKey ){
|
| + sqlite3VdbeJumpHere(v, addr1);
|
| + }
|
| +
|
| + if( hasFK ){
|
| + sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
|
| + }
|
| +
|
| + /* Insert the new index entries and the new record. */
|
| + sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
|
| + regNewRowid, aRegIdx, 1, 0, 0);
|
| +
|
| + /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
|
| + ** handle rows (possibly in other tables) that refer via a foreign key
|
| + ** to the row just updated. */
|
| + if( hasFK ){
|
| + sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
|
| + }
|
| + }
|
| +
|
| + /* Increment the row counter
|
| + */
|
| + if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
|
| + sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
|
| + }
|
| +
|
| + sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
|
| + TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
|
| +
|
| + /* Repeat the above with the next record to be updated, until
|
| + ** all record selected by the WHERE clause have been updated.
|
| + */
|
| + if( okOnePass ){
|
| + /* Nothing to do at end-of-loop for a single-pass */
|
| + }else if( pPk ){
|
| + sqlite3VdbeResolveLabel(v, labelContinue);
|
| + sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
|
| + }else{
|
| + sqlite3VdbeGoto(v, labelContinue);
|
| + }
|
| + sqlite3VdbeResolveLabel(v, labelBreak);
|
| +
|
| + /* Close all tables */
|
| + for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
|
| + assert( aRegIdx );
|
| + if( aToOpen[i+1] ){
|
| + sqlite3VdbeAddOp2(v, OP_Close, iIdxCur+i, 0);
|
| + }
|
| + }
|
| + if( iDataCur<iIdxCur ) sqlite3VdbeAddOp2(v, OP_Close, iDataCur, 0);
|
| +
|
| + /* Update the sqlite_sequence table by storing the content of the
|
| + ** maximum rowid counter values recorded while inserting into
|
| + ** autoincrement tables.
|
| + */
|
| + if( pParse->nested==0 && pParse->pTriggerTab==0 ){
|
| + sqlite3AutoincrementEnd(pParse);
|
| + }
|
| +
|
| + /*
|
| + ** Return the number of rows that were changed. If this routine is
|
| + ** generating code because of a call to sqlite3NestedParse(), do not
|
| + ** invoke the callback function.
|
| + */
|
| + if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
|
| + sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
|
| + sqlite3VdbeSetNumCols(v, 1);
|
| + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
|
| + }
|
| +
|
| +update_cleanup:
|
| + sqlite3AuthContextPop(&sContext);
|
| + sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
|
| + sqlite3SrcListDelete(db, pTabList);
|
| + sqlite3ExprListDelete(db, pChanges);
|
| + sqlite3ExprDelete(db, pWhere);
|
| + return;
|
| +}
|
| +/* Make sure "isView" and other macros defined above are undefined. Otherwise
|
| +** they may interfere with compilation of other functions in this file
|
| +** (or in another file, if this file becomes part of the amalgamation). */
|
| +#ifdef isView
|
| + #undef isView
|
| +#endif
|
| +#ifdef pTrigger
|
| + #undef pTrigger
|
| +#endif
|
| +
|
| +#ifndef SQLITE_OMIT_VIRTUALTABLE
|
| +/*
|
| +** Generate code for an UPDATE of a virtual table.
|
| +**
|
| +** There are two possible strategies - the default and the special
|
| +** "onepass" strategy. Onepass is only used if the virtual table
|
| +** implementation indicates that pWhere may match at most one row.
|
| +**
|
| +** The default strategy is to create an ephemeral table that contains
|
| +** for each row to be changed:
|
| +**
|
| +** (A) The original rowid of that row.
|
| +** (B) The revised rowid for the row.
|
| +** (C) The content of every column in the row.
|
| +**
|
| +** Then loop through the contents of this ephemeral table executing a
|
| +** VUpdate for each row. When finished, drop the ephemeral table.
|
| +**
|
| +** The "onepass" strategy does not use an ephemeral table. Instead, it
|
| +** stores the same values (A, B and C above) in a register array and
|
| +** makes a single invocation of VUpdate.
|
| +*/
|
| +static void updateVirtualTable(
|
| + Parse *pParse, /* The parsing context */
|
| + SrcList *pSrc, /* The virtual table to be modified */
|
| + Table *pTab, /* The virtual table */
|
| + ExprList *pChanges, /* The columns to change in the UPDATE statement */
|
| + Expr *pRowid, /* Expression used to recompute the rowid */
|
| + int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
|
| + Expr *pWhere, /* WHERE clause of the UPDATE statement */
|
| + int onError /* ON CONFLICT strategy */
|
| +){
|
| + Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */
|
| + int ephemTab; /* Table holding the result of the SELECT */
|
| + int i; /* Loop counter */
|
| + sqlite3 *db = pParse->db; /* Database connection */
|
| + const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
|
| + WhereInfo *pWInfo;
|
| + int nArg = 2 + pTab->nCol; /* Number of arguments to VUpdate */
|
| + int regArg; /* First register in VUpdate arg array */
|
| + int regRec; /* Register in which to assemble record */
|
| + int regRowid; /* Register for ephem table rowid */
|
| + int iCsr = pSrc->a[0].iCursor; /* Cursor used for virtual table scan */
|
| + int aDummy[2]; /* Unused arg for sqlite3WhereOkOnePass() */
|
| + int bOnePass; /* True to use onepass strategy */
|
| + int addr; /* Address of OP_OpenEphemeral */
|
| +
|
| + /* Allocate nArg registers to martial the arguments to VUpdate. Then
|
| + ** create and open the ephemeral table in which the records created from
|
| + ** these arguments will be temporarily stored. */
|
| + assert( v );
|
| + ephemTab = pParse->nTab++;
|
| + addr= sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, nArg);
|
| + regArg = pParse->nMem + 1;
|
| + pParse->nMem += nArg;
|
| + regRec = ++pParse->nMem;
|
| + regRowid = ++pParse->nMem;
|
| +
|
| + /* Start scanning the virtual table */
|
| + pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0,0,WHERE_ONEPASS_DESIRED,0);
|
| + if( pWInfo==0 ) return;
|
| +
|
| + /* Populate the argument registers. */
|
| + sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg);
|
| + if( pRowid ){
|
| + sqlite3ExprCode(pParse, pRowid, regArg+1);
|
| + }else{
|
| + sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg+1);
|
| + }
|
| + for(i=0; i<pTab->nCol; i++){
|
| + if( aXRef[i]>=0 ){
|
| + sqlite3ExprCode(pParse, pChanges->a[aXRef[i]].pExpr, regArg+2+i);
|
| + }else{
|
| + sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, i, regArg+2+i);
|
| + }
|
| + }
|
| +
|
| + bOnePass = sqlite3WhereOkOnePass(pWInfo, aDummy);
|
| +
|
| + if( bOnePass ){
|
| + /* If using the onepass strategy, no-op out the OP_OpenEphemeral coded
|
| + ** above. Also, if this is a top-level parse (not a trigger), clear the
|
| + ** multi-write flag so that the VM does not open a statement journal */
|
| + sqlite3VdbeChangeToNoop(v, addr);
|
| + if( sqlite3IsToplevel(pParse) ){
|
| + pParse->isMultiWrite = 0;
|
| + }
|
| + }else{
|
| + /* Create a record from the argument register contents and insert it into
|
| + ** the ephemeral table. */
|
| + sqlite3VdbeAddOp3(v, OP_MakeRecord, regArg, nArg, regRec);
|
| + sqlite3VdbeAddOp2(v, OP_NewRowid, ephemTab, regRowid);
|
| + sqlite3VdbeAddOp3(v, OP_Insert, ephemTab, regRec, regRowid);
|
| + }
|
| +
|
| +
|
| + if( bOnePass==0 ){
|
| + /* End the virtual table scan */
|
| + sqlite3WhereEnd(pWInfo);
|
| +
|
| + /* Begin scannning through the ephemeral table. */
|
| + addr = sqlite3VdbeAddOp1(v, OP_Rewind, ephemTab); VdbeCoverage(v);
|
| +
|
| + /* Extract arguments from the current row of the ephemeral table and
|
| + ** invoke the VUpdate method. */
|
| + for(i=0; i<nArg; i++){
|
| + sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i, regArg+i);
|
| + }
|
| + }
|
| + sqlite3VtabMakeWritable(pParse, pTab);
|
| + sqlite3VdbeAddOp4(v, OP_VUpdate, 0, nArg, regArg, pVTab, P4_VTAB);
|
| + sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
|
| + sqlite3MayAbort(pParse);
|
| +
|
| + /* End of the ephemeral table scan. Or, if using the onepass strategy,
|
| + ** jump to here if the scan visited zero rows. */
|
| + if( bOnePass==0 ){
|
| + sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
|
| + sqlite3VdbeJumpHere(v, addr);
|
| + sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
|
| + }else{
|
| + sqlite3WhereEnd(pWInfo);
|
| + }
|
| +}
|
| +#endif /* SQLITE_OMIT_VIRTUALTABLE */
|
| +
|
| +/************** End of update.c **********************************************/
|
| +/************** Begin file vacuum.c ******************************************/
|
| +/*
|
| +** 2003 April 6
|
| +**
|
| +** The author disclaims copyright to this source code. In place of
|
| +** a legal notice, here is a blessing:
|
| +**
|
| +** May you do good and not evil.
|
| +** May you find forgiveness for yourself and forgive others.
|
| +** May you share freely, never taking more than you give.
|
| +**
|
| +*************************************************************************
|
| +** This file contains code used to implement the VACUUM command.
|
| +**
|
| +** Most of the code in this file may be omitted by defining the
|
| +** SQLITE_OMIT_VACUUM macro.
|
| +*/
|
| +/* #include "sqliteInt.h" */
|
| +/* #include "vdbeInt.h" */
|
| +
|
| +#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
|
| +/*
|
| +** Finalize a prepared statement. If there was an error, store the
|
| +** text of the error message in *pzErrMsg. Return the result code.
|
| +*/
|
| +static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
|
| + int rc;
|
| + rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
|
| + if( rc ){
|
| + sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
|
| + }
|
| + return rc;
|
| +}
|
| +
|
| +/*
|
| +** Execute zSql on database db. Return an error code.
|
| +*/
|
| +static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
|
| + sqlite3_stmt *pStmt;
|
| + VVA_ONLY( int rc; )
|
| + if( !zSql ){
|
| + return SQLITE_NOMEM;
|
| + }
|
| + if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
|
| + sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
|
| + return sqlite3_errcode(db);
|
| + }
|
| + VVA_ONLY( rc = ) sqlite3_step(pStmt);
|
| + assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
|
| + return vacuumFinalize(db, pStmt, pzErrMsg);
|
| +}
|
| +
|
| +/*
|
| +** Execute zSql on database db. The statement returns exactly
|
| +** one column. Execute this as SQL on the same database.
|
| +*/
|
| +static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
|
| + sqlite3_stmt *pStmt;
|
| + int rc;
|
| +
|
| + rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
|
| + if( rc!=SQLITE_OK ) return rc;
|
| +
|
| + while( SQLITE_ROW==sqlite3_step(pStmt) ){
|
| + rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
|
| + if( rc!=SQLITE_OK ){
|
| + vacuumFinalize(db, pStmt, pzErrMsg);
|
| + return rc;
|
| + }
|
| + }
|
| +
|
| + return vacuumFinalize(db, pStmt, pzErrMsg);
|
| +}
|
| +
|
| +/*
|
| +** The VACUUM command is used to clean up the database,
|
| +** collapse free space, etc. It is modelled after the VACUUM command
|
| +** in PostgreSQL. The VACUUM command works as follows:
|
| +**
|
| +** (1) Create a new transient database file
|
| +** (2) Copy all content from the database being vacuumed into
|
| +** the new transient database file
|
| +** (3) Copy content from the transient database back into the
|
| +** original database.
|
| +**
|
| +** The transient database requires temporary disk space approximately
|
| +** equal to the size of the original database. The copy operation of
|
| +** step (3) requires additional temporary disk space approximately equal
|
| +** to the size of the original database for the rollback journal.
|
| +** Hence, temporary disk space that is approximately 2x the size of the
|
| +** original database is required. Every page of the database is written
|
| +** approximately 3 times: Once for step (2) and twice for step (3).
|
| +** Two writes per page are required in step (3) because the original
|
| +** database content must be written into the rollback journal prior to
|
| +** overwriting the database with the vacuumed content.
|
| +**
|
| +** Only 1x temporary space and only 1x writes would be required if
|
| +** the copy of step (3) were replaced by deleting the original database
|
| +** and renaming the transient database as the original. But that will
|
| +** not work if other processes are attached to the original database.
|
| +** And a power loss in between deleting the original and renaming the
|
| +** transient would cause the database file to appear to be deleted
|
| +** following reboot.
|
| +*/
|
| +SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
|
| + Vdbe *v = sqlite3GetVdbe(pParse);
|
| + if( v ){
|
| + sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
|
| + sqlite3VdbeUsesBtree(v, 0);
|
| + }
|
| + return;
|
| +}
|
| +
|
| +/*
|
| +** This routine implements the OP_Vacuum opcode of the VDBE.
|
| +*/
|
| +SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
|
| + int rc = SQLITE_OK; /* Return code from service routines */
|
| + Btree *pMain; /* The database being vacuumed */
|
| + Btree *pTemp; /* The temporary database we vacuum into */
|
| + char *zSql = 0; /* SQL statements */
|
| + int saved_flags; /* Saved value of the db->flags */
|
| + int saved_nChange; /* Saved value of db->nChange */
|
| + int saved_nTotalChange; /* Saved value of db->nTotalChange */
|
| + void (*saved_xTrace)(void*,const char*); /* Saved db->xTrace */
|
| + Db *pDb = 0; /* Database to detach at end of vacuum */
|
| + int isMemDb; /* True if vacuuming a :memory: database */
|
| + int nRes; /* Bytes of reserved space at the end of each page */
|
| + int nDb; /* Number of attached databases */
|
| +
|
| + if( !db->autoCommit ){
|
| + sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
|
| + return SQLITE_ERROR;
|
| + }
|
| + if( db->nVdbeActive>1 ){
|
| + sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
|
| + return SQLITE_ERROR;
|
| + }
|
| +
|
| + /* Save the current value of the database flags so that it can be
|
| + ** restored before returning. Then set the writable-schema flag, and
|
| + ** disable CHECK and foreign key constraints. */
|
| + saved_flags = db->flags;
|
| + saved_nChange = db->nChange;
|
| + saved_nTotalChange = db->nTotalChange;
|
| + saved_xTrace = db->xTrace;
|
| + db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
|
| + db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
|
| + db->xTrace = 0;
|
| +
|
| + pMain = db->aDb[0].pBt;
|
| + isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
|
| +
|
| + /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
|
| + ** can be set to 'off' for this file, as it is not recovered if a crash
|
| + ** occurs anyway. The integrity of the database is maintained by a
|
| + ** (possibly synchronous) transaction opened on the main database before
|
| + ** sqlite3BtreeCopyFile() is called.
|
| + **
|
| + ** An optimisation would be to use a non-journaled pager.
|
| + ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
|
| + ** that actually made the VACUUM run slower. Very little journalling
|
| + ** actually occurs when doing a vacuum since the vacuum_db is initially
|
| + ** empty. Only the journal header is written. Apparently it takes more
|
| + ** time to parse and run the PRAGMA to turn journalling off than it does
|
| + ** to write the journal header file.
|
| + */
|
| + nDb = db->nDb;
|
| + if( sqlite3TempInMemory(db) ){
|
| + zSql = "ATTACH ':memory:' AS vacuum_db;";
|
| + }else{
|
| + zSql = "ATTACH '' AS vacuum_db;";
|
| + }
|
| + rc = execSql(db, pzErrMsg, zSql);
|
| + if( db->nDb>nDb ){
|
| + pDb = &db->aDb[db->nDb-1];
|
| + assert( strcmp(pDb->zName,"vacuum_db")==0 );
|
| + }
|
| + if( rc!=SQLITE_OK ) goto end_of_vacuum;
|
| + pTemp = db->aDb[db->nDb-1].pBt;
|
| +
|
| + /* The call to execSql() to attach the temp database has left the file
|
| + ** locked (as there was more than one active statement when the transaction
|
| + ** to read the schema was concluded. Unlock it here so that this doesn't
|
| + ** cause problems for the call to BtreeSetPageSize() below. */
|
| + sqlite3BtreeCommit(pTemp);
|
| +
|
| + nRes = sqlite3BtreeGetOptimalReserve(pMain);
|
| +
|
| + /* A VACUUM cannot change the pagesize of an encrypted database. */
|
| +#ifdef SQLITE_HAS_CODEC
|
| + if( db->nextPagesize ){
|
| + extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
|
| + int nKey;
|
| + char *zKey;
|
| + sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
|
| + if( nKey ) db->nextPagesize = 0;
|
| + }
|
| +#endif
|
| +
|
| + rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
|
| + if( rc!=SQLITE_OK ) goto end_of_vacuum;
|
| +
|
| + /* Begin a transaction and take an exclusive lock on the main database
|
| + ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
|
| + ** to ensure that we do not try to change the page-size on a WAL database.
|
| + */
|
| + rc = execSql(db, pzErrMsg, "BEGIN;");
|
| + if( rc!=SQLITE_OK ) goto end_of_vacuum;
|
| + rc = sqlite3BtreeBeginTrans(pMain, 2);
|
| + if( rc!=SQLITE_OK ) goto end_of_vacuum;
|
| +
|
| + /* Do not attempt to change the page size for a WAL database */
|
| + if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
|
| + ==PAGER_JOURNALMODE_WAL ){
|
| + db->nextPagesize = 0;
|
| + }
|
| +
|
| + if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
|
| + || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
|
| + || NEVER(db->mallocFailed)
|
| + ){
|
| + rc = SQLITE_NOMEM;
|
| + goto end_of_vacuum;
|
| + }
|
| +
|
| +#ifndef SQLITE_OMIT_AUTOVACUUM
|
| + sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
|
| + sqlite3BtreeGetAutoVacuum(pMain));
|
| +#endif
|
| +
|
| + /* Query the schema of the main database. Create a mirror schema
|
| + ** in the temporary database.
|
| + */
|
| + rc = execExecSql(db, pzErrMsg,
|
| + "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
|
| + " FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
|
| + " AND coalesce(rootpage,1)>0"
|
| + );
|
| + if( rc!=SQLITE_OK ) goto end_of_vacuum;
|
| + rc = execExecSql(db, pzErrMsg,
|
| + "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
|
| + " FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
|
| + if( rc!=SQLITE_OK ) goto end_of_vacuum;
|
| + rc = execExecSql(db, pzErrMsg,
|
| + "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
|
| + " FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
|
| + if( rc!=SQLITE_OK ) goto end_of_vacuum;
|
| +
|
| + /* Loop through the tables in the main database. For each, do
|
| + ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
|
| + ** the contents to the temporary database.
|
| + */
|
| + assert( (db->flags & SQLITE_Vacuum)==0 );
|
| + db->flags |= SQLITE_Vacuum;
|
| + rc = execExecSql(db, pzErrMsg,
|
| + "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
|
| + "|| ' SELECT * FROM main.' || quote(name) || ';'"
|
| + "FROM main.sqlite_master "
|
| + "WHERE type = 'table' AND name!='sqlite_sequence' "
|
| + " AND coalesce(rootpage,1)>0"
|
| + );
|
| + assert( (db->flags & SQLITE_Vacuum)!=0 );
|
| + db->flags &= ~SQLITE_Vacuum;
|
| + if( rc!=SQLITE_OK ) goto end_of_vacuum;
|
| +
|
| + /* Copy over the sequence table
|
| + */
|
| + rc = execExecSql(db, pzErrMsg,
|
| + "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
|
| + "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
|
| + );
|
| + if( rc!=SQLITE_OK ) goto end_of_vacuum;
|
| + rc = execExecSql(db, pzErrMsg,
|
| + "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
|
| + "|| ' SELECT * FROM main.' || quote(name) || ';' "
|
| + "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
|
| + );
|
| + if( rc!=SQLITE_OK ) goto end_of_vacuum;
|
| +
|
| +
|
| + /* Copy the triggers, views, and virtual tables from the main database
|
| + ** over to the temporary database. None of these objects has any
|
| + ** associated storage, so all we have to do is copy their entries
|
| + ** from the SQLITE_MASTER table.
|
| + */
|
| + rc = execSql(db, pzErrMsg,
|
| + "INSERT INTO vacuum_db.sqlite_master "
|
| + " SELECT type, name, tbl_name, rootpage, sql"
|
| + " FROM main.sqlite_master"
|
| + " WHERE type='view' OR type='trigger'"
|
| + " OR (type='table' AND rootpage=0)"
|
| + );
|
| + if( rc ) goto end_of_vacuum;
|
| +
|
| + /* At this point, there is a write transaction open on both the
|
| + ** vacuum database and the main database. Assuming no error occurs,
|
| + ** both transactions are closed by this block - the main database
|
| + ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
|
| + ** call to sqlite3BtreeCommit().
|
| + */
|
| + {
|
| + u32 meta;
|
| + int i;
|
| +
|
| + /* This array determines which meta meta values are preserved in the
|
| + ** vacuum. Even entries are the meta value number and odd entries
|
| + ** are an increment to apply to the meta value after the vacuum.
|
| + ** The increment is used to increase the schema cookie so that other
|
| + ** connections to the same database will know to reread the schema.
|
| + */
|
| + static const unsigned char aCopy[] = {
|
| + BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */
|
| + BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */
|
| + BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */
|
| + BTREE_USER_VERSION, 0, /* Preserve the user version */
|
| + BTREE_APPLICATION_ID, 0, /* Preserve the application id */
|
| + };
|
| +
|
| + assert( 1==sqlite3BtreeIsInTrans(pTemp) );
|
| + assert( 1==sqlite3BtreeIsInTrans(pMain) );
|
| +
|
| + /* Copy Btree meta values */
|
| + for(i=0; i<ArraySize(aCopy); i+=2){
|
| + /* GetMeta() and UpdateMeta() cannot fail in this context because
|
| + ** we already have page 1 loaded into cache and marked dirty. */
|
| + sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
|
| + rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
|
| + if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
|
| + }
|
| +
|
| + rc = sqlite3BtreeCopyFile(pMain, pTemp);
|
| + if( rc!=SQLITE_OK ) goto end_of_vacuum;
|
| + rc = sqlite3BtreeCommit(pTemp);
|
| + if( rc!=SQLITE_OK ) goto end_of_vacuum;
|
| +#ifndef SQLITE_OMIT_AUTOVACUUM
|
| + sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
|
| +#endif
|
| + }
|
| +
|
| + assert( rc==SQLITE_OK );
|
| + rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
|
| +
|
| +end_of_vacuum:
|
| + /* Restore the original value of db->flags */
|
| + db->flags = saved_flags;
|
| + db->nChange = saved_nChange;
|
| + db->nTotalChange = saved_nTotalChange;
|
| + db->xTrace = saved_xTrace;
|
| + sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
|
| +
|
| + /* Currently there is an SQL level transaction open on the vacuum
|
| + ** database. No locks are held on any other files (since the main file
|
| + ** was committed at the btree level). So it safe to end the transaction
|
| + ** by manually setting the autoCommit flag to true and detaching the
|
| + ** vacuum database. The vacuum_db journal file is deleted when the pager
|
| + ** is closed by the DETACH.
|
| + */
|
| + db->autoCommit = 1;
|
| +
|
| + if( pDb ){
|
| + sqlite3BtreeClose(pDb->pBt);
|
| + pDb->pBt = 0;
|
| + pDb->pSchema = 0;
|
| + }
|
| +
|
| + /* This both clears the schemas and reduces the size of the db->aDb[]
|
| + ** array. */
|
| + sqlite3ResetAllSchemasOfConnection(db);
|
| +
|
| + return rc;
|
| +}
|
| +
|
| +#endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
|
| +
|
| +/************** End of vacuum.c **********************************************/
|
| +/************** Begin file vtab.c ********************************************/
|
| +/*
|
| +** 2006 June 10
|
| +**
|
| +** The author disclaims copyright to this source code. In place of
|
| +** a legal notice, here is a blessing:
|
| +**
|
| +** May you do good and not evil.
|
| +** May you find forgiveness for yourself and forgive others.
|
| +** May you share freely, never taking more than you give.
|
| +**
|
| +*************************************************************************
|
| +** This file contains code used to help implement virtual tables.
|
| +*/
|
| +#ifndef SQLITE_OMIT_VIRTUALTABLE
|
| +/* #include "sqliteInt.h" */
|
| +
|
| +/*
|
| +** Before a virtual table xCreate() or xConnect() method is invoked, the
|
| +** sqlite3.pVtabCtx member variable is set to point to an instance of
|
| +** this struct allocated on the stack. It is used by the implementation of
|
| +** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
|
| +** are invoked only from within xCreate and xConnect methods.
|
| +*/
|
| +struct VtabCtx {
|
| + VTable *pVTable; /* The virtual table being constructed */
|
| + Table *pTab; /* The Table object to which the virtual table belongs */
|
| + VtabCtx *pPrior; /* Parent context (if any) */
|
| + int bDeclared; /* True after sqlite3_declare_vtab() is called */
|
| +};
|
| +
|
| +/*
|
| +** The actual function that does the work of creating a new module.
|
| +** This function implements the sqlite3_create_module() and
|
| +** sqlite3_create_module_v2() interfaces.
|
| +*/
|
| +static int createModule(
|
| + sqlite3 *db, /* Database in which module is registered */
|
| + const char *zName, /* Name assigned to this module */
|
| + const sqlite3_module *pModule, /* The definition of the module */
|
| + void *pAux, /* Context pointer for xCreate/xConnect */
|
| + void (*xDestroy)(void *) /* Module destructor function */
|
| +){
|
| + int rc = SQLITE_OK;
|
| + int nName;
|
| +
|
| + sqlite3_mutex_enter(db->mutex);
|
| + nName = sqlite3Strlen30(zName);
|
| + if( sqlite3HashFind(&db->aModule, zName) ){
|
| + rc = SQLITE_MISUSE_BKPT;
|
| + }else{
|
| + Module *pMod;
|
| + pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
|
| + if( pMod ){
|
| + Module *pDel;
|
| + char *zCopy = (char *)(&pMod[1]);
|
| + memcpy(zCopy, zName, nName+1);
|
| + pMod->zName = zCopy;
|
| + pMod->pModule = pModule;
|
| + pMod->pAux = pAux;
|
| + pMod->xDestroy = xDestroy;
|
| + pMod->pEpoTab = 0;
|
| + pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod);
|
| + assert( pDel==0 || pDel==pMod );
|
| + if( pDel ){
|
| + db->mallocFailed = 1;
|
| + sqlite3DbFree(db, pDel);
|
| + }
|
| + }
|
| + }
|
| + rc = sqlite3ApiExit(db, rc);
|
| + if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
|
| +
|
| + sqlite3_mutex_leave(db->mutex);
|
| + return rc;
|
| +}
|
| +
|
| +
|
| +/*
|
| +** External API function used to create a new virtual-table module.
|
| +*/
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_create_module(
|
| + sqlite3 *db, /* Database in which module is registered */
|
| + const char *zName, /* Name assigned to this module */
|
| + const sqlite3_module *pModule, /* The definition of the module */
|
| + void *pAux /* Context pointer for xCreate/xConnect */
|
| +){
|
| +#ifdef SQLITE_ENABLE_API_ARMOR
|
| + if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
|
| +#endif
|
| + return createModule(db, zName, pModule, pAux, 0);
|
| +}
|
| +
|
| +/*
|
| +** External API function used to create a new virtual-table module.
|
| +*/
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_create_module_v2(
|
| + sqlite3 *db, /* Database in which module is registered */
|
| + const char *zName, /* Name assigned to this module */
|
| + const sqlite3_module *pModule, /* The definition of the module */
|
| + void *pAux, /* Context pointer for xCreate/xConnect */
|
| + void (*xDestroy)(void *) /* Module destructor function */
|
| +){
|
| +#ifdef SQLITE_ENABLE_API_ARMOR
|
| + if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
|
| +#endif
|
| + return createModule(db, zName, pModule, pAux, xDestroy);
|
| +}
|
| +
|
| +/*
|
| +** Lock the virtual table so that it cannot be disconnected.
|
| +** Locks nest. Every lock should have a corresponding unlock.
|
| +** If an unlock is omitted, resources leaks will occur.
|
| +**
|
| +** If a disconnect is attempted while a virtual table is locked,
|
| +** the disconnect is deferred until all locks have been removed.
|
| +*/
|
| +SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
|
| + pVTab->nRef++;
|
| +}
|
| +
|
| +
|
| +/*
|
| +** pTab is a pointer to a Table structure representing a virtual-table.
|
| +** Return a pointer to the VTable object used by connection db to access
|
| +** this virtual-table, if one has been created, or NULL otherwise.
|
| +*/
|
| +SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
|
| + VTable *pVtab;
|
| + assert( IsVirtual(pTab) );
|
| + for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
|
| + return pVtab;
|
| +}
|
| +
|
| +/*
|
| +** Decrement the ref-count on a virtual table object. When the ref-count
|
| +** reaches zero, call the xDisconnect() method to delete the object.
|
| +*/
|
| +SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
|
| + sqlite3 *db = pVTab->db;
|
| +
|
| + assert( db );
|
| + assert( pVTab->nRef>0 );
|
| + assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
|
| +
|
| + pVTab->nRef--;
|
| + if( pVTab->nRef==0 ){
|
| + sqlite3_vtab *p = pVTab->pVtab;
|
| + if( p ){
|
| + p->pModule->xDisconnect(p);
|
| + }
|
| + sqlite3DbFree(db, pVTab);
|
| + }
|
| +}
|
| +
|
| +/*
|
| +** Table p is a virtual table. This function moves all elements in the
|
| +** p->pVTable list to the sqlite3.pDisconnect lists of their associated
|
| +** database connections to be disconnected at the next opportunity.
|
| +** Except, if argument db is not NULL, then the entry associated with
|
| +** connection db is left in the p->pVTable list.
|
| +*/
|
| +static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
|
| + VTable *pRet = 0;
|
| + VTable *pVTable = p->pVTable;
|
| + p->pVTable = 0;
|
| +
|
| + /* Assert that the mutex (if any) associated with the BtShared database
|
| + ** that contains table p is held by the caller. See header comments
|
| + ** above function sqlite3VtabUnlockList() for an explanation of why
|
| + ** this makes it safe to access the sqlite3.pDisconnect list of any
|
| + ** database connection that may have an entry in the p->pVTable list.
|
| + */
|
| + assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
|
| +
|
| + while( pVTable ){
|
| + sqlite3 *db2 = pVTable->db;
|
| + VTable *pNext = pVTable->pNext;
|
| + assert( db2 );
|
| + if( db2==db ){
|
| + pRet = pVTable;
|
| + p->pVTable = pRet;
|
| + pRet->pNext = 0;
|
| + }else{
|
| + pVTable->pNext = db2->pDisconnect;
|
| + db2->pDisconnect = pVTable;
|
| + }
|
| + pVTable = pNext;
|
| + }
|
| +
|
| + assert( !db || pRet );
|
| + return pRet;
|
| +}
|
| +
|
| +/*
|
| +** Table *p is a virtual table. This function removes the VTable object
|
| +** for table *p associated with database connection db from the linked
|
| +** list in p->pVTab. It also decrements the VTable ref count. This is
|
| +** used when closing database connection db to free all of its VTable
|
| +** objects without disturbing the rest of the Schema object (which may
|
| +** be being used by other shared-cache connections).
|
| +*/
|
| +SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
|
| + VTable **ppVTab;
|
| +
|
| + assert( IsVirtual(p) );
|
| + assert( sqlite3BtreeHoldsAllMutexes(db) );
|
| + assert( sqlite3_mutex_held(db->mutex) );
|
| +
|
| + for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
|
| + if( (*ppVTab)->db==db ){
|
| + VTable *pVTab = *ppVTab;
|
| + *ppVTab = pVTab->pNext;
|
| + sqlite3VtabUnlock(pVTab);
|
| + break;
|
| + }
|
| + }
|
| +}
|
| +
|
| +
|
| +/*
|
| +** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
|
| +**
|
| +** This function may only be called when the mutexes associated with all
|
| +** shared b-tree databases opened using connection db are held by the
|
| +** caller. This is done to protect the sqlite3.pDisconnect list. The
|
| +** sqlite3.pDisconnect list is accessed only as follows:
|
| +**
|
| +** 1) By this function. In this case, all BtShared mutexes and the mutex
|
| +** associated with the database handle itself must be held.
|
| +**
|
| +** 2) By function vtabDisconnectAll(), when it adds a VTable entry to
|
| +** the sqlite3.pDisconnect list. In this case either the BtShared mutex
|
| +** associated with the database the virtual table is stored in is held
|
| +** or, if the virtual table is stored in a non-sharable database, then
|
| +** the database handle mutex is held.
|
| +**
|
| +** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
|
| +** by multiple threads. It is thread-safe.
|
| +*/
|
| +SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
|
| + VTable *p = db->pDisconnect;
|
| + db->pDisconnect = 0;
|
| +
|
| + assert( sqlite3BtreeHoldsAllMutexes(db) );
|
| + assert( sqlite3_mutex_held(db->mutex) );
|
| +
|
| + if( p ){
|
| + sqlite3ExpirePreparedStatements(db);
|
| + do {
|
| + VTable *pNext = p->pNext;
|
| + sqlite3VtabUnlock(p);
|
| + p = pNext;
|
| + }while( p );
|
| + }
|
| +}
|
| +
|
| +/*
|
| +** Clear any and all virtual-table information from the Table record.
|
| +** This routine is called, for example, just before deleting the Table
|
| +** record.
|
| +**
|
| +** Since it is a virtual-table, the Table structure contains a pointer
|
| +** to the head of a linked list of VTable structures. Each VTable
|
| +** structure is associated with a single sqlite3* user of the schema.
|
| +** The reference count of the VTable structure associated with database
|
| +** connection db is decremented immediately (which may lead to the
|
| +** structure being xDisconnected and free). Any other VTable structures
|
| +** in the list are moved to the sqlite3.pDisconnect list of the associated
|
| +** database connection.
|
| +*/
|
| +SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
|
| + if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
|
| + if( p->azModuleArg ){
|
| + int i;
|
| + for(i=0; i<p->nModuleArg; i++){
|
| + if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
|
| + }
|
| + sqlite3DbFree(db, p->azModuleArg);
|
| + }
|
| +}
|
| +
|
| +/*
|
| +** Add a new module argument to pTable->azModuleArg[].
|
| +** The string is not copied - the pointer is stored. The
|
| +** string will be freed automatically when the table is
|
| +** deleted.
|
| +*/
|
| +static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
|
| + int nBytes = sizeof(char *)*(2+pTable->nModuleArg);
|
| + char **azModuleArg;
|
| + azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
|
| + if( azModuleArg==0 ){
|
| + sqlite3DbFree(db, zArg);
|
| + }else{
|
| + int i = pTable->nModuleArg++;
|
| + azModuleArg[i] = zArg;
|
| + azModuleArg[i+1] = 0;
|
| + pTable->azModuleArg = azModuleArg;
|
| + }
|
| +}
|
| +
|
| +/*
|
| +** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
|
| +** statement. The module name has been parsed, but the optional list
|
| +** of parameters that follow the module name are still pending.
|
| +*/
|
| +SQLITE_PRIVATE void sqlite3VtabBeginParse(
|
| + Parse *pParse, /* Parsing context */
|
| + Token *pName1, /* Name of new table, or database name */
|
| + Token *pName2, /* Name of new table or NULL */
|
| + Token *pModuleName, /* Name of the module for the virtual table */
|
| + int ifNotExists /* No error if the table already exists */
|
| +){
|
| + int iDb; /* The database the table is being created in */
|
| + Table *pTable; /* The new virtual table */
|
| + sqlite3 *db; /* Database connection */
|
| +
|
| + sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
|
| + pTable = pParse->pNewTable;
|
| + if( pTable==0 ) return;
|
| + assert( 0==pTable->pIndex );
|
| +
|
| + db = pParse->db;
|
| + iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
|
| + assert( iDb>=0 );
|
| +
|
| + pTable->tabFlags |= TF_Virtual;
|
| + pTable->nModuleArg = 0;
|
| + addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
|
| + addModuleArgument(db, pTable, 0);
|
| + addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
|
| + assert( (pParse->sNameToken.z==pName2->z && pName2->z!=0)
|
| + || (pParse->sNameToken.z==pName1->z && pName2->z==0)
|
| + );
|
| + pParse->sNameToken.n = (int)(
|
| + &pModuleName->z[pModuleName->n] - pParse->sNameToken.z
|
| + );
|
| +
|
| +#ifndef SQLITE_OMIT_AUTHORIZATION
|
| + /* Creating a virtual table invokes the authorization callback twice.
|
| + ** The first invocation, to obtain permission to INSERT a row into the
|
| + ** sqlite_master table, has already been made by sqlite3StartTable().
|
| + ** The second call, to obtain permission to create the table, is made now.
|
| + */
|
| + if( pTable->azModuleArg ){
|
| + sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
|
| + pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
|
| + }
|
| +#endif
|
| +}
|
| +
|
| +/*
|
| +** This routine takes the module argument that has been accumulating
|
| +** in pParse->zArg[] and appends it to the list of arguments on the
|
| +** virtual table currently under construction in pParse->pTable.
|
| +*/
|
| +static void addArgumentToVtab(Parse *pParse){
|
| + if( pParse->sArg.z && pParse->pNewTable ){
|
| + const char *z = (const char*)pParse->sArg.z;
|
| + int n = pParse->sArg.n;
|
| + sqlite3 *db = pParse->db;
|
| + addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
|
| + }
|
| +}
|
| +
|
| +/*
|
| +** The parser calls this routine after the CREATE VIRTUAL TABLE statement
|
| +** has been completely parsed.
|
| +*/
|
| +SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
|
| + Table *pTab = pParse->pNewTable; /* The table being constructed */
|
| + sqlite3 *db = pParse->db; /* The database connection */
|
| +
|
| + if( pTab==0 ) return;
|
| + addArgumentToVtab(pParse);
|
| + pParse->sArg.z = 0;
|
| + if( pTab->nModuleArg<1 ) return;
|
| +
|
| + /* If the CREATE VIRTUAL TABLE statement is being entered for the
|
| + ** first time (in other words if the virtual table is actually being
|
| + ** created now instead of just being read out of sqlite_master) then
|
| + ** do additional initialization work and store the statement text
|
| + ** in the sqlite_master table.
|
| + */
|
| + if( !db->init.busy ){
|
| + char *zStmt;
|
| + char *zWhere;
|
| + int iDb;
|
| + int iReg;
|
| + Vdbe *v;
|
| +
|
| + /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
|
| + if( pEnd ){
|
| + pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
|
| + }
|
| + zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
|
| +
|
| + /* A slot for the record has already been allocated in the
|
| + ** SQLITE_MASTER table. We just need to update that slot with all
|
| + ** the information we've collected.
|
| + **
|
| + ** The VM register number pParse->regRowid holds the rowid of an
|
| + ** entry in the sqlite_master table tht was created for this vtab
|
| + ** by sqlite3StartTable().
|
| + */
|
| + iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
|
| + sqlite3NestedParse(pParse,
|
| + "UPDATE %Q.%s "
|
| + "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
|
| + "WHERE rowid=#%d",
|
| + db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
|
| + pTab->zName,
|
| + pTab->zName,
|
| + zStmt,
|
| + pParse->regRowid
|
| + );
|
| + sqlite3DbFree(db, zStmt);
|
| + v = sqlite3GetVdbe(pParse);
|
| + sqlite3ChangeCookie(pParse, iDb);
|
| +
|
| + sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
|
| + zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
|
| + sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
|
| +
|
| + iReg = ++pParse->nMem;
|
| + sqlite3VdbeLoadString(v, iReg, pTab->zName);
|
| + sqlite3VdbeAddOp2(v, OP_VCreate, iDb, iReg);
|
| + }
|
| +
|
| + /* If we are rereading the sqlite_master table create the in-memory
|
| + ** record of the table. The xConnect() method is not called until
|
| + ** the first time the virtual table is used in an SQL statement. This
|
| + ** allows a schema that contains virtual tables to be loaded before
|
| + ** the required virtual table implementations are registered. */
|
| + else {
|
| + Table *pOld;
|
| + Schema *pSchema = pTab->pSchema;
|
| + const char *zName = pTab->zName;
|
| + assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
|
| + pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab);
|
| + if( pOld ){
|
| + db->mallocFailed = 1;
|
| + assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */
|
| + return;
|
| + }
|
| + pParse->pNewTable = 0;
|
| + }
|
| +}
|
| +
|
| +/*
|
| +** The parser calls this routine when it sees the first token
|
| +** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
|
| +*/
|
| +SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
|
| + addArgumentToVtab(pParse);
|
| + pParse->sArg.z = 0;
|
| + pParse->sArg.n = 0;
|
| +}
|
| +
|
| +/*
|
| +** The parser calls this routine for each token after the first token
|
| +** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
|
| +*/
|
| +SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
|
| + Token *pArg = &pParse->sArg;
|
| + if( pArg->z==0 ){
|
| + pArg->z = p->z;
|
| + pArg->n = p->n;
|
| + }else{
|
| + assert(pArg->z <= p->z);
|
| + pArg->n = (int)(&p->z[p->n] - pArg->z);
|
| + }
|
| +}
|
| +
|
| +/*
|
| +** Invoke a virtual table constructor (either xCreate or xConnect). The
|
| +** pointer to the function to invoke is passed as the fourth parameter
|
| +** to this procedure.
|
| +*/
|
| +static int vtabCallConstructor(
|
| + sqlite3 *db,
|
| + Table *pTab,
|
| + Module *pMod,
|
| + int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
|
| + char **pzErr
|
| +){
|
| + VtabCtx sCtx;
|
| + VTable *pVTable;
|
| + int rc;
|
| + const char *const*azArg = (const char *const*)pTab->azModuleArg;
|
| + int nArg = pTab->nModuleArg;
|
| + char *zErr = 0;
|
| + char *zModuleName;
|
| + int iDb;
|
| + VtabCtx *pCtx;
|
| +
|
| + /* Check that the virtual-table is not already being initialized */
|
| + for(pCtx=db->pVtabCtx; pCtx; pCtx=pCtx->pPrior){
|
| + if( pCtx->pTab==pTab ){
|
| + *pzErr = sqlite3MPrintf(db,
|
| + "vtable constructor called recursively: %s", pTab->zName
|
| + );
|
| + return SQLITE_LOCKED;
|
| + }
|
| + }
|
| +
|
| + zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
|
| + if( !zModuleName ){
|
| + return SQLITE_NOMEM;
|
| + }
|
| +
|
| + pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
|
| + if( !pVTable ){
|
| + sqlite3DbFree(db, zModuleName);
|
| + return SQLITE_NOMEM;
|
| + }
|
| + pVTable->db = db;
|
| + pVTable->pMod = pMod;
|
| +
|
| + iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
|
| + pTab->azModuleArg[1] = db->aDb[iDb].zName;
|
| +
|
| + /* Invoke the virtual table constructor */
|
| + assert( &db->pVtabCtx );
|
| + assert( xConstruct );
|
| + sCtx.pTab = pTab;
|
| + sCtx.pVTable = pVTable;
|
| + sCtx.pPrior = db->pVtabCtx;
|
| + sCtx.bDeclared = 0;
|
| + db->pVtabCtx = &sCtx;
|
| + rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
|
| + db->pVtabCtx = sCtx.pPrior;
|
| + if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
|
| + assert( sCtx.pTab==pTab );
|
| +
|
| + if( SQLITE_OK!=rc ){
|
| + if( zErr==0 ){
|
| + *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
|
| + }else {
|
| + *pzErr = sqlite3MPrintf(db, "%s", zErr);
|
| + sqlite3_free(zErr);
|
| + }
|
| + sqlite3DbFree(db, pVTable);
|
| + }else if( ALWAYS(pVTable->pVtab) ){
|
| + /* Justification of ALWAYS(): A correct vtab constructor must allocate
|
| + ** the sqlite3_vtab object if successful. */
|
| + memset(pVTable->pVtab, 0, sizeof(pVTable->pVtab[0]));
|
| + pVTable->pVtab->pModule = pMod->pModule;
|
| + pVTable->nRef = 1;
|
| + if( sCtx.bDeclared==0 ){
|
| + const char *zFormat = "vtable constructor did not declare schema: %s";
|
| + *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
|
| + sqlite3VtabUnlock(pVTable);
|
| + rc = SQLITE_ERROR;
|
| + }else{
|
| + int iCol;
|
| + u8 oooHidden = 0;
|
| + /* If everything went according to plan, link the new VTable structure
|
| + ** into the linked list headed by pTab->pVTable. Then loop through the
|
| + ** columns of the table to see if any of them contain the token "hidden".
|
| + ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
|
| + ** the type string. */
|
| + pVTable->pNext = pTab->pVTable;
|
| + pTab->pVTable = pVTable;
|
| +
|
| + for(iCol=0; iCol<pTab->nCol; iCol++){
|
| + char *zType = pTab->aCol[iCol].zType;
|
| + int nType;
|
| + int i = 0;
|
| + if( !zType ){
|
| + pTab->tabFlags |= oooHidden;
|
| + continue;
|
| + }
|
| + nType = sqlite3Strlen30(zType);
|
| + if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
|
| + for(i=0; i<nType; i++){
|
| + if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
|
| + && (zType[i+7]=='\0' || zType[i+7]==' ')
|
| + ){
|
| + i++;
|
| + break;
|
| + }
|
| + }
|
| + }
|
| + if( i<nType ){
|
| + int j;
|
| + int nDel = 6 + (zType[i+6] ? 1 : 0);
|
| + for(j=i; (j+nDel)<=nType; j++){
|
| + zType[j] = zType[j+nDel];
|
| + }
|
| + if( zType[i]=='\0' && i>0 ){
|
| + assert(zType[i-1]==' ');
|
| + zType[i-1] = '\0';
|
| + }
|
| + pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
|
| + oooHidden = TF_OOOHidden;
|
| + }else{
|
| + pTab->tabFlags |= oooHidden;
|
| + }
|
| + }
|
| + }
|
| + }
|
| +
|
| + sqlite3DbFree(db, zModuleName);
|
| + return rc;
|
| +}
|
| +
|
| +/*
|
| +** This function is invoked by the parser to call the xConnect() method
|
| +** of the virtual table pTab. If an error occurs, an error code is returned
|
| +** and an error left in pParse.
|
| +**
|
| +** This call is a no-op if table pTab is not a virtual table.
|
| +*/
|
| +SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
|
| + sqlite3 *db = pParse->db;
|
| + const char *zMod;
|
| + Module *pMod;
|
| + int rc;
|
| +
|
| + assert( pTab );
|
| + if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
|
| + return SQLITE_OK;
|
| + }
|
| +
|
| + /* Locate the required virtual table module */
|
| + zMod = pTab->azModuleArg[0];
|
| + pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
|
| +
|
| + if( !pMod ){
|
| + const char *zModule = pTab->azModuleArg[0];
|
| + sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
|
| + rc = SQLITE_ERROR;
|
| + }else{
|
| + char *zErr = 0;
|
| + rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
|
| + if( rc!=SQLITE_OK ){
|
| + sqlite3ErrorMsg(pParse, "%s", zErr);
|
| + }
|
| + sqlite3DbFree(db, zErr);
|
| + }
|
| +
|
| + return rc;
|
| +}
|
| +/*
|
| +** Grow the db->aVTrans[] array so that there is room for at least one
|
| +** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
|
| +*/
|
| +static int growVTrans(sqlite3 *db){
|
| + const int ARRAY_INCR = 5;
|
| +
|
| + /* Grow the sqlite3.aVTrans array if required */
|
| + if( (db->nVTrans%ARRAY_INCR)==0 ){
|
| + VTable **aVTrans;
|
| + int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
|
| + aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
|
| + if( !aVTrans ){
|
| + return SQLITE_NOMEM;
|
| + }
|
| + memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
|
| + db->aVTrans = aVTrans;
|
| + }
|
| +
|
| + return SQLITE_OK;
|
| +}
|
| +
|
| +/*
|
| +** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
|
| +** have already been reserved using growVTrans().
|
| +*/
|
| +static void addToVTrans(sqlite3 *db, VTable *pVTab){
|
| + /* Add pVtab to the end of sqlite3.aVTrans */
|
| + db->aVTrans[db->nVTrans++] = pVTab;
|
| + sqlite3VtabLock(pVTab);
|
| +}
|
| +
|
| +/*
|
| +** This function is invoked by the vdbe to call the xCreate method
|
| +** of the virtual table named zTab in database iDb.
|
| +**
|
| +** If an error occurs, *pzErr is set to point an an English language
|
| +** description of the error and an SQLITE_XXX error code is returned.
|
| +** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
|
| +*/
|
| +SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
|
| + int rc = SQLITE_OK;
|
| + Table *pTab;
|
| + Module *pMod;
|
| + const char *zMod;
|
| +
|
| + pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
|
| + assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
|
| +
|
| + /* Locate the required virtual table module */
|
| + zMod = pTab->azModuleArg[0];
|
| + pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
|
| +
|
| + /* If the module has been registered and includes a Create method,
|
| + ** invoke it now. If the module has not been registered, return an
|
| + ** error. Otherwise, do nothing.
|
| + */
|
| + if( pMod==0 || pMod->pModule->xCreate==0 || pMod->pModule->xDestroy==0 ){
|
| + *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
|
| + rc = SQLITE_ERROR;
|
| + }else{
|
| + rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
|
| + }
|
| +
|
| + /* Justification of ALWAYS(): The xConstructor method is required to
|
| + ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
|
| + if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
|
| + rc = growVTrans(db);
|
| + if( rc==SQLITE_OK ){
|
| + addToVTrans(db, sqlite3GetVTable(db, pTab));
|
| + }
|
| + }
|
| +
|
| + return rc;
|
| +}
|
| +
|
| +/*
|
| +** This function is used to set the schema of a virtual table. It is only
|
| +** valid to call this function from within the xCreate() or xConnect() of a
|
| +** virtual table module.
|
| +*/
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
|
| + VtabCtx *pCtx;
|
| + Parse *pParse;
|
| + int rc = SQLITE_OK;
|
| + Table *pTab;
|
| + char *zErr = 0;
|
| +
|
| +#ifdef SQLITE_ENABLE_API_ARMOR
|
| + if( !sqlite3SafetyCheckOk(db) || zCreateTable==0 ){
|
| + return SQLITE_MISUSE_BKPT;
|
| + }
|
| +#endif
|
| + sqlite3_mutex_enter(db->mutex);
|
| + pCtx = db->pVtabCtx;
|
| + if( !pCtx || pCtx->bDeclared ){
|
| + sqlite3Error(db, SQLITE_MISUSE);
|
| + sqlite3_mutex_leave(db->mutex);
|
| + return SQLITE_MISUSE_BKPT;
|
| + }
|
| + pTab = pCtx->pTab;
|
| + assert( (pTab->tabFlags & TF_Virtual)!=0 );
|
| +
|
| + pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
|
| + if( pParse==0 ){
|
| + rc = SQLITE_NOMEM;
|
| + }else{
|
| + pParse->declareVtab = 1;
|
| + pParse->db = db;
|
| + pParse->nQueryLoop = 1;
|
| +
|
| + if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
|
| + && pParse->pNewTable
|
| + && !db->mallocFailed
|
| + && !pParse->pNewTable->pSelect
|
| + && (pParse->pNewTable->tabFlags & TF_Virtual)==0
|
| + ){
|
| + if( !pTab->aCol ){
|
| + pTab->aCol = pParse->pNewTable->aCol;
|
| + pTab->nCol = pParse->pNewTable->nCol;
|
| + pParse->pNewTable->nCol = 0;
|
| + pParse->pNewTable->aCol = 0;
|
| + }
|
| + pCtx->bDeclared = 1;
|
| + }else{
|
| + sqlite3ErrorWithMsg(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
|
| + sqlite3DbFree(db, zErr);
|
| + rc = SQLITE_ERROR;
|
| + }
|
| + pParse->declareVtab = 0;
|
| +
|
| + if( pParse->pVdbe ){
|
| + sqlite3VdbeFinalize(pParse->pVdbe);
|
| + }
|
| + sqlite3DeleteTable(db, pParse->pNewTable);
|
| + sqlite3ParserReset(pParse);
|
| + sqlite3StackFree(db, pParse);
|
| + }
|
| +
|
| + assert( (rc&0xff)==rc );
|
| + rc = sqlite3ApiExit(db, rc);
|
| + sqlite3_mutex_leave(db->mutex);
|
| + return rc;
|
| +}
|
| +
|
| +/*
|
| +** This function is invoked by the vdbe to call the xDestroy method
|
| +** of the virtual table named zTab in database iDb. This occurs
|
| +** when a DROP TABLE is mentioned.
|
| +**
|
| +** This call is a no-op if zTab is not a virtual table.
|
| +*/
|
| +SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
|
| + int rc = SQLITE_OK;
|
| + Table *pTab;
|
| +
|
| + pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
|
| + if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
|
| + VTable *p;
|
| + int (*xDestroy)(sqlite3_vtab *);
|
| + for(p=pTab->pVTable; p; p=p->pNext){
|
| + assert( p->pVtab );
|
| + if( p->pVtab->nRef>0 ){
|
| + return SQLITE_LOCKED;
|
| + }
|
| + }
|
| + p = vtabDisconnectAll(db, pTab);
|
| + xDestroy = p->pMod->pModule->xDestroy;
|
| + assert( xDestroy!=0 ); /* Checked before the virtual table is created */
|
| + rc = xDestroy(p->pVtab);
|
| + /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
|
| + if( rc==SQLITE_OK ){
|
| + assert( pTab->pVTable==p && p->pNext==0 );
|
| + p->pVtab = 0;
|
| + pTab->pVTable = 0;
|
| + sqlite3VtabUnlock(p);
|
| + }
|
| + }
|
| +
|
| + return rc;
|
| +}
|
| +
|
| +/*
|
| +** This function invokes either the xRollback or xCommit method
|
| +** of each of the virtual tables in the sqlite3.aVTrans array. The method
|
| +** called is identified by the second argument, "offset", which is
|
| +** the offset of the method to call in the sqlite3_module structure.
|
| +**
|
| +** The array is cleared after invoking the callbacks.
|
| +*/
|
| +static void callFinaliser(sqlite3 *db, int offset){
|
| + int i;
|
| + if( db->aVTrans ){
|
| + VTable **aVTrans = db->aVTrans;
|
| + db->aVTrans = 0;
|
| + for(i=0; i<db->nVTrans; i++){
|
| + VTable *pVTab = aVTrans[i];
|
| + sqlite3_vtab *p = pVTab->pVtab;
|
| + if( p ){
|
| + int (*x)(sqlite3_vtab *);
|
| + x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
|
| + if( x ) x(p);
|
| + }
|
| + pVTab->iSavepoint = 0;
|
| + sqlite3VtabUnlock(pVTab);
|
| + }
|
| + sqlite3DbFree(db, aVTrans);
|
| + db->nVTrans = 0;
|
| + }
|
| +}
|
| +
|
| +/*
|
| +** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
|
| +** array. Return the error code for the first error that occurs, or
|
| +** SQLITE_OK if all xSync operations are successful.
|
| +**
|
| +** If an error message is available, leave it in p->zErrMsg.
|
| +*/
|
| +SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
|
| + int i;
|
| + int rc = SQLITE_OK;
|
| + VTable **aVTrans = db->aVTrans;
|
| +
|
| + db->aVTrans = 0;
|
| + for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
|
| + int (*x)(sqlite3_vtab *);
|
| + sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
|
| + if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
|
| + rc = x(pVtab);
|
| + sqlite3VtabImportErrmsg(p, pVtab);
|
| + }
|
| + }
|
| + db->aVTrans = aVTrans;
|
| + return rc;
|
| +}
|
| +
|
| +/*
|
| +** Invoke the xRollback method of all virtual tables in the
|
| +** sqlite3.aVTrans array. Then clear the array itself.
|
| +*/
|
| +SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
|
| + callFinaliser(db, offsetof(sqlite3_module,xRollback));
|
| + return SQLITE_OK;
|
| +}
|
| +
|
| +/*
|
| +** Invoke the xCommit method of all virtual tables in the
|
| +** sqlite3.aVTrans array. Then clear the array itself.
|
| +*/
|
| +SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
|
| + callFinaliser(db, offsetof(sqlite3_module,xCommit));
|
| + return SQLITE_OK;
|
| +}
|
| +
|
| +/*
|
| +** If the virtual table pVtab supports the transaction interface
|
| +** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
|
| +** not currently open, invoke the xBegin method now.
|
| +**
|
| +** If the xBegin call is successful, place the sqlite3_vtab pointer
|
| +** in the sqlite3.aVTrans array.
|
| +*/
|
| +SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
|
| + int rc = SQLITE_OK;
|
| + const sqlite3_module *pModule;
|
| +
|
| + /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
|
| + ** than zero, then this function is being called from within a
|
| + ** virtual module xSync() callback. It is illegal to write to
|
| + ** virtual module tables in this case, so return SQLITE_LOCKED.
|
| + */
|
| + if( sqlite3VtabInSync(db) ){
|
| + return SQLITE_LOCKED;
|
| + }
|
| + if( !pVTab ){
|
| + return SQLITE_OK;
|
| + }
|
| + pModule = pVTab->pVtab->pModule;
|
| +
|
| + if( pModule->xBegin ){
|
| + int i;
|
| +
|
| + /* If pVtab is already in the aVTrans array, return early */
|
| + for(i=0; i<db->nVTrans; i++){
|
| + if( db->aVTrans[i]==pVTab ){
|
| + return SQLITE_OK;
|
| + }
|
| + }
|
| +
|
| + /* Invoke the xBegin method. If successful, add the vtab to the
|
| + ** sqlite3.aVTrans[] array. */
|
| + rc = growVTrans(db);
|
| + if( rc==SQLITE_OK ){
|
| + rc = pModule->xBegin(pVTab->pVtab);
|
| + if( rc==SQLITE_OK ){
|
| + int iSvpt = db->nStatement + db->nSavepoint;
|
| + addToVTrans(db, pVTab);
|
| + if( iSvpt ) rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, iSvpt-1);
|
| + }
|
| + }
|
| + }
|
| + return rc;
|
| +}
|
| +
|
| +/*
|
| +** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
|
| +** virtual tables that currently have an open transaction. Pass iSavepoint
|
| +** as the second argument to the virtual table method invoked.
|
| +**
|
| +** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
|
| +** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
|
| +** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
|
| +** an open transaction is invoked.
|
| +**
|
| +** If any virtual table method returns an error code other than SQLITE_OK,
|
| +** processing is abandoned and the error returned to the caller of this
|
| +** function immediately. If all calls to virtual table methods are successful,
|
| +** SQLITE_OK is returned.
|
| +*/
|
| +SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
|
| + int rc = SQLITE_OK;
|
| +
|
| + assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
|
| + assert( iSavepoint>=-1 );
|
| + if( db->aVTrans ){
|
| + int i;
|
| + for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
|
| + VTable *pVTab = db->aVTrans[i];
|
| + const sqlite3_module *pMod = pVTab->pMod->pModule;
|
| + if( pVTab->pVtab && pMod->iVersion>=2 ){
|
| + int (*xMethod)(sqlite3_vtab *, int);
|
| + switch( op ){
|
| + case SAVEPOINT_BEGIN:
|
| + xMethod = pMod->xSavepoint;
|
| + pVTab->iSavepoint = iSavepoint+1;
|
| + break;
|
| + case SAVEPOINT_ROLLBACK:
|
| + xMethod = pMod->xRollbackTo;
|
| + break;
|
| + default:
|
| + xMethod = pMod->xRelease;
|
| + break;
|
| + }
|
| + if( xMethod && pVTab->iSavepoint>iSavepoint ){
|
| + rc = xMethod(pVTab->pVtab, iSavepoint);
|
| + }
|
| + }
|
| + }
|
| + }
|
| + return rc;
|
| +}
|
| +
|
| +/*
|
| +** The first parameter (pDef) is a function implementation. The
|
| +** second parameter (pExpr) is the first argument to this function.
|
| +** If pExpr is a column in a virtual table, then let the virtual
|
| +** table implementation have an opportunity to overload the function.
|
| +**
|
| +** This routine is used to allow virtual table implementations to
|
| +** overload MATCH, LIKE, GLOB, and REGEXP operators.
|
| +**
|
| +** Return either the pDef argument (indicating no change) or a
|
| +** new FuncDef structure that is marked as ephemeral using the
|
| +** SQLITE_FUNC_EPHEM flag.
|
| +*/
|
| +SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
|
| + sqlite3 *db, /* Database connection for reporting malloc problems */
|
| + FuncDef *pDef, /* Function to possibly overload */
|
| + int nArg, /* Number of arguments to the function */
|
| + Expr *pExpr /* First argument to the function */
|
| +){
|
| + Table *pTab;
|
| + sqlite3_vtab *pVtab;
|
| + sqlite3_module *pMod;
|
| + void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
|
| + void *pArg = 0;
|
| + FuncDef *pNew;
|
| + int rc = 0;
|
| + char *zLowerName;
|
| + unsigned char *z;
|
| +
|
| +
|
| + /* Check to see the left operand is a column in a virtual table */
|
| + if( NEVER(pExpr==0) ) return pDef;
|
| + if( pExpr->op!=TK_COLUMN ) return pDef;
|
| + pTab = pExpr->pTab;
|
| + if( NEVER(pTab==0) ) return pDef;
|
| + if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
|
| + pVtab = sqlite3GetVTable(db, pTab)->pVtab;
|
| + assert( pVtab!=0 );
|
| + assert( pVtab->pModule!=0 );
|
| + pMod = (sqlite3_module *)pVtab->pModule;
|
| + if( pMod->xFindFunction==0 ) return pDef;
|
| +
|
| + /* Call the xFindFunction method on the virtual table implementation
|
| + ** to see if the implementation wants to overload this function
|
| + */
|
| + zLowerName = sqlite3DbStrDup(db, pDef->zName);
|
| + if( zLowerName ){
|
| + for(z=(unsigned char*)zLowerName; *z; z++){
|
| + *z = sqlite3UpperToLower[*z];
|
| + }
|
| + rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
|
| + sqlite3DbFree(db, zLowerName);
|
| + }
|
| + if( rc==0 ){
|
| + return pDef;
|
| + }
|
| +
|
| + /* Create a new ephemeral function definition for the overloaded
|
| + ** function */
|
| + pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
|
| + + sqlite3Strlen30(pDef->zName) + 1);
|
| + if( pNew==0 ){
|
| + return pDef;
|
| + }
|
| + *pNew = *pDef;
|
| + pNew->zName = (char *)&pNew[1];
|
| + memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
|
| + pNew->xFunc = xFunc;
|
| + pNew->pUserData = pArg;
|
| + pNew->funcFlags |= SQLITE_FUNC_EPHEM;
|
| + return pNew;
|
| +}
|
| +
|
| +/*
|
| +** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
|
| +** array so that an OP_VBegin will get generated for it. Add pTab to the
|
| +** array if it is missing. If pTab is already in the array, this routine
|
| +** is a no-op.
|
| +*/
|
| +SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
|
| + Parse *pToplevel = sqlite3ParseToplevel(pParse);
|
| + int i, n;
|
| + Table **apVtabLock;
|
| +
|
| + assert( IsVirtual(pTab) );
|
| + for(i=0; i<pToplevel->nVtabLock; i++){
|
| + if( pTab==pToplevel->apVtabLock[i] ) return;
|
| + }
|
| + n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
|
| + apVtabLock = sqlite3_realloc64(pToplevel->apVtabLock, n);
|
| + if( apVtabLock ){
|
| + pToplevel->apVtabLock = apVtabLock;
|
| + pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
|
| + }else{
|
| + pToplevel->db->mallocFailed = 1;
|
| + }
|
| +}
|
| +
|
| +/*
|
| +** Check to see if virtual tale module pMod can be have an eponymous
|
| +** virtual table instance. If it can, create one if one does not already
|
| +** exist. Return non-zero if the eponymous virtual table instance exists
|
| +** when this routine returns, and return zero if it does not exist.
|
| +**
|
| +** An eponymous virtual table instance is one that is named after its
|
| +** module, and more importantly, does not require a CREATE VIRTUAL TABLE
|
| +** statement in order to come into existance. Eponymous virtual table
|
| +** instances always exist. They cannot be DROP-ed.
|
| +**
|
| +** Any virtual table module for which xConnect and xCreate are the same
|
| +** method can have an eponymous virtual table instance.
|
| +*/
|
| +SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse *pParse, Module *pMod){
|
| + const sqlite3_module *pModule = pMod->pModule;
|
| + Table *pTab;
|
| + char *zErr = 0;
|
| + int nName;
|
| + int rc;
|
| + sqlite3 *db = pParse->db;
|
| + if( pMod->pEpoTab ) return 1;
|
| + if( pModule->xCreate!=0 && pModule->xCreate!=pModule->xConnect ) return 0;
|
| + nName = sqlite3Strlen30(pMod->zName) + 1;
|
| + pTab = sqlite3DbMallocZero(db, sizeof(Table) + nName);
|
| + if( pTab==0 ) return 0;
|
| + pMod->pEpoTab = pTab;
|
| + pTab->zName = (char*)&pTab[1];
|
| + memcpy(pTab->zName, pMod->zName, nName);
|
| + pTab->nRef = 1;
|
| + pTab->pSchema = db->aDb[0].pSchema;
|
| + pTab->tabFlags |= TF_Virtual;
|
| + pTab->nModuleArg = 0;
|
| + pTab->iPKey = -1;
|
| + addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
|
| + addModuleArgument(db, pTab, 0);
|
| + addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
|
| + rc = vtabCallConstructor(db, pTab, pMod, pModule->xConnect, &zErr);
|
| + if( rc ){
|
| + sqlite3ErrorMsg(pParse, "%s", zErr);
|
| + sqlite3DbFree(db, zErr);
|
| + sqlite3VtabEponymousTableClear(db, pMod);
|
| + return 0;
|
| + }
|
| + return 1;
|
| +}
|
| +
|
| +/*
|
| +** Erase the eponymous virtual table instance associated with
|
| +** virtual table module pMod, if it exists.
|
| +*/
|
| +SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3 *db, Module *pMod){
|
| + Table *pTab = pMod->pEpoTab;
|
| + if( pTab!=0 ){
|
| + sqlite3DeleteColumnNames(db, pTab);
|
| + sqlite3VtabClear(db, pTab);
|
| + sqlite3DbFree(db, pTab);
|
| + pMod->pEpoTab = 0;
|
| + }
|
| +}
|
| +
|
| +/*
|
| +** Return the ON CONFLICT resolution mode in effect for the virtual
|
| +** table update operation currently in progress.
|
| +**
|
| +** The results of this routine are undefined unless it is called from
|
| +** within an xUpdate method.
|
| +*/
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_vtab_on_conflict(sqlite3 *db){
|
| + static const unsigned char aMap[] = {
|
| + SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
|
| + };
|
| +#ifdef SQLITE_ENABLE_API_ARMOR
|
| + if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
|
| +#endif
|
| + assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
|
| + assert( OE_Ignore==4 && OE_Replace==5 );
|
| + assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
|
| + return (int)aMap[db->vtabOnConflict-1];
|
| +}
|
| +
|
| +/*
|
| +** Call from within the xCreate() or xConnect() methods to provide
|
| +** the SQLite core with additional information about the behavior
|
| +** of the virtual table being implemented.
|
| +*/
|
| +SQLITE_API int SQLITE_CDECL sqlite3_vtab_config(sqlite3 *db, int op, ...){
|
| + va_list ap;
|
| + int rc = SQLITE_OK;
|
| +
|
| +#ifdef SQLITE_ENABLE_API_ARMOR
|
| + if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
|
| +#endif
|
| + sqlite3_mutex_enter(db->mutex);
|
| + va_start(ap, op);
|
| + switch( op ){
|
| + case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
|
| + VtabCtx *p = db->pVtabCtx;
|
| + if( !p ){
|
| + rc = SQLITE_MISUSE_BKPT;
|
| + }else{
|
| + assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
|
| + p->pVTable->bConstraint = (u8)va_arg(ap, int);
|
| + }
|
| + break;
|
| + }
|
| + default:
|
| + rc = SQLITE_MISUSE_BKPT;
|
| + break;
|
| + }
|
| + va_end(ap);
|
| +
|
| + if( rc!=SQLITE_OK ) sqlite3Error(db, rc);
|
| + sqlite3_mutex_leave(db->mutex);
|
| + return rc;
|
| +}
|
| +
|
| +#endif /* SQLITE_OMIT_VIRTUALTABLE */
|
| +
|
| +/************** End of vtab.c ************************************************/
|
| +/************** Begin file wherecode.c ***************************************/
|
| +/*
|
| +** 2015-06-06
|
| +**
|
| +** The author disclaims copyright to this source code. In place of
|
| +** a legal notice, here is a blessing:
|
| +**
|
| +** May you do good and not evil.
|
| +** May you find forgiveness for yourself and forgive others.
|
| +** May you share freely, never taking more than you give.
|
| +**
|
| +*************************************************************************
|
| +** This module contains C code that generates VDBE code used to process
|
| +** the WHERE clause of SQL statements.
|
| +**
|
| +** This file was split off from where.c on 2015-06-06 in order to reduce the
|
| +** size of where.c and make it easier to edit. This file contains the routines
|
| +** that actually generate the bulk of the WHERE loop code. The original where.c
|
| +** file retains the code that does query planning and analysis.
|
| +*/
|
| +/* #include "sqliteInt.h" */
|
| +/************** Include whereInt.h in the middle of wherecode.c **************/
|
| +/************** Begin file whereInt.h ****************************************/
|
| +/*
|
| +** 2013-11-12
|
| +**
|
| +** The author disclaims copyright to this source code. In place of
|
| +** a legal notice, here is a blessing:
|
| +**
|
| +** May you do good and not evil.
|
| +** May you find forgiveness for yourself and forgive others.
|
| +** May you share freely, never taking more than you give.
|
| +**
|
| +*************************************************************************
|
| +**
|
| +** This file contains structure and macro definitions for the query
|
| +** planner logic in "where.c". These definitions are broken out into
|
| +** a separate source file for easier editing.
|
| +*/
|
| +
|
| +/*
|
| +** Trace output macros
|
| +*/
|
| +#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
|
| +/***/ int sqlite3WhereTrace;
|
| +#endif
|
| +#if defined(SQLITE_DEBUG) \
|
| + && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
|
| +# define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
|
| +# define WHERETRACE_ENABLED 1
|
| +#else
|
| +# define WHERETRACE(K,X)
|
| +#endif
|
| +
|
| +/* Forward references
|
| +*/
|
| +typedef struct WhereClause WhereClause;
|
| +typedef struct WhereMaskSet WhereMaskSet;
|
| +typedef struct WhereOrInfo WhereOrInfo;
|
| +typedef struct WhereAndInfo WhereAndInfo;
|
| +typedef struct WhereLevel WhereLevel;
|
| +typedef struct WhereLoop WhereLoop;
|
| +typedef struct WherePath WherePath;
|
| +typedef struct WhereTerm WhereTerm;
|
| +typedef struct WhereLoopBuilder WhereLoopBuilder;
|
| +typedef struct WhereScan WhereScan;
|
| +typedef struct WhereOrCost WhereOrCost;
|
| +typedef struct WhereOrSet WhereOrSet;
|
| +
|
| +/*
|
| +** This object contains information needed to implement a single nested
|
| +** loop in WHERE clause.
|
| +**
|
| +** Contrast this object with WhereLoop. This object describes the
|
| +** implementation of the loop. WhereLoop describes the algorithm.
|
| +** This object contains a pointer to the WhereLoop algorithm as one of
|
| +** its elements.
|
| +**
|
| +** The WhereInfo object contains a single instance of this object for
|
| +** each term in the FROM clause (which is to say, for each of the
|
| +** nested loops as implemented). The order of WhereLevel objects determines
|
| +** the loop nested order, with WhereInfo.a[0] being the outer loop and
|
| +** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
|
| +*/
|
| +struct WhereLevel {
|
| + int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
|
| + int iTabCur; /* The VDBE cursor used to access the table */
|
| + int iIdxCur; /* The VDBE cursor used to access pIdx */
|
| + int addrBrk; /* Jump here to break out of the loop */
|
| + int addrNxt; /* Jump here to start the next IN combination */
|
| + int addrSkip; /* Jump here for next iteration of skip-scan */
|
| + int addrCont; /* Jump here to continue with the next loop cycle */
|
| + int addrFirst; /* First instruction of interior of the loop */
|
| + int addrBody; /* Beginning of the body of this loop */
|
| +#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
|
| + int iLikeRepCntr; /* LIKE range processing counter register */
|
| + int addrLikeRep; /* LIKE range processing address */
|
| +#endif
|
| + u8 iFrom; /* Which entry in the FROM clause */
|
| + u8 op, p3, p5; /* Opcode, P3 & P5 of the opcode that ends the loop */
|
| + int p1, p2; /* Operands of the opcode used to ends the loop */
|
| + union { /* Information that depends on pWLoop->wsFlags */
|
| + struct {
|
| + int nIn; /* Number of entries in aInLoop[] */
|
| + struct InLoop {
|
| + int iCur; /* The VDBE cursor used by this IN operator */
|
| + int addrInTop; /* Top of the IN loop */
|
| + u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
|
| + } *aInLoop; /* Information about each nested IN operator */
|
| + } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
|
| + Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */
|
| + } u;
|
| + struct WhereLoop *pWLoop; /* The selected WhereLoop object */
|
| + Bitmask notReady; /* FROM entries not usable at this level */
|
| +#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
|
| + int addrVisit; /* Address at which row is visited */
|
| +#endif
|
| +};
|
| +
|
| +/*
|
| +** Each instance of this object represents an algorithm for evaluating one
|
| +** term of a join. Every term of the FROM clause will have at least
|
| +** one corresponding WhereLoop object (unless INDEXED BY constraints
|
| +** prevent a query solution - which is an error) and many terms of the
|
| +** FROM clause will have multiple WhereLoop objects, each describing a
|
| +** potential way of implementing that FROM-clause term, together with
|
| +** dependencies and cost estimates for using the chosen algorithm.
|
| +**
|
| +** Query planning consists of building up a collection of these WhereLoop
|
| +** objects, then computing a particular sequence of WhereLoop objects, with
|
| +** one WhereLoop object per FROM clause term, that satisfy all dependencies
|
| +** and that minimize the overall cost.
|
| +*/
|
| +struct WhereLoop {
|
| + Bitmask prereq; /* Bitmask of other loops that must run first */
|
| + Bitmask maskSelf; /* Bitmask identifying table iTab */
|
| +#ifdef SQLITE_DEBUG
|
| + char cId; /* Symbolic ID of this loop for debugging use */
|
| +#endif
|
| + u8 iTab; /* Position in FROM clause of table for this loop */
|
| + u8 iSortIdx; /* Sorting index number. 0==None */
|
| + LogEst rSetup; /* One-time setup cost (ex: create transient index) */
|
| + LogEst rRun; /* Cost of running each loop */
|
| + LogEst nOut; /* Estimated number of output rows */
|
| + union {
|
| + struct { /* Information for internal btree tables */
|
| + u16 nEq; /* Number of equality constraints */
|
| + Index *pIndex; /* Index used, or NULL */
|
| + } btree;
|
| + struct { /* Information for virtual tables */
|
| + int idxNum; /* Index number */
|
| + u8 needFree; /* True if sqlite3_free(idxStr) is needed */
|
| + i8 isOrdered; /* True if satisfies ORDER BY */
|
| + u16 omitMask; /* Terms that may be omitted */
|
| + char *idxStr; /* Index identifier string */
|
| + } vtab;
|
| + } u;
|
| + u32 wsFlags; /* WHERE_* flags describing the plan */
|
| + u16 nLTerm; /* Number of entries in aLTerm[] */
|
| + u16 nSkip; /* Number of NULL aLTerm[] entries */
|
| + /**** whereLoopXfer() copies fields above ***********************/
|
| +# define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
|
| + u16 nLSlot; /* Number of slots allocated for aLTerm[] */
|
| + WhereTerm **aLTerm; /* WhereTerms used */
|
| + WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
|
| + WhereTerm *aLTermSpace[3]; /* Initial aLTerm[] space */
|
| +};
|
| +
|
| +/* This object holds the prerequisites and the cost of running a
|
| +** subquery on one operand of an OR operator in the WHERE clause.
|
| +** See WhereOrSet for additional information
|
| +*/
|
| +struct WhereOrCost {
|
| + Bitmask prereq; /* Prerequisites */
|
| + LogEst rRun; /* Cost of running this subquery */
|
| + LogEst nOut; /* Number of outputs for this subquery */
|
| +};
|
| +
|
| +/* The WhereOrSet object holds a set of possible WhereOrCosts that
|
| +** correspond to the subquery(s) of OR-clause processing. Only the
|
| +** best N_OR_COST elements are retained.
|
| +*/
|
| +#define N_OR_COST 3
|
| +struct WhereOrSet {
|
| + u16 n; /* Number of valid a[] entries */
|
| + WhereOrCost a[N_OR_COST]; /* Set of best costs */
|
| +};
|
| +
|
| +/*
|
| +** Each instance of this object holds a sequence of WhereLoop objects
|
| +** that implement some or all of a query plan.
|
| +**
|
| +** Think of each WhereLoop object as a node in a graph with arcs
|
| +** showing dependencies and costs for travelling between nodes. (That is
|
| +** not a completely accurate description because WhereLoop costs are a
|
| +** vector, not a scalar, and because dependencies are many-to-one, not
|
| +** one-to-one as are graph nodes. But it is a useful visualization aid.)
|
| +** Then a WherePath object is a path through the graph that visits some
|
| +** or all of the WhereLoop objects once.
|
| +**
|
| +** The "solver" works by creating the N best WherePath objects of length
|
| +** 1. Then using those as a basis to compute the N best WherePath objects
|
| +** of length 2. And so forth until the length of WherePaths equals the
|
| +** number of nodes in the FROM clause. The best (lowest cost) WherePath
|
| +** at the end is the chosen query plan.
|
| +*/
|
| +struct WherePath {
|
| + Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */
|
| + Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */
|
| + LogEst nRow; /* Estimated number of rows generated by this path */
|
| + LogEst rCost; /* Total cost of this path */
|
| + LogEst rUnsorted; /* Total cost of this path ignoring sorting costs */
|
| + i8 isOrdered; /* No. of ORDER BY terms satisfied. -1 for unknown */
|
| + WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */
|
| +};
|
| +
|
| +/*
|
| +** The query generator uses an array of instances of this structure to
|
| +** help it analyze the subexpressions of the WHERE clause. Each WHERE
|
| +** clause subexpression is separated from the others by AND operators,
|
| +** usually, or sometimes subexpressions separated by OR.
|
| +**
|
| +** All WhereTerms are collected into a single WhereClause structure.
|
| +** The following identity holds:
|
| +**
|
| +** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
|
| +**
|
| +** When a term is of the form:
|
| +**
|
| +** X <op> <expr>
|
| +**
|
| +** where X is a column name and <op> is one of certain operators,
|
| +** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
|
| +** cursor number and column number for X. WhereTerm.eOperator records
|
| +** the <op> using a bitmask encoding defined by WO_xxx below. The
|
| +** use of a bitmask encoding for the operator allows us to search
|
| +** quickly for terms that match any of several different operators.
|
| +**
|
| +** A WhereTerm might also be two or more subterms connected by OR:
|
| +**
|
| +** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
|
| +**
|
| +** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
|
| +** and the WhereTerm.u.pOrInfo field points to auxiliary information that
|
| +** is collected about the OR clause.
|
| +**
|
| +** If a term in the WHERE clause does not match either of the two previous
|
| +** categories, then eOperator==0. The WhereTerm.pExpr field is still set
|
| +** to the original subexpression content and wtFlags is set up appropriately
|
| +** but no other fields in the WhereTerm object are meaningful.
|
| +**
|
| +** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
|
| +** but they do so indirectly. A single WhereMaskSet structure translates
|
| +** cursor number into bits and the translated bit is stored in the prereq
|
| +** fields. The translation is used in order to maximize the number of
|
| +** bits that will fit in a Bitmask. The VDBE cursor numbers might be
|
| +** spread out over the non-negative integers. For example, the cursor
|
| +** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
|
| +** translates these sparse cursor numbers into consecutive integers
|
| +** beginning with 0 in order to make the best possible use of the available
|
| +** bits in the Bitmask. So, in the example above, the cursor numbers
|
| +** would be mapped into integers 0 through 7.
|
| +**
|
| +** The number of terms in a join is limited by the number of bits
|
| +** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
|
| +** is only able to process joins with 64 or fewer tables.
|
| +*/
|
| +struct WhereTerm {
|
| + Expr *pExpr; /* Pointer to the subexpression that is this term */
|
| + int iParent; /* Disable pWC->a[iParent] when this term disabled */
|
| + int leftCursor; /* Cursor number of X in "X <op> <expr>" */
|
| + union {
|
| + int leftColumn; /* Column number of X in "X <op> <expr>" */
|
| + WhereOrInfo *pOrInfo; /* Extra information if (eOperator & WO_OR)!=0 */
|
| + WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
|
| + } u;
|
| + LogEst truthProb; /* Probability of truth for this expression */
|
| + u16 eOperator; /* A WO_xx value describing <op> */
|
| + u16 wtFlags; /* TERM_xxx bit flags. See below */
|
| + u8 nChild; /* Number of children that must disable us */
|
| + u8 eMatchOp; /* Op for vtab MATCH/LIKE/GLOB/REGEXP terms */
|
| + WhereClause *pWC; /* The clause this term is part of */
|
| + Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
|
| + Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
|
| +};
|
| +
|
| +/*
|
| +** Allowed values of WhereTerm.wtFlags
|
| +*/
|
| +#define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */
|
| +#define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
|
| +#define TERM_CODED 0x04 /* This term is already coded */
|
| +#define TERM_COPIED 0x08 /* Has a child */
|
| +#define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
|
| +#define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
|
| +#define TERM_OR_OK 0x40 /* Used during OR-clause processing */
|
| +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
|
| +# define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
|
| +#else
|
| +# define TERM_VNULL 0x00 /* Disabled if not using stat3 */
|
| +#endif
|
| +#define TERM_LIKEOPT 0x100 /* Virtual terms from the LIKE optimization */
|
| +#define TERM_LIKECOND 0x200 /* Conditionally this LIKE operator term */
|
| +#define TERM_LIKE 0x400 /* The original LIKE operator */
|
| +#define TERM_IS 0x800 /* Term.pExpr is an IS operator */
|
| +
|
| +/*
|
| +** An instance of the WhereScan object is used as an iterator for locating
|
| +** terms in the WHERE clause that are useful to the query planner.
|
| +*/
|
| +struct WhereScan {
|
| + WhereClause *pOrigWC; /* Original, innermost WhereClause */
|
| + WhereClause *pWC; /* WhereClause currently being scanned */
|
| + const char *zCollName; /* Required collating sequence, if not NULL */
|
| + Expr *pIdxExpr; /* Search for this index expression */
|
| + char idxaff; /* Must match this affinity, if zCollName!=NULL */
|
| + unsigned char nEquiv; /* Number of entries in aEquiv[] */
|
| + unsigned char iEquiv; /* Next unused slot in aEquiv[] */
|
| + u32 opMask; /* Acceptable operators */
|
| + int k; /* Resume scanning at this->pWC->a[this->k] */
|
| + int aiCur[11]; /* Cursors in the equivalence class */
|
| + i16 aiColumn[11]; /* Corresponding column number in the eq-class */
|
| +};
|
| +
|
| +/*
|
| +** An instance of the following structure holds all information about a
|
| +** WHERE clause. Mostly this is a container for one or more WhereTerms.
|
| +**
|
| +** Explanation of pOuter: For a WHERE clause of the form
|
| +**
|
| +** a AND ((b AND c) OR (d AND e)) AND f
|
| +**
|
| +** There are separate WhereClause objects for the whole clause and for
|
| +** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the
|
| +** subclauses points to the WhereClause object for the whole clause.
|
| +*/
|
| +struct WhereClause {
|
| + WhereInfo *pWInfo; /* WHERE clause processing context */
|
| + WhereClause *pOuter; /* Outer conjunction */
|
| + u8 op; /* Split operator. TK_AND or TK_OR */
|
| + int nTerm; /* Number of terms */
|
| + int nSlot; /* Number of entries in a[] */
|
| + WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
|
| +#if defined(SQLITE_SMALL_STACK)
|
| + WhereTerm aStatic[1]; /* Initial static space for a[] */
|
| +#else
|
| + WhereTerm aStatic[8]; /* Initial static space for a[] */
|
| +#endif
|
| +};
|
| +
|
| +/*
|
| +** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
|
| +** a dynamically allocated instance of the following structure.
|
| +*/
|
| +struct WhereOrInfo {
|
| + WhereClause wc; /* Decomposition into subterms */
|
| + Bitmask indexable; /* Bitmask of all indexable tables in the clause */
|
| +};
|
| +
|
| +/*
|
| +** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
|
| +** a dynamically allocated instance of the following structure.
|
| +*/
|
| +struct WhereAndInfo {
|
| + WhereClause wc; /* The subexpression broken out */
|
| +};
|
| +
|
| +/*
|
| +** An instance of the following structure keeps track of a mapping
|
| +** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
|
| +**
|
| +** The VDBE cursor numbers are small integers contained in
|
| +** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
|
| +** clause, the cursor numbers might not begin with 0 and they might
|
| +** contain gaps in the numbering sequence. But we want to make maximum
|
| +** use of the bits in our bitmasks. This structure provides a mapping
|
| +** from the sparse cursor numbers into consecutive integers beginning
|
| +** with 0.
|
| +**
|
| +** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
|
| +** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
|
| +**
|
| +** For example, if the WHERE clause expression used these VDBE
|
| +** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
|
| +** would map those cursor numbers into bits 0 through 5.
|
| +**
|
| +** Note that the mapping is not necessarily ordered. In the example
|
| +** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
|
| +** 57->5, 73->4. Or one of 719 other combinations might be used. It
|
| +** does not really matter. What is important is that sparse cursor
|
| +** numbers all get mapped into bit numbers that begin with 0 and contain
|
| +** no gaps.
|
| +*/
|
| +struct WhereMaskSet {
|
| + int n; /* Number of assigned cursor values */
|
| + int ix[BMS]; /* Cursor assigned to each bit */
|
| +};
|
| +
|
| +/*
|
| +** Initialize a WhereMaskSet object
|
| +*/
|
| +#define initMaskSet(P) (P)->n=0
|
| +
|
| +/*
|
| +** This object is a convenience wrapper holding all information needed
|
| +** to construct WhereLoop objects for a particular query.
|
| +*/
|
| +struct WhereLoopBuilder {
|
| + WhereInfo *pWInfo; /* Information about this WHERE */
|
| + WhereClause *pWC; /* WHERE clause terms */
|
| + ExprList *pOrderBy; /* ORDER BY clause */
|
| + WhereLoop *pNew; /* Template WhereLoop */
|
| + WhereOrSet *pOrSet; /* Record best loops here, if not NULL */
|
| +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
|
| + UnpackedRecord *pRec; /* Probe for stat4 (if required) */
|
| + int nRecValid; /* Number of valid fields currently in pRec */
|
| +#endif
|
| +};
|
| +
|
| +/*
|
| +** The WHERE clause processing routine has two halves. The
|
| +** first part does the start of the WHERE loop and the second
|
| +** half does the tail of the WHERE loop. An instance of
|
| +** this structure is returned by the first half and passed
|
| +** into the second half to give some continuity.
|
| +**
|
| +** An instance of this object holds the complete state of the query
|
| +** planner.
|
| +*/
|
| +struct WhereInfo {
|
| + Parse *pParse; /* Parsing and code generating context */
|
| + SrcList *pTabList; /* List of tables in the join */
|
| + ExprList *pOrderBy; /* The ORDER BY clause or NULL */
|
| + ExprList *pResultSet; /* Result set. DISTINCT operates on these */
|
| + WhereLoop *pLoops; /* List of all WhereLoop objects */
|
| + Bitmask revMask; /* Mask of ORDER BY terms that need reversing */
|
| + LogEst nRowOut; /* Estimated number of output rows */
|
| + u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
|
| + i8 nOBSat; /* Number of ORDER BY terms satisfied by indices */
|
| + u8 sorted; /* True if really sorted (not just grouped) */
|
| + u8 eOnePass; /* ONEPASS_OFF, or _SINGLE, or _MULTI */
|
| + u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
|
| + u8 eDistinct; /* One of the WHERE_DISTINCT_* values below */
|
| + u8 nLevel; /* Number of nested loop */
|
| + int iTop; /* The very beginning of the WHERE loop */
|
| + int iContinue; /* Jump here to continue with next record */
|
| + int iBreak; /* Jump here to break out of the loop */
|
| + int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
|
| + int aiCurOnePass[2]; /* OP_OpenWrite cursors for the ONEPASS opt */
|
| + WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */
|
| + WhereClause sWC; /* Decomposition of the WHERE clause */
|
| + WhereLevel a[1]; /* Information about each nest loop in WHERE */
|
| +};
|
| +
|
| +/*
|
| +** Private interfaces - callable only by other where.c routines.
|
| +**
|
| +** where.c:
|
| +*/
|
| +SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet*,int);
|
| +SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
|
| + WhereClause *pWC, /* The WHERE clause to be searched */
|
| + int iCur, /* Cursor number of LHS */
|
| + int iColumn, /* Column number of LHS */
|
| + Bitmask notReady, /* RHS must not overlap with this mask */
|
| + u32 op, /* Mask of WO_xx values describing operator */
|
| + Index *pIdx /* Must be compatible with this index, if not NULL */
|
| +);
|
| +
|
| +/* wherecode.c: */
|
| +#ifndef SQLITE_OMIT_EXPLAIN
|
| +SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
|
| + Parse *pParse, /* Parse context */
|
| + SrcList *pTabList, /* Table list this loop refers to */
|
| + WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
|
| + int iLevel, /* Value for "level" column of output */
|
| + int iFrom, /* Value for "from" column of output */
|
| + u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
|
| +);
|
| +#else
|
| +# define sqlite3WhereExplainOneScan(u,v,w,x,y,z) 0
|
| +#endif /* SQLITE_OMIT_EXPLAIN */
|
| +#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
|
| +SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
|
| + Vdbe *v, /* Vdbe to add scanstatus entry to */
|
| + SrcList *pSrclist, /* FROM clause pLvl reads data from */
|
| + WhereLevel *pLvl, /* Level to add scanstatus() entry for */
|
| + int addrExplain /* Address of OP_Explain (or 0) */
|
| +);
|
| +#else
|
| +# define sqlite3WhereAddScanStatus(a, b, c, d) ((void)d)
|
| +#endif
|
| +SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
|
| + WhereInfo *pWInfo, /* Complete information about the WHERE clause */
|
| + int iLevel, /* Which level of pWInfo->a[] should be coded */
|
| + Bitmask notReady /* Which tables are currently available */
|
| +);
|
| +
|
| +/* whereexpr.c: */
|
| +SQLITE_PRIVATE void sqlite3WhereClauseInit(WhereClause*,WhereInfo*);
|
| +SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause*);
|
| +SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause*,Expr*,u8);
|
| +SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet*, Expr*);
|
| +SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet*, ExprList*);
|
| +SQLITE_PRIVATE void sqlite3WhereExprAnalyze(SrcList*, WhereClause*);
|
| +SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, struct SrcList_item*, WhereClause*);
|
| +
|
| +
|
| +
|
| +
|
| +
|
| +/*
|
| +** Bitmasks for the operators on WhereTerm objects. These are all
|
| +** operators that are of interest to the query planner. An
|
| +** OR-ed combination of these values can be used when searching for
|
| +** particular WhereTerms within a WhereClause.
|
| +*/
|
| +#define WO_IN 0x0001
|
| +#define WO_EQ 0x0002
|
| +#define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
|
| +#define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
|
| +#define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
|
| +#define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
|
| +#define WO_MATCH 0x0040
|
| +#define WO_IS 0x0080
|
| +#define WO_ISNULL 0x0100
|
| +#define WO_OR 0x0200 /* Two or more OR-connected terms */
|
| +#define WO_AND 0x0400 /* Two or more AND-connected terms */
|
| +#define WO_EQUIV 0x0800 /* Of the form A==B, both columns */
|
| +#define WO_NOOP 0x1000 /* This term does not restrict search space */
|
| +
|
| +#define WO_ALL 0x1fff /* Mask of all possible WO_* values */
|
| +#define WO_SINGLE 0x01ff /* Mask of all non-compound WO_* values */
|
| +
|
| +/*
|
| +** These are definitions of bits in the WhereLoop.wsFlags field.
|
| +** The particular combination of bits in each WhereLoop help to
|
| +** determine the algorithm that WhereLoop represents.
|
| +*/
|
| +#define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR */
|
| +#define WHERE_COLUMN_RANGE 0x00000002 /* x<EXPR and/or x>EXPR */
|
| +#define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */
|
| +#define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */
|
| +#define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */
|
| +#define WHERE_TOP_LIMIT 0x00000010 /* x<EXPR or x<=EXPR constraint */
|
| +#define WHERE_BTM_LIMIT 0x00000020 /* x>EXPR or x>=EXPR constraint */
|
| +#define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and x<EXPR */
|
| +#define WHERE_IDX_ONLY 0x00000040 /* Use index only - omit table */
|
| +#define WHERE_IPK 0x00000100 /* x is the INTEGER PRIMARY KEY */
|
| +#define WHERE_INDEXED 0x00000200 /* WhereLoop.u.btree.pIndex is valid */
|
| +#define WHERE_VIRTUALTABLE 0x00000400 /* WhereLoop.u.vtab is valid */
|
| +#define WHERE_IN_ABLE 0x00000800 /* Able to support an IN operator */
|
| +#define WHERE_ONEROW 0x00001000 /* Selects no more than one row */
|
| +#define WHERE_MULTI_OR 0x00002000 /* OR using multiple indices */
|
| +#define WHERE_AUTO_INDEX 0x00004000 /* Uses an ephemeral index */
|
| +#define WHERE_SKIPSCAN 0x00008000 /* Uses the skip-scan algorithm */
|
| +#define WHERE_UNQ_WANTED 0x00010000 /* WHERE_ONEROW would have been helpful*/
|
| +#define WHERE_PARTIALIDX 0x00020000 /* The automatic index is partial */
|
| +
|
| +/************** End of whereInt.h ********************************************/
|
| +/************** Continuing where we left off in wherecode.c ******************/
|
| +
|
| +#ifndef SQLITE_OMIT_EXPLAIN
|
| +/*
|
| +** This routine is a helper for explainIndexRange() below
|
| +**
|
| +** pStr holds the text of an expression that we are building up one term
|
| +** at a time. This routine adds a new term to the end of the expression.
|
| +** Terms are separated by AND so add the "AND" text for second and subsequent
|
| +** terms only.
|
| +*/
|
| +static void explainAppendTerm(
|
| + StrAccum *pStr, /* The text expression being built */
|
| + int iTerm, /* Index of this term. First is zero */
|
| + const char *zColumn, /* Name of the column */
|
| + const char *zOp /* Name of the operator */
|
| +){
|
| + if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
|
| + sqlite3StrAccumAppendAll(pStr, zColumn);
|
| + sqlite3StrAccumAppend(pStr, zOp, 1);
|
| + sqlite3StrAccumAppend(pStr, "?", 1);
|
| +}
|
| +
|
| +/*
|
| +** Return the name of the i-th column of the pIdx index.
|
| +*/
|
| +static const char *explainIndexColumnName(Index *pIdx, int i){
|
| + i = pIdx->aiColumn[i];
|
| + if( i==XN_EXPR ) return "<expr>";
|
| + if( i==XN_ROWID ) return "rowid";
|
| + return pIdx->pTable->aCol[i].zName;
|
| +}
|
| +
|
| +/*
|
| +** Argument pLevel describes a strategy for scanning table pTab. This
|
| +** function appends text to pStr that describes the subset of table
|
| +** rows scanned by the strategy in the form of an SQL expression.
|
| +**
|
| +** For example, if the query:
|
| +**
|
| +** SELECT * FROM t1 WHERE a=1 AND b>2;
|
| +**
|
| +** is run and there is an index on (a, b), then this function returns a
|
| +** string similar to:
|
| +**
|
| +** "a=? AND b>?"
|
| +*/
|
| +static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop){
|
| + Index *pIndex = pLoop->u.btree.pIndex;
|
| + u16 nEq = pLoop->u.btree.nEq;
|
| + u16 nSkip = pLoop->nSkip;
|
| + int i, j;
|
| +
|
| + if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
|
| + sqlite3StrAccumAppend(pStr, " (", 2);
|
| + for(i=0; i<nEq; i++){
|
| + const char *z = explainIndexColumnName(pIndex, i);
|
| + if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5);
|
| + sqlite3XPrintf(pStr, 0, i>=nSkip ? "%s=?" : "ANY(%s)", z);
|
| + }
|
| +
|
| + j = i;
|
| + if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
|
| + const char *z = explainIndexColumnName(pIndex, i);
|
| + explainAppendTerm(pStr, i++, z, ">");
|
| + }
|
| + if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
|
| + const char *z = explainIndexColumnName(pIndex, j);
|
| + explainAppendTerm(pStr, i, z, "<");
|
| + }
|
| + sqlite3StrAccumAppend(pStr, ")", 1);
|
| +}
|
| +
|
| +/*
|
| +** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
|
| +** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was
|
| +** defined at compile-time. If it is not a no-op, a single OP_Explain opcode
|
| +** is added to the output to describe the table scan strategy in pLevel.
|
| +**
|
| +** If an OP_Explain opcode is added to the VM, its address is returned.
|
| +** Otherwise, if no OP_Explain is coded, zero is returned.
|
| +*/
|
| +SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
|
| + Parse *pParse, /* Parse context */
|
| + SrcList *pTabList, /* Table list this loop refers to */
|
| + WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
|
| + int iLevel, /* Value for "level" column of output */
|
| + int iFrom, /* Value for "from" column of output */
|
| + u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
|
| +){
|
| + int ret = 0;
|
| +#if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
|
| + if( pParse->explain==2 )
|
| +#endif
|
| + {
|
| + struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
|
| + Vdbe *v = pParse->pVdbe; /* VM being constructed */
|
| + sqlite3 *db = pParse->db; /* Database handle */
|
| + int iId = pParse->iSelectId; /* Select id (left-most output column) */
|
| + int isSearch; /* True for a SEARCH. False for SCAN. */
|
| + WhereLoop *pLoop; /* The controlling WhereLoop object */
|
| + u32 flags; /* Flags that describe this loop */
|
| + char *zMsg; /* Text to add to EQP output */
|
| + StrAccum str; /* EQP output string */
|
| + char zBuf[100]; /* Initial space for EQP output string */
|
| +
|
| + pLoop = pLevel->pWLoop;
|
| + flags = pLoop->wsFlags;
|
| + if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return 0;
|
| +
|
| + isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
|
| + || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
|
| + || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
|
| +
|
| + sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
|
| + sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN");
|
| + if( pItem->pSelect ){
|
| + sqlite3XPrintf(&str, 0, " SUBQUERY %d", pItem->iSelectId);
|
| + }else{
|
| + sqlite3XPrintf(&str, 0, " TABLE %s", pItem->zName);
|
| + }
|
| +
|
| + if( pItem->zAlias ){
|
| + sqlite3XPrintf(&str, 0, " AS %s", pItem->zAlias);
|
| + }
|
| + if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
|
| + const char *zFmt = 0;
|
| + Index *pIdx;
|
| +
|
| + assert( pLoop->u.btree.pIndex!=0 );
|
| + pIdx = pLoop->u.btree.pIndex;
|
| + assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
|
| + if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
|
| + if( isSearch ){
|
| + zFmt = "PRIMARY KEY";
|
| + }
|
| + }else if( flags & WHERE_PARTIALIDX ){
|
| + zFmt = "AUTOMATIC PARTIAL COVERING INDEX";
|
| + }else if( flags & WHERE_AUTO_INDEX ){
|
| + zFmt = "AUTOMATIC COVERING INDEX";
|
| + }else if( flags & WHERE_IDX_ONLY ){
|
| + zFmt = "COVERING INDEX %s";
|
| + }else{
|
| + zFmt = "INDEX %s";
|
| + }
|
| + if( zFmt ){
|
| + sqlite3StrAccumAppend(&str, " USING ", 7);
|
| + sqlite3XPrintf(&str, 0, zFmt, pIdx->zName);
|
| + explainIndexRange(&str, pLoop);
|
| + }
|
| + }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
|
| + const char *zRangeOp;
|
| + if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
|
| + zRangeOp = "=";
|
| + }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
|
| + zRangeOp = ">? AND rowid<";
|
| + }else if( flags&WHERE_BTM_LIMIT ){
|
| + zRangeOp = ">";
|
| + }else{
|
| + assert( flags&WHERE_TOP_LIMIT);
|
| + zRangeOp = "<";
|
| + }
|
| + sqlite3XPrintf(&str, 0, " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp);
|
| + }
|
| +#ifndef SQLITE_OMIT_VIRTUALTABLE
|
| + else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
|
| + sqlite3XPrintf(&str, 0, " VIRTUAL TABLE INDEX %d:%s",
|
| + pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
|
| + }
|
| +#endif
|
| +#ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
|
| + if( pLoop->nOut>=10 ){
|
| + sqlite3XPrintf(&str, 0, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut));
|
| + }else{
|
| + sqlite3StrAccumAppend(&str, " (~1 row)", 9);
|
| + }
|
| +#endif
|
| + zMsg = sqlite3StrAccumFinish(&str);
|
| + ret = sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg,P4_DYNAMIC);
|
| + }
|
| + return ret;
|
| +}
|
| +#endif /* SQLITE_OMIT_EXPLAIN */
|
| +
|
| +#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
|
| +/*
|
| +** Configure the VM passed as the first argument with an
|
| +** sqlite3_stmt_scanstatus() entry corresponding to the scan used to
|
| +** implement level pLvl. Argument pSrclist is a pointer to the FROM
|
| +** clause that the scan reads data from.
|
| +**
|
| +** If argument addrExplain is not 0, it must be the address of an
|
| +** OP_Explain instruction that describes the same loop.
|
| +*/
|
| +SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
|
| + Vdbe *v, /* Vdbe to add scanstatus entry to */
|
| + SrcList *pSrclist, /* FROM clause pLvl reads data from */
|
| + WhereLevel *pLvl, /* Level to add scanstatus() entry for */
|
| + int addrExplain /* Address of OP_Explain (or 0) */
|
| +){
|
| + const char *zObj = 0;
|
| + WhereLoop *pLoop = pLvl->pWLoop;
|
| + if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 && pLoop->u.btree.pIndex!=0 ){
|
| + zObj = pLoop->u.btree.pIndex->zName;
|
| + }else{
|
| + zObj = pSrclist->a[pLvl->iFrom].zName;
|
| + }
|
| + sqlite3VdbeScanStatus(
|
| + v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj
|
| + );
|
| +}
|
| +#endif
|
| +
|
| +
|
| +/*
|
| +** Disable a term in the WHERE clause. Except, do not disable the term
|
| +** if it controls a LEFT OUTER JOIN and it did not originate in the ON
|
| +** or USING clause of that join.
|
| +**
|
| +** Consider the term t2.z='ok' in the following queries:
|
| +**
|
| +** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
|
| +** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
|
| +** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
|
| +**
|
| +** The t2.z='ok' is disabled in the in (2) because it originates
|
| +** in the ON clause. The term is disabled in (3) because it is not part
|
| +** of a LEFT OUTER JOIN. In (1), the term is not disabled.
|
| +**
|
| +** Disabling a term causes that term to not be tested in the inner loop
|
| +** of the join. Disabling is an optimization. When terms are satisfied
|
| +** by indices, we disable them to prevent redundant tests in the inner
|
| +** loop. We would get the correct results if nothing were ever disabled,
|
| +** but joins might run a little slower. The trick is to disable as much
|
| +** as we can without disabling too much. If we disabled in (1), we'd get
|
| +** the wrong answer. See ticket #813.
|
| +**
|
| +** If all the children of a term are disabled, then that term is also
|
| +** automatically disabled. In this way, terms get disabled if derived
|
| +** virtual terms are tested first. For example:
|
| +**
|
| +** x GLOB 'abc*' AND x>='abc' AND x<'acd'
|
| +** \___________/ \______/ \_____/
|
| +** parent child1 child2
|
| +**
|
| +** Only the parent term was in the original WHERE clause. The child1
|
| +** and child2 terms were added by the LIKE optimization. If both of
|
| +** the virtual child terms are valid, then testing of the parent can be
|
| +** skipped.
|
| +**
|
| +** Usually the parent term is marked as TERM_CODED. But if the parent
|
| +** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead.
|
| +** The TERM_LIKECOND marking indicates that the term should be coded inside
|
| +** a conditional such that is only evaluated on the second pass of a
|
| +** LIKE-optimization loop, when scanning BLOBs instead of strings.
|
| +*/
|
| +static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
|
| + int nLoop = 0;
|
| + while( pTerm
|
| + && (pTerm->wtFlags & TERM_CODED)==0
|
| + && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
|
| + && (pLevel->notReady & pTerm->prereqAll)==0
|
| + ){
|
| + if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){
|
| + pTerm->wtFlags |= TERM_LIKECOND;
|
| + }else{
|
| + pTerm->wtFlags |= TERM_CODED;
|
| + }
|
| + if( pTerm->iParent<0 ) break;
|
| + pTerm = &pTerm->pWC->a[pTerm->iParent];
|
| + pTerm->nChild--;
|
| + if( pTerm->nChild!=0 ) break;
|
| + nLoop++;
|
| + }
|
| +}
|
| +
|
| +/*
|
| +** Code an OP_Affinity opcode to apply the column affinity string zAff
|
| +** to the n registers starting at base.
|
| +**
|
| +** As an optimization, SQLITE_AFF_BLOB entries (which are no-ops) at the
|
| +** beginning and end of zAff are ignored. If all entries in zAff are
|
| +** SQLITE_AFF_BLOB, then no code gets generated.
|
| +**
|
| +** This routine makes its own copy of zAff so that the caller is free
|
| +** to modify zAff after this routine returns.
|
| +*/
|
| +static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
|
| + Vdbe *v = pParse->pVdbe;
|
| + if( zAff==0 ){
|
| + assert( pParse->db->mallocFailed );
|
| + return;
|
| + }
|
| + assert( v!=0 );
|
| +
|
| + /* Adjust base and n to skip over SQLITE_AFF_BLOB entries at the beginning
|
| + ** and end of the affinity string.
|
| + */
|
| + while( n>0 && zAff[0]==SQLITE_AFF_BLOB ){
|
| + n--;
|
| + base++;
|
| + zAff++;
|
| + }
|
| + while( n>1 && zAff[n-1]==SQLITE_AFF_BLOB ){
|
| + n--;
|
| + }
|
| +
|
| + /* Code the OP_Affinity opcode if there is anything left to do. */
|
| + if( n>0 ){
|
| + sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
|
| + sqlite3VdbeChangeP4(v, -1, zAff, n);
|
| + sqlite3ExprCacheAffinityChange(pParse, base, n);
|
| + }
|
| +}
|
| +
|
| +
|
| +/*
|
| +** Generate code for a single equality term of the WHERE clause. An equality
|
| +** term can be either X=expr or X IN (...). pTerm is the term to be
|
| +** coded.
|
| +**
|
| +** The current value for the constraint is left in register iReg.
|
| +**
|
| +** For a constraint of the form X=expr, the expression is evaluated and its
|
| +** result is left on the stack. For constraints of the form X IN (...)
|
| +** this routine sets up a loop that will iterate over all values of X.
|
| +*/
|
| +static int codeEqualityTerm(
|
| + Parse *pParse, /* The parsing context */
|
| + WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
|
| + WhereLevel *pLevel, /* The level of the FROM clause we are working on */
|
| + int iEq, /* Index of the equality term within this level */
|
| + int bRev, /* True for reverse-order IN operations */
|
| + int iTarget /* Attempt to leave results in this register */
|
| +){
|
| + Expr *pX = pTerm->pExpr;
|
| + Vdbe *v = pParse->pVdbe;
|
| + int iReg; /* Register holding results */
|
| +
|
| + assert( iTarget>0 );
|
| + if( pX->op==TK_EQ || pX->op==TK_IS ){
|
| + iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
|
| + }else if( pX->op==TK_ISNULL ){
|
| + iReg = iTarget;
|
| + sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
|
| +#ifndef SQLITE_OMIT_SUBQUERY
|
| + }else{
|
| + int eType;
|
| + int iTab;
|
| + struct InLoop *pIn;
|
| + WhereLoop *pLoop = pLevel->pWLoop;
|
| +
|
| + if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
|
| + && pLoop->u.btree.pIndex!=0
|
| + && pLoop->u.btree.pIndex->aSortOrder[iEq]
|
| + ){
|
| + testcase( iEq==0 );
|
| + testcase( bRev );
|
| + bRev = !bRev;
|
| + }
|
| + assert( pX->op==TK_IN );
|
| + iReg = iTarget;
|
| + eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0);
|
| + if( eType==IN_INDEX_INDEX_DESC ){
|
| + testcase( bRev );
|
| + bRev = !bRev;
|
| + }
|
| + iTab = pX->iTable;
|
| + sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
|
| + VdbeCoverageIf(v, bRev);
|
| + VdbeCoverageIf(v, !bRev);
|
| + assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
|
| + pLoop->wsFlags |= WHERE_IN_ABLE;
|
| + if( pLevel->u.in.nIn==0 ){
|
| + pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
|
| + }
|
| + pLevel->u.in.nIn++;
|
| + pLevel->u.in.aInLoop =
|
| + sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
|
| + sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
|
| + pIn = pLevel->u.in.aInLoop;
|
| + if( pIn ){
|
| + pIn += pLevel->u.in.nIn - 1;
|
| + pIn->iCur = iTab;
|
| + if( eType==IN_INDEX_ROWID ){
|
| + pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
|
| + }else{
|
| + pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
|
| + }
|
| + pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
|
| + sqlite3VdbeAddOp1(v, OP_IsNull, iReg); VdbeCoverage(v);
|
| + }else{
|
| + pLevel->u.in.nIn = 0;
|
| + }
|
| +#endif
|
| + }
|
| + disableTerm(pLevel, pTerm);
|
| + return iReg;
|
| +}
|
| +
|
| +/*
|
| +** Generate code that will evaluate all == and IN constraints for an
|
| +** index scan.
|
| +**
|
| +** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
|
| +** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
|
| +** The index has as many as three equality constraints, but in this
|
| +** example, the third "c" value is an inequality. So only two
|
| +** constraints are coded. This routine will generate code to evaluate
|
| +** a==5 and b IN (1,2,3). The current values for a and b will be stored
|
| +** in consecutive registers and the index of the first register is returned.
|
| +**
|
| +** In the example above nEq==2. But this subroutine works for any value
|
| +** of nEq including 0. If nEq==0, this routine is nearly a no-op.
|
| +** The only thing it does is allocate the pLevel->iMem memory cell and
|
| +** compute the affinity string.
|
| +**
|
| +** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints
|
| +** are == or IN and are covered by the nEq. nExtraReg is 1 if there is
|
| +** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
|
| +** occurs after the nEq quality constraints.
|
| +**
|
| +** This routine allocates a range of nEq+nExtraReg memory cells and returns
|
| +** the index of the first memory cell in that range. The code that
|
| +** calls this routine will use that memory range to store keys for
|
| +** start and termination conditions of the loop.
|
| +** key value of the loop. If one or more IN operators appear, then
|
| +** this routine allocates an additional nEq memory cells for internal
|
| +** use.
|
| +**
|
| +** Before returning, *pzAff is set to point to a buffer containing a
|
| +** copy of the column affinity string of the index allocated using
|
| +** sqlite3DbMalloc(). Except, entries in the copy of the string associated
|
| +** with equality constraints that use BLOB or NONE affinity are set to
|
| +** SQLITE_AFF_BLOB. This is to deal with SQL such as the following:
|
| +**
|
| +** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
|
| +** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
|
| +**
|
| +** In the example above, the index on t1(a) has TEXT affinity. But since
|
| +** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity,
|
| +** no conversion should be attempted before using a t2.b value as part of
|
| +** a key to search the index. Hence the first byte in the returned affinity
|
| +** string in this example would be set to SQLITE_AFF_BLOB.
|
| +*/
|
| +static int codeAllEqualityTerms(
|
| + Parse *pParse, /* Parsing context */
|
| + WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
|
| + int bRev, /* Reverse the order of IN operators */
|
| + int nExtraReg, /* Number of extra registers to allocate */
|
| + char **pzAff /* OUT: Set to point to affinity string */
|
| +){
|
| + u16 nEq; /* The number of == or IN constraints to code */
|
| + u16 nSkip; /* Number of left-most columns to skip */
|
| + Vdbe *v = pParse->pVdbe; /* The vm under construction */
|
| + Index *pIdx; /* The index being used for this loop */
|
| + WhereTerm *pTerm; /* A single constraint term */
|
| + WhereLoop *pLoop; /* The WhereLoop object */
|
| + int j; /* Loop counter */
|
| + int regBase; /* Base register */
|
| + int nReg; /* Number of registers to allocate */
|
| + char *zAff; /* Affinity string to return */
|
| +
|
| + /* This module is only called on query plans that use an index. */
|
| + pLoop = pLevel->pWLoop;
|
| + assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
|
| + nEq = pLoop->u.btree.nEq;
|
| + nSkip = pLoop->nSkip;
|
| + pIdx = pLoop->u.btree.pIndex;
|
| + assert( pIdx!=0 );
|
| +
|
| + /* Figure out how many memory cells we will need then allocate them.
|
| + */
|
| + regBase = pParse->nMem + 1;
|
| + nReg = pLoop->u.btree.nEq + nExtraReg;
|
| + pParse->nMem += nReg;
|
| +
|
| + zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx));
|
| + if( !zAff ){
|
| + pParse->db->mallocFailed = 1;
|
| + }
|
| +
|
| + if( nSkip ){
|
| + int iIdxCur = pLevel->iIdxCur;
|
| + sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
|
| + VdbeCoverageIf(v, bRev==0);
|
| + VdbeCoverageIf(v, bRev!=0);
|
| + VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
|
| + j = sqlite3VdbeAddOp0(v, OP_Goto);
|
| + pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
|
| + iIdxCur, 0, regBase, nSkip);
|
| + VdbeCoverageIf(v, bRev==0);
|
| + VdbeCoverageIf(v, bRev!=0);
|
| + sqlite3VdbeJumpHere(v, j);
|
| + for(j=0; j<nSkip; j++){
|
| + sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
|
| + testcase( pIdx->aiColumn[j]==XN_EXPR );
|
| + VdbeComment((v, "%s", explainIndexColumnName(pIdx, j)));
|
| + }
|
| + }
|
| +
|
| + /* Evaluate the equality constraints
|
| + */
|
| + assert( zAff==0 || (int)strlen(zAff)>=nEq );
|
| + for(j=nSkip; j<nEq; j++){
|
| + int r1;
|
| + pTerm = pLoop->aLTerm[j];
|
| + assert( pTerm!=0 );
|
| + /* The following testcase is true for indices with redundant columns.
|
| + ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
|
| + testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
|
| + testcase( pTerm->wtFlags & TERM_VIRTUAL );
|
| + r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
|
| + if( r1!=regBase+j ){
|
| + if( nReg==1 ){
|
| + sqlite3ReleaseTempReg(pParse, regBase);
|
| + regBase = r1;
|
| + }else{
|
| + sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
|
| + }
|
| + }
|
| + testcase( pTerm->eOperator & WO_ISNULL );
|
| + testcase( pTerm->eOperator & WO_IN );
|
| + if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
|
| + Expr *pRight = pTerm->pExpr->pRight;
|
| + if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){
|
| + sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
|
| + VdbeCoverage(v);
|
| + }
|
| + if( zAff ){
|
| + if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){
|
| + zAff[j] = SQLITE_AFF_BLOB;
|
| + }
|
| + if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
|
| + zAff[j] = SQLITE_AFF_BLOB;
|
| + }
|
| + }
|
| + }
|
| + }
|
| + *pzAff = zAff;
|
| + return regBase;
|
| +}
|
| +
|
| +#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
|
| +/*
|
| +** If the most recently coded instruction is a constant range contraint
|
| +** that originated from the LIKE optimization, then change the P3 to be
|
| +** pLoop->iLikeRepCntr and set P5.
|
| +**
|
| +** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range
|
| +** expression: "x>='ABC' AND x<'abd'". But this requires that the range
|
| +** scan loop run twice, once for strings and a second time for BLOBs.
|
| +** The OP_String opcodes on the second pass convert the upper and lower
|
| +** bound string contants to blobs. This routine makes the necessary changes
|
| +** to the OP_String opcodes for that to happen.
|
| +**
|
| +** Except, of course, if SQLITE_LIKE_DOESNT_MATCH_BLOBS is defined, then
|
| +** only the one pass through the string space is required, so this routine
|
| +** becomes a no-op.
|
| +*/
|
| +static void whereLikeOptimizationStringFixup(
|
| + Vdbe *v, /* prepared statement under construction */
|
| + WhereLevel *pLevel, /* The loop that contains the LIKE operator */
|
| + WhereTerm *pTerm /* The upper or lower bound just coded */
|
| +){
|
| + if( pTerm->wtFlags & TERM_LIKEOPT ){
|
| + VdbeOp *pOp;
|
| + assert( pLevel->iLikeRepCntr>0 );
|
| + pOp = sqlite3VdbeGetOp(v, -1);
|
| + assert( pOp!=0 );
|
| + assert( pOp->opcode==OP_String8
|
| + || pTerm->pWC->pWInfo->pParse->db->mallocFailed );
|
| + pOp->p3 = pLevel->iLikeRepCntr;
|
| + pOp->p5 = 1;
|
| + }
|
| +}
|
| +#else
|
| +# define whereLikeOptimizationStringFixup(A,B,C)
|
| +#endif
|
| +
|
| +#ifdef SQLITE_ENABLE_CURSOR_HINTS
|
| +/*
|
| +** Information is passed from codeCursorHint() down to individual nodes of
|
| +** the expression tree (by sqlite3WalkExpr()) using an instance of this
|
| +** structure.
|
| +*/
|
| +struct CCurHint {
|
| + int iTabCur; /* Cursor for the main table */
|
| + int iIdxCur; /* Cursor for the index, if pIdx!=0. Unused otherwise */
|
| + Index *pIdx; /* The index used to access the table */
|
| +};
|
| +
|
| +/*
|
| +** This function is called for every node of an expression that is a candidate
|
| +** for a cursor hint on an index cursor. For TK_COLUMN nodes that reference
|
| +** the table CCurHint.iTabCur, verify that the same column can be
|
| +** accessed through the index. If it cannot, then set pWalker->eCode to 1.
|
| +*/
|
| +static int codeCursorHintCheckExpr(Walker *pWalker, Expr *pExpr){
|
| + struct CCurHint *pHint = pWalker->u.pCCurHint;
|
| + assert( pHint->pIdx!=0 );
|
| + if( pExpr->op==TK_COLUMN
|
| + && pExpr->iTable==pHint->iTabCur
|
| + && sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn)<0
|
| + ){
|
| + pWalker->eCode = 1;
|
| + }
|
| + return WRC_Continue;
|
| +}
|
| +
|
| +
|
| +/*
|
| +** This function is called on every node of an expression tree used as an
|
| +** argument to the OP_CursorHint instruction. If the node is a TK_COLUMN
|
| +** that accesses any table other than the one identified by
|
| +** CCurHint.iTabCur, then do the following:
|
| +**
|
| +** 1) allocate a register and code an OP_Column instruction to read
|
| +** the specified column into the new register, and
|
| +**
|
| +** 2) transform the expression node to a TK_REGISTER node that reads
|
| +** from the newly populated register.
|
| +**
|
| +** Also, if the node is a TK_COLUMN that does access the table idenified
|
| +** by pCCurHint.iTabCur, and an index is being used (which we will
|
| +** know because CCurHint.pIdx!=0) then transform the TK_COLUMN into
|
| +** an access of the index rather than the original table.
|
| +*/
|
| +static int codeCursorHintFixExpr(Walker *pWalker, Expr *pExpr){
|
| + int rc = WRC_Continue;
|
| + struct CCurHint *pHint = pWalker->u.pCCurHint;
|
| + if( pExpr->op==TK_COLUMN ){
|
| + if( pExpr->iTable!=pHint->iTabCur ){
|
| + Vdbe *v = pWalker->pParse->pVdbe;
|
| + int reg = ++pWalker->pParse->nMem; /* Register for column value */
|
| + sqlite3ExprCodeGetColumnOfTable(
|
| + v, pExpr->pTab, pExpr->iTable, pExpr->iColumn, reg
|
| + );
|
| + pExpr->op = TK_REGISTER;
|
| + pExpr->iTable = reg;
|
| + }else if( pHint->pIdx!=0 ){
|
| + pExpr->iTable = pHint->iIdxCur;
|
| + pExpr->iColumn = sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn);
|
| + assert( pExpr->iColumn>=0 );
|
| + }
|
| + }else if( pExpr->op==TK_AGG_FUNCTION ){
|
| + /* An aggregate function in the WHERE clause of a query means this must
|
| + ** be a correlated sub-query, and expression pExpr is an aggregate from
|
| + ** the parent context. Do not walk the function arguments in this case.
|
| + **
|
| + ** todo: It should be possible to replace this node with a TK_REGISTER
|
| + ** expression, as the result of the expression must be stored in a
|
| + ** register at this point. The same holds for TK_AGG_COLUMN nodes. */
|
| + rc = WRC_Prune;
|
| + }
|
| + return rc;
|
| +}
|
| +
|
| +/*
|
| +** Insert an OP_CursorHint instruction if it is appropriate to do so.
|
| +*/
|
| +static void codeCursorHint(
|
| + WhereInfo *pWInfo, /* The where clause */
|
| + WhereLevel *pLevel, /* Which loop to provide hints for */
|
| + WhereTerm *pEndRange /* Hint this end-of-scan boundary term if not NULL */
|
| +){
|
| + Parse *pParse = pWInfo->pParse;
|
| + sqlite3 *db = pParse->db;
|
| + Vdbe *v = pParse->pVdbe;
|
| + Expr *pExpr = 0;
|
| + WhereLoop *pLoop = pLevel->pWLoop;
|
| + int iCur;
|
| + WhereClause *pWC;
|
| + WhereTerm *pTerm;
|
| + int i, j;
|
| + struct CCurHint sHint;
|
| + Walker sWalker;
|
| +
|
| + if( OptimizationDisabled(db, SQLITE_CursorHints) ) return;
|
| + iCur = pLevel->iTabCur;
|
| + assert( iCur==pWInfo->pTabList->a[pLevel->iFrom].iCursor );
|
| + sHint.iTabCur = iCur;
|
| + sHint.iIdxCur = pLevel->iIdxCur;
|
| + sHint.pIdx = pLoop->u.btree.pIndex;
|
| + memset(&sWalker, 0, sizeof(sWalker));
|
| + sWalker.pParse = pParse;
|
| + sWalker.u.pCCurHint = &sHint;
|
| + pWC = &pWInfo->sWC;
|
| + for(i=0; i<pWC->nTerm; i++){
|
| + pTerm = &pWC->a[i];
|
| + if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
|
| + if( pTerm->prereqAll & pLevel->notReady ) continue;
|
| + if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) continue;
|
| +
|
| + /* All terms in pWLoop->aLTerm[] except pEndRange are used to initialize
|
| + ** the cursor. These terms are not needed as hints for a pure range
|
| + ** scan (that has no == terms) so omit them. */
|
| + if( pLoop->u.btree.nEq==0 && pTerm!=pEndRange ){
|
| + for(j=0; j<pLoop->nLTerm && pLoop->aLTerm[j]!=pTerm; j++){}
|
| + if( j<pLoop->nLTerm ) continue;
|
| + }
|
| +
|
| + /* No subqueries or non-deterministic functions allowed */
|
| + if( sqlite3ExprContainsSubquery(pTerm->pExpr) ) continue;
|
| +
|
| + /* For an index scan, make sure referenced columns are actually in
|
| + ** the index. */
|
| + if( sHint.pIdx!=0 ){
|
| + sWalker.eCode = 0;
|
| + sWalker.xExprCallback = codeCursorHintCheckExpr;
|
| + sqlite3WalkExpr(&sWalker, pTerm->pExpr);
|
| + if( sWalker.eCode ) continue;
|
| + }
|
| +
|
| + /* If we survive all prior tests, that means this term is worth hinting */
|
| + pExpr = sqlite3ExprAnd(db, pExpr, sqlite3ExprDup(db, pTerm->pExpr, 0));
|
| + }
|
| + if( pExpr!=0 ){
|
| + sWalker.xExprCallback = codeCursorHintFixExpr;
|
| + sqlite3WalkExpr(&sWalker, pExpr);
|
| + sqlite3VdbeAddOp4(v, OP_CursorHint,
|
| + (sHint.pIdx ? sHint.iIdxCur : sHint.iTabCur), 0, 0,
|
| + (const char*)pExpr, P4_EXPR);
|
| + }
|
| +}
|
| +#else
|
| +# define codeCursorHint(A,B,C) /* No-op */
|
| +#endif /* SQLITE_ENABLE_CURSOR_HINTS */
|
| +
|
| +/*
|
| +** Generate code for the start of the iLevel-th loop in the WHERE clause
|
| +** implementation described by pWInfo.
|
| +*/
|
| +SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
|
| + WhereInfo *pWInfo, /* Complete information about the WHERE clause */
|
| + int iLevel, /* Which level of pWInfo->a[] should be coded */
|
| + Bitmask notReady /* Which tables are currently available */
|
| +){
|
| + int j, k; /* Loop counters */
|
| + int iCur; /* The VDBE cursor for the table */
|
| + int addrNxt; /* Where to jump to continue with the next IN case */
|
| + int omitTable; /* True if we use the index only */
|
| + int bRev; /* True if we need to scan in reverse order */
|
| + WhereLevel *pLevel; /* The where level to be coded */
|
| + WhereLoop *pLoop; /* The WhereLoop object being coded */
|
| + WhereClause *pWC; /* Decomposition of the entire WHERE clause */
|
| + WhereTerm *pTerm; /* A WHERE clause term */
|
| + Parse *pParse; /* Parsing context */
|
| + sqlite3 *db; /* Database connection */
|
| + Vdbe *v; /* The prepared stmt under constructions */
|
| + struct SrcList_item *pTabItem; /* FROM clause term being coded */
|
| + int addrBrk; /* Jump here to break out of the loop */
|
| + int addrCont; /* Jump here to continue with next cycle */
|
| + int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
|
| + int iReleaseReg = 0; /* Temp register to free before returning */
|
| +
|
| + pParse = pWInfo->pParse;
|
| + v = pParse->pVdbe;
|
| + pWC = &pWInfo->sWC;
|
| + db = pParse->db;
|
| + pLevel = &pWInfo->a[iLevel];
|
| + pLoop = pLevel->pWLoop;
|
| + pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
|
| + iCur = pTabItem->iCursor;
|
| + pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
|
| + bRev = (pWInfo->revMask>>iLevel)&1;
|
| + omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
|
| + && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
|
| + VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
|
| +
|
| + /* Create labels for the "break" and "continue" instructions
|
| + ** for the current loop. Jump to addrBrk to break out of a loop.
|
| + ** Jump to cont to go immediately to the next iteration of the
|
| + ** loop.
|
| + **
|
| + ** When there is an IN operator, we also have a "addrNxt" label that
|
| + ** means to continue with the next IN value combination. When
|
| + ** there are no IN operators in the constraints, the "addrNxt" label
|
| + ** is the same as "addrBrk".
|
| + */
|
| + addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
|
| + addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
|
| +
|
| + /* If this is the right table of a LEFT OUTER JOIN, allocate and
|
| + ** initialize a memory cell that records if this table matches any
|
| + ** row of the left table of the join.
|
| + */
|
| + if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){
|
| + pLevel->iLeftJoin = ++pParse->nMem;
|
| + sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
|
| + VdbeComment((v, "init LEFT JOIN no-match flag"));
|
| + }
|
| +
|
| + /* Special case of a FROM clause subquery implemented as a co-routine */
|
| + if( pTabItem->fg.viaCoroutine ){
|
| + int regYield = pTabItem->regReturn;
|
| + sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
|
| + pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
|
| + VdbeCoverage(v);
|
| + VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
|
| + pLevel->op = OP_Goto;
|
| + }else
|
| +
|
| +#ifndef SQLITE_OMIT_VIRTUALTABLE
|
| + if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
|
| + /* Case 1: The table is a virtual-table. Use the VFilter and VNext
|
| + ** to access the data.
|
| + */
|
| + int iReg; /* P3 Value for OP_VFilter */
|
| + int addrNotFound;
|
| + int nConstraint = pLoop->nLTerm;
|
| +
|
| + sqlite3ExprCachePush(pParse);
|
| + iReg = sqlite3GetTempRange(pParse, nConstraint+2);
|
| + addrNotFound = pLevel->addrBrk;
|
| + for(j=0; j<nConstraint; j++){
|
| + int iTarget = iReg+j+2;
|
| + pTerm = pLoop->aLTerm[j];
|
| + if( pTerm==0 ) continue;
|
| + if( pTerm->eOperator & WO_IN ){
|
| + codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
|
| + addrNotFound = pLevel->addrNxt;
|
| + }else{
|
| + sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
|
| + }
|
| + }
|
| + sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
|
| + sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
|
| + sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
|
| + pLoop->u.vtab.idxStr,
|
| + pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
|
| + VdbeCoverage(v);
|
| + pLoop->u.vtab.needFree = 0;
|
| + for(j=0; j<nConstraint && j<16; j++){
|
| + if( (pLoop->u.vtab.omitMask>>j)&1 ){
|
| + disableTerm(pLevel, pLoop->aLTerm[j]);
|
| + }
|
| + }
|
| + pLevel->p1 = iCur;
|
| + pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext;
|
| + pLevel->p2 = sqlite3VdbeCurrentAddr(v);
|
| + sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
|
| + sqlite3ExprCachePop(pParse);
|
| + }else
|
| +#endif /* SQLITE_OMIT_VIRTUALTABLE */
|
| +
|
| + if( (pLoop->wsFlags & WHERE_IPK)!=0
|
| + && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
|
| + ){
|
| + /* Case 2: We can directly reference a single row using an
|
| + ** equality comparison against the ROWID field. Or
|
| + ** we reference multiple rows using a "rowid IN (...)"
|
| + ** construct.
|
| + */
|
| + assert( pLoop->u.btree.nEq==1 );
|
| + pTerm = pLoop->aLTerm[0];
|
| + assert( pTerm!=0 );
|
| + assert( pTerm->pExpr!=0 );
|
| + assert( omitTable==0 );
|
| + testcase( pTerm->wtFlags & TERM_VIRTUAL );
|
| + iReleaseReg = ++pParse->nMem;
|
| + iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
|
| + if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
|
| + addrNxt = pLevel->addrNxt;
|
| + sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt); VdbeCoverage(v);
|
| + sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
|
| + VdbeCoverage(v);
|
| + sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
|
| + sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
|
| + VdbeComment((v, "pk"));
|
| + pLevel->op = OP_Noop;
|
| + }else if( (pLoop->wsFlags & WHERE_IPK)!=0
|
| + && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
|
| + ){
|
| + /* Case 3: We have an inequality comparison against the ROWID field.
|
| + */
|
| + int testOp = OP_Noop;
|
| + int start;
|
| + int memEndValue = 0;
|
| + WhereTerm *pStart, *pEnd;
|
| +
|
| + assert( omitTable==0 );
|
| + j = 0;
|
| + pStart = pEnd = 0;
|
| + if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
|
| + if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
|
| + assert( pStart!=0 || pEnd!=0 );
|
| + if( bRev ){
|
| + pTerm = pStart;
|
| + pStart = pEnd;
|
| + pEnd = pTerm;
|
| + }
|
| + codeCursorHint(pWInfo, pLevel, pEnd);
|
| + if( pStart ){
|
| + Expr *pX; /* The expression that defines the start bound */
|
| + int r1, rTemp; /* Registers for holding the start boundary */
|
| +
|
| + /* The following constant maps TK_xx codes into corresponding
|
| + ** seek opcodes. It depends on a particular ordering of TK_xx
|
| + */
|
| + const u8 aMoveOp[] = {
|
| + /* TK_GT */ OP_SeekGT,
|
| + /* TK_LE */ OP_SeekLE,
|
| + /* TK_LT */ OP_SeekLT,
|
| + /* TK_GE */ OP_SeekGE
|
| + };
|
| + assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
|
| + assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
|
| + assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
|
| +
|
| + assert( (pStart->wtFlags & TERM_VNULL)==0 );
|
| + testcase( pStart->wtFlags & TERM_VIRTUAL );
|
| + pX = pStart->pExpr;
|
| + assert( pX!=0 );
|
| + testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
|
| + r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
|
| + sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
|
| + VdbeComment((v, "pk"));
|
| + VdbeCoverageIf(v, pX->op==TK_GT);
|
| + VdbeCoverageIf(v, pX->op==TK_LE);
|
| + VdbeCoverageIf(v, pX->op==TK_LT);
|
| + VdbeCoverageIf(v, pX->op==TK_GE);
|
| + sqlite3ExprCacheAffinityChange(pParse, r1, 1);
|
| + sqlite3ReleaseTempReg(pParse, rTemp);
|
| + disableTerm(pLevel, pStart);
|
| + }else{
|
| + sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
|
| + VdbeCoverageIf(v, bRev==0);
|
| + VdbeCoverageIf(v, bRev!=0);
|
| + }
|
| + if( pEnd ){
|
| + Expr *pX;
|
| + pX = pEnd->pExpr;
|
| + assert( pX!=0 );
|
| + assert( (pEnd->wtFlags & TERM_VNULL)==0 );
|
| + testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
|
| + testcase( pEnd->wtFlags & TERM_VIRTUAL );
|
| + memEndValue = ++pParse->nMem;
|
| + sqlite3ExprCode(pParse, pX->pRight, memEndValue);
|
| + if( pX->op==TK_LT || pX->op==TK_GT ){
|
| + testOp = bRev ? OP_Le : OP_Ge;
|
| + }else{
|
| + testOp = bRev ? OP_Lt : OP_Gt;
|
| + }
|
| + disableTerm(pLevel, pEnd);
|
| + }
|
| + start = sqlite3VdbeCurrentAddr(v);
|
| + pLevel->op = bRev ? OP_Prev : OP_Next;
|
| + pLevel->p1 = iCur;
|
| + pLevel->p2 = start;
|
| + assert( pLevel->p5==0 );
|
| + if( testOp!=OP_Noop ){
|
| + iRowidReg = ++pParse->nMem;
|
| + sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
|
| + sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
|
| + sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
|
| + VdbeCoverageIf(v, testOp==OP_Le);
|
| + VdbeCoverageIf(v, testOp==OP_Lt);
|
| + VdbeCoverageIf(v, testOp==OP_Ge);
|
| + VdbeCoverageIf(v, testOp==OP_Gt);
|
| + sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
|
| + }
|
| + }else if( pLoop->wsFlags & WHERE_INDEXED ){
|
| + /* Case 4: A scan using an index.
|
| + **
|
| + ** The WHERE clause may contain zero or more equality
|
| + ** terms ("==" or "IN" operators) that refer to the N
|
| + ** left-most columns of the index. It may also contain
|
| + ** inequality constraints (>, <, >= or <=) on the indexed
|
| + ** column that immediately follows the N equalities. Only
|
| + ** the right-most column can be an inequality - the rest must
|
| + ** use the "==" and "IN" operators. For example, if the
|
| + ** index is on (x,y,z), then the following clauses are all
|
| + ** optimized:
|
| + **
|
| + ** x=5
|
| + ** x=5 AND y=10
|
| + ** x=5 AND y<10
|
| + ** x=5 AND y>5 AND y<10
|
| + ** x=5 AND y=5 AND z<=10
|
| + **
|
| + ** The z<10 term of the following cannot be used, only
|
| + ** the x=5 term:
|
| + **
|
| + ** x=5 AND z<10
|
| + **
|
| + ** N may be zero if there are inequality constraints.
|
| + ** If there are no inequality constraints, then N is at
|
| + ** least one.
|
| + **
|
| + ** This case is also used when there are no WHERE clause
|
| + ** constraints but an index is selected anyway, in order
|
| + ** to force the output order to conform to an ORDER BY.
|
| + */
|
| + static const u8 aStartOp[] = {
|
| + 0,
|
| + 0,
|
| + OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
|
| + OP_Last, /* 3: (!start_constraints && startEq && bRev) */
|
| + OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */
|
| + OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */
|
| + OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */
|
| + OP_SeekLE /* 7: (start_constraints && startEq && bRev) */
|
| + };
|
| + static const u8 aEndOp[] = {
|
| + OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */
|
| + OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */
|
| + OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */
|
| + OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */
|
| + };
|
| + u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
|
| + int regBase; /* Base register holding constraint values */
|
| + WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
|
| + WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
|
| + int startEq; /* True if range start uses ==, >= or <= */
|
| + int endEq; /* True if range end uses ==, >= or <= */
|
| + int start_constraints; /* Start of range is constrained */
|
| + int nConstraint; /* Number of constraint terms */
|
| + Index *pIdx; /* The index we will be using */
|
| + int iIdxCur; /* The VDBE cursor for the index */
|
| + int nExtraReg = 0; /* Number of extra registers needed */
|
| + int op; /* Instruction opcode */
|
| + char *zStartAff; /* Affinity for start of range constraint */
|
| + char cEndAff = 0; /* Affinity for end of range constraint */
|
| + u8 bSeekPastNull = 0; /* True to seek past initial nulls */
|
| + u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */
|
| +
|
| + pIdx = pLoop->u.btree.pIndex;
|
| + iIdxCur = pLevel->iIdxCur;
|
| + assert( nEq>=pLoop->nSkip );
|
| +
|
| + /* If this loop satisfies a sort order (pOrderBy) request that
|
| + ** was passed to this function to implement a "SELECT min(x) ..."
|
| + ** query, then the caller will only allow the loop to run for
|
| + ** a single iteration. This means that the first row returned
|
| + ** should not have a NULL value stored in 'x'. If column 'x' is
|
| + ** the first one after the nEq equality constraints in the index,
|
| + ** this requires some special handling.
|
| + */
|
| + assert( pWInfo->pOrderBy==0
|
| + || pWInfo->pOrderBy->nExpr==1
|
| + || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
|
| + if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
|
| + && pWInfo->nOBSat>0
|
| + && (pIdx->nKeyCol>nEq)
|
| + ){
|
| + assert( pLoop->nSkip==0 );
|
| + bSeekPastNull = 1;
|
| + nExtraReg = 1;
|
| + }
|
| +
|
| + /* Find any inequality constraint terms for the start and end
|
| + ** of the range.
|
| + */
|
| + j = nEq;
|
| + if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
|
| + pRangeStart = pLoop->aLTerm[j++];
|
| + nExtraReg = 1;
|
| + /* Like optimization range constraints always occur in pairs */
|
| + assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 ||
|
| + (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 );
|
| + }
|
| + if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
|
| + pRangeEnd = pLoop->aLTerm[j++];
|
| + nExtraReg = 1;
|
| +#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
|
| + if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
|
| + assert( pRangeStart!=0 ); /* LIKE opt constraints */
|
| + assert( pRangeStart->wtFlags & TERM_LIKEOPT ); /* occur in pairs */
|
| + pLevel->iLikeRepCntr = ++pParse->nMem;
|
| + testcase( bRev );
|
| + testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
|
| + sqlite3VdbeAddOp2(v, OP_Integer,
|
| + bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC),
|
| + pLevel->iLikeRepCntr);
|
| + VdbeComment((v, "LIKE loop counter"));
|
| + pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
|
| + }
|
| +#endif
|
| + if( pRangeStart==0
|
| + && (j = pIdx->aiColumn[nEq])>=0
|
| + && pIdx->pTable->aCol[j].notNull==0
|
| + ){
|
| + bSeekPastNull = 1;
|
| + }
|
| + }
|
| + assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
|
| +
|
| + /* If we are doing a reverse order scan on an ascending index, or
|
| + ** a forward order scan on a descending index, interchange the
|
| + ** start and end terms (pRangeStart and pRangeEnd).
|
| + */
|
| + if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
|
| + || (bRev && pIdx->nKeyCol==nEq)
|
| + ){
|
| + SWAP(WhereTerm *, pRangeEnd, pRangeStart);
|
| + SWAP(u8, bSeekPastNull, bStopAtNull);
|
| + }
|
| +
|
| + /* Generate code to evaluate all constraint terms using == or IN
|
| + ** and store the values of those terms in an array of registers
|
| + ** starting at regBase.
|
| + */
|
| + codeCursorHint(pWInfo, pLevel, pRangeEnd);
|
| + regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
|
| + assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
|
| + if( zStartAff ) cEndAff = zStartAff[nEq];
|
| + addrNxt = pLevel->addrNxt;
|
| +
|
| + testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
|
| + testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
|
| + testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
|
| + testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
|
| + startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
|
| + endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
|
| + start_constraints = pRangeStart || nEq>0;
|
| +
|
| + /* Seek the index cursor to the start of the range. */
|
| + nConstraint = nEq;
|
| + if( pRangeStart ){
|
| + Expr *pRight = pRangeStart->pExpr->pRight;
|
| + sqlite3ExprCode(pParse, pRight, regBase+nEq);
|
| + whereLikeOptimizationStringFixup(v, pLevel, pRangeStart);
|
| + if( (pRangeStart->wtFlags & TERM_VNULL)==0
|
| + && sqlite3ExprCanBeNull(pRight)
|
| + ){
|
| + sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
|
| + VdbeCoverage(v);
|
| + }
|
| + if( zStartAff ){
|
| + if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_BLOB){
|
| + /* Since the comparison is to be performed with no conversions
|
| + ** applied to the operands, set the affinity to apply to pRight to
|
| + ** SQLITE_AFF_BLOB. */
|
| + zStartAff[nEq] = SQLITE_AFF_BLOB;
|
| + }
|
| + if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
|
| + zStartAff[nEq] = SQLITE_AFF_BLOB;
|
| + }
|
| + }
|
| + nConstraint++;
|
| + testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
|
| + }else if( bSeekPastNull ){
|
| + sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
|
| + nConstraint++;
|
| + startEq = 0;
|
| + start_constraints = 1;
|
| + }
|
| + codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
|
| + op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
|
| + assert( op!=0 );
|
| + sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
|
| + VdbeCoverage(v);
|
| + VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind );
|
| + VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last );
|
| + VdbeCoverageIf(v, op==OP_SeekGT); testcase( op==OP_SeekGT );
|
| + VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE );
|
| + VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE );
|
| + VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT );
|
| +
|
| + /* Load the value for the inequality constraint at the end of the
|
| + ** range (if any).
|
| + */
|
| + nConstraint = nEq;
|
| + if( pRangeEnd ){
|
| + Expr *pRight = pRangeEnd->pExpr->pRight;
|
| + sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
|
| + sqlite3ExprCode(pParse, pRight, regBase+nEq);
|
| + whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd);
|
| + if( (pRangeEnd->wtFlags & TERM_VNULL)==0
|
| + && sqlite3ExprCanBeNull(pRight)
|
| + ){
|
| + sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
|
| + VdbeCoverage(v);
|
| + }
|
| + if( sqlite3CompareAffinity(pRight, cEndAff)!=SQLITE_AFF_BLOB
|
| + && !sqlite3ExprNeedsNoAffinityChange(pRight, cEndAff)
|
| + ){
|
| + codeApplyAffinity(pParse, regBase+nEq, 1, &cEndAff);
|
| + }
|
| + nConstraint++;
|
| + testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
|
| + }else if( bStopAtNull ){
|
| + sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
|
| + endEq = 0;
|
| + nConstraint++;
|
| + }
|
| + sqlite3DbFree(db, zStartAff);
|
| +
|
| + /* Top of the loop body */
|
| + pLevel->p2 = sqlite3VdbeCurrentAddr(v);
|
| +
|
| + /* Check if the index cursor is past the end of the range. */
|
| + if( nConstraint ){
|
| + op = aEndOp[bRev*2 + endEq];
|
| + sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
|
| + testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT );
|
| + testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE );
|
| + testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT );
|
| + testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE );
|
| + }
|
| +
|
| + /* Seek the table cursor, if required */
|
| + disableTerm(pLevel, pRangeStart);
|
| + disableTerm(pLevel, pRangeEnd);
|
| + if( omitTable ){
|
| + /* pIdx is a covering index. No need to access the main table. */
|
| + }else if( HasRowid(pIdx->pTable) ){
|
| + iRowidReg = ++pParse->nMem;
|
| + sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
|
| + sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
|
| + if( pWInfo->eOnePass!=ONEPASS_OFF ){
|
| + sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowidReg);
|
| + VdbeCoverage(v);
|
| + }else{
|
| + sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */
|
| + }
|
| + }else if( iCur!=iIdxCur ){
|
| + Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
|
| + iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
|
| + for(j=0; j<pPk->nKeyCol; j++){
|
| + k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
|
| + sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
|
| + }
|
| + sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
|
| + iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
|
| + }
|
| +
|
| + /* Record the instruction used to terminate the loop. Disable
|
| + ** WHERE clause terms made redundant by the index range scan.
|
| + */
|
| + if( pLoop->wsFlags & WHERE_ONEROW ){
|
| + pLevel->op = OP_Noop;
|
| + }else if( bRev ){
|
| + pLevel->op = OP_Prev;
|
| + }else{
|
| + pLevel->op = OP_Next;
|
| + }
|
| + pLevel->p1 = iIdxCur;
|
| + pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
|
| + if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
|
| + pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
|
| + }else{
|
| + assert( pLevel->p5==0 );
|
| + }
|
| + }else
|
| +
|
| +#ifndef SQLITE_OMIT_OR_OPTIMIZATION
|
| + if( pLoop->wsFlags & WHERE_MULTI_OR ){
|
| + /* Case 5: Two or more separately indexed terms connected by OR
|
| + **
|
| + ** Example:
|
| + **
|
| + ** CREATE TABLE t1(a,b,c,d);
|
| + ** CREATE INDEX i1 ON t1(a);
|
| + ** CREATE INDEX i2 ON t1(b);
|
| + ** CREATE INDEX i3 ON t1(c);
|
| + **
|
| + ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
|
| + **
|
| + ** In the example, there are three indexed terms connected by OR.
|
| + ** The top of the loop looks like this:
|
| + **
|
| + ** Null 1 # Zero the rowset in reg 1
|
| + **
|
| + ** Then, for each indexed term, the following. The arguments to
|
| + ** RowSetTest are such that the rowid of the current row is inserted
|
| + ** into the RowSet. If it is already present, control skips the
|
| + ** Gosub opcode and jumps straight to the code generated by WhereEnd().
|
| + **
|
| + ** sqlite3WhereBegin(<term>)
|
| + ** RowSetTest # Insert rowid into rowset
|
| + ** Gosub 2 A
|
| + ** sqlite3WhereEnd()
|
| + **
|
| + ** Following the above, code to terminate the loop. Label A, the target
|
| + ** of the Gosub above, jumps to the instruction right after the Goto.
|
| + **
|
| + ** Null 1 # Zero the rowset in reg 1
|
| + ** Goto B # The loop is finished.
|
| + **
|
| + ** A: <loop body> # Return data, whatever.
|
| + **
|
| + ** Return 2 # Jump back to the Gosub
|
| + **
|
| + ** B: <after the loop>
|
| + **
|
| + ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
|
| + ** use an ephemeral index instead of a RowSet to record the primary
|
| + ** keys of the rows we have already seen.
|
| + **
|
| + */
|
| + WhereClause *pOrWc; /* The OR-clause broken out into subterms */
|
| + SrcList *pOrTab; /* Shortened table list or OR-clause generation */
|
| + Index *pCov = 0; /* Potential covering index (or NULL) */
|
| + int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
|
| +
|
| + int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
|
| + int regRowset = 0; /* Register for RowSet object */
|
| + int regRowid = 0; /* Register holding rowid */
|
| + int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
|
| + int iRetInit; /* Address of regReturn init */
|
| + int untestedTerms = 0; /* Some terms not completely tested */
|
| + int ii; /* Loop counter */
|
| + u16 wctrlFlags; /* Flags for sub-WHERE clause */
|
| + Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
|
| + Table *pTab = pTabItem->pTab;
|
| +
|
| + pTerm = pLoop->aLTerm[0];
|
| + assert( pTerm!=0 );
|
| + assert( pTerm->eOperator & WO_OR );
|
| + assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
|
| + pOrWc = &pTerm->u.pOrInfo->wc;
|
| + pLevel->op = OP_Return;
|
| + pLevel->p1 = regReturn;
|
| +
|
| + /* Set up a new SrcList in pOrTab containing the table being scanned
|
| + ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
|
| + ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
|
| + */
|
| + if( pWInfo->nLevel>1 ){
|
| + int nNotReady; /* The number of notReady tables */
|
| + struct SrcList_item *origSrc; /* Original list of tables */
|
| + nNotReady = pWInfo->nLevel - iLevel - 1;
|
| + pOrTab = sqlite3StackAllocRaw(db,
|
| + sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
|
| + if( pOrTab==0 ) return notReady;
|
| + pOrTab->nAlloc = (u8)(nNotReady + 1);
|
| + pOrTab->nSrc = pOrTab->nAlloc;
|
| + memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
|
| + origSrc = pWInfo->pTabList->a;
|
| + for(k=1; k<=nNotReady; k++){
|
| + memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
|
| + }
|
| + }else{
|
| + pOrTab = pWInfo->pTabList;
|
| + }
|
| +
|
| + /* Initialize the rowset register to contain NULL. An SQL NULL is
|
| + ** equivalent to an empty rowset. Or, create an ephemeral index
|
| + ** capable of holding primary keys in the case of a WITHOUT ROWID.
|
| + **
|
| + ** Also initialize regReturn to contain the address of the instruction
|
| + ** immediately following the OP_Return at the bottom of the loop. This
|
| + ** is required in a few obscure LEFT JOIN cases where control jumps
|
| + ** over the top of the loop into the body of it. In this case the
|
| + ** correct response for the end-of-loop code (the OP_Return) is to
|
| + ** fall through to the next instruction, just as an OP_Next does if
|
| + ** called on an uninitialized cursor.
|
| + */
|
| + if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
|
| + if( HasRowid(pTab) ){
|
| + regRowset = ++pParse->nMem;
|
| + sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
|
| + }else{
|
| + Index *pPk = sqlite3PrimaryKeyIndex(pTab);
|
| + regRowset = pParse->nTab++;
|
| + sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
|
| + sqlite3VdbeSetP4KeyInfo(pParse, pPk);
|
| + }
|
| + regRowid = ++pParse->nMem;
|
| + }
|
| + iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
|
| +
|
| + /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
|
| + ** Then for every term xN, evaluate as the subexpression: xN AND z
|
| + ** That way, terms in y that are factored into the disjunction will
|
| + ** be picked up by the recursive calls to sqlite3WhereBegin() below.
|
| + **
|
| + ** Actually, each subexpression is converted to "xN AND w" where w is
|
| + ** the "interesting" terms of z - terms that did not originate in the
|
| + ** ON or USING clause of a LEFT JOIN, and terms that are usable as
|
| + ** indices.
|
| + **
|
| + ** This optimization also only applies if the (x1 OR x2 OR ...) term
|
| + ** is not contained in the ON clause of a LEFT JOIN.
|
| + ** See ticket http://www.sqlite.org/src/info/f2369304e4
|
| + */
|
| + if( pWC->nTerm>1 ){
|
| + int iTerm;
|
| + for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
|
| + Expr *pExpr = pWC->a[iTerm].pExpr;
|
| + if( &pWC->a[iTerm] == pTerm ) continue;
|
| + if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
|
| + if( (pWC->a[iTerm].wtFlags & TERM_VIRTUAL)!=0 ) continue;
|
| + if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
|
| + testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
|
| + pExpr = sqlite3ExprDup(db, pExpr, 0);
|
| + pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
|
| + }
|
| + if( pAndExpr ){
|
| + pAndExpr = sqlite3PExpr(pParse, TK_AND|TKFLG_DONTFOLD, 0, pAndExpr, 0);
|
| + }
|
| + }
|
| +
|
| + /* Run a separate WHERE clause for each term of the OR clause. After
|
| + ** eliminating duplicates from other WHERE clauses, the action for each
|
| + ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
|
| + */
|
| + wctrlFlags = WHERE_OMIT_OPEN_CLOSE
|
| + | WHERE_FORCE_TABLE
|
| + | WHERE_ONETABLE_ONLY
|
| + | WHERE_NO_AUTOINDEX;
|
| + for(ii=0; ii<pOrWc->nTerm; ii++){
|
| + WhereTerm *pOrTerm = &pOrWc->a[ii];
|
| + if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
|
| + WhereInfo *pSubWInfo; /* Info for single OR-term scan */
|
| + Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
|
| + int jmp1 = 0; /* Address of jump operation */
|
| + if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
|
| + pAndExpr->pLeft = pOrExpr;
|
| + pOrExpr = pAndExpr;
|
| + }
|
| + /* Loop through table entries that match term pOrTerm. */
|
| + WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
|
| + pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
|
| + wctrlFlags, iCovCur);
|
| + assert( pSubWInfo || pParse->nErr || db->mallocFailed );
|
| + if( pSubWInfo ){
|
| + WhereLoop *pSubLoop;
|
| + int addrExplain = sqlite3WhereExplainOneScan(
|
| + pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
|
| + );
|
| + sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain);
|
| +
|
| + /* This is the sub-WHERE clause body. First skip over
|
| + ** duplicate rows from prior sub-WHERE clauses, and record the
|
| + ** rowid (or PRIMARY KEY) for the current row so that the same
|
| + ** row will be skipped in subsequent sub-WHERE clauses.
|
| + */
|
| + if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
|
| + int r;
|
| + int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
|
| + if( HasRowid(pTab) ){
|
| + r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0);
|
| + jmp1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0,
|
| + r,iSet);
|
| + VdbeCoverage(v);
|
| + }else{
|
| + Index *pPk = sqlite3PrimaryKeyIndex(pTab);
|
| + int nPk = pPk->nKeyCol;
|
| + int iPk;
|
| +
|
| + /* Read the PK into an array of temp registers. */
|
| + r = sqlite3GetTempRange(pParse, nPk);
|
| + for(iPk=0; iPk<nPk; iPk++){
|
| + int iCol = pPk->aiColumn[iPk];
|
| + sqlite3ExprCodeGetColumnToReg(pParse, pTab, iCol, iCur, r+iPk);
|
| + }
|
| +
|
| + /* Check if the temp table already contains this key. If so,
|
| + ** the row has already been included in the result set and
|
| + ** can be ignored (by jumping past the Gosub below). Otherwise,
|
| + ** insert the key into the temp table and proceed with processing
|
| + ** the row.
|
| + **
|
| + ** Use some of the same optimizations as OP_RowSetTest: If iSet
|
| + ** is zero, assume that the key cannot already be present in
|
| + ** the temp table. And if iSet is -1, assume that there is no
|
| + ** need to insert the key into the temp table, as it will never
|
| + ** be tested for. */
|
| + if( iSet ){
|
| + jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
|
| + VdbeCoverage(v);
|
| + }
|
| + if( iSet>=0 ){
|
| + sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
|
| + sqlite3VdbeAddOp3(v, OP_IdxInsert, regRowset, regRowid, 0);
|
| + if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
|
| + }
|
| +
|
| + /* Release the array of temp registers */
|
| + sqlite3ReleaseTempRange(pParse, r, nPk);
|
| + }
|
| + }
|
| +
|
| + /* Invoke the main loop body as a subroutine */
|
| + sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
|
| +
|
| + /* Jump here (skipping the main loop body subroutine) if the
|
| + ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
|
| + if( jmp1 ) sqlite3VdbeJumpHere(v, jmp1);
|
| +
|
| + /* The pSubWInfo->untestedTerms flag means that this OR term
|
| + ** contained one or more AND term from a notReady table. The
|
| + ** terms from the notReady table could not be tested and will
|
| + ** need to be tested later.
|
| + */
|
| + if( pSubWInfo->untestedTerms ) untestedTerms = 1;
|
| +
|
| + /* If all of the OR-connected terms are optimized using the same
|
| + ** index, and the index is opened using the same cursor number
|
| + ** by each call to sqlite3WhereBegin() made by this loop, it may
|
| + ** be possible to use that index as a covering index.
|
| + **
|
| + ** If the call to sqlite3WhereBegin() above resulted in a scan that
|
| + ** uses an index, and this is either the first OR-connected term
|
| + ** processed or the index is the same as that used by all previous
|
| + ** terms, set pCov to the candidate covering index. Otherwise, set
|
| + ** pCov to NULL to indicate that no candidate covering index will
|
| + ** be available.
|
| + */
|
| + pSubLoop = pSubWInfo->a[0].pWLoop;
|
| + assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
|
| + if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
|
| + && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
|
| + && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
|
| + ){
|
| + assert( pSubWInfo->a[0].iIdxCur==iCovCur );
|
| + pCov = pSubLoop->u.btree.pIndex;
|
| + wctrlFlags |= WHERE_REOPEN_IDX;
|
| + }else{
|
| + pCov = 0;
|
| + }
|
| +
|
| + /* Finish the loop through table entries that match term pOrTerm. */
|
| + sqlite3WhereEnd(pSubWInfo);
|
| + }
|
| + }
|
| + }
|
| + pLevel->u.pCovidx = pCov;
|
| + if( pCov ) pLevel->iIdxCur = iCovCur;
|
| + if( pAndExpr ){
|
| + pAndExpr->pLeft = 0;
|
| + sqlite3ExprDelete(db, pAndExpr);
|
| + }
|
| + sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
|
| + sqlite3VdbeGoto(v, pLevel->addrBrk);
|
| + sqlite3VdbeResolveLabel(v, iLoopBody);
|
| +
|
| + if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
|
| + if( !untestedTerms ) disableTerm(pLevel, pTerm);
|
| + }else
|
| +#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
|
| +
|
| + {
|
| + /* Case 6: There is no usable index. We must do a complete
|
| + ** scan of the entire table.
|
| + */
|
| + static const u8 aStep[] = { OP_Next, OP_Prev };
|
| + static const u8 aStart[] = { OP_Rewind, OP_Last };
|
| + assert( bRev==0 || bRev==1 );
|
| + if( pTabItem->fg.isRecursive ){
|
| + /* Tables marked isRecursive have only a single row that is stored in
|
| + ** a pseudo-cursor. No need to Rewind or Next such cursors. */
|
| + pLevel->op = OP_Noop;
|
| + }else{
|
| + codeCursorHint(pWInfo, pLevel, 0);
|
| + pLevel->op = aStep[bRev];
|
| + pLevel->p1 = iCur;
|
| + pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
|
| + VdbeCoverageIf(v, bRev==0);
|
| + VdbeCoverageIf(v, bRev!=0);
|
| + pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
|
| + }
|
| + }
|
| +
|
| +#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
|
| + pLevel->addrVisit = sqlite3VdbeCurrentAddr(v);
|
| +#endif
|
| +
|
| + /* Insert code to test every subexpression that can be completely
|
| + ** computed using the current set of tables.
|
| + */
|
| + for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
|
| + Expr *pE;
|
| + int skipLikeAddr = 0;
|
| + testcase( pTerm->wtFlags & TERM_VIRTUAL );
|
| + testcase( pTerm->wtFlags & TERM_CODED );
|
| + if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
|
| + if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
|
| + testcase( pWInfo->untestedTerms==0
|
| + && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
|
| + pWInfo->untestedTerms = 1;
|
| + continue;
|
| + }
|
| + pE = pTerm->pExpr;
|
| + assert( pE!=0 );
|
| + if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
|
| + continue;
|
| + }
|
| + if( pTerm->wtFlags & TERM_LIKECOND ){
|
| +#ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
|
| + continue;
|
| +#else
|
| + assert( pLevel->iLikeRepCntr>0 );
|
| + skipLikeAddr = sqlite3VdbeAddOp1(v, OP_IfNot, pLevel->iLikeRepCntr);
|
| + VdbeCoverage(v);
|
| +#endif
|
| + }
|
| + sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
|
| + if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);
|
| + pTerm->wtFlags |= TERM_CODED;
|
| + }
|
| +
|
| + /* Insert code to test for implied constraints based on transitivity
|
| + ** of the "==" operator.
|
| + **
|
| + ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
|
| + ** and we are coding the t1 loop and the t2 loop has not yet coded,
|
| + ** then we cannot use the "t1.a=t2.b" constraint, but we can code
|
| + ** the implied "t1.a=123" constraint.
|
| + */
|
| + for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
|
| + Expr *pE, *pEAlt;
|
| + WhereTerm *pAlt;
|
| + if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
|
| + if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue;
|
| + if( (pTerm->eOperator & WO_EQUIV)==0 ) continue;
|
| + if( pTerm->leftCursor!=iCur ) continue;
|
| + if( pLevel->iLeftJoin ) continue;
|
| + pE = pTerm->pExpr;
|
| + assert( !ExprHasProperty(pE, EP_FromJoin) );
|
| + assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
|
| + pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.leftColumn, notReady,
|
| + WO_EQ|WO_IN|WO_IS, 0);
|
| + if( pAlt==0 ) continue;
|
| + if( pAlt->wtFlags & (TERM_CODED) ) continue;
|
| + testcase( pAlt->eOperator & WO_EQ );
|
| + testcase( pAlt->eOperator & WO_IS );
|
| + testcase( pAlt->eOperator & WO_IN );
|
| + VdbeModuleComment((v, "begin transitive constraint"));
|
| + pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
|
| + if( pEAlt ){
|
| + *pEAlt = *pAlt->pExpr;
|
| + pEAlt->pLeft = pE->pLeft;
|
| + sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
|
| + sqlite3StackFree(db, pEAlt);
|
| + }
|
| + }
|
| +
|
| + /* For a LEFT OUTER JOIN, generate code that will record the fact that
|
| + ** at least one row of the right table has matched the left table.
|
| + */
|
| + if( pLevel->iLeftJoin ){
|
| + pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
|
| + sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
|
| + VdbeComment((v, "record LEFT JOIN hit"));
|
| + sqlite3ExprCacheClear(pParse);
|
| + for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
|
| + testcase( pTerm->wtFlags & TERM_VIRTUAL );
|
| + testcase( pTerm->wtFlags & TERM_CODED );
|
| + if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
|
| + if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
|
| + assert( pWInfo->untestedTerms );
|
| + continue;
|
| + }
|
| + assert( pTerm->pExpr );
|
| + sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
|
| + pTerm->wtFlags |= TERM_CODED;
|
| + }
|
| + }
|
| +
|
| + return pLevel->notReady;
|
| +}
|
| +
|
| +/************** End of wherecode.c *******************************************/
|
| +/************** Begin file whereexpr.c ***************************************/
|
| +/*
|
| +** 2015-06-08
|
| +**
|
| +** The author disclaims copyright to this source code. In place of
|
| +** a legal notice, here is a blessing:
|
| +**
|
| +** May you do good and not evil.
|
| +** May you find forgiveness for yourself and forgive others.
|
| +** May you share freely, never taking more than you give.
|
| +**
|
| +*************************************************************************
|
| +** This module contains C code that generates VDBE code used to process
|
| +** the WHERE clause of SQL statements.
|
| +**
|
| +** This file was originally part of where.c but was split out to improve
|
| +** readability and editabiliity. This file contains utility routines for
|
| +** analyzing Expr objects in the WHERE clause.
|
| +*/
|
| +/* #include "sqliteInt.h" */
|
| +/* #include "whereInt.h" */
|
| +
|
| +/* Forward declarations */
|
| +static void exprAnalyze(SrcList*, WhereClause*, int);
|
| +
|
| +/*
|
| +** Deallocate all memory associated with a WhereOrInfo object.
|
| +*/
|
| +static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
|
| + sqlite3WhereClauseClear(&p->wc);
|
| + sqlite3DbFree(db, p);
|
| +}
|
| +
|
| +/*
|
| +** Deallocate all memory associated with a WhereAndInfo object.
|
| +*/
|
| +static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
|
| + sqlite3WhereClauseClear(&p->wc);
|
| + sqlite3DbFree(db, p);
|
| +}
|
| +
|
| +/*
|
| +** Add a single new WhereTerm entry to the WhereClause object pWC.
|
| +** The new WhereTerm object is constructed from Expr p and with wtFlags.
|
| +** The index in pWC->a[] of the new WhereTerm is returned on success.
|
| +** 0 is returned if the new WhereTerm could not be added due to a memory
|
| +** allocation error. The memory allocation failure will be recorded in
|
| +** the db->mallocFailed flag so that higher-level functions can detect it.
|
| +**
|
| +** This routine will increase the size of the pWC->a[] array as necessary.
|
| +**
|
| +** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
|
| +** for freeing the expression p is assumed by the WhereClause object pWC.
|
| +** This is true even if this routine fails to allocate a new WhereTerm.
|
| +**
|
| +** WARNING: This routine might reallocate the space used to store
|
| +** WhereTerms. All pointers to WhereTerms should be invalidated after
|
| +** calling this routine. Such pointers may be reinitialized by referencing
|
| +** the pWC->a[] array.
|
| +*/
|
| +static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags){
|
| + WhereTerm *pTerm;
|
| + int idx;
|
| + testcase( wtFlags & TERM_VIRTUAL );
|
| + if( pWC->nTerm>=pWC->nSlot ){
|
| + WhereTerm *pOld = pWC->a;
|
| + sqlite3 *db = pWC->pWInfo->pParse->db;
|
| + pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
|
| + if( pWC->a==0 ){
|
| + if( wtFlags & TERM_DYNAMIC ){
|
| + sqlite3ExprDelete(db, p);
|
| + }
|
| + pWC->a = pOld;
|
| + return 0;
|
| + }
|
| + memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
|
| + if( pOld!=pWC->aStatic ){
|
| + sqlite3DbFree(db, pOld);
|
| + }
|
| + pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
|
| + memset(&pWC->a[pWC->nTerm], 0, sizeof(pWC->a[0])*(pWC->nSlot-pWC->nTerm));
|
| + }
|
| + pTerm = &pWC->a[idx = pWC->nTerm++];
|
| + if( p && ExprHasProperty(p, EP_Unlikely) ){
|
| + pTerm->truthProb = sqlite3LogEst(p->iTable) - 270;
|
| + }else{
|
| + pTerm->truthProb = 1;
|
| + }
|
| + pTerm->pExpr = sqlite3ExprSkipCollate(p);
|
| + pTerm->wtFlags = wtFlags;
|
| + pTerm->pWC = pWC;
|
| + pTerm->iParent = -1;
|
| + return idx;
|
| +}
|
| +
|
| +/*
|
| +** Return TRUE if the given operator is one of the operators that is
|
| +** allowed for an indexable WHERE clause term. The allowed operators are
|
| +** "=", "<", ">", "<=", ">=", "IN", and "IS NULL"
|
| +*/
|
| +static int allowedOp(int op){
|
| + assert( TK_GT>TK_EQ && TK_GT<TK_GE );
|
| + assert( TK_LT>TK_EQ && TK_LT<TK_GE );
|
| + assert( TK_LE>TK_EQ && TK_LE<TK_GE );
|
| + assert( TK_GE==TK_EQ+4 );
|
| + return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL || op==TK_IS;
|
| +}
|
| +
|
| +/*
|
| +** Commute a comparison operator. Expressions of the form "X op Y"
|
| +** are converted into "Y op X".
|
| +**
|
| +** If left/right precedence rules come into play when determining the
|
| +** collating sequence, then COLLATE operators are adjusted to ensure
|
| +** that the collating sequence does not change. For example:
|
| +** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
|
| +** the left hand side of a comparison overrides any collation sequence
|
| +** attached to the right. For the same reason the EP_Collate flag
|
| +** is not commuted.
|
| +*/
|
| +static void exprCommute(Parse *pParse, Expr *pExpr){
|
| + u16 expRight = (pExpr->pRight->flags & EP_Collate);
|
| + u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
|
| + assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
|
| + if( expRight==expLeft ){
|
| + /* Either X and Y both have COLLATE operator or neither do */
|
| + if( expRight ){
|
| + /* Both X and Y have COLLATE operators. Make sure X is always
|
| + ** used by clearing the EP_Collate flag from Y. */
|
| + pExpr->pRight->flags &= ~EP_Collate;
|
| + }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
|
| + /* Neither X nor Y have COLLATE operators, but X has a non-default
|
| + ** collating sequence. So add the EP_Collate marker on X to cause
|
| + ** it to be searched first. */
|
| + pExpr->pLeft->flags |= EP_Collate;
|
| + }
|
| + }
|
| + SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
|
| + if( pExpr->op>=TK_GT ){
|
| + assert( TK_LT==TK_GT+2 );
|
| + assert( TK_GE==TK_LE+2 );
|
| + assert( TK_GT>TK_EQ );
|
| + assert( TK_GT<TK_LE );
|
| + assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
|
| + pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
|
| + }
|
| +}
|
| +
|
| +/*
|
| +** Translate from TK_xx operator to WO_xx bitmask.
|
| +*/
|
| +static u16 operatorMask(int op){
|
| + u16 c;
|
| + assert( allowedOp(op) );
|
| + if( op==TK_IN ){
|
| + c = WO_IN;
|
| + }else if( op==TK_ISNULL ){
|
| + c = WO_ISNULL;
|
| + }else if( op==TK_IS ){
|
| + c = WO_IS;
|
| + }else{
|
| + assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
|
| + c = (u16)(WO_EQ<<(op-TK_EQ));
|
| + }
|
| + assert( op!=TK_ISNULL || c==WO_ISNULL );
|
| + assert( op!=TK_IN || c==WO_IN );
|
| + assert( op!=TK_EQ || c==WO_EQ );
|
| + assert( op!=TK_LT || c==WO_LT );
|
| + assert( op!=TK_LE || c==WO_LE );
|
| + assert( op!=TK_GT || c==WO_GT );
|
| + assert( op!=TK_GE || c==WO_GE );
|
| + assert( op!=TK_IS || c==WO_IS );
|
| + return c;
|
| +}
|
| +
|
| +
|
| +#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
|
| +/*
|
| +** Check to see if the given expression is a LIKE or GLOB operator that
|
| +** can be optimized using inequality constraints. Return TRUE if it is
|
| +** so and false if not.
|
| +**
|
| +** In order for the operator to be optimizible, the RHS must be a string
|
| +** literal that does not begin with a wildcard. The LHS must be a column
|
| +** that may only be NULL, a string, or a BLOB, never a number. (This means
|
| +** that virtual tables cannot participate in the LIKE optimization.) The
|
| +** collating sequence for the column on the LHS must be appropriate for
|
| +** the operator.
|
| +*/
|
| +static int isLikeOrGlob(
|
| + Parse *pParse, /* Parsing and code generating context */
|
| + Expr *pExpr, /* Test this expression */
|
| + Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
|
| + int *pisComplete, /* True if the only wildcard is % in the last character */
|
| + int *pnoCase /* True if uppercase is equivalent to lowercase */
|
| +){
|
| + const char *z = 0; /* String on RHS of LIKE operator */
|
| + Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
|
| + ExprList *pList; /* List of operands to the LIKE operator */
|
| + int c; /* One character in z[] */
|
| + int cnt; /* Number of non-wildcard prefix characters */
|
| + char wc[3]; /* Wildcard characters */
|
| + sqlite3 *db = pParse->db; /* Database connection */
|
| + sqlite3_value *pVal = 0;
|
| + int op; /* Opcode of pRight */
|
| +
|
| + if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
|
| + return 0;
|
| + }
|
| +#ifdef SQLITE_EBCDIC
|
| + if( *pnoCase ) return 0;
|
| +#endif
|
| + pList = pExpr->x.pList;
|
| + pLeft = pList->a[1].pExpr;
|
| + if( pLeft->op!=TK_COLUMN
|
| + || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
|
| + || IsVirtual(pLeft->pTab) /* Value might be numeric */
|
| + ){
|
| + /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
|
| + ** be the name of an indexed column with TEXT affinity. */
|
| + return 0;
|
| + }
|
| + assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
|
| +
|
| + pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
|
| + op = pRight->op;
|
| + if( op==TK_VARIABLE ){
|
| + Vdbe *pReprepare = pParse->pReprepare;
|
| + int iCol = pRight->iColumn;
|
| + pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_BLOB);
|
| + if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
|
| + z = (char *)sqlite3_value_text(pVal);
|
| + }
|
| + sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
|
| + assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
|
| + }else if( op==TK_STRING ){
|
| + z = pRight->u.zToken;
|
| + }
|
| + if( z ){
|
| + cnt = 0;
|
| + while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
|
| + cnt++;
|
| + }
|
| + if( cnt!=0 && 255!=(u8)z[cnt-1] ){
|
| + Expr *pPrefix;
|
| + *pisComplete = c==wc[0] && z[cnt+1]==0;
|
| + pPrefix = sqlite3Expr(db, TK_STRING, z);
|
| + if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
|
| + *ppPrefix = pPrefix;
|
| + if( op==TK_VARIABLE ){
|
| + Vdbe *v = pParse->pVdbe;
|
| + sqlite3VdbeSetVarmask(v, pRight->iColumn);
|
| + if( *pisComplete && pRight->u.zToken[1] ){
|
| + /* If the rhs of the LIKE expression is a variable, and the current
|
| + ** value of the variable means there is no need to invoke the LIKE
|
| + ** function, then no OP_Variable will be added to the program.
|
| + ** This causes problems for the sqlite3_bind_parameter_name()
|
| + ** API. To work around them, add a dummy OP_Variable here.
|
| + */
|
| + int r1 = sqlite3GetTempReg(pParse);
|
| + sqlite3ExprCodeTarget(pParse, pRight, r1);
|
| + sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
|
| + sqlite3ReleaseTempReg(pParse, r1);
|
| + }
|
| + }
|
| + }else{
|
| + z = 0;
|
| + }
|
| + }
|
| +
|
| + sqlite3ValueFree(pVal);
|
| + return (z!=0);
|
| +}
|
| +#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
|
| +
|
| +
|
| +#ifndef SQLITE_OMIT_VIRTUALTABLE
|
| +/*
|
| +** Check to see if the given expression is of the form
|
| +**
|
| +** column OP expr
|
| +**
|
| +** where OP is one of MATCH, GLOB, LIKE or REGEXP and "column" is a
|
| +** column of a virtual table.
|
| +**
|
| +** If it is then return TRUE. If not, return FALSE.
|
| +*/
|
| +static int isMatchOfColumn(
|
| + Expr *pExpr, /* Test this expression */
|
| + unsigned char *peOp2 /* OUT: 0 for MATCH, or else an op2 value */
|
| +){
|
| + struct Op2 {
|
| + const char *zOp;
|
| + unsigned char eOp2;
|
| + } aOp[] = {
|
| + { "match", SQLITE_INDEX_CONSTRAINT_MATCH },
|
| + { "glob", SQLITE_INDEX_CONSTRAINT_GLOB },
|
| + { "like", SQLITE_INDEX_CONSTRAINT_LIKE },
|
| + { "regexp", SQLITE_INDEX_CONSTRAINT_REGEXP }
|
| + };
|
| + ExprList *pList;
|
| + Expr *pCol; /* Column reference */
|
| + int i;
|
| +
|
| + if( pExpr->op!=TK_FUNCTION ){
|
| + return 0;
|
| + }
|
| + pList = pExpr->x.pList;
|
| + if( pList==0 || pList->nExpr!=2 ){
|
| + return 0;
|
| + }
|
| + pCol = pList->a[1].pExpr;
|
| + if( pCol->op!=TK_COLUMN || !IsVirtual(pCol->pTab) ){
|
| + return 0;
|
| + }
|
| + for(i=0; i<ArraySize(aOp); i++){
|
| + if( sqlite3StrICmp(pExpr->u.zToken, aOp[i].zOp)==0 ){
|
| + *peOp2 = aOp[i].eOp2;
|
| + return 1;
|
| + }
|
| + }
|
| + return 0;
|
| +}
|
| +#endif /* SQLITE_OMIT_VIRTUALTABLE */
|
| +
|
| +/*
|
| +** If the pBase expression originated in the ON or USING clause of
|
| +** a join, then transfer the appropriate markings over to derived.
|
| +*/
|
| +static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
|
| + if( pDerived ){
|
| + pDerived->flags |= pBase->flags & EP_FromJoin;
|
| + pDerived->iRightJoinTable = pBase->iRightJoinTable;
|
| + }
|
| +}
|
| +
|
| +/*
|
| +** Mark term iChild as being a child of term iParent
|
| +*/
|
| +static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
|
| + pWC->a[iChild].iParent = iParent;
|
| + pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
|
| + pWC->a[iParent].nChild++;
|
| +}
|
| +
|
| +/*
|
| +** Return the N-th AND-connected subterm of pTerm. Or if pTerm is not
|
| +** a conjunction, then return just pTerm when N==0. If N is exceeds
|
| +** the number of available subterms, return NULL.
|
| +*/
|
| +static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){
|
| + if( pTerm->eOperator!=WO_AND ){
|
| + return N==0 ? pTerm : 0;
|
| + }
|
| + if( N<pTerm->u.pAndInfo->wc.nTerm ){
|
| + return &pTerm->u.pAndInfo->wc.a[N];
|
| + }
|
| + return 0;
|
| +}
|
| +
|
| +/*
|
| +** Subterms pOne and pTwo are contained within WHERE clause pWC. The
|
| +** two subterms are in disjunction - they are OR-ed together.
|
| +**
|
| +** If these two terms are both of the form: "A op B" with the same
|
| +** A and B values but different operators and if the operators are
|
| +** compatible (if one is = and the other is <, for example) then
|
| +** add a new virtual AND term to pWC that is the combination of the
|
| +** two.
|
| +**
|
| +** Some examples:
|
| +**
|
| +** x<y OR x=y --> x<=y
|
| +** x=y OR x=y --> x=y
|
| +** x<=y OR x<y --> x<=y
|
| +**
|
| +** The following is NOT generated:
|
| +**
|
| +** x<y OR x>y --> x!=y
|
| +*/
|
| +static void whereCombineDisjuncts(
|
| + SrcList *pSrc, /* the FROM clause */
|
| + WhereClause *pWC, /* The complete WHERE clause */
|
| + WhereTerm *pOne, /* First disjunct */
|
| + WhereTerm *pTwo /* Second disjunct */
|
| +){
|
| + u16 eOp = pOne->eOperator | pTwo->eOperator;
|
| + sqlite3 *db; /* Database connection (for malloc) */
|
| + Expr *pNew; /* New virtual expression */
|
| + int op; /* Operator for the combined expression */
|
| + int idxNew; /* Index in pWC of the next virtual term */
|
| +
|
| + if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
|
| + if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
|
| + if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp
|
| + && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return;
|
| + assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 );
|
| + assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 );
|
| + if( sqlite3ExprCompare(pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return;
|
| + if( sqlite3ExprCompare(pOne->pExpr->pRight, pTwo->pExpr->pRight, -1) )return;
|
| + /* If we reach this point, it means the two subterms can be combined */
|
| + if( (eOp & (eOp-1))!=0 ){
|
| + if( eOp & (WO_LT|WO_LE) ){
|
| + eOp = WO_LE;
|
| + }else{
|
| + assert( eOp & (WO_GT|WO_GE) );
|
| + eOp = WO_GE;
|
| + }
|
| + }
|
| + db = pWC->pWInfo->pParse->db;
|
| + pNew = sqlite3ExprDup(db, pOne->pExpr, 0);
|
| + if( pNew==0 ) return;
|
| + for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); }
|
| + pNew->op = op;
|
| + idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
|
| + exprAnalyze(pSrc, pWC, idxNew);
|
| +}
|
| +
|
| +#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
|
| +/*
|
| +** Analyze a term that consists of two or more OR-connected
|
| +** subterms. So in:
|
| +**
|
| +** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
|
| +** ^^^^^^^^^^^^^^^^^^^^
|
| +**
|
| +** This routine analyzes terms such as the middle term in the above example.
|
| +** A WhereOrTerm object is computed and attached to the term under
|
| +** analysis, regardless of the outcome of the analysis. Hence:
|
| +**
|
| +** WhereTerm.wtFlags |= TERM_ORINFO
|
| +** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
|
| +**
|
| +** The term being analyzed must have two or more of OR-connected subterms.
|
| +** A single subterm might be a set of AND-connected sub-subterms.
|
| +** Examples of terms under analysis:
|
| +**
|
| +** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
|
| +** (B) x=expr1 OR expr2=x OR x=expr3
|
| +** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
|
| +** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
|
| +** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
|
| +** (F) x>A OR (x=A AND y>=B)
|
| +**
|
| +** CASE 1:
|
| +**
|
| +** If all subterms are of the form T.C=expr for some single column of C and
|
| +** a single table T (as shown in example B above) then create a new virtual
|
| +** term that is an equivalent IN expression. In other words, if the term
|
| +** being analyzed is:
|
| +**
|
| +** x = expr1 OR expr2 = x OR x = expr3
|
| +**
|
| +** then create a new virtual term like this:
|
| +**
|
| +** x IN (expr1,expr2,expr3)
|
| +**
|
| +** CASE 2:
|
| +**
|
| +** If there are exactly two disjuncts and one side has x>A and the other side
|
| +** has x=A (for the same x and A) then add a new virtual conjunct term to the
|
| +** WHERE clause of the form "x>=A". Example:
|
| +**
|
| +** x>A OR (x=A AND y>B) adds: x>=A
|
| +**
|
| +** The added conjunct can sometimes be helpful in query planning.
|
| +**
|
| +** CASE 3:
|
| +**
|
| +** If all subterms are indexable by a single table T, then set
|
| +**
|
| +** WhereTerm.eOperator = WO_OR
|
| +** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
|
| +**
|
| +** A subterm is "indexable" if it is of the form
|
| +** "T.C <op> <expr>" where C is any column of table T and
|
| +** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
|
| +** A subterm is also indexable if it is an AND of two or more
|
| +** subsubterms at least one of which is indexable. Indexable AND
|
| +** subterms have their eOperator set to WO_AND and they have
|
| +** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
|
| +**
|
| +** From another point of view, "indexable" means that the subterm could
|
| +** potentially be used with an index if an appropriate index exists.
|
| +** This analysis does not consider whether or not the index exists; that
|
| +** is decided elsewhere. This analysis only looks at whether subterms
|
| +** appropriate for indexing exist.
|
| +**
|
| +** All examples A through E above satisfy case 3. But if a term
|
| +** also satisfies case 1 (such as B) we know that the optimizer will
|
| +** always prefer case 1, so in that case we pretend that case 3 is not
|
| +** satisfied.
|
| +**
|
| +** It might be the case that multiple tables are indexable. For example,
|
| +** (E) above is indexable on tables P, Q, and R.
|
| +**
|
| +** Terms that satisfy case 3 are candidates for lookup by using
|
| +** separate indices to find rowids for each subterm and composing
|
| +** the union of all rowids using a RowSet object. This is similar
|
| +** to "bitmap indices" in other database engines.
|
| +**
|
| +** OTHERWISE:
|
| +**
|
| +** If none of cases 1, 2, or 3 apply, then leave the eOperator set to
|
| +** zero. This term is not useful for search.
|
| +*/
|
| +static void exprAnalyzeOrTerm(
|
| + SrcList *pSrc, /* the FROM clause */
|
| + WhereClause *pWC, /* the complete WHERE clause */
|
| + int idxTerm /* Index of the OR-term to be analyzed */
|
| +){
|
| + WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
|
| + Parse *pParse = pWInfo->pParse; /* Parser context */
|
| + sqlite3 *db = pParse->db; /* Database connection */
|
| + WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
|
| + Expr *pExpr = pTerm->pExpr; /* The expression of the term */
|
| + int i; /* Loop counters */
|
| + WhereClause *pOrWc; /* Breakup of pTerm into subterms */
|
| + WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
|
| + WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
|
| + Bitmask chngToIN; /* Tables that might satisfy case 1 */
|
| + Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
|
| +
|
| + /*
|
| + ** Break the OR clause into its separate subterms. The subterms are
|
| + ** stored in a WhereClause structure containing within the WhereOrInfo
|
| + ** object that is attached to the original OR clause term.
|
| + */
|
| + assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
|
| + assert( pExpr->op==TK_OR );
|
| + pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
|
| + if( pOrInfo==0 ) return;
|
| + pTerm->wtFlags |= TERM_ORINFO;
|
| + pOrWc = &pOrInfo->wc;
|
| + sqlite3WhereClauseInit(pOrWc, pWInfo);
|
| + sqlite3WhereSplit(pOrWc, pExpr, TK_OR);
|
| + sqlite3WhereExprAnalyze(pSrc, pOrWc);
|
| + if( db->mallocFailed ) return;
|
| + assert( pOrWc->nTerm>=2 );
|
| +
|
| + /*
|
| + ** Compute the set of tables that might satisfy cases 1 or 3.
|
| + */
|
| + indexable = ~(Bitmask)0;
|
| + chngToIN = ~(Bitmask)0;
|
| + for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
|
| + if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
|
| + WhereAndInfo *pAndInfo;
|
| + assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
|
| + chngToIN = 0;
|
| + pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
|
| + if( pAndInfo ){
|
| + WhereClause *pAndWC;
|
| + WhereTerm *pAndTerm;
|
| + int j;
|
| + Bitmask b = 0;
|
| + pOrTerm->u.pAndInfo = pAndInfo;
|
| + pOrTerm->wtFlags |= TERM_ANDINFO;
|
| + pOrTerm->eOperator = WO_AND;
|
| + pAndWC = &pAndInfo->wc;
|
| + sqlite3WhereClauseInit(pAndWC, pWC->pWInfo);
|
| + sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
|
| + sqlite3WhereExprAnalyze(pSrc, pAndWC);
|
| + pAndWC->pOuter = pWC;
|
| + testcase( db->mallocFailed );
|
| + if( !db->mallocFailed ){
|
| + for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
|
| + assert( pAndTerm->pExpr );
|
| + if( allowedOp(pAndTerm->pExpr->op) ){
|
| + b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
|
| + }
|
| + }
|
| + }
|
| + indexable &= b;
|
| + }
|
| + }else if( pOrTerm->wtFlags & TERM_COPIED ){
|
| + /* Skip this term for now. We revisit it when we process the
|
| + ** corresponding TERM_VIRTUAL term */
|
| + }else{
|
| + Bitmask b;
|
| + b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
|
| + if( pOrTerm->wtFlags & TERM_VIRTUAL ){
|
| + WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
|
| + b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor);
|
| + }
|
| + indexable &= b;
|
| + if( (pOrTerm->eOperator & WO_EQ)==0 ){
|
| + chngToIN = 0;
|
| + }else{
|
| + chngToIN &= b;
|
| + }
|
| + }
|
| + }
|
| +
|
| + /*
|
| + ** Record the set of tables that satisfy case 3. The set might be
|
| + ** empty.
|
| + */
|
| + pOrInfo->indexable = indexable;
|
| + pTerm->eOperator = indexable==0 ? 0 : WO_OR;
|
| +
|
| + /* For a two-way OR, attempt to implementation case 2.
|
| + */
|
| + if( indexable && pOrWc->nTerm==2 ){
|
| + int iOne = 0;
|
| + WhereTerm *pOne;
|
| + while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){
|
| + int iTwo = 0;
|
| + WhereTerm *pTwo;
|
| + while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){
|
| + whereCombineDisjuncts(pSrc, pWC, pOne, pTwo);
|
| + }
|
| + }
|
| + }
|
| +
|
| + /*
|
| + ** chngToIN holds a set of tables that *might* satisfy case 1. But
|
| + ** we have to do some additional checking to see if case 1 really
|
| + ** is satisfied.
|
| + **
|
| + ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
|
| + ** that there is no possibility of transforming the OR clause into an
|
| + ** IN operator because one or more terms in the OR clause contain
|
| + ** something other than == on a column in the single table. The 1-bit
|
| + ** case means that every term of the OR clause is of the form
|
| + ** "table.column=expr" for some single table. The one bit that is set
|
| + ** will correspond to the common table. We still need to check to make
|
| + ** sure the same column is used on all terms. The 2-bit case is when
|
| + ** the all terms are of the form "table1.column=table2.column". It
|
| + ** might be possible to form an IN operator with either table1.column
|
| + ** or table2.column as the LHS if either is common to every term of
|
| + ** the OR clause.
|
| + **
|
| + ** Note that terms of the form "table.column1=table.column2" (the
|
| + ** same table on both sizes of the ==) cannot be optimized.
|
| + */
|
| + if( chngToIN ){
|
| + int okToChngToIN = 0; /* True if the conversion to IN is valid */
|
| + int iColumn = -1; /* Column index on lhs of IN operator */
|
| + int iCursor = -1; /* Table cursor common to all terms */
|
| + int j = 0; /* Loop counter */
|
| +
|
| + /* Search for a table and column that appears on one side or the
|
| + ** other of the == operator in every subterm. That table and column
|
| + ** will be recorded in iCursor and iColumn. There might not be any
|
| + ** such table and column. Set okToChngToIN if an appropriate table
|
| + ** and column is found but leave okToChngToIN false if not found.
|
| + */
|
| + for(j=0; j<2 && !okToChngToIN; j++){
|
| + pOrTerm = pOrWc->a;
|
| + for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
|
| + assert( pOrTerm->eOperator & WO_EQ );
|
| + pOrTerm->wtFlags &= ~TERM_OR_OK;
|
| + if( pOrTerm->leftCursor==iCursor ){
|
| + /* This is the 2-bit case and we are on the second iteration and
|
| + ** current term is from the first iteration. So skip this term. */
|
| + assert( j==1 );
|
| + continue;
|
| + }
|
| + if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet,
|
| + pOrTerm->leftCursor))==0 ){
|
| + /* This term must be of the form t1.a==t2.b where t2 is in the
|
| + ** chngToIN set but t1 is not. This term will be either preceded
|
| + ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
|
| + ** and use its inversion. */
|
| + testcase( pOrTerm->wtFlags & TERM_COPIED );
|
| + testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
|
| + assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
|
| + continue;
|
| + }
|
| + iColumn = pOrTerm->u.leftColumn;
|
| + iCursor = pOrTerm->leftCursor;
|
| + break;
|
| + }
|
| + if( i<0 ){
|
| + /* No candidate table+column was found. This can only occur
|
| + ** on the second iteration */
|
| + assert( j==1 );
|
| + assert( IsPowerOfTwo(chngToIN) );
|
| + assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) );
|
| + break;
|
| + }
|
| + testcase( j==1 );
|
| +
|
| + /* We have found a candidate table and column. Check to see if that
|
| + ** table and column is common to every term in the OR clause */
|
| + okToChngToIN = 1;
|
| + for(; i>=0 && okToChngToIN; i--, pOrTerm++){
|
| + assert( pOrTerm->eOperator & WO_EQ );
|
| + if( pOrTerm->leftCursor!=iCursor ){
|
| + pOrTerm->wtFlags &= ~TERM_OR_OK;
|
| + }else if( pOrTerm->u.leftColumn!=iColumn ){
|
| + okToChngToIN = 0;
|
| + }else{
|
| + int affLeft, affRight;
|
| + /* If the right-hand side is also a column, then the affinities
|
| + ** of both right and left sides must be such that no type
|
| + ** conversions are required on the right. (Ticket #2249)
|
| + */
|
| + affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
|
| + affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
|
| + if( affRight!=0 && affRight!=affLeft ){
|
| + okToChngToIN = 0;
|
| + }else{
|
| + pOrTerm->wtFlags |= TERM_OR_OK;
|
| + }
|
| + }
|
| + }
|
| + }
|
| +
|
| + /* At this point, okToChngToIN is true if original pTerm satisfies
|
| + ** case 1. In that case, construct a new virtual term that is
|
| + ** pTerm converted into an IN operator.
|
| + */
|
| + if( okToChngToIN ){
|
| + Expr *pDup; /* A transient duplicate expression */
|
| + ExprList *pList = 0; /* The RHS of the IN operator */
|
| + Expr *pLeft = 0; /* The LHS of the IN operator */
|
| + Expr *pNew; /* The complete IN operator */
|
| +
|
| + for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
|
| + if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
|
| + assert( pOrTerm->eOperator & WO_EQ );
|
| + assert( pOrTerm->leftCursor==iCursor );
|
| + assert( pOrTerm->u.leftColumn==iColumn );
|
| + pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
|
| + pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
|
| + pLeft = pOrTerm->pExpr->pLeft;
|
| + }
|
| + assert( pLeft!=0 );
|
| + pDup = sqlite3ExprDup(db, pLeft, 0);
|
| + pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
|
| + if( pNew ){
|
| + int idxNew;
|
| + transferJoinMarkings(pNew, pExpr);
|
| + assert( !ExprHasProperty(pNew, EP_xIsSelect) );
|
| + pNew->x.pList = pList;
|
| + idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
|
| + testcase( idxNew==0 );
|
| + exprAnalyze(pSrc, pWC, idxNew);
|
| + pTerm = &pWC->a[idxTerm];
|
| + markTermAsChild(pWC, idxNew, idxTerm);
|
| + }else{
|
| + sqlite3ExprListDelete(db, pList);
|
| + }
|
| + pTerm->eOperator = WO_NOOP; /* case 1 trumps case 3 */
|
| + }
|
| + }
|
| +}
|
| +#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
|
| +
|
| +/*
|
| +** We already know that pExpr is a binary operator where both operands are
|
| +** column references. This routine checks to see if pExpr is an equivalence
|
| +** relation:
|
| +** 1. The SQLITE_Transitive optimization must be enabled
|
| +** 2. Must be either an == or an IS operator
|
| +** 3. Not originating in the ON clause of an OUTER JOIN
|
| +** 4. The affinities of A and B must be compatible
|
| +** 5a. Both operands use the same collating sequence OR
|
| +** 5b. The overall collating sequence is BINARY
|
| +** If this routine returns TRUE, that means that the RHS can be substituted
|
| +** for the LHS anyplace else in the WHERE clause where the LHS column occurs.
|
| +** This is an optimization. No harm comes from returning 0. But if 1 is
|
| +** returned when it should not be, then incorrect answers might result.
|
| +*/
|
| +static int termIsEquivalence(Parse *pParse, Expr *pExpr){
|
| + char aff1, aff2;
|
| + CollSeq *pColl;
|
| + const char *zColl1, *zColl2;
|
| + if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0;
|
| + if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0;
|
| + if( ExprHasProperty(pExpr, EP_FromJoin) ) return 0;
|
| + aff1 = sqlite3ExprAffinity(pExpr->pLeft);
|
| + aff2 = sqlite3ExprAffinity(pExpr->pRight);
|
| + if( aff1!=aff2
|
| + && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2))
|
| + ){
|
| + return 0;
|
| + }
|
| + pColl = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight);
|
| + if( pColl==0 || sqlite3StrICmp(pColl->zName, "BINARY")==0 ) return 1;
|
| + pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
|
| + /* Since pLeft and pRight are both a column references, their collating
|
| + ** sequence should always be defined. */
|
| + zColl1 = ALWAYS(pColl) ? pColl->zName : 0;
|
| + pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
|
| + zColl2 = ALWAYS(pColl) ? pColl->zName : 0;
|
| + return sqlite3StrICmp(zColl1, zColl2)==0;
|
| +}
|
| +
|
| +/*
|
| +** Recursively walk the expressions of a SELECT statement and generate
|
| +** a bitmask indicating which tables are used in that expression
|
| +** tree.
|
| +*/
|
| +static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){
|
| + Bitmask mask = 0;
|
| + while( pS ){
|
| + SrcList *pSrc = pS->pSrc;
|
| + mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList);
|
| + mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy);
|
| + mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy);
|
| + mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere);
|
| + mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving);
|
| + if( ALWAYS(pSrc!=0) ){
|
| + int i;
|
| + for(i=0; i<pSrc->nSrc; i++){
|
| + mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect);
|
| + mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].pOn);
|
| + }
|
| + }
|
| + pS = pS->pPrior;
|
| + }
|
| + return mask;
|
| +}
|
| +
|
| +/*
|
| +** Expression pExpr is one operand of a comparison operator that might
|
| +** be useful for indexing. This routine checks to see if pExpr appears
|
| +** in any index. Return TRUE (1) if pExpr is an indexed term and return
|
| +** FALSE (0) if not. If TRUE is returned, also set *piCur to the cursor
|
| +** number of the table that is indexed and *piColumn to the column number
|
| +** of the column that is indexed, or -2 if an expression is being indexed.
|
| +**
|
| +** If pExpr is a TK_COLUMN column reference, then this routine always returns
|
| +** true even if that particular column is not indexed, because the column
|
| +** might be added to an automatic index later.
|
| +*/
|
| +static int exprMightBeIndexed(
|
| + SrcList *pFrom, /* The FROM clause */
|
| + Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */
|
| + Expr *pExpr, /* An operand of a comparison operator */
|
| + int *piCur, /* Write the referenced table cursor number here */
|
| + int *piColumn /* Write the referenced table column number here */
|
| +){
|
| + Index *pIdx;
|
| + int i;
|
| + int iCur;
|
| + if( pExpr->op==TK_COLUMN ){
|
| + *piCur = pExpr->iTable;
|
| + *piColumn = pExpr->iColumn;
|
| + return 1;
|
| + }
|
| + if( mPrereq==0 ) return 0; /* No table references */
|
| + if( (mPrereq&(mPrereq-1))!=0 ) return 0; /* Refs more than one table */
|
| + for(i=0; mPrereq>1; i++, mPrereq>>=1){}
|
| + iCur = pFrom->a[i].iCursor;
|
| + for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){
|
| + if( pIdx->aColExpr==0 ) continue;
|
| + for(i=0; i<pIdx->nKeyCol; i++){
|
| + if( pIdx->aiColumn[i]!=(-2) ) continue;
|
| + if( sqlite3ExprCompare(pExpr, pIdx->aColExpr->a[i].pExpr, iCur)==0 ){
|
| + *piCur = iCur;
|
| + *piColumn = -2;
|
| + return 1;
|
| + }
|
| + }
|
| + }
|
| + return 0;
|
| +}
|
| +
|
| +/*
|
| +** The input to this routine is an WhereTerm structure with only the
|
| +** "pExpr" field filled in. The job of this routine is to analyze the
|
| +** subexpression and populate all the other fields of the WhereTerm
|
| +** structure.
|
| +**
|
| +** If the expression is of the form "<expr> <op> X" it gets commuted
|
| +** to the standard form of "X <op> <expr>".
|
| +**
|
| +** If the expression is of the form "X <op> Y" where both X and Y are
|
| +** columns, then the original expression is unchanged and a new virtual
|
| +** term of the form "Y <op> X" is added to the WHERE clause and
|
| +** analyzed separately. The original term is marked with TERM_COPIED
|
| +** and the new term is marked with TERM_DYNAMIC (because it's pExpr
|
| +** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
|
| +** is a commuted copy of a prior term.) The original term has nChild=1
|
| +** and the copy has idxParent set to the index of the original term.
|
| +*/
|
| +static void exprAnalyze(
|
| + SrcList *pSrc, /* the FROM clause */
|
| + WhereClause *pWC, /* the WHERE clause */
|
| + int idxTerm /* Index of the term to be analyzed */
|
| +){
|
| + WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
|
| + WhereTerm *pTerm; /* The term to be analyzed */
|
| + WhereMaskSet *pMaskSet; /* Set of table index masks */
|
| + Expr *pExpr; /* The expression to be analyzed */
|
| + Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
|
| + Bitmask prereqAll; /* Prerequesites of pExpr */
|
| + Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
|
| + Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
|
| + int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
|
| + int noCase = 0; /* uppercase equivalent to lowercase */
|
| + int op; /* Top-level operator. pExpr->op */
|
| + Parse *pParse = pWInfo->pParse; /* Parsing context */
|
| + sqlite3 *db = pParse->db; /* Database connection */
|
| + unsigned char eOp2; /* op2 value for LIKE/REGEXP/GLOB */
|
| +
|
| + if( db->mallocFailed ){
|
| + return;
|
| + }
|
| + pTerm = &pWC->a[idxTerm];
|
| + pMaskSet = &pWInfo->sMaskSet;
|
| + pExpr = pTerm->pExpr;
|
| + assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
|
| + prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft);
|
| + op = pExpr->op;
|
| + if( op==TK_IN ){
|
| + assert( pExpr->pRight==0 );
|
| + if( ExprHasProperty(pExpr, EP_xIsSelect) ){
|
| + pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect);
|
| + }else{
|
| + pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList);
|
| + }
|
| + }else if( op==TK_ISNULL ){
|
| + pTerm->prereqRight = 0;
|
| + }else{
|
| + pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight);
|
| + }
|
| + prereqAll = sqlite3WhereExprUsage(pMaskSet, pExpr);
|
| + if( ExprHasProperty(pExpr, EP_FromJoin) ){
|
| + Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable);
|
| + prereqAll |= x;
|
| + extraRight = x-1; /* ON clause terms may not be used with an index
|
| + ** on left table of a LEFT JOIN. Ticket #3015 */
|
| + }
|
| + pTerm->prereqAll = prereqAll;
|
| + pTerm->leftCursor = -1;
|
| + pTerm->iParent = -1;
|
| + pTerm->eOperator = 0;
|
| + if( allowedOp(op) ){
|
| + int iCur, iColumn;
|
| + Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
|
| + Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
|
| + u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
|
| + if( exprMightBeIndexed(pSrc, prereqLeft, pLeft, &iCur, &iColumn) ){
|
| + pTerm->leftCursor = iCur;
|
| + pTerm->u.leftColumn = iColumn;
|
| + pTerm->eOperator = operatorMask(op) & opMask;
|
| + }
|
| + if( op==TK_IS ) pTerm->wtFlags |= TERM_IS;
|
| + if( pRight
|
| + && exprMightBeIndexed(pSrc, pTerm->prereqRight, pRight, &iCur, &iColumn)
|
| + ){
|
| + WhereTerm *pNew;
|
| + Expr *pDup;
|
| + u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
|
| + if( pTerm->leftCursor>=0 ){
|
| + int idxNew;
|
| + pDup = sqlite3ExprDup(db, pExpr, 0);
|
| + if( db->mallocFailed ){
|
| + sqlite3ExprDelete(db, pDup);
|
| + return;
|
| + }
|
| + idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
|
| + if( idxNew==0 ) return;
|
| + pNew = &pWC->a[idxNew];
|
| + markTermAsChild(pWC, idxNew, idxTerm);
|
| + if( op==TK_IS ) pNew->wtFlags |= TERM_IS;
|
| + pTerm = &pWC->a[idxTerm];
|
| + pTerm->wtFlags |= TERM_COPIED;
|
| +
|
| + if( termIsEquivalence(pParse, pDup) ){
|
| + pTerm->eOperator |= WO_EQUIV;
|
| + eExtraOp = WO_EQUIV;
|
| + }
|
| + }else{
|
| + pDup = pExpr;
|
| + pNew = pTerm;
|
| + }
|
| + exprCommute(pParse, pDup);
|
| + pNew->leftCursor = iCur;
|
| + pNew->u.leftColumn = iColumn;
|
| + testcase( (prereqLeft | extraRight) != prereqLeft );
|
| + pNew->prereqRight = prereqLeft | extraRight;
|
| + pNew->prereqAll = prereqAll;
|
| + pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
|
| + }
|
| + }
|
| +
|
| +#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
|
| + /* If a term is the BETWEEN operator, create two new virtual terms
|
| + ** that define the range that the BETWEEN implements. For example:
|
| + **
|
| + ** a BETWEEN b AND c
|
| + **
|
| + ** is converted into:
|
| + **
|
| + ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
|
| + **
|
| + ** The two new terms are added onto the end of the WhereClause object.
|
| + ** The new terms are "dynamic" and are children of the original BETWEEN
|
| + ** term. That means that if the BETWEEN term is coded, the children are
|
| + ** skipped. Or, if the children are satisfied by an index, the original
|
| + ** BETWEEN term is skipped.
|
| + */
|
| + else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
|
| + ExprList *pList = pExpr->x.pList;
|
| + int i;
|
| + static const u8 ops[] = {TK_GE, TK_LE};
|
| + assert( pList!=0 );
|
| + assert( pList->nExpr==2 );
|
| + for(i=0; i<2; i++){
|
| + Expr *pNewExpr;
|
| + int idxNew;
|
| + pNewExpr = sqlite3PExpr(pParse, ops[i],
|
| + sqlite3ExprDup(db, pExpr->pLeft, 0),
|
| + sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
|
| + transferJoinMarkings(pNewExpr, pExpr);
|
| + idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
|
| + testcase( idxNew==0 );
|
| + exprAnalyze(pSrc, pWC, idxNew);
|
| + pTerm = &pWC->a[idxTerm];
|
| + markTermAsChild(pWC, idxNew, idxTerm);
|
| + }
|
| + }
|
| +#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
|
| +
|
| +#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
|
| + /* Analyze a term that is composed of two or more subterms connected by
|
| + ** an OR operator.
|
| + */
|
| + else if( pExpr->op==TK_OR ){
|
| + assert( pWC->op==TK_AND );
|
| + exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
|
| + pTerm = &pWC->a[idxTerm];
|
| + }
|
| +#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
|
| +
|
| +#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
|
| + /* Add constraints to reduce the search space on a LIKE or GLOB
|
| + ** operator.
|
| + **
|
| + ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints
|
| + **
|
| + ** x>='ABC' AND x<'abd' AND x LIKE 'aBc%'
|
| + **
|
| + ** The last character of the prefix "abc" is incremented to form the
|
| + ** termination condition "abd". If case is not significant (the default
|
| + ** for LIKE) then the lower-bound is made all uppercase and the upper-
|
| + ** bound is made all lowercase so that the bounds also work when comparing
|
| + ** BLOBs.
|
| + */
|
| + if( pWC->op==TK_AND
|
| + && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
|
| + ){
|
| + Expr *pLeft; /* LHS of LIKE/GLOB operator */
|
| + Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
|
| + Expr *pNewExpr1;
|
| + Expr *pNewExpr2;
|
| + int idxNew1;
|
| + int idxNew2;
|
| + const char *zCollSeqName; /* Name of collating sequence */
|
| + const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
|
| +
|
| + pLeft = pExpr->x.pList->a[1].pExpr;
|
| + pStr2 = sqlite3ExprDup(db, pStr1, 0);
|
| +
|
| + /* Convert the lower bound to upper-case and the upper bound to
|
| + ** lower-case (upper-case is less than lower-case in ASCII) so that
|
| + ** the range constraints also work for BLOBs
|
| + */
|
| + if( noCase && !pParse->db->mallocFailed ){
|
| + int i;
|
| + char c;
|
| + pTerm->wtFlags |= TERM_LIKE;
|
| + for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
|
| + pStr1->u.zToken[i] = sqlite3Toupper(c);
|
| + pStr2->u.zToken[i] = sqlite3Tolower(c);
|
| + }
|
| + }
|
| +
|
| + if( !db->mallocFailed ){
|
| + u8 c, *pC; /* Last character before the first wildcard */
|
| + pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
|
| + c = *pC;
|
| + if( noCase ){
|
| + /* The point is to increment the last character before the first
|
| + ** wildcard. But if we increment '@', that will push it into the
|
| + ** alphabetic range where case conversions will mess up the
|
| + ** inequality. To avoid this, make sure to also run the full
|
| + ** LIKE on all candidate expressions by clearing the isComplete flag
|
| + */
|
| + if( c=='A'-1 ) isComplete = 0;
|
| + c = sqlite3UpperToLower[c];
|
| + }
|
| + *pC = c + 1;
|
| + }
|
| + zCollSeqName = noCase ? "NOCASE" : "BINARY";
|
| + pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
|
| + pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
|
| + sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
|
| + pStr1, 0);
|
| + transferJoinMarkings(pNewExpr1, pExpr);
|
| + idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);
|
| + testcase( idxNew1==0 );
|
| + exprAnalyze(pSrc, pWC, idxNew1);
|
| + pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
|
| + pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
|
| + sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
|
| + pStr2, 0);
|
| + transferJoinMarkings(pNewExpr2, pExpr);
|
| + idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);
|
| + testcase( idxNew2==0 );
|
| + exprAnalyze(pSrc, pWC, idxNew2);
|
| + pTerm = &pWC->a[idxTerm];
|
| + if( isComplete ){
|
| + markTermAsChild(pWC, idxNew1, idxTerm);
|
| + markTermAsChild(pWC, idxNew2, idxTerm);
|
| + }
|
| + }
|
| +#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
|
| +
|
| +#ifndef SQLITE_OMIT_VIRTUALTABLE
|
| + /* Add a WO_MATCH auxiliary term to the constraint set if the
|
| + ** current expression is of the form: column MATCH expr.
|
| + ** This information is used by the xBestIndex methods of
|
| + ** virtual tables. The native query optimizer does not attempt
|
| + ** to do anything with MATCH functions.
|
| + */
|
| + if( isMatchOfColumn(pExpr, &eOp2) ){
|
| + int idxNew;
|
| + Expr *pRight, *pLeft;
|
| + WhereTerm *pNewTerm;
|
| + Bitmask prereqColumn, prereqExpr;
|
| +
|
| + pRight = pExpr->x.pList->a[0].pExpr;
|
| + pLeft = pExpr->x.pList->a[1].pExpr;
|
| + prereqExpr = sqlite3WhereExprUsage(pMaskSet, pRight);
|
| + prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft);
|
| + if( (prereqExpr & prereqColumn)==0 ){
|
| + Expr *pNewExpr;
|
| + pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
|
| + 0, sqlite3ExprDup(db, pRight, 0), 0);
|
| + idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
|
| + testcase( idxNew==0 );
|
| + pNewTerm = &pWC->a[idxNew];
|
| + pNewTerm->prereqRight = prereqExpr;
|
| + pNewTerm->leftCursor = pLeft->iTable;
|
| + pNewTerm->u.leftColumn = pLeft->iColumn;
|
| + pNewTerm->eOperator = WO_MATCH;
|
| + pNewTerm->eMatchOp = eOp2;
|
| + markTermAsChild(pWC, idxNew, idxTerm);
|
| + pTerm = &pWC->a[idxTerm];
|
| + pTerm->wtFlags |= TERM_COPIED;
|
| + pNewTerm->prereqAll = pTerm->prereqAll;
|
| + }
|
| + }
|
| +#endif /* SQLITE_OMIT_VIRTUALTABLE */
|
| +
|
| +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
|
| + /* When sqlite_stat3 histogram data is available an operator of the
|
| + ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
|
| + ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
|
| + ** virtual term of that form.
|
| + **
|
| + ** Note that the virtual term must be tagged with TERM_VNULL.
|
| + */
|
| + if( pExpr->op==TK_NOTNULL
|
| + && pExpr->pLeft->op==TK_COLUMN
|
| + && pExpr->pLeft->iColumn>=0
|
| + && OptimizationEnabled(db, SQLITE_Stat34)
|
| + ){
|
| + Expr *pNewExpr;
|
| + Expr *pLeft = pExpr->pLeft;
|
| + int idxNew;
|
| + WhereTerm *pNewTerm;
|
| +
|
| + pNewExpr = sqlite3PExpr(pParse, TK_GT,
|
| + sqlite3ExprDup(db, pLeft, 0),
|
| + sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
|
| +
|
| + idxNew = whereClauseInsert(pWC, pNewExpr,
|
| + TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
|
| + if( idxNew ){
|
| + pNewTerm = &pWC->a[idxNew];
|
| + pNewTerm->prereqRight = 0;
|
| + pNewTerm->leftCursor = pLeft->iTable;
|
| + pNewTerm->u.leftColumn = pLeft->iColumn;
|
| + pNewTerm->eOperator = WO_GT;
|
| + markTermAsChild(pWC, idxNew, idxTerm);
|
| + pTerm = &pWC->a[idxTerm];
|
| + pTerm->wtFlags |= TERM_COPIED;
|
| + pNewTerm->prereqAll = pTerm->prereqAll;
|
| + }
|
| + }
|
| +#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
|
| +
|
| + /* Prevent ON clause terms of a LEFT JOIN from being used to drive
|
| + ** an index for tables to the left of the join.
|
| + */
|
| + pTerm->prereqRight |= extraRight;
|
| +}
|
| +
|
| +/***************************************************************************
|
| +** Routines with file scope above. Interface to the rest of the where.c
|
| +** subsystem follows.
|
| +***************************************************************************/
|
| +
|
| +/*
|
| +** This routine identifies subexpressions in the WHERE clause where
|
| +** each subexpression is separated by the AND operator or some other
|
| +** operator specified in the op parameter. The WhereClause structure
|
| +** is filled with pointers to subexpressions. For example:
|
| +**
|
| +** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
|
| +** \________/ \_______________/ \________________/
|
| +** slot[0] slot[1] slot[2]
|
| +**
|
| +** The original WHERE clause in pExpr is unaltered. All this routine
|
| +** does is make slot[] entries point to substructure within pExpr.
|
| +**
|
| +** In the previous sentence and in the diagram, "slot[]" refers to
|
| +** the WhereClause.a[] array. The slot[] array grows as needed to contain
|
| +** all terms of the WHERE clause.
|
| +*/
|
| +SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
|
| + Expr *pE2 = sqlite3ExprSkipCollate(pExpr);
|
| + pWC->op = op;
|
| + if( pE2==0 ) return;
|
| + if( pE2->op!=op ){
|
| + whereClauseInsert(pWC, pExpr, 0);
|
| + }else{
|
| + sqlite3WhereSplit(pWC, pE2->pLeft, op);
|
| + sqlite3WhereSplit(pWC, pE2->pRight, op);
|
| + }
|
| +}
|
| +
|
| +/*
|
| +** Initialize a preallocated WhereClause structure.
|
| +*/
|
| +SQLITE_PRIVATE void sqlite3WhereClauseInit(
|
| + WhereClause *pWC, /* The WhereClause to be initialized */
|
| + WhereInfo *pWInfo /* The WHERE processing context */
|
| +){
|
| + pWC->pWInfo = pWInfo;
|
| + pWC->pOuter = 0;
|
| + pWC->nTerm = 0;
|
| + pWC->nSlot = ArraySize(pWC->aStatic);
|
| + pWC->a = pWC->aStatic;
|
| +}
|
| +
|
| +/*
|
| +** Deallocate a WhereClause structure. The WhereClause structure
|
| +** itself is not freed. This routine is the inverse of
|
| +** sqlite3WhereClauseInit().
|
| +*/
|
| +SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause *pWC){
|
| + int i;
|
| + WhereTerm *a;
|
| + sqlite3 *db = pWC->pWInfo->pParse->db;
|
| + for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
|
| + if( a->wtFlags & TERM_DYNAMIC ){
|
| + sqlite3ExprDelete(db, a->pExpr);
|
| + }
|
| + if( a->wtFlags & TERM_ORINFO ){
|
| + whereOrInfoDelete(db, a->u.pOrInfo);
|
| + }else if( a->wtFlags & TERM_ANDINFO ){
|
| + whereAndInfoDelete(db, a->u.pAndInfo);
|
| + }
|
| + }
|
| + if( pWC->a!=pWC->aStatic ){
|
| + sqlite3DbFree(db, pWC->a);
|
| + }
|
| +}
|
| +
|
| +
|
| +/*
|
| +** These routines walk (recursively) an expression tree and generate
|
| +** a bitmask indicating which tables are used in that expression
|
| +** tree.
|
| +*/
|
| +SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){
|
| + Bitmask mask = 0;
|
| + if( p==0 ) return 0;
|
| + if( p->op==TK_COLUMN ){
|
| + mask = sqlite3WhereGetMask(pMaskSet, p->iTable);
|
| + return mask;
|
| + }
|
| + mask = sqlite3WhereExprUsage(pMaskSet, p->pRight);
|
| + mask |= sqlite3WhereExprUsage(pMaskSet, p->pLeft);
|
| + if( ExprHasProperty(p, EP_xIsSelect) ){
|
| + mask |= exprSelectUsage(pMaskSet, p->x.pSelect);
|
| + }else{
|
| + mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
|
| + }
|
| + return mask;
|
| +}
|
| +SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){
|
| + int i;
|
| + Bitmask mask = 0;
|
| + if( pList ){
|
| + for(i=0; i<pList->nExpr; i++){
|
| + mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr);
|
| + }
|
| + }
|
| + return mask;
|
| +}
|
| +
|
| +
|
| +/*
|
| +** Call exprAnalyze on all terms in a WHERE clause.
|
| +**
|
| +** Note that exprAnalyze() might add new virtual terms onto the
|
| +** end of the WHERE clause. We do not want to analyze these new
|
| +** virtual terms, so start analyzing at the end and work forward
|
| +** so that the added virtual terms are never processed.
|
| +*/
|
| +SQLITE_PRIVATE void sqlite3WhereExprAnalyze(
|
| + SrcList *pTabList, /* the FROM clause */
|
| + WhereClause *pWC /* the WHERE clause to be analyzed */
|
| +){
|
| + int i;
|
| + for(i=pWC->nTerm-1; i>=0; i--){
|
| + exprAnalyze(pTabList, pWC, i);
|
| + }
|
| +}
|
| +
|
| +/*
|
| +** For table-valued-functions, transform the function arguments into
|
| +** new WHERE clause terms.
|
| +**
|
| +** Each function argument translates into an equality constraint against
|
| +** a HIDDEN column in the table.
|
| +*/
|
| +SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(
|
| + Parse *pParse, /* Parsing context */
|
| + struct SrcList_item *pItem, /* The FROM clause term to process */
|
| + WhereClause *pWC /* Xfer function arguments to here */
|
| +){
|
| + Table *pTab;
|
| + int j, k;
|
| + ExprList *pArgs;
|
| + Expr *pColRef;
|
| + Expr *pTerm;
|
| + if( pItem->fg.isTabFunc==0 ) return;
|
| + pTab = pItem->pTab;
|
| + assert( pTab!=0 );
|
| + pArgs = pItem->u1.pFuncArg;
|
| + if( pArgs==0 ) return;
|
| + for(j=k=0; j<pArgs->nExpr; j++){
|
| + while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){k++;}
|
| + if( k>=pTab->nCol ){
|
| + sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d",
|
| + pTab->zName, j);
|
| + return;
|
| + }
|
| + pColRef = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
|
| + if( pColRef==0 ) return;
|
| + pColRef->iTable = pItem->iCursor;
|
| + pColRef->iColumn = k++;
|
| + pColRef->pTab = pTab;
|
| + pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef,
|
| + sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0), 0);
|
| + whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);
|
| + }
|
| +}
|
| +
|
| +/************** End of whereexpr.c *******************************************/
|
| +/************** Begin file where.c *******************************************/
|
| +/*
|
| +** 2001 September 15
|
| +**
|
| +** The author disclaims copyright to this source code. In place of
|
| +** a legal notice, here is a blessing:
|
| +**
|
| +** May you do good and not evil.
|
| +** May you find forgiveness for yourself and forgive others.
|
| +** May you share freely, never taking more than you give.
|
| +**
|
| +*************************************************************************
|
| +** This module contains C code that generates VDBE code used to process
|
| +** the WHERE clause of SQL statements. This module is responsible for
|
| +** generating the code that loops through a table looking for applicable
|
| +** rows. Indices are selected and used to speed the search when doing
|
| +** so is applicable. Because this module is responsible for selecting
|
| +** indices, you might also think of this module as the "query optimizer".
|
| +*/
|
| +/* #include "sqliteInt.h" */
|
| +/* #include "whereInt.h" */
|
| +
|
| +/* Forward declaration of methods */
|
| +static int whereLoopResize(sqlite3*, WhereLoop*, int);
|
| +
|
| +/* Test variable that can be set to enable WHERE tracing */
|
| +#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
|
| +/***/ int sqlite3WhereTrace = 0;
|
| +#endif
|
| +
|
| +
|
| +/*
|
| +** Return the estimated number of output rows from a WHERE clause
|
| +*/
|
| +SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
|
| + return sqlite3LogEstToInt(pWInfo->nRowOut);
|
| +}
|
| +
|
| +/*
|
| +** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
|
| +** WHERE clause returns outputs for DISTINCT processing.
|
| +*/
|
| +SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
|
| + return pWInfo->eDistinct;
|
| +}
|
| +
|
| +/*
|
| +** Return TRUE if the WHERE clause returns rows in ORDER BY order.
|
| +** Return FALSE if the output needs to be sorted.
|
| +*/
|
| +SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
|
| + return pWInfo->nOBSat;
|
| +}
|
| +
|
| +/*
|
| +** Return the VDBE address or label to jump to in order to continue
|
| +** immediately with the next row of a WHERE clause.
|
| +*/
|
| +SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
|
| + assert( pWInfo->iContinue!=0 );
|
| + return pWInfo->iContinue;
|
| +}
|
| +
|
| +/*
|
| +** Return the VDBE address or label to jump to in order to break
|
| +** out of a WHERE loop.
|
| +*/
|
| +SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
|
| + return pWInfo->iBreak;
|
| +}
|
| +
|
| +/*
|
| +** Return ONEPASS_OFF (0) if an UPDATE or DELETE statement is unable to
|
| +** operate directly on the rowis returned by a WHERE clause. Return
|
| +** ONEPASS_SINGLE (1) if the statement can operation directly because only
|
| +** a single row is to be changed. Return ONEPASS_MULTI (2) if the one-pass
|
| +** optimization can be used on multiple
|
| +**
|
| +** If the ONEPASS optimization is used (if this routine returns true)
|
| +** then also write the indices of open cursors used by ONEPASS
|
| +** into aiCur[0] and aiCur[1]. iaCur[0] gets the cursor of the data
|
| +** table and iaCur[1] gets the cursor used by an auxiliary index.
|
| +** Either value may be -1, indicating that cursor is not used.
|
| +** Any cursors returned will have been opened for writing.
|
| +**
|
| +** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
|
| +** unable to use the ONEPASS optimization.
|
| +*/
|
| +SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
|
| + memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
|
| +#ifdef WHERETRACE_ENABLED
|
| + if( sqlite3WhereTrace && pWInfo->eOnePass!=ONEPASS_OFF ){
|
| + sqlite3DebugPrintf("%s cursors: %d %d\n",
|
| + pWInfo->eOnePass==ONEPASS_SINGLE ? "ONEPASS_SINGLE" : "ONEPASS_MULTI",
|
| + aiCur[0], aiCur[1]);
|
| + }
|
| +#endif
|
| + return pWInfo->eOnePass;
|
| +}
|
| +
|
| +/*
|
| +** Move the content of pSrc into pDest
|
| +*/
|
| +static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
|
| + pDest->n = pSrc->n;
|
| + memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
|
| +}
|
| +
|
| +/*
|
| +** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
|
| +**
|
| +** The new entry might overwrite an existing entry, or it might be
|
| +** appended, or it might be discarded. Do whatever is the right thing
|
| +** so that pSet keeps the N_OR_COST best entries seen so far.
|
| +*/
|
| +static int whereOrInsert(
|
| + WhereOrSet *pSet, /* The WhereOrSet to be updated */
|
| + Bitmask prereq, /* Prerequisites of the new entry */
|
| + LogEst rRun, /* Run-cost of the new entry */
|
| + LogEst nOut /* Number of outputs for the new entry */
|
| +){
|
| + u16 i;
|
| + WhereOrCost *p;
|
| + for(i=pSet->n, p=pSet->a; i>0; i--, p++){
|
| + if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
|
| + goto whereOrInsert_done;
|
| + }
|
| + if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
|
| + return 0;
|
| + }
|
| + }
|
| + if( pSet->n<N_OR_COST ){
|
| + p = &pSet->a[pSet->n++];
|
| + p->nOut = nOut;
|
| + }else{
|
| + p = pSet->a;
|
| + for(i=1; i<pSet->n; i++){
|
| + if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
|
| + }
|
| + if( p->rRun<=rRun ) return 0;
|
| + }
|
| +whereOrInsert_done:
|
| + p->prereq = prereq;
|
| + p->rRun = rRun;
|
| + if( p->nOut>nOut ) p->nOut = nOut;
|
| + return 1;
|
| +}
|
| +
|
| +/*
|
| +** Return the bitmask for the given cursor number. Return 0 if
|
| +** iCursor is not in the set.
|
| +*/
|
| +SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){
|
| + int i;
|
| + assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
|
| + for(i=0; i<pMaskSet->n; i++){
|
| + if( pMaskSet->ix[i]==iCursor ){
|
| + return MASKBIT(i);
|
| + }
|
| + }
|
| + return 0;
|
| +}
|
| +
|
| +/*
|
| +** Create a new mask for cursor iCursor.
|
| +**
|
| +** There is one cursor per table in the FROM clause. The number of
|
| +** tables in the FROM clause is limited by a test early in the
|
| +** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
|
| +** array will never overflow.
|
| +*/
|
| +static void createMask(WhereMaskSet *pMaskSet, int iCursor){
|
| + assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
|
| + pMaskSet->ix[pMaskSet->n++] = iCursor;
|
| +}
|
| +
|
| +/*
|
| +** Advance to the next WhereTerm that matches according to the criteria
|
| +** established when the pScan object was initialized by whereScanInit().
|
| +** Return NULL if there are no more matching WhereTerms.
|
| +*/
|
| +static WhereTerm *whereScanNext(WhereScan *pScan){
|
| + int iCur; /* The cursor on the LHS of the term */
|
| + i16 iColumn; /* The column on the LHS of the term. -1 for IPK */
|
| + Expr *pX; /* An expression being tested */
|
| + WhereClause *pWC; /* Shorthand for pScan->pWC */
|
| + WhereTerm *pTerm; /* The term being tested */
|
| + int k = pScan->k; /* Where to start scanning */
|
| +
|
| + while( pScan->iEquiv<=pScan->nEquiv ){
|
| + iCur = pScan->aiCur[pScan->iEquiv-1];
|
| + iColumn = pScan->aiColumn[pScan->iEquiv-1];
|
| + if( iColumn==XN_EXPR && pScan->pIdxExpr==0 ) return 0;
|
| + while( (pWC = pScan->pWC)!=0 ){
|
| + for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
|
| + if( pTerm->leftCursor==iCur
|
| + && pTerm->u.leftColumn==iColumn
|
| + && (iColumn!=XN_EXPR
|
| + || sqlite3ExprCompare(pTerm->pExpr->pLeft,pScan->pIdxExpr,iCur)==0)
|
| + && (pScan->iEquiv<=1 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
|
| + ){
|
| + if( (pTerm->eOperator & WO_EQUIV)!=0
|
| + && pScan->nEquiv<ArraySize(pScan->aiCur)
|
| + && (pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight))->op==TK_COLUMN
|
| + ){
|
| + int j;
|
| + for(j=0; j<pScan->nEquiv; j++){
|
| + if( pScan->aiCur[j]==pX->iTable
|
| + && pScan->aiColumn[j]==pX->iColumn ){
|
| + break;
|
| + }
|
| + }
|
| + if( j==pScan->nEquiv ){
|
| + pScan->aiCur[j] = pX->iTable;
|
| + pScan->aiColumn[j] = pX->iColumn;
|
| + pScan->nEquiv++;
|
| + }
|
| + }
|
| + if( (pTerm->eOperator & pScan->opMask)!=0 ){
|
| + /* Verify the affinity and collating sequence match */
|
| + if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
|
| + CollSeq *pColl;
|
| + Parse *pParse = pWC->pWInfo->pParse;
|
| + pX = pTerm->pExpr;
|
| + if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
|
| + continue;
|
| + }
|
| + assert(pX->pLeft);
|
| + pColl = sqlite3BinaryCompareCollSeq(pParse,
|
| + pX->pLeft, pX->pRight);
|
| + if( pColl==0 ) pColl = pParse->db->pDfltColl;
|
| + if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
|
| + continue;
|
| + }
|
| + }
|
| + if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0
|
| + && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
|
| + && pX->iTable==pScan->aiCur[0]
|
| + && pX->iColumn==pScan->aiColumn[0]
|
| + ){
|
| + testcase( pTerm->eOperator & WO_IS );
|
| + continue;
|
| + }
|
| + pScan->k = k+1;
|
| + return pTerm;
|
| + }
|
| + }
|
| + }
|
| + pScan->pWC = pScan->pWC->pOuter;
|
| + k = 0;
|
| + }
|
| + pScan->pWC = pScan->pOrigWC;
|
| + k = 0;
|
| + pScan->iEquiv++;
|
| + }
|
| + return 0;
|
| +}
|
| +
|
| +/*
|
| +** Initialize a WHERE clause scanner object. Return a pointer to the
|
| +** first match. Return NULL if there are no matches.
|
| +**
|
| +** The scanner will be searching the WHERE clause pWC. It will look
|
| +** for terms of the form "X <op> <expr>" where X is column iColumn of table
|
| +** iCur. The <op> must be one of the operators described by opMask.
|
| +**
|
| +** If the search is for X and the WHERE clause contains terms of the
|
| +** form X=Y then this routine might also return terms of the form
|
| +** "Y <op> <expr>". The number of levels of transitivity is limited,
|
| +** but is enough to handle most commonly occurring SQL statements.
|
| +**
|
| +** If X is not the INTEGER PRIMARY KEY then X must be compatible with
|
| +** index pIdx.
|
| +*/
|
| +static WhereTerm *whereScanInit(
|
| + WhereScan *pScan, /* The WhereScan object being initialized */
|
| + WhereClause *pWC, /* The WHERE clause to be scanned */
|
| + int iCur, /* Cursor to scan for */
|
| + int iColumn, /* Column to scan for */
|
| + u32 opMask, /* Operator(s) to scan for */
|
| + Index *pIdx /* Must be compatible with this index */
|
| +){
|
| + int j = 0;
|
| +
|
| + /* memset(pScan, 0, sizeof(*pScan)); */
|
| + pScan->pOrigWC = pWC;
|
| + pScan->pWC = pWC;
|
| + pScan->pIdxExpr = 0;
|
| + if( pIdx ){
|
| + j = iColumn;
|
| + iColumn = pIdx->aiColumn[j];
|
| + if( iColumn==XN_EXPR ) pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr;
|
| + }
|
| + if( pIdx && iColumn>=0 ){
|
| + pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
|
| + pScan->zCollName = pIdx->azColl[j];
|
| + }else{
|
| + pScan->idxaff = 0;
|
| + pScan->zCollName = 0;
|
| + }
|
| + pScan->opMask = opMask;
|
| + pScan->k = 0;
|
| + pScan->aiCur[0] = iCur;
|
| + pScan->aiColumn[0] = iColumn;
|
| + pScan->nEquiv = 1;
|
| + pScan->iEquiv = 1;
|
| + return whereScanNext(pScan);
|
| +}
|
| +
|
| +/*
|
| +** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
|
| +** where X is a reference to the iColumn of table iCur and <op> is one of
|
| +** the WO_xx operator codes specified by the op parameter.
|
| +** Return a pointer to the term. Return 0 if not found.
|
| +**
|
| +** If pIdx!=0 then search for terms matching the iColumn-th column of pIdx
|
| +** rather than the iColumn-th column of table iCur.
|
| +**
|
| +** The term returned might by Y=<expr> if there is another constraint in
|
| +** the WHERE clause that specifies that X=Y. Any such constraints will be
|
| +** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
|
| +** aiCur[]/iaColumn[] arrays hold X and all its equivalents. There are 11
|
| +** slots in aiCur[]/aiColumn[] so that means we can look for X plus up to 10
|
| +** other equivalent values. Hence a search for X will return <expr> if X=A1
|
| +** and A1=A2 and A2=A3 and ... and A9=A10 and A10=<expr>.
|
| +**
|
| +** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
|
| +** then try for the one with no dependencies on <expr> - in other words where
|
| +** <expr> is a constant expression of some kind. Only return entries of
|
| +** the form "X <op> Y" where Y is a column in another table if no terms of
|
| +** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
|
| +** exist, try to return a term that does not use WO_EQUIV.
|
| +*/
|
| +SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
|
| + WhereClause *pWC, /* The WHERE clause to be searched */
|
| + int iCur, /* Cursor number of LHS */
|
| + int iColumn, /* Column number of LHS */
|
| + Bitmask notReady, /* RHS must not overlap with this mask */
|
| + u32 op, /* Mask of WO_xx values describing operator */
|
| + Index *pIdx /* Must be compatible with this index, if not NULL */
|
| +){
|
| + WhereTerm *pResult = 0;
|
| + WhereTerm *p;
|
| + WhereScan scan;
|
| +
|
| + p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
|
| + op &= WO_EQ|WO_IS;
|
| + while( p ){
|
| + if( (p->prereqRight & notReady)==0 ){
|
| + if( p->prereqRight==0 && (p->eOperator&op)!=0 ){
|
| + testcase( p->eOperator & WO_IS );
|
| + return p;
|
| + }
|
| + if( pResult==0 ) pResult = p;
|
| + }
|
| + p = whereScanNext(&scan);
|
| + }
|
| + return pResult;
|
| +}
|
| +
|
| +/*
|
| +** This function searches pList for an entry that matches the iCol-th column
|
| +** of index pIdx.
|
| +**
|
| +** If such an expression is found, its index in pList->a[] is returned. If
|
| +** no expression is found, -1 is returned.
|
| +*/
|
| +static int findIndexCol(
|
| + Parse *pParse, /* Parse context */
|
| + ExprList *pList, /* Expression list to search */
|
| + int iBase, /* Cursor for table associated with pIdx */
|
| + Index *pIdx, /* Index to match column of */
|
| + int iCol /* Column of index to match */
|
| +){
|
| + int i;
|
| + const char *zColl = pIdx->azColl[iCol];
|
| +
|
| + for(i=0; i<pList->nExpr; i++){
|
| + Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
|
| + if( p->op==TK_COLUMN
|
| + && p->iColumn==pIdx->aiColumn[iCol]
|
| + && p->iTable==iBase
|
| + ){
|
| + CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
|
| + if( pColl && 0==sqlite3StrICmp(pColl->zName, zColl) ){
|
| + return i;
|
| + }
|
| + }
|
| + }
|
| +
|
| + return -1;
|
| +}
|
| +
|
| +/*
|
| +** Return TRUE if the iCol-th column of index pIdx is NOT NULL
|
| +*/
|
| +static int indexColumnNotNull(Index *pIdx, int iCol){
|
| + int j;
|
| + assert( pIdx!=0 );
|
| + assert( iCol>=0 && iCol<pIdx->nColumn );
|
| + j = pIdx->aiColumn[iCol];
|
| + if( j>=0 ){
|
| + return pIdx->pTable->aCol[j].notNull;
|
| + }else if( j==(-1) ){
|
| + return 1;
|
| + }else{
|
| + assert( j==(-2) );
|
| + return 0; /* Assume an indexed expression can always yield a NULL */
|
| +
|
| + }
|
| +}
|
| +
|
| +/*
|
| +** Return true if the DISTINCT expression-list passed as the third argument
|
| +** is redundant.
|
| +**
|
| +** A DISTINCT list is redundant if any subset of the columns in the
|
| +** DISTINCT list are collectively unique and individually non-null.
|
| +*/
|
| +static int isDistinctRedundant(
|
| + Parse *pParse, /* Parsing context */
|
| + SrcList *pTabList, /* The FROM clause */
|
| + WhereClause *pWC, /* The WHERE clause */
|
| + ExprList *pDistinct /* The result set that needs to be DISTINCT */
|
| +){
|
| + Table *pTab;
|
| + Index *pIdx;
|
| + int i;
|
| + int iBase;
|
| +
|
| + /* If there is more than one table or sub-select in the FROM clause of
|
| + ** this query, then it will not be possible to show that the DISTINCT
|
| + ** clause is redundant. */
|
| + if( pTabList->nSrc!=1 ) return 0;
|
| + iBase = pTabList->a[0].iCursor;
|
| + pTab = pTabList->a[0].pTab;
|
| +
|
| + /* If any of the expressions is an IPK column on table iBase, then return
|
| + ** true. Note: The (p->iTable==iBase) part of this test may be false if the
|
| + ** current SELECT is a correlated sub-query.
|
| + */
|
| + for(i=0; i<pDistinct->nExpr; i++){
|
| + Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
|
| + if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
|
| + }
|
| +
|
| + /* Loop through all indices on the table, checking each to see if it makes
|
| + ** the DISTINCT qualifier redundant. It does so if:
|
| + **
|
| + ** 1. The index is itself UNIQUE, and
|
| + **
|
| + ** 2. All of the columns in the index are either part of the pDistinct
|
| + ** list, or else the WHERE clause contains a term of the form "col=X",
|
| + ** where X is a constant value. The collation sequences of the
|
| + ** comparison and select-list expressions must match those of the index.
|
| + **
|
| + ** 3. All of those index columns for which the WHERE clause does not
|
| + ** contain a "col=X" term are subject to a NOT NULL constraint.
|
| + */
|
| + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
|
| + if( !IsUniqueIndex(pIdx) ) continue;
|
| + for(i=0; i<pIdx->nKeyCol; i++){
|
| + if( 0==sqlite3WhereFindTerm(pWC, iBase, i, ~(Bitmask)0, WO_EQ, pIdx) ){
|
| + if( findIndexCol(pParse, pDistinct, iBase, pIdx, i)<0 ) break;
|
| + if( indexColumnNotNull(pIdx, i)==0 ) break;
|
| + }
|
| + }
|
| + if( i==pIdx->nKeyCol ){
|
| + /* This index implies that the DISTINCT qualifier is redundant. */
|
| + return 1;
|
| + }
|
| + }
|
| +
|
| + return 0;
|
| +}
|
| +
|
| +
|
| +/*
|
| +** Estimate the logarithm of the input value to base 2.
|
| +*/
|
| +static LogEst estLog(LogEst N){
|
| + return N<=10 ? 0 : sqlite3LogEst(N) - 33;
|
| +}
|
| +
|
| +/*
|
| +** Convert OP_Column opcodes to OP_Copy in previously generated code.
|
| +**
|
| +** This routine runs over generated VDBE code and translates OP_Column
|
| +** opcodes into OP_Copy when the table is being accessed via co-routine
|
| +** instead of via table lookup.
|
| +**
|
| +** If the bIncrRowid parameter is 0, then any OP_Rowid instructions on
|
| +** cursor iTabCur are transformed into OP_Null. Or, if bIncrRowid is non-zero,
|
| +** then each OP_Rowid is transformed into an instruction to increment the
|
| +** value stored in its output register.
|
| +*/
|
| +static void translateColumnToCopy(
|
| + Vdbe *v, /* The VDBE containing code to translate */
|
| + int iStart, /* Translate from this opcode to the end */
|
| + int iTabCur, /* OP_Column/OP_Rowid references to this table */
|
| + int iRegister, /* The first column is in this register */
|
| + int bIncrRowid /* If non-zero, transform OP_rowid to OP_AddImm(1) */
|
| +){
|
| + VdbeOp *pOp = sqlite3VdbeGetOp(v, iStart);
|
| + int iEnd = sqlite3VdbeCurrentAddr(v);
|
| + for(; iStart<iEnd; iStart++, pOp++){
|
| + if( pOp->p1!=iTabCur ) continue;
|
| + if( pOp->opcode==OP_Column ){
|
| + pOp->opcode = OP_Copy;
|
| + pOp->p1 = pOp->p2 + iRegister;
|
| + pOp->p2 = pOp->p3;
|
| + pOp->p3 = 0;
|
| + }else if( pOp->opcode==OP_Rowid ){
|
| + if( bIncrRowid ){
|
| + /* Increment the value stored in the P2 operand of the OP_Rowid. */
|
| + pOp->opcode = OP_AddImm;
|
| + pOp->p1 = pOp->p2;
|
| + pOp->p2 = 1;
|
| + }else{
|
| + pOp->opcode = OP_Null;
|
| + pOp->p1 = 0;
|
| + pOp->p3 = 0;
|
| + }
|
| + }
|
| + }
|
| +}
|
| +
|
| +/*
|
| +** Two routines for printing the content of an sqlite3_index_info
|
| +** structure. Used for testing and debugging only. If neither
|
| +** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
|
| +** are no-ops.
|
| +*/
|
| +#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
|
| +static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
|
| + int i;
|
| + if( !sqlite3WhereTrace ) return;
|
| + for(i=0; i<p->nConstraint; i++){
|
| + sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
|
| + i,
|
| + p->aConstraint[i].iColumn,
|
| + p->aConstraint[i].iTermOffset,
|
| + p->aConstraint[i].op,
|
| + p->aConstraint[i].usable);
|
| + }
|
| + for(i=0; i<p->nOrderBy; i++){
|
| + sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
|
| + i,
|
| + p->aOrderBy[i].iColumn,
|
| + p->aOrderBy[i].desc);
|
| + }
|
| +}
|
| +static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
|
| + int i;
|
| + if( !sqlite3WhereTrace ) return;
|
| + for(i=0; i<p->nConstraint; i++){
|
| + sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
|
| + i,
|
| + p->aConstraintUsage[i].argvIndex,
|
| + p->aConstraintUsage[i].omit);
|
| + }
|
| + sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
|
| + sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
|
| + sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
|
| + sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
|
| + sqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows);
|
| +}
|
| +#else
|
| +#define TRACE_IDX_INPUTS(A)
|
| +#define TRACE_IDX_OUTPUTS(A)
|
| +#endif
|
| +
|
| +#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
|
| +/*
|
| +** Return TRUE if the WHERE clause term pTerm is of a form where it
|
| +** could be used with an index to access pSrc, assuming an appropriate
|
| +** index existed.
|
| +*/
|
| +static int termCanDriveIndex(
|
| + WhereTerm *pTerm, /* WHERE clause term to check */
|
| + struct SrcList_item *pSrc, /* Table we are trying to access */
|
| + Bitmask notReady /* Tables in outer loops of the join */
|
| +){
|
| + char aff;
|
| + if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
|
| + if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0;
|
| + if( (pTerm->prereqRight & notReady)!=0 ) return 0;
|
| + if( pTerm->u.leftColumn<0 ) return 0;
|
| + aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
|
| + if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
|
| + testcase( pTerm->pExpr->op==TK_IS );
|
| + return 1;
|
| +}
|
| +#endif
|
| +
|
| +
|
| +#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
|
| +/*
|
| +** Generate code to construct the Index object for an automatic index
|
| +** and to set up the WhereLevel object pLevel so that the code generator
|
| +** makes use of the automatic index.
|
| +*/
|
| +static void constructAutomaticIndex(
|
| + Parse *pParse, /* The parsing context */
|
| + WhereClause *pWC, /* The WHERE clause */
|
| + struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
|
| + Bitmask notReady, /* Mask of cursors that are not available */
|
| + WhereLevel *pLevel /* Write new index here */
|
| +){
|
| + int nKeyCol; /* Number of columns in the constructed index */
|
| + WhereTerm *pTerm; /* A single term of the WHERE clause */
|
| + WhereTerm *pWCEnd; /* End of pWC->a[] */
|
| + Index *pIdx; /* Object describing the transient index */
|
| + Vdbe *v; /* Prepared statement under construction */
|
| + int addrInit; /* Address of the initialization bypass jump */
|
| + Table *pTable; /* The table being indexed */
|
| + int addrTop; /* Top of the index fill loop */
|
| + int regRecord; /* Register holding an index record */
|
| + int n; /* Column counter */
|
| + int i; /* Loop counter */
|
| + int mxBitCol; /* Maximum column in pSrc->colUsed */
|
| + CollSeq *pColl; /* Collating sequence to on a column */
|
| + WhereLoop *pLoop; /* The Loop object */
|
| + char *zNotUsed; /* Extra space on the end of pIdx */
|
| + Bitmask idxCols; /* Bitmap of columns used for indexing */
|
| + Bitmask extraCols; /* Bitmap of additional columns */
|
| + u8 sentWarning = 0; /* True if a warnning has been issued */
|
| + Expr *pPartial = 0; /* Partial Index Expression */
|
| + int iContinue = 0; /* Jump here to skip excluded rows */
|
| + struct SrcList_item *pTabItem; /* FROM clause term being indexed */
|
| + int addrCounter = 0; /* Address where integer counter is initialized */
|
| + int regBase; /* Array of registers where record is assembled */
|
| +
|
| + /* Generate code to skip over the creation and initialization of the
|
| + ** transient index on 2nd and subsequent iterations of the loop. */
|
| + v = pParse->pVdbe;
|
| + assert( v!=0 );
|
| + addrInit = sqlite3CodeOnce(pParse); VdbeCoverage(v);
|
| +
|
| + /* Count the number of columns that will be added to the index
|
| + ** and used to match WHERE clause constraints */
|
| + nKeyCol = 0;
|
| + pTable = pSrc->pTab;
|
| + pWCEnd = &pWC->a[pWC->nTerm];
|
| + pLoop = pLevel->pWLoop;
|
| + idxCols = 0;
|
| + for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
|
| + Expr *pExpr = pTerm->pExpr;
|
| + assert( !ExprHasProperty(pExpr, EP_FromJoin) /* prereq always non-zero */
|
| + || pExpr->iRightJoinTable!=pSrc->iCursor /* for the right-hand */
|
| + || pLoop->prereq!=0 ); /* table of a LEFT JOIN */
|
| + if( pLoop->prereq==0
|
| + && (pTerm->wtFlags & TERM_VIRTUAL)==0
|
| + && !ExprHasProperty(pExpr, EP_FromJoin)
|
| + && sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){
|
| + pPartial = sqlite3ExprAnd(pParse->db, pPartial,
|
| + sqlite3ExprDup(pParse->db, pExpr, 0));
|
| + }
|
| + if( termCanDriveIndex(pTerm, pSrc, notReady) ){
|
| + int iCol = pTerm->u.leftColumn;
|
| + Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
|
| + testcase( iCol==BMS );
|
| + testcase( iCol==BMS-1 );
|
| + if( !sentWarning ){
|
| + sqlite3_log(SQLITE_WARNING_AUTOINDEX,
|
| + "automatic index on %s(%s)", pTable->zName,
|
| + pTable->aCol[iCol].zName);
|
| + sentWarning = 1;
|
| + }
|
| + if( (idxCols & cMask)==0 ){
|
| + if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
|
| + goto end_auto_index_create;
|
| + }
|
| + pLoop->aLTerm[nKeyCol++] = pTerm;
|
| + idxCols |= cMask;
|
| + }
|
| + }
|
| + }
|
| + assert( nKeyCol>0 );
|
| + pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
|
| + pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
|
| + | WHERE_AUTO_INDEX;
|
| +
|
| + /* Count the number of additional columns needed to create a
|
| + ** covering index. A "covering index" is an index that contains all
|
| + ** columns that are needed by the query. With a covering index, the
|
| + ** original table never needs to be accessed. Automatic indices must
|
| + ** be a covering index because the index will not be updated if the
|
| + ** original table changes and the index and table cannot both be used
|
| + ** if they go out of sync.
|
| + */
|
| + extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
|
| + mxBitCol = MIN(BMS-1,pTable->nCol);
|
| + testcase( pTable->nCol==BMS-1 );
|
| + testcase( pTable->nCol==BMS-2 );
|
| + for(i=0; i<mxBitCol; i++){
|
| + if( extraCols & MASKBIT(i) ) nKeyCol++;
|
| + }
|
| + if( pSrc->colUsed & MASKBIT(BMS-1) ){
|
| + nKeyCol += pTable->nCol - BMS + 1;
|
| + }
|
| +
|
| + /* Construct the Index object to describe this index */
|
| + pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
|
| + if( pIdx==0 ) goto end_auto_index_create;
|
| + pLoop->u.btree.pIndex = pIdx;
|
| + pIdx->zName = "auto-index";
|
| + pIdx->pTable = pTable;
|
| + n = 0;
|
| + idxCols = 0;
|
| + for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
|
| + if( termCanDriveIndex(pTerm, pSrc, notReady) ){
|
| + int iCol = pTerm->u.leftColumn;
|
| + Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
|
| + testcase( iCol==BMS-1 );
|
| + testcase( iCol==BMS );
|
| + if( (idxCols & cMask)==0 ){
|
| + Expr *pX = pTerm->pExpr;
|
| + idxCols |= cMask;
|
| + pIdx->aiColumn[n] = pTerm->u.leftColumn;
|
| + pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
|
| + pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY;
|
| + n++;
|
| + }
|
| + }
|
| + }
|
| + assert( (u32)n==pLoop->u.btree.nEq );
|
| +
|
| + /* Add additional columns needed to make the automatic index into
|
| + ** a covering index */
|
| + for(i=0; i<mxBitCol; i++){
|
| + if( extraCols & MASKBIT(i) ){
|
| + pIdx->aiColumn[n] = i;
|
| + pIdx->azColl[n] = sqlite3StrBINARY;
|
| + n++;
|
| + }
|
| + }
|
| + if( pSrc->colUsed & MASKBIT(BMS-1) ){
|
| + for(i=BMS-1; i<pTable->nCol; i++){
|
| + pIdx->aiColumn[n] = i;
|
| + pIdx->azColl[n] = sqlite3StrBINARY;
|
| + n++;
|
| + }
|
| + }
|
| + assert( n==nKeyCol );
|
| + pIdx->aiColumn[n] = XN_ROWID;
|
| + pIdx->azColl[n] = sqlite3StrBINARY;
|
| +
|
| + /* Create the automatic index */
|
| + assert( pLevel->iIdxCur>=0 );
|
| + pLevel->iIdxCur = pParse->nTab++;
|
| + sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
|
| + sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
|
| + VdbeComment((v, "for %s", pTable->zName));
|
| +
|
| + /* Fill the automatic index with content */
|
| + sqlite3ExprCachePush(pParse);
|
| + pTabItem = &pWC->pWInfo->pTabList->a[pLevel->iFrom];
|
| + if( pTabItem->fg.viaCoroutine ){
|
| + int regYield = pTabItem->regReturn;
|
| + addrCounter = sqlite3VdbeAddOp2(v, OP_Integer, 0, 0);
|
| + sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
|
| + addrTop = sqlite3VdbeAddOp1(v, OP_Yield, regYield);
|
| + VdbeCoverage(v);
|
| + VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
|
| + }else{
|
| + addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
|
| + }
|
| + if( pPartial ){
|
| + iContinue = sqlite3VdbeMakeLabel(v);
|
| + sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
|
| + pLoop->wsFlags |= WHERE_PARTIALIDX;
|
| + }
|
| + regRecord = sqlite3GetTempReg(pParse);
|
| + regBase = sqlite3GenerateIndexKey(
|
| + pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0
|
| + );
|
| + sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
|
| + sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
|
| + if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
|
| + if( pTabItem->fg.viaCoroutine ){
|
| + sqlite3VdbeChangeP2(v, addrCounter, regBase+n);
|
| + translateColumnToCopy(v, addrTop, pLevel->iTabCur, pTabItem->regResult, 1);
|
| + sqlite3VdbeGoto(v, addrTop);
|
| + pTabItem->fg.viaCoroutine = 0;
|
| + }else{
|
| + sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
|
| + }
|
| + sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
|
| + sqlite3VdbeJumpHere(v, addrTop);
|
| + sqlite3ReleaseTempReg(pParse, regRecord);
|
| + sqlite3ExprCachePop(pParse);
|
| +
|
| + /* Jump here when skipping the initialization */
|
| + sqlite3VdbeJumpHere(v, addrInit);
|
| +
|
| +end_auto_index_create:
|
| + sqlite3ExprDelete(pParse->db, pPartial);
|
| +}
|
| +#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
|
| +
|
| +#ifndef SQLITE_OMIT_VIRTUALTABLE
|
| +/*
|
| +** Allocate and populate an sqlite3_index_info structure. It is the
|
| +** responsibility of the caller to eventually release the structure
|
| +** by passing the pointer returned by this function to sqlite3_free().
|
| +*/
|
| +static sqlite3_index_info *allocateIndexInfo(
|
| + Parse *pParse,
|
| + WhereClause *pWC,
|
| + Bitmask mUnusable, /* Ignore terms with these prereqs */
|
| + struct SrcList_item *pSrc,
|
| + ExprList *pOrderBy
|
| +){
|
| + int i, j;
|
| + int nTerm;
|
| + struct sqlite3_index_constraint *pIdxCons;
|
| + struct sqlite3_index_orderby *pIdxOrderBy;
|
| + struct sqlite3_index_constraint_usage *pUsage;
|
| + WhereTerm *pTerm;
|
| + int nOrderBy;
|
| + sqlite3_index_info *pIdxInfo;
|
| +
|
| + /* Count the number of possible WHERE clause constraints referring
|
| + ** to this virtual table */
|
| + for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
|
| + if( pTerm->leftCursor != pSrc->iCursor ) continue;
|
| + if( pTerm->prereqRight & mUnusable ) continue;
|
| + assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
|
| + testcase( pTerm->eOperator & WO_IN );
|
| + testcase( pTerm->eOperator & WO_ISNULL );
|
| + testcase( pTerm->eOperator & WO_IS );
|
| + testcase( pTerm->eOperator & WO_ALL );
|
| + if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue;
|
| + if( pTerm->wtFlags & TERM_VNULL ) continue;
|
| + assert( pTerm->u.leftColumn>=(-1) );
|
| + nTerm++;
|
| + }
|
| +
|
| + /* If the ORDER BY clause contains only columns in the current
|
| + ** virtual table then allocate space for the aOrderBy part of
|
| + ** the sqlite3_index_info structure.
|
| + */
|
| + nOrderBy = 0;
|
| + if( pOrderBy ){
|
| + int n = pOrderBy->nExpr;
|
| + for(i=0; i<n; i++){
|
| + Expr *pExpr = pOrderBy->a[i].pExpr;
|
| + if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
|
| + }
|
| + if( i==n){
|
| + nOrderBy = n;
|
| + }
|
| + }
|
| +
|
| + /* Allocate the sqlite3_index_info structure
|
| + */
|
| + pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
|
| + + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
|
| + + sizeof(*pIdxOrderBy)*nOrderBy );
|
| + if( pIdxInfo==0 ){
|
| + sqlite3ErrorMsg(pParse, "out of memory");
|
| + return 0;
|
| + }
|
| +
|
| + /* Initialize the structure. The sqlite3_index_info structure contains
|
| + ** many fields that are declared "const" to prevent xBestIndex from
|
| + ** changing them. We have to do some funky casting in order to
|
| + ** initialize those fields.
|
| + */
|
| + pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
|
| + pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
|
| + pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
|
| + *(int*)&pIdxInfo->nConstraint = nTerm;
|
| + *(int*)&pIdxInfo->nOrderBy = nOrderBy;
|
| + *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
|
| + *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
|
| + *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
|
| + pUsage;
|
| +
|
| + for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
|
| + u8 op;
|
| + if( pTerm->leftCursor != pSrc->iCursor ) continue;
|
| + if( pTerm->prereqRight & mUnusable ) continue;
|
| + assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
|
| + testcase( pTerm->eOperator & WO_IN );
|
| + testcase( pTerm->eOperator & WO_IS );
|
| + testcase( pTerm->eOperator & WO_ISNULL );
|
| + testcase( pTerm->eOperator & WO_ALL );
|
| + if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue;
|
| + if( pTerm->wtFlags & TERM_VNULL ) continue;
|
| + assert( pTerm->u.leftColumn>=(-1) );
|
| + pIdxCons[j].iColumn = pTerm->u.leftColumn;
|
| + pIdxCons[j].iTermOffset = i;
|
| + op = (u8)pTerm->eOperator & WO_ALL;
|
| + if( op==WO_IN ) op = WO_EQ;
|
| + if( op==WO_MATCH ){
|
| + op = pTerm->eMatchOp;
|
| + }
|
| + pIdxCons[j].op = op;
|
| + /* The direct assignment in the previous line is possible only because
|
| + ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
|
| + ** following asserts verify this fact. */
|
| + assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
|
| + assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
|
| + assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
|
| + assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
|
| + assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
|
| + assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
|
| + assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
|
| + j++;
|
| + }
|
| + for(i=0; i<nOrderBy; i++){
|
| + Expr *pExpr = pOrderBy->a[i].pExpr;
|
| + pIdxOrderBy[i].iColumn = pExpr->iColumn;
|
| + pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
|
| + }
|
| +
|
| + return pIdxInfo;
|
| +}
|
| +
|
| +/*
|
| +** The table object reference passed as the second argument to this function
|
| +** must represent a virtual table. This function invokes the xBestIndex()
|
| +** method of the virtual table with the sqlite3_index_info object that
|
| +** comes in as the 3rd argument to this function.
|
| +**
|
| +** If an error occurs, pParse is populated with an error message and a
|
| +** non-zero value is returned. Otherwise, 0 is returned and the output
|
| +** part of the sqlite3_index_info structure is left populated.
|
| +**
|
| +** Whether or not an error is returned, it is the responsibility of the
|
| +** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
|
| +** that this is required.
|
| +*/
|
| +static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
|
| + sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
|
| + int i;
|
| + int rc;
|
| +
|
| + TRACE_IDX_INPUTS(p);
|
| + rc = pVtab->pModule->xBestIndex(pVtab, p);
|
| + TRACE_IDX_OUTPUTS(p);
|
| +
|
| + if( rc!=SQLITE_OK ){
|
| + if( rc==SQLITE_NOMEM ){
|
| + pParse->db->mallocFailed = 1;
|
| + }else if( !pVtab->zErrMsg ){
|
| + sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
|
| + }else{
|
| + sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
|
| + }
|
| + }
|
| + sqlite3_free(pVtab->zErrMsg);
|
| + pVtab->zErrMsg = 0;
|
| +
|
| + for(i=0; i<p->nConstraint; i++){
|
| + if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
|
| + sqlite3ErrorMsg(pParse,
|
| + "table %s: xBestIndex returned an invalid plan", pTab->zName);
|
| + }
|
| + }
|
| +
|
| + return pParse->nErr;
|
| +}
|
| +#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
|
| +
|
| +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
|
| +/*
|
| +** Estimate the location of a particular key among all keys in an
|
| +** index. Store the results in aStat as follows:
|
| +**
|
| +** aStat[0] Est. number of rows less than pRec
|
| +** aStat[1] Est. number of rows equal to pRec
|
| +**
|
| +** Return the index of the sample that is the smallest sample that
|
| +** is greater than or equal to pRec. Note that this index is not an index
|
| +** into the aSample[] array - it is an index into a virtual set of samples
|
| +** based on the contents of aSample[] and the number of fields in record
|
| +** pRec.
|
| +*/
|
| +static int whereKeyStats(
|
| + Parse *pParse, /* Database connection */
|
| + Index *pIdx, /* Index to consider domain of */
|
| + UnpackedRecord *pRec, /* Vector of values to consider */
|
| + int roundUp, /* Round up if true. Round down if false */
|
| + tRowcnt *aStat /* OUT: stats written here */
|
| +){
|
| + IndexSample *aSample = pIdx->aSample;
|
| + int iCol; /* Index of required stats in anEq[] etc. */
|
| + int i; /* Index of first sample >= pRec */
|
| + int iSample; /* Smallest sample larger than or equal to pRec */
|
| + int iMin = 0; /* Smallest sample not yet tested */
|
| + int iTest; /* Next sample to test */
|
| + int res; /* Result of comparison operation */
|
| + int nField; /* Number of fields in pRec */
|
| + tRowcnt iLower = 0; /* anLt[] + anEq[] of largest sample pRec is > */
|
| +
|
| +#ifndef SQLITE_DEBUG
|
| + UNUSED_PARAMETER( pParse );
|
| +#endif
|
| + assert( pRec!=0 );
|
| + assert( pIdx->nSample>0 );
|
| + assert( pRec->nField>0 && pRec->nField<=pIdx->nSampleCol );
|
| +
|
| + /* Do a binary search to find the first sample greater than or equal
|
| + ** to pRec. If pRec contains a single field, the set of samples to search
|
| + ** is simply the aSample[] array. If the samples in aSample[] contain more
|
| + ** than one fields, all fields following the first are ignored.
|
| + **
|
| + ** If pRec contains N fields, where N is more than one, then as well as the
|
| + ** samples in aSample[] (truncated to N fields), the search also has to
|
| + ** consider prefixes of those samples. For example, if the set of samples
|
| + ** in aSample is:
|
| + **
|
| + ** aSample[0] = (a, 5)
|
| + ** aSample[1] = (a, 10)
|
| + ** aSample[2] = (b, 5)
|
| + ** aSample[3] = (c, 100)
|
| + ** aSample[4] = (c, 105)
|
| + **
|
| + ** Then the search space should ideally be the samples above and the
|
| + ** unique prefixes [a], [b] and [c]. But since that is hard to organize,
|
| + ** the code actually searches this set:
|
| + **
|
| + ** 0: (a)
|
| + ** 1: (a, 5)
|
| + ** 2: (a, 10)
|
| + ** 3: (a, 10)
|
| + ** 4: (b)
|
| + ** 5: (b, 5)
|
| + ** 6: (c)
|
| + ** 7: (c, 100)
|
| + ** 8: (c, 105)
|
| + ** 9: (c, 105)
|
| + **
|
| + ** For each sample in the aSample[] array, N samples are present in the
|
| + ** effective sample array. In the above, samples 0 and 1 are based on
|
| + ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc.
|
| + **
|
| + ** Often, sample i of each block of N effective samples has (i+1) fields.
|
| + ** Except, each sample may be extended to ensure that it is greater than or
|
| + ** equal to the previous sample in the array. For example, in the above,
|
| + ** sample 2 is the first sample of a block of N samples, so at first it
|
| + ** appears that it should be 1 field in size. However, that would make it
|
| + ** smaller than sample 1, so the binary search would not work. As a result,
|
| + ** it is extended to two fields. The duplicates that this creates do not
|
| + ** cause any problems.
|
| + */
|
| + nField = pRec->nField;
|
| + iCol = 0;
|
| + iSample = pIdx->nSample * nField;
|
| + do{
|
| + int iSamp; /* Index in aSample[] of test sample */
|
| + int n; /* Number of fields in test sample */
|
| +
|
| + iTest = (iMin+iSample)/2;
|
| + iSamp = iTest / nField;
|
| + if( iSamp>0 ){
|
| + /* The proposed effective sample is a prefix of sample aSample[iSamp].
|
| + ** Specifically, the shortest prefix of at least (1 + iTest%nField)
|
| + ** fields that is greater than the previous effective sample. */
|
| + for(n=(iTest % nField) + 1; n<nField; n++){
|
| + if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break;
|
| + }
|
| + }else{
|
| + n = iTest + 1;
|
| + }
|
| +
|
| + pRec->nField = n;
|
| + res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec);
|
| + if( res<0 ){
|
| + iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1];
|
| + iMin = iTest+1;
|
| + }else if( res==0 && n<nField ){
|
| + iLower = aSample[iSamp].anLt[n-1];
|
| + iMin = iTest+1;
|
| + res = -1;
|
| + }else{
|
| + iSample = iTest;
|
| + iCol = n-1;
|
| + }
|
| + }while( res && iMin<iSample );
|
| + i = iSample / nField;
|
| +
|
| +#ifdef SQLITE_DEBUG
|
| + /* The following assert statements check that the binary search code
|
| + ** above found the right answer. This block serves no purpose other
|
| + ** than to invoke the asserts. */
|
| + if( pParse->db->mallocFailed==0 ){
|
| + if( res==0 ){
|
| + /* If (res==0) is true, then pRec must be equal to sample i. */
|
| + assert( i<pIdx->nSample );
|
| + assert( iCol==nField-1 );
|
| + pRec->nField = nField;
|
| + assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
|
| + || pParse->db->mallocFailed
|
| + );
|
| + }else{
|
| + /* Unless i==pIdx->nSample, indicating that pRec is larger than
|
| + ** all samples in the aSample[] array, pRec must be smaller than the
|
| + ** (iCol+1) field prefix of sample i. */
|
| + assert( i<=pIdx->nSample && i>=0 );
|
| + pRec->nField = iCol+1;
|
| + assert( i==pIdx->nSample
|
| + || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
|
| + || pParse->db->mallocFailed );
|
| +
|
| + /* if i==0 and iCol==0, then record pRec is smaller than all samples
|
| + ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must
|
| + ** be greater than or equal to the (iCol) field prefix of sample i.
|
| + ** If (i>0), then pRec must also be greater than sample (i-1). */
|
| + if( iCol>0 ){
|
| + pRec->nField = iCol;
|
| + assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0
|
| + || pParse->db->mallocFailed );
|
| + }
|
| + if( i>0 ){
|
| + pRec->nField = nField;
|
| + assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
|
| + || pParse->db->mallocFailed );
|
| + }
|
| + }
|
| + }
|
| +#endif /* ifdef SQLITE_DEBUG */
|
| +
|
| + if( res==0 ){
|
| + /* Record pRec is equal to sample i */
|
| + assert( iCol==nField-1 );
|
| + aStat[0] = aSample[i].anLt[iCol];
|
| + aStat[1] = aSample[i].anEq[iCol];
|
| + }else{
|
| + /* At this point, the (iCol+1) field prefix of aSample[i] is the first
|
| + ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec
|
| + ** is larger than all samples in the array. */
|
| + tRowcnt iUpper, iGap;
|
| + if( i>=pIdx->nSample ){
|
| + iUpper = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
|
| + }else{
|
| + iUpper = aSample[i].anLt[iCol];
|
| + }
|
| +
|
| + if( iLower>=iUpper ){
|
| + iGap = 0;
|
| + }else{
|
| + iGap = iUpper - iLower;
|
| + }
|
| + if( roundUp ){
|
| + iGap = (iGap*2)/3;
|
| + }else{
|
| + iGap = iGap/3;
|
| + }
|
| + aStat[0] = iLower + iGap;
|
| + aStat[1] = pIdx->aAvgEq[iCol];
|
| + }
|
| +
|
| + /* Restore the pRec->nField value before returning. */
|
| + pRec->nField = nField;
|
| + return i;
|
| +}
|
| +#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
|
| +
|
| +/*
|
| +** If it is not NULL, pTerm is a term that provides an upper or lower
|
| +** bound on a range scan. Without considering pTerm, it is estimated
|
| +** that the scan will visit nNew rows. This function returns the number
|
| +** estimated to be visited after taking pTerm into account.
|
| +**
|
| +** If the user explicitly specified a likelihood() value for this term,
|
| +** then the return value is the likelihood multiplied by the number of
|
| +** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
|
| +** has a likelihood of 0.50, and any other term a likelihood of 0.25.
|
| +*/
|
| +static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
|
| + LogEst nRet = nNew;
|
| + if( pTerm ){
|
| + if( pTerm->truthProb<=0 ){
|
| + nRet += pTerm->truthProb;
|
| + }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
|
| + nRet -= 20; assert( 20==sqlite3LogEst(4) );
|
| + }
|
| + }
|
| + return nRet;
|
| +}
|
| +
|
| +
|
| +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
|
| +/*
|
| +** Return the affinity for a single column of an index.
|
| +*/
|
| +static char sqlite3IndexColumnAffinity(sqlite3 *db, Index *pIdx, int iCol){
|
| + assert( iCol>=0 && iCol<pIdx->nColumn );
|
| + if( !pIdx->zColAff ){
|
| + if( sqlite3IndexAffinityStr(db, pIdx)==0 ) return SQLITE_AFF_BLOB;
|
| + }
|
| + return pIdx->zColAff[iCol];
|
| +}
|
| +#endif
|
| +
|
| +
|
| +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
|
| +/*
|
| +** This function is called to estimate the number of rows visited by a
|
| +** range-scan on a skip-scan index. For example:
|
| +**
|
| +** CREATE INDEX i1 ON t1(a, b, c);
|
| +** SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
|
| +**
|
| +** Value pLoop->nOut is currently set to the estimated number of rows
|
| +** visited for scanning (a=? AND b=?). This function reduces that estimate
|
| +** by some factor to account for the (c BETWEEN ? AND ?) expression based
|
| +** on the stat4 data for the index. this scan will be peformed multiple
|
| +** times (once for each (a,b) combination that matches a=?) is dealt with
|
| +** by the caller.
|
| +**
|
| +** It does this by scanning through all stat4 samples, comparing values
|
| +** extracted from pLower and pUpper with the corresponding column in each
|
| +** sample. If L and U are the number of samples found to be less than or
|
| +** equal to the values extracted from pLower and pUpper respectively, and
|
| +** N is the total number of samples, the pLoop->nOut value is adjusted
|
| +** as follows:
|
| +**
|
| +** nOut = nOut * ( min(U - L, 1) / N )
|
| +**
|
| +** If pLower is NULL, or a value cannot be extracted from the term, L is
|
| +** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
|
| +** U is set to N.
|
| +**
|
| +** Normally, this function sets *pbDone to 1 before returning. However,
|
| +** if no value can be extracted from either pLower or pUpper (and so the
|
| +** estimate of the number of rows delivered remains unchanged), *pbDone
|
| +** is left as is.
|
| +**
|
| +** If an error occurs, an SQLite error code is returned. Otherwise,
|
| +** SQLITE_OK.
|
| +*/
|
| +static int whereRangeSkipScanEst(
|
| + Parse *pParse, /* Parsing & code generating context */
|
| + WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
|
| + WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
|
| + WhereLoop *pLoop, /* Update the .nOut value of this loop */
|
| + int *pbDone /* Set to true if at least one expr. value extracted */
|
| +){
|
| + Index *p = pLoop->u.btree.pIndex;
|
| + int nEq = pLoop->u.btree.nEq;
|
| + sqlite3 *db = pParse->db;
|
| + int nLower = -1;
|
| + int nUpper = p->nSample+1;
|
| + int rc = SQLITE_OK;
|
| + u8 aff = sqlite3IndexColumnAffinity(db, p, nEq);
|
| + CollSeq *pColl;
|
| +
|
| + sqlite3_value *p1 = 0; /* Value extracted from pLower */
|
| + sqlite3_value *p2 = 0; /* Value extracted from pUpper */
|
| + sqlite3_value *pVal = 0; /* Value extracted from record */
|
| +
|
| + pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
|
| + if( pLower ){
|
| + rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
|
| + nLower = 0;
|
| + }
|
| + if( pUpper && rc==SQLITE_OK ){
|
| + rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
|
| + nUpper = p2 ? 0 : p->nSample;
|
| + }
|
| +
|
| + if( p1 || p2 ){
|
| + int i;
|
| + int nDiff;
|
| + for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
|
| + rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
|
| + if( rc==SQLITE_OK && p1 ){
|
| + int res = sqlite3MemCompare(p1, pVal, pColl);
|
| + if( res>=0 ) nLower++;
|
| + }
|
| + if( rc==SQLITE_OK && p2 ){
|
| + int res = sqlite3MemCompare(p2, pVal, pColl);
|
| + if( res>=0 ) nUpper++;
|
| + }
|
| + }
|
| + nDiff = (nUpper - nLower);
|
| + if( nDiff<=0 ) nDiff = 1;
|
| +
|
| + /* If there is both an upper and lower bound specified, and the
|
| + ** comparisons indicate that they are close together, use the fallback
|
| + ** method (assume that the scan visits 1/64 of the rows) for estimating
|
| + ** the number of rows visited. Otherwise, estimate the number of rows
|
| + ** using the method described in the header comment for this function. */
|
| + if( nDiff!=1 || pUpper==0 || pLower==0 ){
|
| + int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
|
| + pLoop->nOut -= nAdjust;
|
| + *pbDone = 1;
|
| + WHERETRACE(0x10, ("range skip-scan regions: %u..%u adjust=%d est=%d\n",
|
| + nLower, nUpper, nAdjust*-1, pLoop->nOut));
|
| + }
|
| +
|
| + }else{
|
| + assert( *pbDone==0 );
|
| + }
|
| +
|
| + sqlite3ValueFree(p1);
|
| + sqlite3ValueFree(p2);
|
| + sqlite3ValueFree(pVal);
|
| +
|
| + return rc;
|
| +}
|
| +#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
|
| +
|
| +/*
|
| +** This function is used to estimate the number of rows that will be visited
|
| +** by scanning an index for a range of values. The range may have an upper
|
| +** bound, a lower bound, or both. The WHERE clause terms that set the upper
|
| +** and lower bounds are represented by pLower and pUpper respectively. For
|
| +** example, assuming that index p is on t1(a):
|
| +**
|
| +** ... FROM t1 WHERE a > ? AND a < ? ...
|
| +** |_____| |_____|
|
| +** | |
|
| +** pLower pUpper
|
| +**
|
| +** If either of the upper or lower bound is not present, then NULL is passed in
|
| +** place of the corresponding WhereTerm.
|
| +**
|
| +** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index
|
| +** column subject to the range constraint. Or, equivalently, the number of
|
| +** equality constraints optimized by the proposed index scan. For example,
|
| +** assuming index p is on t1(a, b), and the SQL query is:
|
| +**
|
| +** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
|
| +**
|
| +** then nEq is set to 1 (as the range restricted column, b, is the second
|
| +** left-most column of the index). Or, if the query is:
|
| +**
|
| +** ... FROM t1 WHERE a > ? AND a < ? ...
|
| +**
|
| +** then nEq is set to 0.
|
| +**
|
| +** When this function is called, *pnOut is set to the sqlite3LogEst() of the
|
| +** number of rows that the index scan is expected to visit without
|
| +** considering the range constraints. If nEq is 0, then *pnOut is the number of
|
| +** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
|
| +** to account for the range constraints pLower and pUpper.
|
| +**
|
| +** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
|
| +** used, a single range inequality reduces the search space by a factor of 4.
|
| +** and a pair of constraints (x>? AND x<?) reduces the expected number of
|
| +** rows visited by a factor of 64.
|
| +*/
|
| +static int whereRangeScanEst(
|
| + Parse *pParse, /* Parsing & code generating context */
|
| + WhereLoopBuilder *pBuilder,
|
| + WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
|
| + WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
|
| + WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */
|
| +){
|
| + int rc = SQLITE_OK;
|
| + int nOut = pLoop->nOut;
|
| + LogEst nNew;
|
| +
|
| +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
|
| + Index *p = pLoop->u.btree.pIndex;
|
| + int nEq = pLoop->u.btree.nEq;
|
| +
|
| + if( p->nSample>0 && nEq<p->nSampleCol ){
|
| + if( nEq==pBuilder->nRecValid ){
|
| + UnpackedRecord *pRec = pBuilder->pRec;
|
| + tRowcnt a[2];
|
| + u8 aff;
|
| +
|
| + /* Variable iLower will be set to the estimate of the number of rows in
|
| + ** the index that are less than the lower bound of the range query. The
|
| + ** lower bound being the concatenation of $P and $L, where $P is the
|
| + ** key-prefix formed by the nEq values matched against the nEq left-most
|
| + ** columns of the index, and $L is the value in pLower.
|
| + **
|
| + ** Or, if pLower is NULL or $L cannot be extracted from it (because it
|
| + ** is not a simple variable or literal value), the lower bound of the
|
| + ** range is $P. Due to a quirk in the way whereKeyStats() works, even
|
| + ** if $L is available, whereKeyStats() is called for both ($P) and
|
| + ** ($P:$L) and the larger of the two returned values is used.
|
| + **
|
| + ** Similarly, iUpper is to be set to the estimate of the number of rows
|
| + ** less than the upper bound of the range query. Where the upper bound
|
| + ** is either ($P) or ($P:$U). Again, even if $U is available, both values
|
| + ** of iUpper are requested of whereKeyStats() and the smaller used.
|
| + **
|
| + ** The number of rows between the two bounds is then just iUpper-iLower.
|
| + */
|
| + tRowcnt iLower; /* Rows less than the lower bound */
|
| + tRowcnt iUpper; /* Rows less than the upper bound */
|
| + int iLwrIdx = -2; /* aSample[] for the lower bound */
|
| + int iUprIdx = -1; /* aSample[] for the upper bound */
|
| +
|
| + if( pRec ){
|
| + testcase( pRec->nField!=pBuilder->nRecValid );
|
| + pRec->nField = pBuilder->nRecValid;
|
| + }
|
| + aff = sqlite3IndexColumnAffinity(pParse->db, p, nEq);
|
| + assert( nEq!=p->nKeyCol || aff==SQLITE_AFF_INTEGER );
|
| + /* Determine iLower and iUpper using ($P) only. */
|
| + if( nEq==0 ){
|
| + iLower = 0;
|
| + iUpper = p->nRowEst0;
|
| + }else{
|
| + /* Note: this call could be optimized away - since the same values must
|
| + ** have been requested when testing key $P in whereEqualScanEst(). */
|
| + whereKeyStats(pParse, p, pRec, 0, a);
|
| + iLower = a[0];
|
| + iUpper = a[0] + a[1];
|
| + }
|
| +
|
| + assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
|
| + assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
|
| + assert( p->aSortOrder!=0 );
|
| + if( p->aSortOrder[nEq] ){
|
| + /* The roles of pLower and pUpper are swapped for a DESC index */
|
| + SWAP(WhereTerm*, pLower, pUpper);
|
| + }
|
| +
|
| + /* If possible, improve on the iLower estimate using ($P:$L). */
|
| + if( pLower ){
|
| + int bOk; /* True if value is extracted from pExpr */
|
| + Expr *pExpr = pLower->pExpr->pRight;
|
| + rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
|
| + if( rc==SQLITE_OK && bOk ){
|
| + tRowcnt iNew;
|
| + iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a);
|
| + iNew = a[0] + ((pLower->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
|
| + if( iNew>iLower ) iLower = iNew;
|
| + nOut--;
|
| + pLower = 0;
|
| + }
|
| + }
|
| +
|
| + /* If possible, improve on the iUpper estimate using ($P:$U). */
|
| + if( pUpper ){
|
| + int bOk; /* True if value is extracted from pExpr */
|
| + Expr *pExpr = pUpper->pExpr->pRight;
|
| + rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
|
| + if( rc==SQLITE_OK && bOk ){
|
| + tRowcnt iNew;
|
| + iUprIdx = whereKeyStats(pParse, p, pRec, 1, a);
|
| + iNew = a[0] + ((pUpper->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
|
| + if( iNew<iUpper ) iUpper = iNew;
|
| + nOut--;
|
| + pUpper = 0;
|
| + }
|
| + }
|
| +
|
| + pBuilder->pRec = pRec;
|
| + if( rc==SQLITE_OK ){
|
| + if( iUpper>iLower ){
|
| + nNew = sqlite3LogEst(iUpper - iLower);
|
| + /* TUNING: If both iUpper and iLower are derived from the same
|
| + ** sample, then assume they are 4x more selective. This brings
|
| + ** the estimated selectivity more in line with what it would be
|
| + ** if estimated without the use of STAT3/4 tables. */
|
| + if( iLwrIdx==iUprIdx ) nNew -= 20; assert( 20==sqlite3LogEst(4) );
|
| + }else{
|
| + nNew = 10; assert( 10==sqlite3LogEst(2) );
|
| + }
|
| + if( nNew<nOut ){
|
| + nOut = nNew;
|
| + }
|
| + WHERETRACE(0x10, ("STAT4 range scan: %u..%u est=%d\n",
|
| + (u32)iLower, (u32)iUpper, nOut));
|
| + }
|
| + }else{
|
| + int bDone = 0;
|
| + rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
|
| + if( bDone ) return rc;
|
| + }
|
| + }
|
| +#else
|
| + UNUSED_PARAMETER(pParse);
|
| + UNUSED_PARAMETER(pBuilder);
|
| + assert( pLower || pUpper );
|
| +#endif
|
| + assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
|
| + nNew = whereRangeAdjust(pLower, nOut);
|
| + nNew = whereRangeAdjust(pUpper, nNew);
|
| +
|
| + /* TUNING: If there is both an upper and lower limit and neither limit
|
| + ** has an application-defined likelihood(), assume the range is
|
| + ** reduced by an additional 75%. This means that, by default, an open-ended
|
| + ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
|
| + ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
|
| + ** match 1/64 of the index. */
|
| + if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
|
| + nNew -= 20;
|
| + }
|
| +
|
| + nOut -= (pLower!=0) + (pUpper!=0);
|
| + if( nNew<10 ) nNew = 10;
|
| + if( nNew<nOut ) nOut = nNew;
|
| +#if defined(WHERETRACE_ENABLED)
|
| + if( pLoop->nOut>nOut ){
|
| + WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n",
|
| + pLoop->nOut, nOut));
|
| + }
|
| +#endif
|
| + pLoop->nOut = (LogEst)nOut;
|
| + return rc;
|
| +}
|
| +
|
| +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
|
| +/*
|
| +** Estimate the number of rows that will be returned based on
|
| +** an equality constraint x=VALUE and where that VALUE occurs in
|
| +** the histogram data. This only works when x is the left-most
|
| +** column of an index and sqlite_stat3 histogram data is available
|
| +** for that index. When pExpr==NULL that means the constraint is
|
| +** "x IS NULL" instead of "x=VALUE".
|
| +**
|
| +** Write the estimated row count into *pnRow and return SQLITE_OK.
|
| +** If unable to make an estimate, leave *pnRow unchanged and return
|
| +** non-zero.
|
| +**
|
| +** This routine can fail if it is unable to load a collating sequence
|
| +** required for string comparison, or if unable to allocate memory
|
| +** for a UTF conversion required for comparison. The error is stored
|
| +** in the pParse structure.
|
| +*/
|
| +static int whereEqualScanEst(
|
| + Parse *pParse, /* Parsing & code generating context */
|
| + WhereLoopBuilder *pBuilder,
|
| + Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
|
| + tRowcnt *pnRow /* Write the revised row estimate here */
|
| +){
|
| + Index *p = pBuilder->pNew->u.btree.pIndex;
|
| + int nEq = pBuilder->pNew->u.btree.nEq;
|
| + UnpackedRecord *pRec = pBuilder->pRec;
|
| + u8 aff; /* Column affinity */
|
| + int rc; /* Subfunction return code */
|
| + tRowcnt a[2]; /* Statistics */
|
| + int bOk;
|
| +
|
| + assert( nEq>=1 );
|
| + assert( nEq<=p->nColumn );
|
| + assert( p->aSample!=0 );
|
| + assert( p->nSample>0 );
|
| + assert( pBuilder->nRecValid<nEq );
|
| +
|
| + /* If values are not available for all fields of the index to the left
|
| + ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
|
| + if( pBuilder->nRecValid<(nEq-1) ){
|
| + return SQLITE_NOTFOUND;
|
| + }
|
| +
|
| + /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
|
| + ** below would return the same value. */
|
| + if( nEq>=p->nColumn ){
|
| + *pnRow = 1;
|
| + return SQLITE_OK;
|
| + }
|
| +
|
| + aff = sqlite3IndexColumnAffinity(pParse->db, p, nEq-1);
|
| + rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk);
|
| + pBuilder->pRec = pRec;
|
| + if( rc!=SQLITE_OK ) return rc;
|
| + if( bOk==0 ) return SQLITE_NOTFOUND;
|
| + pBuilder->nRecValid = nEq;
|
| +
|
| + whereKeyStats(pParse, p, pRec, 0, a);
|
| + WHERETRACE(0x10,("equality scan regions: %d\n", (int)a[1]));
|
| + *pnRow = a[1];
|
| +
|
| + return rc;
|
| +}
|
| +#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
|
| +
|
| +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
|
| +/*
|
| +** Estimate the number of rows that will be returned based on
|
| +** an IN constraint where the right-hand side of the IN operator
|
| +** is a list of values. Example:
|
| +**
|
| +** WHERE x IN (1,2,3,4)
|
| +**
|
| +** Write the estimated row count into *pnRow and return SQLITE_OK.
|
| +** If unable to make an estimate, leave *pnRow unchanged and return
|
| +** non-zero.
|
| +**
|
| +** This routine can fail if it is unable to load a collating sequence
|
| +** required for string comparison, or if unable to allocate memory
|
| +** for a UTF conversion required for comparison. The error is stored
|
| +** in the pParse structure.
|
| +*/
|
| +static int whereInScanEst(
|
| + Parse *pParse, /* Parsing & code generating context */
|
| + WhereLoopBuilder *pBuilder,
|
| + ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
|
| + tRowcnt *pnRow /* Write the revised row estimate here */
|
| +){
|
| + Index *p = pBuilder->pNew->u.btree.pIndex;
|
| + i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
|
| + int nRecValid = pBuilder->nRecValid;
|
| + int rc = SQLITE_OK; /* Subfunction return code */
|
| + tRowcnt nEst; /* Number of rows for a single term */
|
| + tRowcnt nRowEst = 0; /* New estimate of the number of rows */
|
| + int i; /* Loop counter */
|
| +
|
| + assert( p->aSample!=0 );
|
| + for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
|
| + nEst = nRow0;
|
| + rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
|
| + nRowEst += nEst;
|
| + pBuilder->nRecValid = nRecValid;
|
| + }
|
| +
|
| + if( rc==SQLITE_OK ){
|
| + if( nRowEst > nRow0 ) nRowEst = nRow0;
|
| + *pnRow = nRowEst;
|
| + WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst));
|
| + }
|
| + assert( pBuilder->nRecValid==nRecValid );
|
| + return rc;
|
| +}
|
| +#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
|
| +
|
| +
|
| +#ifdef WHERETRACE_ENABLED
|
| +/*
|
| +** Print the content of a WhereTerm object
|
| +*/
|
| +static void whereTermPrint(WhereTerm *pTerm, int iTerm){
|
| + if( pTerm==0 ){
|
| + sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
|
| + }else{
|
| + char zType[4];
|
| + memcpy(zType, "...", 4);
|
| + if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
|
| + if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E';
|
| + if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
|
| + sqlite3DebugPrintf(
|
| + "TERM-%-3d %p %s cursor=%-3d prob=%-3d op=0x%03x wtFlags=0x%04x\n",
|
| + iTerm, pTerm, zType, pTerm->leftCursor, pTerm->truthProb,
|
| + pTerm->eOperator, pTerm->wtFlags);
|
| + sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
|
| + }
|
| +}
|
| +#endif
|
| +
|
| +#ifdef WHERETRACE_ENABLED
|
| +/*
|
| +** Print a WhereLoop object for debugging purposes
|
| +*/
|
| +static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
|
| + WhereInfo *pWInfo = pWC->pWInfo;
|
| + int nb = 1+(pWInfo->pTabList->nSrc+7)/8;
|
| + struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
|
| + Table *pTab = pItem->pTab;
|
| + sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
|
| + p->iTab, nb, p->maskSelf, nb, p->prereq);
|
| + sqlite3DebugPrintf(" %12s",
|
| + pItem->zAlias ? pItem->zAlias : pTab->zName);
|
| + if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
|
| + const char *zName;
|
| + if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
|
| + if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
|
| + int i = sqlite3Strlen30(zName) - 1;
|
| + while( zName[i]!='_' ) i--;
|
| + zName += i;
|
| + }
|
| + sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
|
| + }else{
|
| + sqlite3DebugPrintf("%20s","");
|
| + }
|
| + }else{
|
| + char *z;
|
| + if( p->u.vtab.idxStr ){
|
| + z = sqlite3_mprintf("(%d,\"%s\",%x)",
|
| + p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
|
| + }else{
|
| + z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
|
| + }
|
| + sqlite3DebugPrintf(" %-19s", z);
|
| + sqlite3_free(z);
|
| + }
|
| + if( p->wsFlags & WHERE_SKIPSCAN ){
|
| + sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
|
| + }else{
|
| + sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
|
| + }
|
| + sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
|
| + if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
|
| + int i;
|
| + for(i=0; i<p->nLTerm; i++){
|
| + whereTermPrint(p->aLTerm[i], i);
|
| + }
|
| + }
|
| +}
|
| +#endif
|
| +
|
| +/*
|
| +** Convert bulk memory into a valid WhereLoop that can be passed
|
| +** to whereLoopClear harmlessly.
|
| +*/
|
| +static void whereLoopInit(WhereLoop *p){
|
| + p->aLTerm = p->aLTermSpace;
|
| + p->nLTerm = 0;
|
| + p->nLSlot = ArraySize(p->aLTermSpace);
|
| + p->wsFlags = 0;
|
| +}
|
| +
|
| +/*
|
| +** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
|
| +*/
|
| +static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
|
| + if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
|
| + if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
|
| + sqlite3_free(p->u.vtab.idxStr);
|
| + p->u.vtab.needFree = 0;
|
| + p->u.vtab.idxStr = 0;
|
| + }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
|
| + sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
|
| + sqlite3DbFree(db, p->u.btree.pIndex);
|
| + p->u.btree.pIndex = 0;
|
| + }
|
| + }
|
| +}
|
| +
|
| +/*
|
| +** Deallocate internal memory used by a WhereLoop object
|
| +*/
|
| +static void whereLoopClear(sqlite3 *db, WhereLoop *p){
|
| + if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
|
| + whereLoopClearUnion(db, p);
|
| + whereLoopInit(p);
|
| +}
|
| +
|
| +/*
|
| +** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
|
| +*/
|
| +static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
|
| + WhereTerm **paNew;
|
| + if( p->nLSlot>=n ) return SQLITE_OK;
|
| + n = (n+7)&~7;
|
| + paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n);
|
| + if( paNew==0 ) return SQLITE_NOMEM;
|
| + memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
|
| + if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
|
| + p->aLTerm = paNew;
|
| + p->nLSlot = n;
|
| + return SQLITE_OK;
|
| +}
|
| +
|
| +/*
|
| +** Transfer content from the second pLoop into the first.
|
| +*/
|
| +static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
|
| + whereLoopClearUnion(db, pTo);
|
| + if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
|
| + memset(&pTo->u, 0, sizeof(pTo->u));
|
| + return SQLITE_NOMEM;
|
| + }
|
| + memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
|
| + memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
|
| + if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
|
| + pFrom->u.vtab.needFree = 0;
|
| + }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
|
| + pFrom->u.btree.pIndex = 0;
|
| + }
|
| + return SQLITE_OK;
|
| +}
|
| +
|
| +/*
|
| +** Delete a WhereLoop object
|
| +*/
|
| +static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
|
| + whereLoopClear(db, p);
|
| + sqlite3DbFree(db, p);
|
| +}
|
| +
|
| +/*
|
| +** Free a WhereInfo structure
|
| +*/
|
| +static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
|
| + if( ALWAYS(pWInfo) ){
|
| + int i;
|
| + for(i=0; i<pWInfo->nLevel; i++){
|
| + WhereLevel *pLevel = &pWInfo->a[i];
|
| + if( pLevel->pWLoop && (pLevel->pWLoop->wsFlags & WHERE_IN_ABLE) ){
|
| + sqlite3DbFree(db, pLevel->u.in.aInLoop);
|
| + }
|
| + }
|
| + sqlite3WhereClauseClear(&pWInfo->sWC);
|
| + while( pWInfo->pLoops ){
|
| + WhereLoop *p = pWInfo->pLoops;
|
| + pWInfo->pLoops = p->pNextLoop;
|
| + whereLoopDelete(db, p);
|
| + }
|
| + sqlite3DbFree(db, pWInfo);
|
| + }
|
| +}
|
| +
|
| +/*
|
| +** Return TRUE if all of the following are true:
|
| +**
|
| +** (1) X has the same or lower cost that Y
|
| +** (2) X is a proper subset of Y
|
| +** (3) X skips at least as many columns as Y
|
| +**
|
| +** By "proper subset" we mean that X uses fewer WHERE clause terms
|
| +** than Y and that every WHERE clause term used by X is also used
|
| +** by Y.
|
| +**
|
| +** If X is a proper subset of Y then Y is a better choice and ought
|
| +** to have a lower cost. This routine returns TRUE when that cost
|
| +** relationship is inverted and needs to be adjusted. The third rule
|
| +** was added because if X uses skip-scan less than Y it still might
|
| +** deserve a lower cost even if it is a proper subset of Y.
|
| +*/
|
| +static int whereLoopCheaperProperSubset(
|
| + const WhereLoop *pX, /* First WhereLoop to compare */
|
| + const WhereLoop *pY /* Compare against this WhereLoop */
|
| +){
|
| + int i, j;
|
| + if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
|
| + return 0; /* X is not a subset of Y */
|
| + }
|
| + if( pY->nSkip > pX->nSkip ) return 0;
|
| + if( pX->rRun >= pY->rRun ){
|
| + if( pX->rRun > pY->rRun ) return 0; /* X costs more than Y */
|
| + if( pX->nOut > pY->nOut ) return 0; /* X costs more than Y */
|
| + }
|
| + for(i=pX->nLTerm-1; i>=0; i--){
|
| + if( pX->aLTerm[i]==0 ) continue;
|
| + for(j=pY->nLTerm-1; j>=0; j--){
|
| + if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
|
| + }
|
| + if( j<0 ) return 0; /* X not a subset of Y since term X[i] not used by Y */
|
| + }
|
| + return 1; /* All conditions meet */
|
| +}
|
| +
|
| +/*
|
| +** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
|
| +** that:
|
| +**
|
| +** (1) pTemplate costs less than any other WhereLoops that are a proper
|
| +** subset of pTemplate
|
| +**
|
| +** (2) pTemplate costs more than any other WhereLoops for which pTemplate
|
| +** is a proper subset.
|
| +**
|
| +** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
|
| +** WHERE clause terms than Y and that every WHERE clause term used by X is
|
| +** also used by Y.
|
| +*/
|
| +static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
|
| + if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
|
| + for(; p; p=p->pNextLoop){
|
| + if( p->iTab!=pTemplate->iTab ) continue;
|
| + if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
|
| + if( whereLoopCheaperProperSubset(p, pTemplate) ){
|
| + /* Adjust pTemplate cost downward so that it is cheaper than its
|
| + ** subset p. */
|
| + WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
|
| + pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1));
|
| + pTemplate->rRun = p->rRun;
|
| + pTemplate->nOut = p->nOut - 1;
|
| + }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
|
| + /* Adjust pTemplate cost upward so that it is costlier than p since
|
| + ** pTemplate is a proper subset of p */
|
| + WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
|
| + pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1));
|
| + pTemplate->rRun = p->rRun;
|
| + pTemplate->nOut = p->nOut + 1;
|
| + }
|
| + }
|
| +}
|
| +
|
| +/*
|
| +** Search the list of WhereLoops in *ppPrev looking for one that can be
|
| +** supplanted by pTemplate.
|
| +**
|
| +** Return NULL if the WhereLoop list contains an entry that can supplant
|
| +** pTemplate, in other words if pTemplate does not belong on the list.
|
| +**
|
| +** If pX is a WhereLoop that pTemplate can supplant, then return the
|
| +** link that points to pX.
|
| +**
|
| +** If pTemplate cannot supplant any existing element of the list but needs
|
| +** to be added to the list, then return a pointer to the tail of the list.
|
| +*/
|
| +static WhereLoop **whereLoopFindLesser(
|
| + WhereLoop **ppPrev,
|
| + const WhereLoop *pTemplate
|
| +){
|
| + WhereLoop *p;
|
| + for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
|
| + if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
|
| + /* If either the iTab or iSortIdx values for two WhereLoop are different
|
| + ** then those WhereLoops need to be considered separately. Neither is
|
| + ** a candidate to replace the other. */
|
| + continue;
|
| + }
|
| + /* In the current implementation, the rSetup value is either zero
|
| + ** or the cost of building an automatic index (NlogN) and the NlogN
|
| + ** is the same for compatible WhereLoops. */
|
| + assert( p->rSetup==0 || pTemplate->rSetup==0
|
| + || p->rSetup==pTemplate->rSetup );
|
| +
|
| + /* whereLoopAddBtree() always generates and inserts the automatic index
|
| + ** case first. Hence compatible candidate WhereLoops never have a larger
|
| + ** rSetup. Call this SETUP-INVARIANT */
|
| + assert( p->rSetup>=pTemplate->rSetup );
|
| +
|
| + /* Any loop using an appliation-defined index (or PRIMARY KEY or
|
| + ** UNIQUE constraint) with one or more == constraints is better
|
| + ** than an automatic index. Unless it is a skip-scan. */
|
| + if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
|
| + && (pTemplate->nSkip)==0
|
| + && (pTemplate->wsFlags & WHERE_INDEXED)!=0
|
| + && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
|
| + && (p->prereq & pTemplate->prereq)==pTemplate->prereq
|
| + ){
|
| + break;
|
| + }
|
| +
|
| + /* If existing WhereLoop p is better than pTemplate, pTemplate can be
|
| + ** discarded. WhereLoop p is better if:
|
| + ** (1) p has no more dependencies than pTemplate, and
|
| + ** (2) p has an equal or lower cost than pTemplate
|
| + */
|
| + if( (p->prereq & pTemplate->prereq)==p->prereq /* (1) */
|
| + && p->rSetup<=pTemplate->rSetup /* (2a) */
|
| + && p->rRun<=pTemplate->rRun /* (2b) */
|
| + && p->nOut<=pTemplate->nOut /* (2c) */
|
| + ){
|
| + return 0; /* Discard pTemplate */
|
| + }
|
| +
|
| + /* If pTemplate is always better than p, then cause p to be overwritten
|
| + ** with pTemplate. pTemplate is better than p if:
|
| + ** (1) pTemplate has no more dependences than p, and
|
| + ** (2) pTemplate has an equal or lower cost than p.
|
| + */
|
| + if( (p->prereq & pTemplate->prereq)==pTemplate->prereq /* (1) */
|
| + && p->rRun>=pTemplate->rRun /* (2a) */
|
| + && p->nOut>=pTemplate->nOut /* (2b) */
|
| + ){
|
| + assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
|
| + break; /* Cause p to be overwritten by pTemplate */
|
| + }
|
| + }
|
| + return ppPrev;
|
| +}
|
| +
|
| +/*
|
| +** Insert or replace a WhereLoop entry using the template supplied.
|
| +**
|
| +** An existing WhereLoop entry might be overwritten if the new template
|
| +** is better and has fewer dependencies. Or the template will be ignored
|
| +** and no insert will occur if an existing WhereLoop is faster and has
|
| +** fewer dependencies than the template. Otherwise a new WhereLoop is
|
| +** added based on the template.
|
| +**
|
| +** If pBuilder->pOrSet is not NULL then we care about only the
|
| +** prerequisites and rRun and nOut costs of the N best loops. That
|
| +** information is gathered in the pBuilder->pOrSet object. This special
|
| +** processing mode is used only for OR clause processing.
|
| +**
|
| +** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
|
| +** still might overwrite similar loops with the new template if the
|
| +** new template is better. Loops may be overwritten if the following
|
| +** conditions are met:
|
| +**
|
| +** (1) They have the same iTab.
|
| +** (2) They have the same iSortIdx.
|
| +** (3) The template has same or fewer dependencies than the current loop
|
| +** (4) The template has the same or lower cost than the current loop
|
| +*/
|
| +static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
|
| + WhereLoop **ppPrev, *p;
|
| + WhereInfo *pWInfo = pBuilder->pWInfo;
|
| + sqlite3 *db = pWInfo->pParse->db;
|
| +
|
| + /* If pBuilder->pOrSet is defined, then only keep track of the costs
|
| + ** and prereqs.
|
| + */
|
| + if( pBuilder->pOrSet!=0 ){
|
| + if( pTemplate->nLTerm ){
|
| +#if WHERETRACE_ENABLED
|
| + u16 n = pBuilder->pOrSet->n;
|
| + int x =
|
| +#endif
|
| + whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
|
| + pTemplate->nOut);
|
| +#if WHERETRACE_ENABLED /* 0x8 */
|
| + if( sqlite3WhereTrace & 0x8 ){
|
| + sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
|
| + whereLoopPrint(pTemplate, pBuilder->pWC);
|
| + }
|
| +#endif
|
| + }
|
| + return SQLITE_OK;
|
| + }
|
| +
|
| + /* Look for an existing WhereLoop to replace with pTemplate
|
| + */
|
| + whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
|
| + ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
|
| +
|
| + if( ppPrev==0 ){
|
| + /* There already exists a WhereLoop on the list that is better
|
| + ** than pTemplate, so just ignore pTemplate */
|
| +#if WHERETRACE_ENABLED /* 0x8 */
|
| + if( sqlite3WhereTrace & 0x8 ){
|
| + sqlite3DebugPrintf(" skip: ");
|
| + whereLoopPrint(pTemplate, pBuilder->pWC);
|
| + }
|
| +#endif
|
| + return SQLITE_OK;
|
| + }else{
|
| + p = *ppPrev;
|
| + }
|
| +
|
| + /* If we reach this point it means that either p[] should be overwritten
|
| + ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
|
| + ** WhereLoop and insert it.
|
| + */
|
| +#if WHERETRACE_ENABLED /* 0x8 */
|
| + if( sqlite3WhereTrace & 0x8 ){
|
| + if( p!=0 ){
|
| + sqlite3DebugPrintf("replace: ");
|
| + whereLoopPrint(p, pBuilder->pWC);
|
| + }
|
| + sqlite3DebugPrintf(" add: ");
|
| + whereLoopPrint(pTemplate, pBuilder->pWC);
|
| + }
|
| +#endif
|
| + if( p==0 ){
|
| + /* Allocate a new WhereLoop to add to the end of the list */
|
| + *ppPrev = p = sqlite3DbMallocRaw(db, sizeof(WhereLoop));
|
| + if( p==0 ) return SQLITE_NOMEM;
|
| + whereLoopInit(p);
|
| + p->pNextLoop = 0;
|
| + }else{
|
| + /* We will be overwriting WhereLoop p[]. But before we do, first
|
| + ** go through the rest of the list and delete any other entries besides
|
| + ** p[] that are also supplated by pTemplate */
|
| + WhereLoop **ppTail = &p->pNextLoop;
|
| + WhereLoop *pToDel;
|
| + while( *ppTail ){
|
| + ppTail = whereLoopFindLesser(ppTail, pTemplate);
|
| + if( ppTail==0 ) break;
|
| + pToDel = *ppTail;
|
| + if( pToDel==0 ) break;
|
| + *ppTail = pToDel->pNextLoop;
|
| +#if WHERETRACE_ENABLED /* 0x8 */
|
| + if( sqlite3WhereTrace & 0x8 ){
|
| + sqlite3DebugPrintf(" delete: ");
|
| + whereLoopPrint(pToDel, pBuilder->pWC);
|
| + }
|
| +#endif
|
| + whereLoopDelete(db, pToDel);
|
| + }
|
| + }
|
| + whereLoopXfer(db, p, pTemplate);
|
| + if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
|
| + Index *pIndex = p->u.btree.pIndex;
|
| + if( pIndex && pIndex->tnum==0 ){
|
| + p->u.btree.pIndex = 0;
|
| + }
|
| + }
|
| + return SQLITE_OK;
|
| +}
|
| +
|
| +/*
|
| +** Adjust the WhereLoop.nOut value downward to account for terms of the
|
| +** WHERE clause that reference the loop but which are not used by an
|
| +** index.
|
| +*
|
| +** For every WHERE clause term that is not used by the index
|
| +** and which has a truth probability assigned by one of the likelihood(),
|
| +** likely(), or unlikely() SQL functions, reduce the estimated number
|
| +** of output rows by the probability specified.
|
| +**
|
| +** TUNING: For every WHERE clause term that is not used by the index
|
| +** and which does not have an assigned truth probability, heuristics
|
| +** described below are used to try to estimate the truth probability.
|
| +** TODO --> Perhaps this is something that could be improved by better
|
| +** table statistics.
|
| +**
|
| +** Heuristic 1: Estimate the truth probability as 93.75%. The 93.75%
|
| +** value corresponds to -1 in LogEst notation, so this means decrement
|
| +** the WhereLoop.nOut field for every such WHERE clause term.
|
| +**
|
| +** Heuristic 2: If there exists one or more WHERE clause terms of the
|
| +** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the
|
| +** final output row estimate is no greater than 1/4 of the total number
|
| +** of rows in the table. In other words, assume that x==EXPR will filter
|
| +** out at least 3 out of 4 rows. If EXPR is -1 or 0 or 1, then maybe the
|
| +** "x" column is boolean or else -1 or 0 or 1 is a common default value
|
| +** on the "x" column and so in that case only cap the output row estimate
|
| +** at 1/2 instead of 1/4.
|
| +*/
|
| +static void whereLoopOutputAdjust(
|
| + WhereClause *pWC, /* The WHERE clause */
|
| + WhereLoop *pLoop, /* The loop to adjust downward */
|
| + LogEst nRow /* Number of rows in the entire table */
|
| +){
|
| + WhereTerm *pTerm, *pX;
|
| + Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
|
| + int i, j, k;
|
| + LogEst iReduce = 0; /* pLoop->nOut should not exceed nRow-iReduce */
|
| +
|
| + assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
|
| + for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
|
| + if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
|
| + if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
|
| + if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
|
| + for(j=pLoop->nLTerm-1; j>=0; j--){
|
| + pX = pLoop->aLTerm[j];
|
| + if( pX==0 ) continue;
|
| + if( pX==pTerm ) break;
|
| + if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
|
| + }
|
| + if( j<0 ){
|
| + if( pTerm->truthProb<=0 ){
|
| + /* If a truth probability is specified using the likelihood() hints,
|
| + ** then use the probability provided by the application. */
|
| + pLoop->nOut += pTerm->truthProb;
|
| + }else{
|
| + /* In the absence of explicit truth probabilities, use heuristics to
|
| + ** guess a reasonable truth probability. */
|
| + pLoop->nOut--;
|
| + if( pTerm->eOperator&(WO_EQ|WO_IS) ){
|
| + Expr *pRight = pTerm->pExpr->pRight;
|
| + testcase( pTerm->pExpr->op==TK_IS );
|
| + if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){
|
| + k = 10;
|
| + }else{
|
| + k = 20;
|
| + }
|
| + if( iReduce<k ) iReduce = k;
|
| + }
|
| + }
|
| + }
|
| + }
|
| + if( pLoop->nOut > nRow-iReduce ) pLoop->nOut = nRow - iReduce;
|
| +}
|
| +
|
| +/*
|
| +** Adjust the cost C by the costMult facter T. This only occurs if
|
| +** compiled with -DSQLITE_ENABLE_COSTMULT
|
| +*/
|
| +#ifdef SQLITE_ENABLE_COSTMULT
|
| +# define ApplyCostMultiplier(C,T) C += T
|
| +#else
|
| +# define ApplyCostMultiplier(C,T)
|
| +#endif
|
| +
|
| +/*
|
| +** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
|
| +** index pIndex. Try to match one more.
|
| +**
|
| +** When this function is called, pBuilder->pNew->nOut contains the
|
| +** number of rows expected to be visited by filtering using the nEq
|
| +** terms only. If it is modified, this value is restored before this
|
| +** function returns.
|
| +**
|
| +** If pProbe->tnum==0, that means pIndex is a fake index used for the
|
| +** INTEGER PRIMARY KEY.
|
| +*/
|
| +static int whereLoopAddBtreeIndex(
|
| + WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
|
| + struct SrcList_item *pSrc, /* FROM clause term being analyzed */
|
| + Index *pProbe, /* An index on pSrc */
|
| + LogEst nInMul /* log(Number of iterations due to IN) */
|
| +){
|
| + WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
|
| + Parse *pParse = pWInfo->pParse; /* Parsing context */
|
| + sqlite3 *db = pParse->db; /* Database connection malloc context */
|
| + WhereLoop *pNew; /* Template WhereLoop under construction */
|
| + WhereTerm *pTerm; /* A WhereTerm under consideration */
|
| + int opMask; /* Valid operators for constraints */
|
| + WhereScan scan; /* Iterator for WHERE terms */
|
| + Bitmask saved_prereq; /* Original value of pNew->prereq */
|
| + u16 saved_nLTerm; /* Original value of pNew->nLTerm */
|
| + u16 saved_nEq; /* Original value of pNew->u.btree.nEq */
|
| + u16 saved_nSkip; /* Original value of pNew->nSkip */
|
| + u32 saved_wsFlags; /* Original value of pNew->wsFlags */
|
| + LogEst saved_nOut; /* Original value of pNew->nOut */
|
| + int rc = SQLITE_OK; /* Return code */
|
| + LogEst rSize; /* Number of rows in the table */
|
| + LogEst rLogSize; /* Logarithm of table size */
|
| + WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
|
| +
|
| + pNew = pBuilder->pNew;
|
| + if( db->mallocFailed ) return SQLITE_NOMEM;
|
| +
|
| + assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
|
| + assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
|
| + if( pNew->wsFlags & WHERE_BTM_LIMIT ){
|
| + opMask = WO_LT|WO_LE;
|
| + }else if( /*pProbe->tnum<=0 ||*/ (pSrc->fg.jointype & JT_LEFT)!=0 ){
|
| + opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE;
|
| + }else{
|
| + opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE|WO_ISNULL|WO_IS;
|
| + }
|
| + if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
|
| +
|
| + assert( pNew->u.btree.nEq<pProbe->nColumn );
|
| +
|
| + saved_nEq = pNew->u.btree.nEq;
|
| + saved_nSkip = pNew->nSkip;
|
| + saved_nLTerm = pNew->nLTerm;
|
| + saved_wsFlags = pNew->wsFlags;
|
| + saved_prereq = pNew->prereq;
|
| + saved_nOut = pNew->nOut;
|
| + pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, saved_nEq,
|
| + opMask, pProbe);
|
| + pNew->rSetup = 0;
|
| + rSize = pProbe->aiRowLogEst[0];
|
| + rLogSize = estLog(rSize);
|
| + for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
|
| + u16 eOp = pTerm->eOperator; /* Shorthand for pTerm->eOperator */
|
| + LogEst rCostIdx;
|
| + LogEst nOutUnadjusted; /* nOut before IN() and WHERE adjustments */
|
| + int nIn = 0;
|
| +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
|
| + int nRecValid = pBuilder->nRecValid;
|
| +#endif
|
| + if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
|
| + && indexColumnNotNull(pProbe, saved_nEq)
|
| + ){
|
| + continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
|
| + }
|
| + if( pTerm->prereqRight & pNew->maskSelf ) continue;
|
| +
|
| + /* Do not allow the upper bound of a LIKE optimization range constraint
|
| + ** to mix with a lower range bound from some other source */
|
| + if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue;
|
| +
|
| + pNew->wsFlags = saved_wsFlags;
|
| + pNew->u.btree.nEq = saved_nEq;
|
| + pNew->nLTerm = saved_nLTerm;
|
| + if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
|
| + pNew->aLTerm[pNew->nLTerm++] = pTerm;
|
| + pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
|
| +
|
| + assert( nInMul==0
|
| + || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
|
| + || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
|
| + || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
|
| + );
|
| +
|
| + if( eOp & WO_IN ){
|
| + Expr *pExpr = pTerm->pExpr;
|
| + pNew->wsFlags |= WHERE_COLUMN_IN;
|
| + if( ExprHasProperty(pExpr, EP_xIsSelect) ){
|
| + /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
|
| + nIn = 46; assert( 46==sqlite3LogEst(25) );
|
| + }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
|
| + /* "x IN (value, value, ...)" */
|
| + nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
|
| + }
|
| + assert( nIn>0 ); /* RHS always has 2 or more terms... The parser
|
| + ** changes "x IN (?)" into "x=?". */
|
| +
|
| + }else if( eOp & (WO_EQ|WO_IS) ){
|
| + int iCol = pProbe->aiColumn[saved_nEq];
|
| + pNew->wsFlags |= WHERE_COLUMN_EQ;
|
| + assert( saved_nEq==pNew->u.btree.nEq );
|
| + if( iCol==XN_ROWID
|
| + || (iCol>0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1)
|
| + ){
|
| + if( iCol>=0 && pProbe->uniqNotNull==0 ){
|
| + pNew->wsFlags |= WHERE_UNQ_WANTED;
|
| + }else{
|
| + pNew->wsFlags |= WHERE_ONEROW;
|
| + }
|
| + }
|
| + }else if( eOp & WO_ISNULL ){
|
| + pNew->wsFlags |= WHERE_COLUMN_NULL;
|
| + }else if( eOp & (WO_GT|WO_GE) ){
|
| + testcase( eOp & WO_GT );
|
| + testcase( eOp & WO_GE );
|
| + pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
|
| + pBtm = pTerm;
|
| + pTop = 0;
|
| + if( pTerm->wtFlags & TERM_LIKEOPT ){
|
| + /* Range contraints that come from the LIKE optimization are
|
| + ** always used in pairs. */
|
| + pTop = &pTerm[1];
|
| + assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm );
|
| + assert( pTop->wtFlags & TERM_LIKEOPT );
|
| + assert( pTop->eOperator==WO_LT );
|
| + if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
|
| + pNew->aLTerm[pNew->nLTerm++] = pTop;
|
| + pNew->wsFlags |= WHERE_TOP_LIMIT;
|
| + }
|
| + }else{
|
| + assert( eOp & (WO_LT|WO_LE) );
|
| + testcase( eOp & WO_LT );
|
| + testcase( eOp & WO_LE );
|
| + pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
|
| + pTop = pTerm;
|
| + pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
|
| + pNew->aLTerm[pNew->nLTerm-2] : 0;
|
| + }
|
| +
|
| + /* At this point pNew->nOut is set to the number of rows expected to
|
| + ** be visited by the index scan before considering term pTerm, or the
|
| + ** values of nIn and nInMul. In other words, assuming that all
|
| + ** "x IN(...)" terms are replaced with "x = ?". This block updates
|
| + ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul). */
|
| + assert( pNew->nOut==saved_nOut );
|
| + if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
|
| + /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4
|
| + ** data, using some other estimate. */
|
| + whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
|
| + }else{
|
| + int nEq = ++pNew->u.btree.nEq;
|
| + assert( eOp & (WO_ISNULL|WO_EQ|WO_IN|WO_IS) );
|
| +
|
| + assert( pNew->nOut==saved_nOut );
|
| + if( pTerm->truthProb<=0 && pProbe->aiColumn[saved_nEq]>=0 ){
|
| + assert( (eOp & WO_IN) || nIn==0 );
|
| + testcase( eOp & WO_IN );
|
| + pNew->nOut += pTerm->truthProb;
|
| + pNew->nOut -= nIn;
|
| + }else{
|
| +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
|
| + tRowcnt nOut = 0;
|
| + if( nInMul==0
|
| + && pProbe->nSample
|
| + && pNew->u.btree.nEq<=pProbe->nSampleCol
|
| + && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
|
| + ){
|
| + Expr *pExpr = pTerm->pExpr;
|
| + if( (eOp & (WO_EQ|WO_ISNULL|WO_IS))!=0 ){
|
| + testcase( eOp & WO_EQ );
|
| + testcase( eOp & WO_IS );
|
| + testcase( eOp & WO_ISNULL );
|
| + rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
|
| + }else{
|
| + rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
|
| + }
|
| + if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
|
| + if( rc!=SQLITE_OK ) break; /* Jump out of the pTerm loop */
|
| + if( nOut ){
|
| + pNew->nOut = sqlite3LogEst(nOut);
|
| + if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
|
| + pNew->nOut -= nIn;
|
| + }
|
| + }
|
| + if( nOut==0 )
|
| +#endif
|
| + {
|
| + pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
|
| + if( eOp & WO_ISNULL ){
|
| + /* TUNING: If there is no likelihood() value, assume that a
|
| + ** "col IS NULL" expression matches twice as many rows
|
| + ** as (col=?). */
|
| + pNew->nOut += 10;
|
| + }
|
| + }
|
| + }
|
| + }
|
| +
|
| + /* Set rCostIdx to the cost of visiting selected rows in index. Add
|
| + ** it to pNew->rRun, which is currently set to the cost of the index
|
| + ** seek only. Then, if this is a non-covering index, add the cost of
|
| + ** visiting the rows in the main table. */
|
| + rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
|
| + pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
|
| + if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
|
| + pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
|
| + }
|
| + ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
|
| +
|
| + nOutUnadjusted = pNew->nOut;
|
| + pNew->rRun += nInMul + nIn;
|
| + pNew->nOut += nInMul + nIn;
|
| + whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
|
| + rc = whereLoopInsert(pBuilder, pNew);
|
| +
|
| + if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
|
| + pNew->nOut = saved_nOut;
|
| + }else{
|
| + pNew->nOut = nOutUnadjusted;
|
| + }
|
| +
|
| + if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
|
| + && pNew->u.btree.nEq<pProbe->nColumn
|
| + ){
|
| + whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
|
| + }
|
| + pNew->nOut = saved_nOut;
|
| +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
|
| + pBuilder->nRecValid = nRecValid;
|
| +#endif
|
| + }
|
| + pNew->prereq = saved_prereq;
|
| + pNew->u.btree.nEq = saved_nEq;
|
| + pNew->nSkip = saved_nSkip;
|
| + pNew->wsFlags = saved_wsFlags;
|
| + pNew->nOut = saved_nOut;
|
| + pNew->nLTerm = saved_nLTerm;
|
| +
|
| + /* Consider using a skip-scan if there are no WHERE clause constraints
|
| + ** available for the left-most terms of the index, and if the average
|
| + ** number of repeats in the left-most terms is at least 18.
|
| + **
|
| + ** The magic number 18 is selected on the basis that scanning 17 rows
|
| + ** is almost always quicker than an index seek (even though if the index
|
| + ** contains fewer than 2^17 rows we assume otherwise in other parts of
|
| + ** the code). And, even if it is not, it should not be too much slower.
|
| + ** On the other hand, the extra seeks could end up being significantly
|
| + ** more expensive. */
|
| + assert( 42==sqlite3LogEst(18) );
|
| + if( saved_nEq==saved_nSkip
|
| + && saved_nEq+1<pProbe->nKeyCol
|
| + && pProbe->noSkipScan==0
|
| + && pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */
|
| + && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
|
| + ){
|
| + LogEst nIter;
|
| + pNew->u.btree.nEq++;
|
| + pNew->nSkip++;
|
| + pNew->aLTerm[pNew->nLTerm++] = 0;
|
| + pNew->wsFlags |= WHERE_SKIPSCAN;
|
| + nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
|
| + pNew->nOut -= nIter;
|
| + /* TUNING: Because uncertainties in the estimates for skip-scan queries,
|
| + ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
|
| + nIter += 5;
|
| + whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
|
| + pNew->nOut = saved_nOut;
|
| + pNew->u.btree.nEq = saved_nEq;
|
| + pNew->nSkip = saved_nSkip;
|
| + pNew->wsFlags = saved_wsFlags;
|
| + }
|
| +
|
| + return rc;
|
| +}
|
| +
|
| +/*
|
| +** Return True if it is possible that pIndex might be useful in
|
| +** implementing the ORDER BY clause in pBuilder.
|
| +**
|
| +** Return False if pBuilder does not contain an ORDER BY clause or
|
| +** if there is no way for pIndex to be useful in implementing that
|
| +** ORDER BY clause.
|
| +*/
|
| +static int indexMightHelpWithOrderBy(
|
| + WhereLoopBuilder *pBuilder,
|
| + Index *pIndex,
|
| + int iCursor
|
| +){
|
| + ExprList *pOB;
|
| + ExprList *aColExpr;
|
| + int ii, jj;
|
| +
|
| + if( pIndex->bUnordered ) return 0;
|
| + if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
|
| + for(ii=0; ii<pOB->nExpr; ii++){
|
| + Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
|
| + if( pExpr->op==TK_COLUMN && pExpr->iTable==iCursor ){
|
| + if( pExpr->iColumn<0 ) return 1;
|
| + for(jj=0; jj<pIndex->nKeyCol; jj++){
|
| + if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
|
| + }
|
| + }else if( (aColExpr = pIndex->aColExpr)!=0 ){
|
| + for(jj=0; jj<pIndex->nKeyCol; jj++){
|
| + if( pIndex->aiColumn[jj]!=XN_EXPR ) continue;
|
| + if( sqlite3ExprCompare(pExpr,aColExpr->a[jj].pExpr,iCursor)==0 ){
|
| + return 1;
|
| + }
|
| + }
|
| + }
|
| + }
|
| + return 0;
|
| +}
|
| +
|
| +/*
|
| +** Return a bitmask where 1s indicate that the corresponding column of
|
| +** the table is used by an index. Only the first 63 columns are considered.
|
| +*/
|
| +static Bitmask columnsInIndex(Index *pIdx){
|
| + Bitmask m = 0;
|
| + int j;
|
| + for(j=pIdx->nColumn-1; j>=0; j--){
|
| + int x = pIdx->aiColumn[j];
|
| + if( x>=0 ){
|
| + testcase( x==BMS-1 );
|
| + testcase( x==BMS-2 );
|
| + if( x<BMS-1 ) m |= MASKBIT(x);
|
| + }
|
| + }
|
| + return m;
|
| +}
|
| +
|
| +/* Check to see if a partial index with pPartIndexWhere can be used
|
| +** in the current query. Return true if it can be and false if not.
|
| +*/
|
| +static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
|
| + int i;
|
| + WhereTerm *pTerm;
|
| + while( pWhere->op==TK_AND ){
|
| + if( !whereUsablePartialIndex(iTab,pWC,pWhere->pLeft) ) return 0;
|
| + pWhere = pWhere->pRight;
|
| + }
|
| + for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
|
| + Expr *pExpr = pTerm->pExpr;
|
| + if( sqlite3ExprImpliesExpr(pExpr, pWhere, iTab)
|
| + && (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab)
|
| + ){
|
| + return 1;
|
| + }
|
| + }
|
| + return 0;
|
| +}
|
| +
|
| +/*
|
| +** Add all WhereLoop objects for a single table of the join where the table
|
| +** is idenfied by pBuilder->pNew->iTab. That table is guaranteed to be
|
| +** a b-tree table, not a virtual table.
|
| +**
|
| +** The costs (WhereLoop.rRun) of the b-tree loops added by this function
|
| +** are calculated as follows:
|
| +**
|
| +** For a full scan, assuming the table (or index) contains nRow rows:
|
| +**
|
| +** cost = nRow * 3.0 // full-table scan
|
| +** cost = nRow * K // scan of covering index
|
| +** cost = nRow * (K+3.0) // scan of non-covering index
|
| +**
|
| +** where K is a value between 1.1 and 3.0 set based on the relative
|
| +** estimated average size of the index and table records.
|
| +**
|
| +** For an index scan, where nVisit is the number of index rows visited
|
| +** by the scan, and nSeek is the number of seek operations required on
|
| +** the index b-tree:
|
| +**
|
| +** cost = nSeek * (log(nRow) + K * nVisit) // covering index
|
| +** cost = nSeek * (log(nRow) + (K+3.0) * nVisit) // non-covering index
|
| +**
|
| +** Normally, nSeek is 1. nSeek values greater than 1 come about if the
|
| +** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
|
| +** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
|
| +**
|
| +** The estimated values (nRow, nVisit, nSeek) often contain a large amount
|
| +** of uncertainty. For this reason, scoring is designed to pick plans that
|
| +** "do the least harm" if the estimates are inaccurate. For example, a
|
| +** log(nRow) factor is omitted from a non-covering index scan in order to
|
| +** bias the scoring in favor of using an index, since the worst-case
|
| +** performance of using an index is far better than the worst-case performance
|
| +** of a full table scan.
|
| +*/
|
| +static int whereLoopAddBtree(
|
| + WhereLoopBuilder *pBuilder, /* WHERE clause information */
|
| + Bitmask mExtra /* Extra prerequesites for using this table */
|
| +){
|
| + WhereInfo *pWInfo; /* WHERE analysis context */
|
| + Index *pProbe; /* An index we are evaluating */
|
| + Index sPk; /* A fake index object for the primary key */
|
| + LogEst aiRowEstPk[2]; /* The aiRowLogEst[] value for the sPk index */
|
| + i16 aiColumnPk = -1; /* The aColumn[] value for the sPk index */
|
| + SrcList *pTabList; /* The FROM clause */
|
| + struct SrcList_item *pSrc; /* The FROM clause btree term to add */
|
| + WhereLoop *pNew; /* Template WhereLoop object */
|
| + int rc = SQLITE_OK; /* Return code */
|
| + int iSortIdx = 1; /* Index number */
|
| + int b; /* A boolean value */
|
| + LogEst rSize; /* number of rows in the table */
|
| + LogEst rLogSize; /* Logarithm of the number of rows in the table */
|
| + WhereClause *pWC; /* The parsed WHERE clause */
|
| + Table *pTab; /* Table being queried */
|
| +
|
| + pNew = pBuilder->pNew;
|
| + pWInfo = pBuilder->pWInfo;
|
| + pTabList = pWInfo->pTabList;
|
| + pSrc = pTabList->a + pNew->iTab;
|
| + pTab = pSrc->pTab;
|
| + pWC = pBuilder->pWC;
|
| + assert( !IsVirtual(pSrc->pTab) );
|
| +
|
| + if( pSrc->pIBIndex ){
|
| + /* An INDEXED BY clause specifies a particular index to use */
|
| + pProbe = pSrc->pIBIndex;
|
| + }else if( !HasRowid(pTab) ){
|
| + pProbe = pTab->pIndex;
|
| + }else{
|
| + /* There is no INDEXED BY clause. Create a fake Index object in local
|
| + ** variable sPk to represent the rowid primary key index. Make this
|
| + ** fake index the first in a chain of Index objects with all of the real
|
| + ** indices to follow */
|
| + Index *pFirst; /* First of real indices on the table */
|
| + memset(&sPk, 0, sizeof(Index));
|
| + sPk.nKeyCol = 1;
|
| + sPk.nColumn = 1;
|
| + sPk.aiColumn = &aiColumnPk;
|
| + sPk.aiRowLogEst = aiRowEstPk;
|
| + sPk.onError = OE_Replace;
|
| + sPk.pTable = pTab;
|
| + sPk.szIdxRow = pTab->szTabRow;
|
| + aiRowEstPk[0] = pTab->nRowLogEst;
|
| + aiRowEstPk[1] = 0;
|
| + pFirst = pSrc->pTab->pIndex;
|
| + if( pSrc->fg.notIndexed==0 ){
|
| + /* The real indices of the table are only considered if the
|
| + ** NOT INDEXED qualifier is omitted from the FROM clause */
|
| + sPk.pNext = pFirst;
|
| + }
|
| + pProbe = &sPk;
|
| + }
|
| + rSize = pTab->nRowLogEst;
|
| + rLogSize = estLog(rSize);
|
| +
|
| +#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
|
| + /* Automatic indexes */
|
| + if( !pBuilder->pOrSet /* Not part of an OR optimization */
|
| + && (pWInfo->wctrlFlags & WHERE_NO_AUTOINDEX)==0
|
| + && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
|
| + && pSrc->pIBIndex==0 /* Has no INDEXED BY clause */
|
| + && !pSrc->fg.notIndexed /* Has no NOT INDEXED clause */
|
| + && HasRowid(pTab) /* Not WITHOUT ROWID table. (FIXME: Why not?) */
|
| + && !pSrc->fg.isCorrelated /* Not a correlated subquery */
|
| + && !pSrc->fg.isRecursive /* Not a recursive common table expression. */
|
| + ){
|
| + /* Generate auto-index WhereLoops */
|
| + WhereTerm *pTerm;
|
| + WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
|
| + for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
|
| + if( pTerm->prereqRight & pNew->maskSelf ) continue;
|
| + if( termCanDriveIndex(pTerm, pSrc, 0) ){
|
| + pNew->u.btree.nEq = 1;
|
| + pNew->nSkip = 0;
|
| + pNew->u.btree.pIndex = 0;
|
| + pNew->nLTerm = 1;
|
| + pNew->aLTerm[0] = pTerm;
|
| + /* TUNING: One-time cost for computing the automatic index is
|
| + ** estimated to be X*N*log2(N) where N is the number of rows in
|
| + ** the table being indexed and where X is 7 (LogEst=28) for normal
|
| + ** tables or 1.375 (LogEst=4) for views and subqueries. The value
|
| + ** of X is smaller for views and subqueries so that the query planner
|
| + ** will be more aggressive about generating automatic indexes for
|
| + ** those objects, since there is no opportunity to add schema
|
| + ** indexes on subqueries and views. */
|
| + pNew->rSetup = rLogSize + rSize + 4;
|
| + if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){
|
| + pNew->rSetup += 24;
|
| + }
|
| + ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
|
| + /* TUNING: Each index lookup yields 20 rows in the table. This
|
| + ** is more than the usual guess of 10 rows, since we have no way
|
| + ** of knowing how selective the index will ultimately be. It would
|
| + ** not be unreasonable to make this value much larger. */
|
| + pNew->nOut = 43; assert( 43==sqlite3LogEst(20) );
|
| + pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
|
| + pNew->wsFlags = WHERE_AUTO_INDEX;
|
| + pNew->prereq = mExtra | pTerm->prereqRight;
|
| + rc = whereLoopInsert(pBuilder, pNew);
|
| + }
|
| + }
|
| + }
|
| +#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
|
| +
|
| + /* Loop over all indices
|
| + */
|
| + for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
|
| + if( pProbe->pPartIdxWhere!=0
|
| + && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){
|
| + testcase( pNew->iTab!=pSrc->iCursor ); /* See ticket [98d973b8f5] */
|
| + continue; /* Partial index inappropriate for this query */
|
| + }
|
| + rSize = pProbe->aiRowLogEst[0];
|
| + pNew->u.btree.nEq = 0;
|
| + pNew->nSkip = 0;
|
| + pNew->nLTerm = 0;
|
| + pNew->iSortIdx = 0;
|
| + pNew->rSetup = 0;
|
| + pNew->prereq = mExtra;
|
| + pNew->nOut = rSize;
|
| + pNew->u.btree.pIndex = pProbe;
|
| + b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
|
| + /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
|
| + assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
|
| + if( pProbe->tnum<=0 ){
|
| + /* Integer primary key index */
|
| + pNew->wsFlags = WHERE_IPK;
|
| +
|
| + /* Full table scan */
|
| + pNew->iSortIdx = b ? iSortIdx : 0;
|
| + /* TUNING: Cost of full table scan is (N*3.0). */
|
| + pNew->rRun = rSize + 16;
|
| + ApplyCostMultiplier(pNew->rRun, pTab->costMult);
|
| + whereLoopOutputAdjust(pWC, pNew, rSize);
|
| + rc = whereLoopInsert(pBuilder, pNew);
|
| + pNew->nOut = rSize;
|
| + if( rc ) break;
|
| + }else{
|
| + Bitmask m;
|
| + if( pProbe->isCovering ){
|
| + pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
|
| + m = 0;
|
| + }else{
|
| + m = pSrc->colUsed & ~columnsInIndex(pProbe);
|
| + pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
|
| + }
|
| +
|
| + /* Full scan via index */
|
| + if( b
|
| + || !HasRowid(pTab)
|
| + || ( m==0
|
| + && pProbe->bUnordered==0
|
| + && (pProbe->szIdxRow<pTab->szTabRow)
|
| + && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
|
| + && sqlite3GlobalConfig.bUseCis
|
| + && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
|
| + )
|
| + ){
|
| + pNew->iSortIdx = b ? iSortIdx : 0;
|
| +
|
| + /* The cost of visiting the index rows is N*K, where K is
|
| + ** between 1.1 and 3.0, depending on the relative sizes of the
|
| + ** index and table rows. If this is a non-covering index scan,
|
| + ** also add the cost of visiting table rows (N*3.0). */
|
| + pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
|
| + if( m!=0 ){
|
| + pNew->rRun = sqlite3LogEstAdd(pNew->rRun, rSize+16);
|
| + }
|
| + ApplyCostMultiplier(pNew->rRun, pTab->costMult);
|
| + whereLoopOutputAdjust(pWC, pNew, rSize);
|
| + rc = whereLoopInsert(pBuilder, pNew);
|
| + pNew->nOut = rSize;
|
| + if( rc ) break;
|
| + }
|
| + }
|
| +
|
| + rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
|
| +#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
|
| + sqlite3Stat4ProbeFree(pBuilder->pRec);
|
| + pBuilder->nRecValid = 0;
|
| + pBuilder->pRec = 0;
|
| +#endif
|
| +
|
| + /* If there was an INDEXED BY clause, then only that one index is
|
| + ** considered. */
|
| + if( pSrc->pIBIndex ) break;
|
| + }
|
| + return rc;
|
| +}
|
| +
|
| +#ifndef SQLITE_OMIT_VIRTUALTABLE
|
| +/*
|
| +** Add all WhereLoop objects for a table of the join identified by
|
| +** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
|
| +**
|
| +** If there are no LEFT or CROSS JOIN joins in the query, both mExtra and
|
| +** mUnusable are set to 0. Otherwise, mExtra is a mask of all FROM clause
|
| +** entries that occur before the virtual table in the FROM clause and are
|
| +** separated from it by at least one LEFT or CROSS JOIN. Similarly, the
|
| +** mUnusable mask contains all FROM clause entries that occur after the
|
| +** virtual table and are separated from it by at least one LEFT or
|
| +** CROSS JOIN.
|
| +**
|
| +** For example, if the query were:
|
| +**
|
| +** ... FROM t1, t2 LEFT JOIN t3, t4, vt CROSS JOIN t5, t6;
|
| +**
|
| +** then mExtra corresponds to (t1, t2) and mUnusable to (t5, t6).
|
| +**
|
| +** All the tables in mExtra must be scanned before the current virtual
|
| +** table. So any terms for which all prerequisites are satisfied by
|
| +** mExtra may be specified as "usable" in all calls to xBestIndex.
|
| +** Conversely, all tables in mUnusable must be scanned after the current
|
| +** virtual table, so any terms for which the prerequisites overlap with
|
| +** mUnusable should always be configured as "not-usable" for xBestIndex.
|
| +*/
|
| +static int whereLoopAddVirtual(
|
| + WhereLoopBuilder *pBuilder, /* WHERE clause information */
|
| + Bitmask mExtra, /* Tables that must be scanned before this one */
|
| + Bitmask mUnusable /* Tables that must be scanned after this one */
|
| +){
|
| + WhereInfo *pWInfo; /* WHERE analysis context */
|
| + Parse *pParse; /* The parsing context */
|
| + WhereClause *pWC; /* The WHERE clause */
|
| + struct SrcList_item *pSrc; /* The FROM clause term to search */
|
| + Table *pTab;
|
| + sqlite3 *db;
|
| + sqlite3_index_info *pIdxInfo;
|
| + struct sqlite3_index_constraint *pIdxCons;
|
| + struct sqlite3_index_constraint_usage *pUsage;
|
| + WhereTerm *pTerm;
|
| + int i, j;
|
| + int iTerm, mxTerm;
|
| + int nConstraint;
|
| + int seenIn = 0; /* True if an IN operator is seen */
|
| + int seenVar = 0; /* True if a non-constant constraint is seen */
|
| + int iPhase; /* 0: const w/o IN, 1: const, 2: no IN, 2: IN */
|
| + WhereLoop *pNew;
|
| + int rc = SQLITE_OK;
|
| +
|
| + assert( (mExtra & mUnusable)==0 );
|
| + pWInfo = pBuilder->pWInfo;
|
| + pParse = pWInfo->pParse;
|
| + db = pParse->db;
|
| + pWC = pBuilder->pWC;
|
| + pNew = pBuilder->pNew;
|
| + pSrc = &pWInfo->pTabList->a[pNew->iTab];
|
| + pTab = pSrc->pTab;
|
| + assert( IsVirtual(pTab) );
|
| + pIdxInfo = allocateIndexInfo(pParse, pWC, mUnusable, pSrc,pBuilder->pOrderBy);
|
| + if( pIdxInfo==0 ) return SQLITE_NOMEM;
|
| + pNew->prereq = 0;
|
| + pNew->rSetup = 0;
|
| + pNew->wsFlags = WHERE_VIRTUALTABLE;
|
| + pNew->nLTerm = 0;
|
| + pNew->u.vtab.needFree = 0;
|
| + pUsage = pIdxInfo->aConstraintUsage;
|
| + nConstraint = pIdxInfo->nConstraint;
|
| + if( whereLoopResize(db, pNew, nConstraint) ){
|
| + sqlite3DbFree(db, pIdxInfo);
|
| + return SQLITE_NOMEM;
|
| + }
|
| +
|
| + for(iPhase=0; iPhase<=3; iPhase++){
|
| + if( !seenIn && (iPhase&1)!=0 ){
|
| + iPhase++;
|
| + if( iPhase>3 ) break;
|
| + }
|
| + if( !seenVar && iPhase>1 ) break;
|
| + pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
|
| + for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
|
| + j = pIdxCons->iTermOffset;
|
| + pTerm = &pWC->a[j];
|
| + switch( iPhase ){
|
| + case 0: /* Constants without IN operator */
|
| + pIdxCons->usable = 0;
|
| + if( (pTerm->eOperator & WO_IN)!=0 ){
|
| + seenIn = 1;
|
| + }
|
| + if( (pTerm->prereqRight & ~mExtra)!=0 ){
|
| + seenVar = 1;
|
| + }else if( (pTerm->eOperator & WO_IN)==0 ){
|
| + pIdxCons->usable = 1;
|
| + }
|
| + break;
|
| + case 1: /* Constants with IN operators */
|
| + assert( seenIn );
|
| + pIdxCons->usable = (pTerm->prereqRight & ~mExtra)==0;
|
| + break;
|
| + case 2: /* Variables without IN */
|
| + assert( seenVar );
|
| + pIdxCons->usable = (pTerm->eOperator & WO_IN)==0;
|
| + break;
|
| + default: /* Variables with IN */
|
| + assert( seenVar && seenIn );
|
| + pIdxCons->usable = 1;
|
| + break;
|
| + }
|
| + }
|
| + memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
|
| + if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
|
| + pIdxInfo->idxStr = 0;
|
| + pIdxInfo->idxNum = 0;
|
| + pIdxInfo->needToFreeIdxStr = 0;
|
| + pIdxInfo->orderByConsumed = 0;
|
| + pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
|
| + pIdxInfo->estimatedRows = 25;
|
| + pIdxInfo->idxFlags = 0;
|
| + pIdxInfo->colUsed = (sqlite3_int64)pSrc->colUsed;
|
| + rc = vtabBestIndex(pParse, pTab, pIdxInfo);
|
| + if( rc ) goto whereLoopAddVtab_exit;
|
| + pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
|
| + pNew->prereq = mExtra;
|
| + mxTerm = -1;
|
| + assert( pNew->nLSlot>=nConstraint );
|
| + for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
|
| + pNew->u.vtab.omitMask = 0;
|
| + for(i=0; i<nConstraint; i++, pIdxCons++){
|
| + if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
|
| + j = pIdxCons->iTermOffset;
|
| + if( iTerm>=nConstraint
|
| + || j<0
|
| + || j>=pWC->nTerm
|
| + || pNew->aLTerm[iTerm]!=0
|
| + ){
|
| + rc = SQLITE_ERROR;
|
| + sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName);
|
| + goto whereLoopAddVtab_exit;
|
| + }
|
| + testcase( iTerm==nConstraint-1 );
|
| + testcase( j==0 );
|
| + testcase( j==pWC->nTerm-1 );
|
| + pTerm = &pWC->a[j];
|
| + pNew->prereq |= pTerm->prereqRight;
|
| + assert( iTerm<pNew->nLSlot );
|
| + pNew->aLTerm[iTerm] = pTerm;
|
| + if( iTerm>mxTerm ) mxTerm = iTerm;
|
| + testcase( iTerm==15 );
|
| + testcase( iTerm==16 );
|
| + if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
|
| + if( (pTerm->eOperator & WO_IN)!=0 ){
|
| + if( pUsage[i].omit==0 ){
|
| + /* Do not attempt to use an IN constraint if the virtual table
|
| + ** says that the equivalent EQ constraint cannot be safely omitted.
|
| + ** If we do attempt to use such a constraint, some rows might be
|
| + ** repeated in the output. */
|
| + break;
|
| + }
|
| + /* A virtual table that is constrained by an IN clause may not
|
| + ** consume the ORDER BY clause because (1) the order of IN terms
|
| + ** is not necessarily related to the order of output terms and
|
| + ** (2) Multiple outputs from a single IN value will not merge
|
| + ** together. */
|
| + pIdxInfo->orderByConsumed = 0;
|
| + pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE;
|
| + }
|
| + }
|
| + }
|
| + if( i>=nConstraint ){
|
| + pNew->nLTerm = mxTerm+1;
|
| + assert( pNew->nLTerm<=pNew->nLSlot );
|
| + pNew->u.vtab.idxNum = pIdxInfo->idxNum;
|
| + pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
|
| + pIdxInfo->needToFreeIdxStr = 0;
|
| + pNew->u.vtab.idxStr = pIdxInfo->idxStr;
|
| + pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
|
| + pIdxInfo->nOrderBy : 0);
|
| + pNew->rSetup = 0;
|
| + pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
|
| + pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
|
| +
|
| + /* Set the WHERE_ONEROW flag if the xBestIndex() method indicated
|
| + ** that the scan will visit at most one row. Clear it otherwise. */
|
| + if( pIdxInfo->idxFlags & SQLITE_INDEX_SCAN_UNIQUE ){
|
| + pNew->wsFlags |= WHERE_ONEROW;
|
| + }else{
|
| + pNew->wsFlags &= ~WHERE_ONEROW;
|
| + }
|
| + whereLoopInsert(pBuilder, pNew);
|
| + if( pNew->u.vtab.needFree ){
|
| + sqlite3_free(pNew->u.vtab.idxStr);
|
| + pNew->u.vtab.needFree = 0;
|
| + }
|
| + }
|
| + }
|
| +
|
| +whereLoopAddVtab_exit:
|
| + if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
|
| + sqlite3DbFree(db, pIdxInfo);
|
| + return rc;
|
| +}
|
| +#endif /* SQLITE_OMIT_VIRTUALTABLE */
|
| +
|
| +/*
|
| +** Add WhereLoop entries to handle OR terms. This works for either
|
| +** btrees or virtual tables.
|
| +*/
|
| +static int whereLoopAddOr(
|
| + WhereLoopBuilder *pBuilder,
|
| + Bitmask mExtra,
|
| + Bitmask mUnusable
|
| +){
|
| + WhereInfo *pWInfo = pBuilder->pWInfo;
|
| + WhereClause *pWC;
|
| + WhereLoop *pNew;
|
| + WhereTerm *pTerm, *pWCEnd;
|
| + int rc = SQLITE_OK;
|
| + int iCur;
|
| + WhereClause tempWC;
|
| + WhereLoopBuilder sSubBuild;
|
| + WhereOrSet sSum, sCur;
|
| + struct SrcList_item *pItem;
|
| +
|
| + pWC = pBuilder->pWC;
|
| + pWCEnd = pWC->a + pWC->nTerm;
|
| + pNew = pBuilder->pNew;
|
| + memset(&sSum, 0, sizeof(sSum));
|
| + pItem = pWInfo->pTabList->a + pNew->iTab;
|
| + iCur = pItem->iCursor;
|
| +
|
| + for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
|
| + if( (pTerm->eOperator & WO_OR)!=0
|
| + && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
|
| + ){
|
| + WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
|
| + WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
|
| + WhereTerm *pOrTerm;
|
| + int once = 1;
|
| + int i, j;
|
| +
|
| + sSubBuild = *pBuilder;
|
| + sSubBuild.pOrderBy = 0;
|
| + sSubBuild.pOrSet = &sCur;
|
| +
|
| + WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm));
|
| + for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
|
| + if( (pOrTerm->eOperator & WO_AND)!=0 ){
|
| + sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
|
| + }else if( pOrTerm->leftCursor==iCur ){
|
| + tempWC.pWInfo = pWC->pWInfo;
|
| + tempWC.pOuter = pWC;
|
| + tempWC.op = TK_AND;
|
| + tempWC.nTerm = 1;
|
| + tempWC.a = pOrTerm;
|
| + sSubBuild.pWC = &tempWC;
|
| + }else{
|
| + continue;
|
| + }
|
| + sCur.n = 0;
|
| +#ifdef WHERETRACE_ENABLED
|
| + WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n",
|
| + (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
|
| + if( sqlite3WhereTrace & 0x400 ){
|
| + for(i=0; i<sSubBuild.pWC->nTerm; i++){
|
| + whereTermPrint(&sSubBuild.pWC->a[i], i);
|
| + }
|
| + }
|
| +#endif
|
| +#ifndef SQLITE_OMIT_VIRTUALTABLE
|
| + if( IsVirtual(pItem->pTab) ){
|
| + rc = whereLoopAddVirtual(&sSubBuild, mExtra, mUnusable);
|
| + }else
|
| +#endif
|
| + {
|
| + rc = whereLoopAddBtree(&sSubBuild, mExtra);
|
| + }
|
| + if( rc==SQLITE_OK ){
|
| + rc = whereLoopAddOr(&sSubBuild, mExtra, mUnusable);
|
| + }
|
| + assert( rc==SQLITE_OK || sCur.n==0 );
|
| + if( sCur.n==0 ){
|
| + sSum.n = 0;
|
| + break;
|
| + }else if( once ){
|
| + whereOrMove(&sSum, &sCur);
|
| + once = 0;
|
| + }else{
|
| + WhereOrSet sPrev;
|
| + whereOrMove(&sPrev, &sSum);
|
| + sSum.n = 0;
|
| + for(i=0; i<sPrev.n; i++){
|
| + for(j=0; j<sCur.n; j++){
|
| + whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
|
| + sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
|
| + sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
|
| + }
|
| + }
|
| + }
|
| + }
|
| + pNew->nLTerm = 1;
|
| + pNew->aLTerm[0] = pTerm;
|
| + pNew->wsFlags = WHERE_MULTI_OR;
|
| + pNew->rSetup = 0;
|
| + pNew->iSortIdx = 0;
|
| + memset(&pNew->u, 0, sizeof(pNew->u));
|
| + for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
|
| + /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
|
| + ** of all sub-scans required by the OR-scan. However, due to rounding
|
| + ** errors, it may be that the cost of the OR-scan is equal to its
|
| + ** most expensive sub-scan. Add the smallest possible penalty
|
| + ** (equivalent to multiplying the cost by 1.07) to ensure that
|
| + ** this does not happen. Otherwise, for WHERE clauses such as the
|
| + ** following where there is an index on "y":
|
| + **
|
| + ** WHERE likelihood(x=?, 0.99) OR y=?
|
| + **
|
| + ** the planner may elect to "OR" together a full-table scan and an
|
| + ** index lookup. And other similarly odd results. */
|
| + pNew->rRun = sSum.a[i].rRun + 1;
|
| + pNew->nOut = sSum.a[i].nOut;
|
| + pNew->prereq = sSum.a[i].prereq;
|
| + rc = whereLoopInsert(pBuilder, pNew);
|
| + }
|
| + WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm));
|
| + }
|
| + }
|
| + return rc;
|
| +}
|
| +
|
| +/*
|
| +** Add all WhereLoop objects for all tables
|
| +*/
|
| +static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
|
| + WhereInfo *pWInfo = pBuilder->pWInfo;
|
| + Bitmask mExtra = 0;
|
| + Bitmask mPrior = 0;
|
| + int iTab;
|
| + SrcList *pTabList = pWInfo->pTabList;
|
| + struct SrcList_item *pItem;
|
| + struct SrcList_item *pEnd = &pTabList->a[pWInfo->nLevel];
|
| + sqlite3 *db = pWInfo->pParse->db;
|
| + int rc = SQLITE_OK;
|
| + WhereLoop *pNew;
|
| + u8 priorJointype = 0;
|
| +
|
| + /* Loop over the tables in the join, from left to right */
|
| + pNew = pBuilder->pNew;
|
| + whereLoopInit(pNew);
|
| + for(iTab=0, pItem=pTabList->a; pItem<pEnd; iTab++, pItem++){
|
| + Bitmask mUnusable = 0;
|
| + pNew->iTab = iTab;
|
| + pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor);
|
| + if( ((pItem->fg.jointype|priorJointype) & (JT_LEFT|JT_CROSS))!=0 ){
|
| + /* This condition is true when pItem is the FROM clause term on the
|
| + ** right-hand-side of a LEFT or CROSS JOIN. */
|
| + mExtra = mPrior;
|
| + }
|
| + priorJointype = pItem->fg.jointype;
|
| + if( IsVirtual(pItem->pTab) ){
|
| + struct SrcList_item *p;
|
| + for(p=&pItem[1]; p<pEnd; p++){
|
| + if( mUnusable || (p->fg.jointype & (JT_LEFT|JT_CROSS)) ){
|
| + mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor);
|
| + }
|
| + }
|
| + rc = whereLoopAddVirtual(pBuilder, mExtra, mUnusable);
|
| + }else{
|
| + rc = whereLoopAddBtree(pBuilder, mExtra);
|
| + }
|
| + if( rc==SQLITE_OK ){
|
| + rc = whereLoopAddOr(pBuilder, mExtra, mUnusable);
|
| + }
|
| + mPrior |= pNew->maskSelf;
|
| + if( rc || db->mallocFailed ) break;
|
| + }
|
| +
|
| + whereLoopClear(db, pNew);
|
| + return rc;
|
| +}
|
| +
|
| +/*
|
| +** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
|
| +** parameters) to see if it outputs rows in the requested ORDER BY
|
| +** (or GROUP BY) without requiring a separate sort operation. Return N:
|
| +**
|
| +** N>0: N terms of the ORDER BY clause are satisfied
|
| +** N==0: No terms of the ORDER BY clause are satisfied
|
| +** N<0: Unknown yet how many terms of ORDER BY might be satisfied.
|
| +**
|
| +** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
|
| +** strict. With GROUP BY and DISTINCT the only requirement is that
|
| +** equivalent rows appear immediately adjacent to one another. GROUP BY
|
| +** and DISTINCT do not require rows to appear in any particular order as long
|
| +** as equivalent rows are grouped together. Thus for GROUP BY and DISTINCT
|
| +** the pOrderBy terms can be matched in any order. With ORDER BY, the
|
| +** pOrderBy terms must be matched in strict left-to-right order.
|
| +*/
|
| +static i8 wherePathSatisfiesOrderBy(
|
| + WhereInfo *pWInfo, /* The WHERE clause */
|
| + ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
|
| + WherePath *pPath, /* The WherePath to check */
|
| + u16 wctrlFlags, /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */
|
| + u16 nLoop, /* Number of entries in pPath->aLoop[] */
|
| + WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
|
| + Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
|
| +){
|
| + u8 revSet; /* True if rev is known */
|
| + u8 rev; /* Composite sort order */
|
| + u8 revIdx; /* Index sort order */
|
| + u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
|
| + u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
|
| + u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
|
| + u16 nKeyCol; /* Number of key columns in pIndex */
|
| + u16 nColumn; /* Total number of ordered columns in the index */
|
| + u16 nOrderBy; /* Number terms in the ORDER BY clause */
|
| + int iLoop; /* Index of WhereLoop in pPath being processed */
|
| + int i, j; /* Loop counters */
|
| + int iCur; /* Cursor number for current WhereLoop */
|
| + int iColumn; /* A column number within table iCur */
|
| + WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
|
| + WhereTerm *pTerm; /* A single term of the WHERE clause */
|
| + Expr *pOBExpr; /* An expression from the ORDER BY clause */
|
| + CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
|
| + Index *pIndex; /* The index associated with pLoop */
|
| + sqlite3 *db = pWInfo->pParse->db; /* Database connection */
|
| + Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
|
| + Bitmask obDone; /* Mask of all ORDER BY terms */
|
| + Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
|
| + Bitmask ready; /* Mask of inner loops */
|
| +
|
| + /*
|
| + ** We say the WhereLoop is "one-row" if it generates no more than one
|
| + ** row of output. A WhereLoop is one-row if all of the following are true:
|
| + ** (a) All index columns match with WHERE_COLUMN_EQ.
|
| + ** (b) The index is unique
|
| + ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
|
| + ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
|
| + **
|
| + ** We say the WhereLoop is "order-distinct" if the set of columns from
|
| + ** that WhereLoop that are in the ORDER BY clause are different for every
|
| + ** row of the WhereLoop. Every one-row WhereLoop is automatically
|
| + ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
|
| + ** is not order-distinct. To be order-distinct is not quite the same as being
|
| + ** UNIQUE since a UNIQUE column or index can have multiple rows that
|
| + ** are NULL and NULL values are equivalent for the purpose of order-distinct.
|
| + ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
|
| + **
|
| + ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
|
| + ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
|
| + ** automatically order-distinct.
|
| + */
|
| +
|
| + assert( pOrderBy!=0 );
|
| + if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
|
| +
|
| + nOrderBy = pOrderBy->nExpr;
|
| + testcase( nOrderBy==BMS-1 );
|
| + if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
|
| + isOrderDistinct = 1;
|
| + obDone = MASKBIT(nOrderBy)-1;
|
| + orderDistinctMask = 0;
|
| + ready = 0;
|
| + for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
|
| + if( iLoop>0 ) ready |= pLoop->maskSelf;
|
| + pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
|
| + if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
|
| + if( pLoop->u.vtab.isOrdered ) obSat = obDone;
|
| + break;
|
| + }
|
| + iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
|
| +
|
| + /* Mark off any ORDER BY term X that is a column in the table of
|
| + ** the current loop for which there is term in the WHERE
|
| + ** clause of the form X IS NULL or X=? that reference only outer
|
| + ** loops.
|
| + */
|
| + for(i=0; i<nOrderBy; i++){
|
| + if( MASKBIT(i) & obSat ) continue;
|
| + pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
|
| + if( pOBExpr->op!=TK_COLUMN ) continue;
|
| + if( pOBExpr->iTable!=iCur ) continue;
|
| + pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
|
| + ~ready, WO_EQ|WO_ISNULL|WO_IS, 0);
|
| + if( pTerm==0 ) continue;
|
| + if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){
|
| + const char *z1, *z2;
|
| + pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
|
| + if( !pColl ) pColl = db->pDfltColl;
|
| + z1 = pColl->zName;
|
| + pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
|
| + if( !pColl ) pColl = db->pDfltColl;
|
| + z2 = pColl->zName;
|
| + if( sqlite3StrICmp(z1, z2)!=0 ) continue;
|
| + testcase( pTerm->pExpr->op==TK_IS );
|
| + }
|
| + obSat |= MASKBIT(i);
|
| + }
|
| +
|
| + if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
|
| + if( pLoop->wsFlags & WHERE_IPK ){
|
| + pIndex = 0;
|
| + nKeyCol = 0;
|
| + nColumn = 1;
|
| + }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
|
| + return 0;
|
| + }else{
|
| + nKeyCol = pIndex->nKeyCol;
|
| + nColumn = pIndex->nColumn;
|
| + assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
|
| + assert( pIndex->aiColumn[nColumn-1]==XN_ROWID
|
| + || !HasRowid(pIndex->pTable));
|
| + isOrderDistinct = IsUniqueIndex(pIndex);
|
| + }
|
| +
|
| + /* Loop through all columns of the index and deal with the ones
|
| + ** that are not constrained by == or IN.
|
| + */
|
| + rev = revSet = 0;
|
| + distinctColumns = 0;
|
| + for(j=0; j<nColumn; j++){
|
| + u8 bOnce; /* True to run the ORDER BY search loop */
|
| +
|
| + /* Skip over == and IS NULL terms */
|
| + if( j<pLoop->u.btree.nEq
|
| + && pLoop->nSkip==0
|
| + && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL|WO_IS))!=0
|
| + ){
|
| + if( i & WO_ISNULL ){
|
| + testcase( isOrderDistinct );
|
| + isOrderDistinct = 0;
|
| + }
|
| + continue;
|
| + }
|
| +
|
| + /* Get the column number in the table (iColumn) and sort order
|
| + ** (revIdx) for the j-th column of the index.
|
| + */
|
| + if( pIndex ){
|
| + iColumn = pIndex->aiColumn[j];
|
| + revIdx = pIndex->aSortOrder[j];
|
| + if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
|
| + }else{
|
| + iColumn = XN_ROWID;
|
| + revIdx = 0;
|
| + }
|
| +
|
| + /* An unconstrained column that might be NULL means that this
|
| + ** WhereLoop is not well-ordered
|
| + */
|
| + if( isOrderDistinct
|
| + && iColumn>=0
|
| + && j>=pLoop->u.btree.nEq
|
| + && pIndex->pTable->aCol[iColumn].notNull==0
|
| + ){
|
| + isOrderDistinct = 0;
|
| + }
|
| +
|
| + /* Find the ORDER BY term that corresponds to the j-th column
|
| + ** of the index and mark that ORDER BY term off
|
| + */
|
| + bOnce = 1;
|
| + isMatch = 0;
|
| + for(i=0; bOnce && i<nOrderBy; i++){
|
| + if( MASKBIT(i) & obSat ) continue;
|
| + pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
|
| + testcase( wctrlFlags & WHERE_GROUPBY );
|
| + testcase( wctrlFlags & WHERE_DISTINCTBY );
|
| + if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
|
| + if( iColumn>=(-1) ){
|
| + if( pOBExpr->op!=TK_COLUMN ) continue;
|
| + if( pOBExpr->iTable!=iCur ) continue;
|
| + if( pOBExpr->iColumn!=iColumn ) continue;
|
| + }else{
|
| + if( sqlite3ExprCompare(pOBExpr,pIndex->aColExpr->a[j].pExpr,iCur) ){
|
| + continue;
|
| + }
|
| + }
|
| + if( iColumn>=0 ){
|
| + pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
|
| + if( !pColl ) pColl = db->pDfltColl;
|
| + if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
|
| + }
|
| + isMatch = 1;
|
| + break;
|
| + }
|
| + if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
|
| + /* Make sure the sort order is compatible in an ORDER BY clause.
|
| + ** Sort order is irrelevant for a GROUP BY clause. */
|
| + if( revSet ){
|
| + if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0;
|
| + }else{
|
| + rev = revIdx ^ pOrderBy->a[i].sortOrder;
|
| + if( rev ) *pRevMask |= MASKBIT(iLoop);
|
| + revSet = 1;
|
| + }
|
| + }
|
| + if( isMatch ){
|
| + if( iColumn<0 ){
|
| + testcase( distinctColumns==0 );
|
| + distinctColumns = 1;
|
| + }
|
| + obSat |= MASKBIT(i);
|
| + }else{
|
| + /* No match found */
|
| + if( j==0 || j<nKeyCol ){
|
| + testcase( isOrderDistinct!=0 );
|
| + isOrderDistinct = 0;
|
| + }
|
| + break;
|
| + }
|
| + } /* end Loop over all index columns */
|
| + if( distinctColumns ){
|
| + testcase( isOrderDistinct==0 );
|
| + isOrderDistinct = 1;
|
| + }
|
| + } /* end-if not one-row */
|
| +
|
| + /* Mark off any other ORDER BY terms that reference pLoop */
|
| + if( isOrderDistinct ){
|
| + orderDistinctMask |= pLoop->maskSelf;
|
| + for(i=0; i<nOrderBy; i++){
|
| + Expr *p;
|
| + Bitmask mTerm;
|
| + if( MASKBIT(i) & obSat ) continue;
|
| + p = pOrderBy->a[i].pExpr;
|
| + mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p);
|
| + if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
|
| + if( (mTerm&~orderDistinctMask)==0 ){
|
| + obSat |= MASKBIT(i);
|
| + }
|
| + }
|
| + }
|
| + } /* End the loop over all WhereLoops from outer-most down to inner-most */
|
| + if( obSat==obDone ) return (i8)nOrderBy;
|
| + if( !isOrderDistinct ){
|
| + for(i=nOrderBy-1; i>0; i--){
|
| + Bitmask m = MASKBIT(i) - 1;
|
| + if( (obSat&m)==m ) return i;
|
| + }
|
| + return 0;
|
| + }
|
| + return -1;
|
| +}
|
| +
|
| +
|
| +/*
|
| +** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
|
| +** the planner assumes that the specified pOrderBy list is actually a GROUP
|
| +** BY clause - and so any order that groups rows as required satisfies the
|
| +** request.
|
| +**
|
| +** Normally, in this case it is not possible for the caller to determine
|
| +** whether or not the rows are really being delivered in sorted order, or
|
| +** just in some other order that provides the required grouping. However,
|
| +** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
|
| +** this function may be called on the returned WhereInfo object. It returns
|
| +** true if the rows really will be sorted in the specified order, or false
|
| +** otherwise.
|
| +**
|
| +** For example, assuming:
|
| +**
|
| +** CREATE INDEX i1 ON t1(x, Y);
|
| +**
|
| +** then
|
| +**
|
| +** SELECT * FROM t1 GROUP BY x,y ORDER BY x,y; -- IsSorted()==1
|
| +** SELECT * FROM t1 GROUP BY y,x ORDER BY y,x; -- IsSorted()==0
|
| +*/
|
| +SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *pWInfo){
|
| + assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
|
| + assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
|
| + return pWInfo->sorted;
|
| +}
|
| +
|
| +#ifdef WHERETRACE_ENABLED
|
| +/* For debugging use only: */
|
| +static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
|
| + static char zName[65];
|
| + int i;
|
| + for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
|
| + if( pLast ) zName[i++] = pLast->cId;
|
| + zName[i] = 0;
|
| + return zName;
|
| +}
|
| +#endif
|
| +
|
| +/*
|
| +** Return the cost of sorting nRow rows, assuming that the keys have
|
| +** nOrderby columns and that the first nSorted columns are already in
|
| +** order.
|
| +*/
|
| +static LogEst whereSortingCost(
|
| + WhereInfo *pWInfo,
|
| + LogEst nRow,
|
| + int nOrderBy,
|
| + int nSorted
|
| +){
|
| + /* TUNING: Estimated cost of a full external sort, where N is
|
| + ** the number of rows to sort is:
|
| + **
|
| + ** cost = (3.0 * N * log(N)).
|
| + **
|
| + ** Or, if the order-by clause has X terms but only the last Y
|
| + ** terms are out of order, then block-sorting will reduce the
|
| + ** sorting cost to:
|
| + **
|
| + ** cost = (3.0 * N * log(N)) * (Y/X)
|
| + **
|
| + ** The (Y/X) term is implemented using stack variable rScale
|
| + ** below. */
|
| + LogEst rScale, rSortCost;
|
| + assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
|
| + rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
|
| + rSortCost = nRow + estLog(nRow) + rScale + 16;
|
| +
|
| + /* TUNING: The cost of implementing DISTINCT using a B-TREE is
|
| + ** similar but with a larger constant of proportionality.
|
| + ** Multiply by an additional factor of 3.0. */
|
| + if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
|
| + rSortCost += 16;
|
| + }
|
| +
|
| + return rSortCost;
|
| +}
|
| +
|
| +/*
|
| +** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
|
| +** attempts to find the lowest cost path that visits each WhereLoop
|
| +** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
|
| +**
|
| +** Assume that the total number of output rows that will need to be sorted
|
| +** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
|
| +** costs if nRowEst==0.
|
| +**
|
| +** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
|
| +** error occurs.
|
| +*/
|
| +static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
|
| + int mxChoice; /* Maximum number of simultaneous paths tracked */
|
| + int nLoop; /* Number of terms in the join */
|
| + Parse *pParse; /* Parsing context */
|
| + sqlite3 *db; /* The database connection */
|
| + int iLoop; /* Loop counter over the terms of the join */
|
| + int ii, jj; /* Loop counters */
|
| + int mxI = 0; /* Index of next entry to replace */
|
| + int nOrderBy; /* Number of ORDER BY clause terms */
|
| + LogEst mxCost = 0; /* Maximum cost of a set of paths */
|
| + LogEst mxUnsorted = 0; /* Maximum unsorted cost of a set of path */
|
| + int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
|
| + WherePath *aFrom; /* All nFrom paths at the previous level */
|
| + WherePath *aTo; /* The nTo best paths at the current level */
|
| + WherePath *pFrom; /* An element of aFrom[] that we are working on */
|
| + WherePath *pTo; /* An element of aTo[] that we are working on */
|
| + WhereLoop *pWLoop; /* One of the WhereLoop objects */
|
| + WhereLoop **pX; /* Used to divy up the pSpace memory */
|
| + LogEst *aSortCost = 0; /* Sorting and partial sorting costs */
|
| + char *pSpace; /* Temporary memory used by this routine */
|
| + int nSpace; /* Bytes of space allocated at pSpace */
|
| +
|
| + pParse = pWInfo->pParse;
|
| + db = pParse->db;
|
| + nLoop = pWInfo->nLevel;
|
| + /* TUNING: For simple queries, only the best path is tracked.
|
| + ** For 2-way joins, the 5 best paths are followed.
|
| + ** For joins of 3 or more tables, track the 10 best paths */
|
| + mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
|
| + assert( nLoop<=pWInfo->pTabList->nSrc );
|
| + WHERETRACE(0x002, ("---- begin solver. (nRowEst=%d)\n", nRowEst));
|
| +
|
| + /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
|
| + ** case the purpose of this call is to estimate the number of rows returned
|
| + ** by the overall query. Once this estimate has been obtained, the caller
|
| + ** will invoke this function a second time, passing the estimate as the
|
| + ** nRowEst parameter. */
|
| + if( pWInfo->pOrderBy==0 || nRowEst==0 ){
|
| + nOrderBy = 0;
|
| + }else{
|
| + nOrderBy = pWInfo->pOrderBy->nExpr;
|
| + }
|
| +
|
| + /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
|
| + nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
|
| + nSpace += sizeof(LogEst) * nOrderBy;
|
| + pSpace = sqlite3DbMallocRaw(db, nSpace);
|
| + if( pSpace==0 ) return SQLITE_NOMEM;
|
| + aTo = (WherePath*)pSpace;
|
| + aFrom = aTo+mxChoice;
|
| + memset(aFrom, 0, sizeof(aFrom[0]));
|
| + pX = (WhereLoop**)(aFrom+mxChoice);
|
| + for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
|
| + pFrom->aLoop = pX;
|
| + }
|
| + if( nOrderBy ){
|
| + /* If there is an ORDER BY clause and it is not being ignored, set up
|
| + ** space for the aSortCost[] array. Each element of the aSortCost array
|
| + ** is either zero - meaning it has not yet been initialized - or the
|
| + ** cost of sorting nRowEst rows of data where the first X terms of
|
| + ** the ORDER BY clause are already in order, where X is the array
|
| + ** index. */
|
| + aSortCost = (LogEst*)pX;
|
| + memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
|
| + }
|
| + assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
|
| + assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
|
| +
|
| + /* Seed the search with a single WherePath containing zero WhereLoops.
|
| + **
|
| + ** TUNING: Do not let the number of iterations go above 28. If the cost
|
| + ** of computing an automatic index is not paid back within the first 28
|
| + ** rows, then do not use the automatic index. */
|
| + aFrom[0].nRow = MIN(pParse->nQueryLoop, 48); assert( 48==sqlite3LogEst(28) );
|
| + nFrom = 1;
|
| + assert( aFrom[0].isOrdered==0 );
|
| + if( nOrderBy ){
|
| + /* If nLoop is zero, then there are no FROM terms in the query. Since
|
| + ** in this case the query may return a maximum of one row, the results
|
| + ** are already in the requested order. Set isOrdered to nOrderBy to
|
| + ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
|
| + ** -1, indicating that the result set may or may not be ordered,
|
| + ** depending on the loops added to the current plan. */
|
| + aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
|
| + }
|
| +
|
| + /* Compute successively longer WherePaths using the previous generation
|
| + ** of WherePaths as the basis for the next. Keep track of the mxChoice
|
| + ** best paths at each generation */
|
| + for(iLoop=0; iLoop<nLoop; iLoop++){
|
| + nTo = 0;
|
| + for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
|
| + for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
|
| + LogEst nOut; /* Rows visited by (pFrom+pWLoop) */
|
| + LogEst rCost; /* Cost of path (pFrom+pWLoop) */
|
| + LogEst rUnsorted; /* Unsorted cost of (pFrom+pWLoop) */
|
| + i8 isOrdered = pFrom->isOrdered; /* isOrdered for (pFrom+pWLoop) */
|
| + Bitmask maskNew; /* Mask of src visited by (..) */
|
| + Bitmask revMask = 0; /* Mask of rev-order loops for (..) */
|
| +
|
| + if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
|
| + if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
|
| + /* At this point, pWLoop is a candidate to be the next loop.
|
| + ** Compute its cost */
|
| + rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
|
| + rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
|
| + nOut = pFrom->nRow + pWLoop->nOut;
|
| + maskNew = pFrom->maskLoop | pWLoop->maskSelf;
|
| + if( isOrdered<0 ){
|
| + isOrdered = wherePathSatisfiesOrderBy(pWInfo,
|
| + pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
|
| + iLoop, pWLoop, &revMask);
|
| + }else{
|
| + revMask = pFrom->revLoop;
|
| + }
|
| + if( isOrdered>=0 && isOrdered<nOrderBy ){
|
| + if( aSortCost[isOrdered]==0 ){
|
| + aSortCost[isOrdered] = whereSortingCost(
|
| + pWInfo, nRowEst, nOrderBy, isOrdered
|
| + );
|
| + }
|
| + rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]);
|
| +
|
| + WHERETRACE(0x002,
|
| + ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
|
| + aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
|
| + rUnsorted, rCost));
|
| + }else{
|
| + rCost = rUnsorted;
|
| + }
|
| +
|
| + /* Check to see if pWLoop should be added to the set of
|
| + ** mxChoice best-so-far paths.
|
| + **
|
| + ** First look for an existing path among best-so-far paths
|
| + ** that covers the same set of loops and has the same isOrdered
|
| + ** setting as the current path candidate.
|
| + **
|
| + ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
|
| + ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
|
| + ** of legal values for isOrdered, -1..64.
|
| + */
|
| + for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
|
| + if( pTo->maskLoop==maskNew
|
| + && ((pTo->isOrdered^isOrdered)&0x80)==0
|
| + ){
|
| + testcase( jj==nTo-1 );
|
| + break;
|
| + }
|
| + }
|
| + if( jj>=nTo ){
|
| + /* None of the existing best-so-far paths match the candidate. */
|
| + if( nTo>=mxChoice
|
| + && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
|
| + ){
|
| + /* The current candidate is no better than any of the mxChoice
|
| + ** paths currently in the best-so-far buffer. So discard
|
| + ** this candidate as not viable. */
|
| +#ifdef WHERETRACE_ENABLED /* 0x4 */
|
| + if( sqlite3WhereTrace&0x4 ){
|
| + sqlite3DebugPrintf("Skip %s cost=%-3d,%3d order=%c\n",
|
| + wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
|
| + isOrdered>=0 ? isOrdered+'0' : '?');
|
| + }
|
| +#endif
|
| + continue;
|
| + }
|
| + /* If we reach this points it means that the new candidate path
|
| + ** needs to be added to the set of best-so-far paths. */
|
| + if( nTo<mxChoice ){
|
| + /* Increase the size of the aTo set by one */
|
| + jj = nTo++;
|
| + }else{
|
| + /* New path replaces the prior worst to keep count below mxChoice */
|
| + jj = mxI;
|
| + }
|
| + pTo = &aTo[jj];
|
| +#ifdef WHERETRACE_ENABLED /* 0x4 */
|
| + if( sqlite3WhereTrace&0x4 ){
|
| + sqlite3DebugPrintf("New %s cost=%-3d,%3d order=%c\n",
|
| + wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
|
| + isOrdered>=0 ? isOrdered+'0' : '?');
|
| + }
|
| +#endif
|
| + }else{
|
| + /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
|
| + ** same set of loops and has the sam isOrdered setting as the
|
| + ** candidate path. Check to see if the candidate should replace
|
| + ** pTo or if the candidate should be skipped */
|
| + if( pTo->rCost<rCost || (pTo->rCost==rCost && pTo->nRow<=nOut) ){
|
| +#ifdef WHERETRACE_ENABLED /* 0x4 */
|
| + if( sqlite3WhereTrace&0x4 ){
|
| + sqlite3DebugPrintf(
|
| + "Skip %s cost=%-3d,%3d order=%c",
|
| + wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
|
| + isOrdered>=0 ? isOrdered+'0' : '?');
|
| + sqlite3DebugPrintf(" vs %s cost=%-3d,%d order=%c\n",
|
| + wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
|
| + pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
|
| + }
|
| +#endif
|
| + /* Discard the candidate path from further consideration */
|
| + testcase( pTo->rCost==rCost );
|
| + continue;
|
| + }
|
| + testcase( pTo->rCost==rCost+1 );
|
| + /* Control reaches here if the candidate path is better than the
|
| + ** pTo path. Replace pTo with the candidate. */
|
| +#ifdef WHERETRACE_ENABLED /* 0x4 */
|
| + if( sqlite3WhereTrace&0x4 ){
|
| + sqlite3DebugPrintf(
|
| + "Update %s cost=%-3d,%3d order=%c",
|
| + wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
|
| + isOrdered>=0 ? isOrdered+'0' : '?');
|
| + sqlite3DebugPrintf(" was %s cost=%-3d,%3d order=%c\n",
|
| + wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
|
| + pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
|
| + }
|
| +#endif
|
| + }
|
| + /* pWLoop is a winner. Add it to the set of best so far */
|
| + pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
|
| + pTo->revLoop = revMask;
|
| + pTo->nRow = nOut;
|
| + pTo->rCost = rCost;
|
| + pTo->rUnsorted = rUnsorted;
|
| + pTo->isOrdered = isOrdered;
|
| + memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
|
| + pTo->aLoop[iLoop] = pWLoop;
|
| + if( nTo>=mxChoice ){
|
| + mxI = 0;
|
| + mxCost = aTo[0].rCost;
|
| + mxUnsorted = aTo[0].nRow;
|
| + for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
|
| + if( pTo->rCost>mxCost
|
| + || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
|
| + ){
|
| + mxCost = pTo->rCost;
|
| + mxUnsorted = pTo->rUnsorted;
|
| + mxI = jj;
|
| + }
|
| + }
|
| + }
|
| + }
|
| + }
|
| +
|
| +#ifdef WHERETRACE_ENABLED /* >=2 */
|
| + if( sqlite3WhereTrace & 0x02 ){
|
| + sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
|
| + for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
|
| + sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
|
| + wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
|
| + pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
|
| + if( pTo->isOrdered>0 ){
|
| + sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
|
| + }else{
|
| + sqlite3DebugPrintf("\n");
|
| + }
|
| + }
|
| + }
|
| +#endif
|
| +
|
| + /* Swap the roles of aFrom and aTo for the next generation */
|
| + pFrom = aTo;
|
| + aTo = aFrom;
|
| + aFrom = pFrom;
|
| + nFrom = nTo;
|
| + }
|
| +
|
| + if( nFrom==0 ){
|
| + sqlite3ErrorMsg(pParse, "no query solution");
|
| + sqlite3DbFree(db, pSpace);
|
| + return SQLITE_ERROR;
|
| + }
|
| +
|
| + /* Find the lowest cost path. pFrom will be left pointing to that path */
|
| + pFrom = aFrom;
|
| + for(ii=1; ii<nFrom; ii++){
|
| + if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
|
| + }
|
| + assert( pWInfo->nLevel==nLoop );
|
| + /* Load the lowest cost path into pWInfo */
|
| + for(iLoop=0; iLoop<nLoop; iLoop++){
|
| + WhereLevel *pLevel = pWInfo->a + iLoop;
|
| + pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
|
| + pLevel->iFrom = pWLoop->iTab;
|
| + pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
|
| + }
|
| + if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
|
| + && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
|
| + && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
|
| + && nRowEst
|
| + ){
|
| + Bitmask notUsed;
|
| + int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
|
| + WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], ¬Used);
|
| + if( rc==pWInfo->pResultSet->nExpr ){
|
| + pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
|
| + }
|
| + }
|
| + if( pWInfo->pOrderBy ){
|
| + if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
|
| + if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
|
| + pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
|
| + }
|
| + }else{
|
| + pWInfo->nOBSat = pFrom->isOrdered;
|
| + if( pWInfo->nOBSat<0 ) pWInfo->nOBSat = 0;
|
| + pWInfo->revMask = pFrom->revLoop;
|
| + }
|
| + if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
|
| + && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0
|
| + ){
|
| + Bitmask revMask = 0;
|
| + int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
|
| + pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
|
| + );
|
| + assert( pWInfo->sorted==0 );
|
| + if( nOrder==pWInfo->pOrderBy->nExpr ){
|
| + pWInfo->sorted = 1;
|
| + pWInfo->revMask = revMask;
|
| + }
|
| + }
|
| + }
|
| +
|
| +
|
| + pWInfo->nRowOut = pFrom->nRow;
|
| +
|
| + /* Free temporary memory and return success */
|
| + sqlite3DbFree(db, pSpace);
|
| + return SQLITE_OK;
|
| +}
|
| +
|
| +/*
|
| +** Most queries use only a single table (they are not joins) and have
|
| +** simple == constraints against indexed fields. This routine attempts
|
| +** to plan those simple cases using much less ceremony than the
|
| +** general-purpose query planner, and thereby yield faster sqlite3_prepare()
|
| +** times for the common case.
|
| +**
|
| +** Return non-zero on success, if this query can be handled by this
|
| +** no-frills query planner. Return zero if this query needs the
|
| +** general-purpose query planner.
|
| +*/
|
| +static int whereShortCut(WhereLoopBuilder *pBuilder){
|
| + WhereInfo *pWInfo;
|
| + struct SrcList_item *pItem;
|
| + WhereClause *pWC;
|
| + WhereTerm *pTerm;
|
| + WhereLoop *pLoop;
|
| + int iCur;
|
| + int j;
|
| + Table *pTab;
|
| + Index *pIdx;
|
| +
|
| + pWInfo = pBuilder->pWInfo;
|
| + if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0;
|
| + assert( pWInfo->pTabList->nSrc>=1 );
|
| + pItem = pWInfo->pTabList->a;
|
| + pTab = pItem->pTab;
|
| + if( IsVirtual(pTab) ) return 0;
|
| + if( pItem->fg.isIndexedBy ) return 0;
|
| + iCur = pItem->iCursor;
|
| + pWC = &pWInfo->sWC;
|
| + pLoop = pBuilder->pNew;
|
| + pLoop->wsFlags = 0;
|
| + pLoop->nSkip = 0;
|
| + pTerm = sqlite3WhereFindTerm(pWC, iCur, -1, 0, WO_EQ|WO_IS, 0);
|
| + if( pTerm ){
|
| + testcase( pTerm->eOperator & WO_IS );
|
| + pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
|
| + pLoop->aLTerm[0] = pTerm;
|
| + pLoop->nLTerm = 1;
|
| + pLoop->u.btree.nEq = 1;
|
| + /* TUNING: Cost of a rowid lookup is 10 */
|
| + pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */
|
| + }else{
|
| + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
|
| + int opMask;
|
| + assert( pLoop->aLTermSpace==pLoop->aLTerm );
|
| + if( !IsUniqueIndex(pIdx)
|
| + || pIdx->pPartIdxWhere!=0
|
| + || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
|
| + ) continue;
|
| + opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ;
|
| + for(j=0; j<pIdx->nKeyCol; j++){
|
| + pTerm = sqlite3WhereFindTerm(pWC, iCur, j, 0, opMask, pIdx);
|
| + if( pTerm==0 ) break;
|
| + testcase( pTerm->eOperator & WO_IS );
|
| + pLoop->aLTerm[j] = pTerm;
|
| + }
|
| + if( j!=pIdx->nKeyCol ) continue;
|
| + pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
|
| + if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
|
| + pLoop->wsFlags |= WHERE_IDX_ONLY;
|
| + }
|
| + pLoop->nLTerm = j;
|
| + pLoop->u.btree.nEq = j;
|
| + pLoop->u.btree.pIndex = pIdx;
|
| + /* TUNING: Cost of a unique index lookup is 15 */
|
| + pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */
|
| + break;
|
| + }
|
| + }
|
| + if( pLoop->wsFlags ){
|
| + pLoop->nOut = (LogEst)1;
|
| + pWInfo->a[0].pWLoop = pLoop;
|
| + pLoop->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
|
| + pWInfo->a[0].iTabCur = iCur;
|
| + pWInfo->nRowOut = 1;
|
| + if( pWInfo->pOrderBy ) pWInfo->nOBSat = pWInfo->pOrderBy->nExpr;
|
| + if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
|
| + pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
|
| + }
|
| +#ifdef SQLITE_DEBUG
|
| + pLoop->cId = '0';
|
| +#endif
|
| + return 1;
|
| + }
|
| + return 0;
|
| +}
|
| +
|
| +/*
|
| +** Generate the beginning of the loop used for WHERE clause processing.
|
| +** The return value is a pointer to an opaque structure that contains
|
| +** information needed to terminate the loop. Later, the calling routine
|
| +** should invoke sqlite3WhereEnd() with the return value of this function
|
| +** in order to complete the WHERE clause processing.
|
| +**
|
| +** If an error occurs, this routine returns NULL.
|
| +**
|
| +** The basic idea is to do a nested loop, one loop for each table in
|
| +** the FROM clause of a select. (INSERT and UPDATE statements are the
|
| +** same as a SELECT with only a single table in the FROM clause.) For
|
| +** example, if the SQL is this:
|
| +**
|
| +** SELECT * FROM t1, t2, t3 WHERE ...;
|
| +**
|
| +** Then the code generated is conceptually like the following:
|
| +**
|
| +** foreach row1 in t1 do \ Code generated
|
| +** foreach row2 in t2 do |-- by sqlite3WhereBegin()
|
| +** foreach row3 in t3 do /
|
| +** ...
|
| +** end \ Code generated
|
| +** end |-- by sqlite3WhereEnd()
|
| +** end /
|
| +**
|
| +** Note that the loops might not be nested in the order in which they
|
| +** appear in the FROM clause if a different order is better able to make
|
| +** use of indices. Note also that when the IN operator appears in
|
| +** the WHERE clause, it might result in additional nested loops for
|
| +** scanning through all values on the right-hand side of the IN.
|
| +**
|
| +** There are Btree cursors associated with each table. t1 uses cursor
|
| +** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
|
| +** And so forth. This routine generates code to open those VDBE cursors
|
| +** and sqlite3WhereEnd() generates the code to close them.
|
| +**
|
| +** The code that sqlite3WhereBegin() generates leaves the cursors named
|
| +** in pTabList pointing at their appropriate entries. The [...] code
|
| +** can use OP_Column and OP_Rowid opcodes on these cursors to extract
|
| +** data from the various tables of the loop.
|
| +**
|
| +** If the WHERE clause is empty, the foreach loops must each scan their
|
| +** entire tables. Thus a three-way join is an O(N^3) operation. But if
|
| +** the tables have indices and there are terms in the WHERE clause that
|
| +** refer to those indices, a complete table scan can be avoided and the
|
| +** code will run much faster. Most of the work of this routine is checking
|
| +** to see if there are indices that can be used to speed up the loop.
|
| +**
|
| +** Terms of the WHERE clause are also used to limit which rows actually
|
| +** make it to the "..." in the middle of the loop. After each "foreach",
|
| +** terms of the WHERE clause that use only terms in that loop and outer
|
| +** loops are evaluated and if false a jump is made around all subsequent
|
| +** inner loops (or around the "..." if the test occurs within the inner-
|
| +** most loop)
|
| +**
|
| +** OUTER JOINS
|
| +**
|
| +** An outer join of tables t1 and t2 is conceptally coded as follows:
|
| +**
|
| +** foreach row1 in t1 do
|
| +** flag = 0
|
| +** foreach row2 in t2 do
|
| +** start:
|
| +** ...
|
| +** flag = 1
|
| +** end
|
| +** if flag==0 then
|
| +** move the row2 cursor to a null row
|
| +** goto start
|
| +** fi
|
| +** end
|
| +**
|
| +** ORDER BY CLAUSE PROCESSING
|
| +**
|
| +** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
|
| +** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
|
| +** if there is one. If there is no ORDER BY clause or if this routine
|
| +** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
|
| +**
|
| +** The iIdxCur parameter is the cursor number of an index. If
|
| +** WHERE_ONETABLE_ONLY is set, iIdxCur is the cursor number of an index
|
| +** to use for OR clause processing. The WHERE clause should use this
|
| +** specific cursor. If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
|
| +** the first cursor in an array of cursors for all indices. iIdxCur should
|
| +** be used to compute the appropriate cursor depending on which index is
|
| +** used.
|
| +*/
|
| +SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
|
| + Parse *pParse, /* The parser context */
|
| + SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
|
| + Expr *pWhere, /* The WHERE clause */
|
| + ExprList *pOrderBy, /* An ORDER BY (or GROUP BY) clause, or NULL */
|
| + ExprList *pResultSet, /* Result set of the query */
|
| + u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
|
| + int iIdxCur /* If WHERE_ONETABLE_ONLY is set, index cursor number */
|
| +){
|
| + int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
|
| + int nTabList; /* Number of elements in pTabList */
|
| + WhereInfo *pWInfo; /* Will become the return value of this function */
|
| + Vdbe *v = pParse->pVdbe; /* The virtual database engine */
|
| + Bitmask notReady; /* Cursors that are not yet positioned */
|
| + WhereLoopBuilder sWLB; /* The WhereLoop builder */
|
| + WhereMaskSet *pMaskSet; /* The expression mask set */
|
| + WhereLevel *pLevel; /* A single level in pWInfo->a[] */
|
| + WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
|
| + int ii; /* Loop counter */
|
| + sqlite3 *db; /* Database connection */
|
| + int rc; /* Return code */
|
| + u8 bFordelete = 0;
|
| +
|
| + assert( (wctrlFlags & WHERE_ONEPASS_MULTIROW)==0 || (
|
| + (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
|
| + && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
|
| + ));
|
| +
|
| + /* Variable initialization */
|
| + db = pParse->db;
|
| + memset(&sWLB, 0, sizeof(sWLB));
|
| +
|
| + /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
|
| + testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
|
| + if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
|
| + sWLB.pOrderBy = pOrderBy;
|
| +
|
| + /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
|
| + ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
|
| + if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
|
| + wctrlFlags &= ~WHERE_WANT_DISTINCT;
|
| + }
|
| +
|
| + /* The number of tables in the FROM clause is limited by the number of
|
| + ** bits in a Bitmask
|
| + */
|
| + testcase( pTabList->nSrc==BMS );
|
| + if( pTabList->nSrc>BMS ){
|
| + sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
|
| + return 0;
|
| + }
|
| +
|
| + /* This function normally generates a nested loop for all tables in
|
| + ** pTabList. But if the WHERE_ONETABLE_ONLY flag is set, then we should
|
| + ** only generate code for the first table in pTabList and assume that
|
| + ** any cursors associated with subsequent tables are uninitialized.
|
| + */
|
| + nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
|
| +
|
| + /* Allocate and initialize the WhereInfo structure that will become the
|
| + ** return value. A single allocation is used to store the WhereInfo
|
| + ** struct, the contents of WhereInfo.a[], the WhereClause structure
|
| + ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
|
| + ** field (type Bitmask) it must be aligned on an 8-byte boundary on
|
| + ** some architectures. Hence the ROUND8() below.
|
| + */
|
| + nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
|
| + pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
|
| + if( db->mallocFailed ){
|
| + sqlite3DbFree(db, pWInfo);
|
| + pWInfo = 0;
|
| + goto whereBeginError;
|
| + }
|
| + pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
|
| + pWInfo->nLevel = nTabList;
|
| + pWInfo->pParse = pParse;
|
| + pWInfo->pTabList = pTabList;
|
| + pWInfo->pOrderBy = pOrderBy;
|
| + pWInfo->pResultSet = pResultSet;
|
| + pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v);
|
| + pWInfo->wctrlFlags = wctrlFlags;
|
| + pWInfo->savedNQueryLoop = pParse->nQueryLoop;
|
| + assert( pWInfo->eOnePass==ONEPASS_OFF ); /* ONEPASS defaults to OFF */
|
| + pMaskSet = &pWInfo->sMaskSet;
|
| + sWLB.pWInfo = pWInfo;
|
| + sWLB.pWC = &pWInfo->sWC;
|
| + sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
|
| + assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
|
| + whereLoopInit(sWLB.pNew);
|
| +#ifdef SQLITE_DEBUG
|
| + sWLB.pNew->cId = '*';
|
| +#endif
|
| +
|
| + /* Split the WHERE clause into separate subexpressions where each
|
| + ** subexpression is separated by an AND operator.
|
| + */
|
| + initMaskSet(pMaskSet);
|
| + sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo);
|
| + sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND);
|
| +
|
| + /* Special case: a WHERE clause that is constant. Evaluate the
|
| + ** expression and either jump over all of the code or fall thru.
|
| + */
|
| + for(ii=0; ii<sWLB.pWC->nTerm; ii++){
|
| + if( nTabList==0 || sqlite3ExprIsConstantNotJoin(sWLB.pWC->a[ii].pExpr) ){
|
| + sqlite3ExprIfFalse(pParse, sWLB.pWC->a[ii].pExpr, pWInfo->iBreak,
|
| + SQLITE_JUMPIFNULL);
|
| + sWLB.pWC->a[ii].wtFlags |= TERM_CODED;
|
| + }
|
| + }
|
| +
|
| + /* Special case: No FROM clause
|
| + */
|
| + if( nTabList==0 ){
|
| + if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
|
| + if( wctrlFlags & WHERE_WANT_DISTINCT ){
|
| + pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
|
| + }
|
| + }
|
| +
|
| + /* Assign a bit from the bitmask to every term in the FROM clause.
|
| + **
|
| + ** The N-th term of the FROM clause is assigned a bitmask of 1<<N.
|
| + **
|
| + ** The rule of the previous sentence ensures thta if X is the bitmask for
|
| + ** a table T, then X-1 is the bitmask for all other tables to the left of T.
|
| + ** Knowing the bitmask for all tables to the left of a left join is
|
| + ** important. Ticket #3015.
|
| + **
|
| + ** Note that bitmasks are created for all pTabList->nSrc tables in
|
| + ** pTabList, not just the first nTabList tables. nTabList is normally
|
| + ** equal to pTabList->nSrc but might be shortened to 1 if the
|
| + ** WHERE_ONETABLE_ONLY flag is set.
|
| + */
|
| + for(ii=0; ii<pTabList->nSrc; ii++){
|
| + createMask(pMaskSet, pTabList->a[ii].iCursor);
|
| + sqlite3WhereTabFuncArgs(pParse, &pTabList->a[ii], &pWInfo->sWC);
|
| + }
|
| +#ifdef SQLITE_DEBUG
|
| + for(ii=0; ii<pTabList->nSrc; ii++){
|
| + Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor);
|
| + assert( m==MASKBIT(ii) );
|
| + }
|
| +#endif
|
| +
|
| + /* Analyze all of the subexpressions. */
|
| + sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC);
|
| + if( db->mallocFailed ) goto whereBeginError;
|
| +
|
| + if( wctrlFlags & WHERE_WANT_DISTINCT ){
|
| + if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
|
| + /* The DISTINCT marking is pointless. Ignore it. */
|
| + pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
|
| + }else if( pOrderBy==0 ){
|
| + /* Try to ORDER BY the result set to make distinct processing easier */
|
| + pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
|
| + pWInfo->pOrderBy = pResultSet;
|
| + }
|
| + }
|
| +
|
| + /* Construct the WhereLoop objects */
|
| + WHERETRACE(0xffff,("*** Optimizer Start *** (wctrlFlags: 0x%x)\n",
|
| + wctrlFlags));
|
| +#if defined(WHERETRACE_ENABLED)
|
| + if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */
|
| + int i;
|
| + for(i=0; i<sWLB.pWC->nTerm; i++){
|
| + whereTermPrint(&sWLB.pWC->a[i], i);
|
| + }
|
| + }
|
| +#endif
|
| +
|
| + if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
|
| + rc = whereLoopAddAll(&sWLB);
|
| + if( rc ) goto whereBeginError;
|
| +
|
| +#ifdef WHERETRACE_ENABLED
|
| + if( sqlite3WhereTrace ){ /* Display all of the WhereLoop objects */
|
| + WhereLoop *p;
|
| + int i;
|
| + static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
|
| + "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
|
| + for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
|
| + p->cId = zLabel[i%sizeof(zLabel)];
|
| + whereLoopPrint(p, sWLB.pWC);
|
| + }
|
| + }
|
| +#endif
|
| +
|
| + wherePathSolver(pWInfo, 0);
|
| + if( db->mallocFailed ) goto whereBeginError;
|
| + if( pWInfo->pOrderBy ){
|
| + wherePathSolver(pWInfo, pWInfo->nRowOut+1);
|
| + if( db->mallocFailed ) goto whereBeginError;
|
| + }
|
| + }
|
| + if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
|
| + pWInfo->revMask = (Bitmask)(-1);
|
| + }
|
| + if( pParse->nErr || NEVER(db->mallocFailed) ){
|
| + goto whereBeginError;
|
| + }
|
| +#ifdef WHERETRACE_ENABLED
|
| + if( sqlite3WhereTrace ){
|
| + sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
|
| + if( pWInfo->nOBSat>0 ){
|
| + sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
|
| + }
|
| + switch( pWInfo->eDistinct ){
|
| + case WHERE_DISTINCT_UNIQUE: {
|
| + sqlite3DebugPrintf(" DISTINCT=unique");
|
| + break;
|
| + }
|
| + case WHERE_DISTINCT_ORDERED: {
|
| + sqlite3DebugPrintf(" DISTINCT=ordered");
|
| + break;
|
| + }
|
| + case WHERE_DISTINCT_UNORDERED: {
|
| + sqlite3DebugPrintf(" DISTINCT=unordered");
|
| + break;
|
| + }
|
| + }
|
| + sqlite3DebugPrintf("\n");
|
| + for(ii=0; ii<pWInfo->nLevel; ii++){
|
| + whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
|
| + }
|
| + }
|
| +#endif
|
| + /* Attempt to omit tables from the join that do not effect the result */
|
| + if( pWInfo->nLevel>=2
|
| + && pResultSet!=0
|
| + && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
|
| + ){
|
| + Bitmask tabUsed = sqlite3WhereExprListUsage(pMaskSet, pResultSet);
|
| + if( sWLB.pOrderBy ){
|
| + tabUsed |= sqlite3WhereExprListUsage(pMaskSet, sWLB.pOrderBy);
|
| + }
|
| + while( pWInfo->nLevel>=2 ){
|
| + WhereTerm *pTerm, *pEnd;
|
| + pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
|
| + if( (pWInfo->pTabList->a[pLoop->iTab].fg.jointype & JT_LEFT)==0 ) break;
|
| + if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
|
| + && (pLoop->wsFlags & WHERE_ONEROW)==0
|
| + ){
|
| + break;
|
| + }
|
| + if( (tabUsed & pLoop->maskSelf)!=0 ) break;
|
| + pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
|
| + for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
|
| + if( (pTerm->prereqAll & pLoop->maskSelf)!=0
|
| + && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
|
| + ){
|
| + break;
|
| + }
|
| + }
|
| + if( pTerm<pEnd ) break;
|
| + WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
|
| + pWInfo->nLevel--;
|
| + nTabList--;
|
| + }
|
| + }
|
| + WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
|
| + pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
|
| +
|
| + /* If the caller is an UPDATE or DELETE statement that is requesting
|
| + ** to use a one-pass algorithm, determine if this is appropriate.
|
| + ** The one-pass algorithm only works if the WHERE clause constrains
|
| + ** the statement to update or delete a single row.
|
| + */
|
| + assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
|
| + if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 ){
|
| + int wsFlags = pWInfo->a[0].pWLoop->wsFlags;
|
| + int bOnerow = (wsFlags & WHERE_ONEROW)!=0;
|
| + if( bOnerow || ( (wctrlFlags & WHERE_ONEPASS_MULTIROW)
|
| + && 0==(wsFlags & WHERE_VIRTUALTABLE)
|
| + )){
|
| + pWInfo->eOnePass = bOnerow ? ONEPASS_SINGLE : ONEPASS_MULTI;
|
| + if( HasRowid(pTabList->a[0].pTab) && (wsFlags & WHERE_IDX_ONLY) ){
|
| + if( wctrlFlags & WHERE_ONEPASS_MULTIROW ){
|
| + bFordelete = OPFLAG_FORDELETE;
|
| + }
|
| + pWInfo->a[0].pWLoop->wsFlags = (wsFlags & ~WHERE_IDX_ONLY);
|
| + }
|
| + }
|
| + }
|
| +
|
| + /* Open all tables in the pTabList and any indices selected for
|
| + ** searching those tables.
|
| + */
|
| + for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
|
| + Table *pTab; /* Table to open */
|
| + int iDb; /* Index of database containing table/index */
|
| + struct SrcList_item *pTabItem;
|
| +
|
| + pTabItem = &pTabList->a[pLevel->iFrom];
|
| + pTab = pTabItem->pTab;
|
| + iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
|
| + pLoop = pLevel->pWLoop;
|
| + if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
|
| + /* Do nothing */
|
| + }else
|
| +#ifndef SQLITE_OMIT_VIRTUALTABLE
|
| + if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
|
| + const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
|
| + int iCur = pTabItem->iCursor;
|
| + sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
|
| + }else if( IsVirtual(pTab) ){
|
| + /* noop */
|
| + }else
|
| +#endif
|
| + if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
|
| + && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
|
| + int op = OP_OpenRead;
|
| + if( pWInfo->eOnePass!=ONEPASS_OFF ){
|
| + op = OP_OpenWrite;
|
| + pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
|
| + };
|
| + sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
|
| + assert( pTabItem->iCursor==pLevel->iTabCur );
|
| + testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS-1 );
|
| + testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS );
|
| + if( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol<BMS && HasRowid(pTab) ){
|
| + Bitmask b = pTabItem->colUsed;
|
| + int n = 0;
|
| + for(; b; b=b>>1, n++){}
|
| + sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
|
| + SQLITE_INT_TO_PTR(n), P4_INT32);
|
| + assert( n<=pTab->nCol );
|
| + }
|
| +#ifdef SQLITE_ENABLE_CURSOR_HINTS
|
| + if( pLoop->u.btree.pIndex!=0 ){
|
| + sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ|bFordelete);
|
| + }else
|
| +#endif
|
| + {
|
| + sqlite3VdbeChangeP5(v, bFordelete);
|
| + }
|
| +#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
|
| + sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0,
|
| + (const u8*)&pTabItem->colUsed, P4_INT64);
|
| +#endif
|
| + }else{
|
| + sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
|
| + }
|
| + if( pLoop->wsFlags & WHERE_INDEXED ){
|
| + Index *pIx = pLoop->u.btree.pIndex;
|
| + int iIndexCur;
|
| + int op = OP_OpenRead;
|
| + /* iIdxCur is always set if to a positive value if ONEPASS is possible */
|
| + assert( iIdxCur!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
|
| + if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
|
| + && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0
|
| + ){
|
| + /* This is one term of an OR-optimization using the PRIMARY KEY of a
|
| + ** WITHOUT ROWID table. No need for a separate index */
|
| + iIndexCur = pLevel->iTabCur;
|
| + op = 0;
|
| + }else if( pWInfo->eOnePass!=ONEPASS_OFF ){
|
| + Index *pJ = pTabItem->pTab->pIndex;
|
| + iIndexCur = iIdxCur;
|
| + assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
|
| + while( ALWAYS(pJ) && pJ!=pIx ){
|
| + iIndexCur++;
|
| + pJ = pJ->pNext;
|
| + }
|
| + op = OP_OpenWrite;
|
| + pWInfo->aiCurOnePass[1] = iIndexCur;
|
| + }else if( iIdxCur && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0 ){
|
| + iIndexCur = iIdxCur;
|
| + if( wctrlFlags & WHERE_REOPEN_IDX ) op = OP_ReopenIdx;
|
| + }else{
|
| + iIndexCur = pParse->nTab++;
|
| + }
|
| + pLevel->iIdxCur = iIndexCur;
|
| + assert( pIx->pSchema==pTab->pSchema );
|
| + assert( iIndexCur>=0 );
|
| + if( op ){
|
| + sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
|
| + sqlite3VdbeSetP4KeyInfo(pParse, pIx);
|
| + if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0
|
| + && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0
|
| + && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0
|
| + ){
|
| + sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ); /* Hint to COMDB2 */
|
| + }
|
| + VdbeComment((v, "%s", pIx->zName));
|
| +#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
|
| + {
|
| + u64 colUsed = 0;
|
| + int ii, jj;
|
| + for(ii=0; ii<pIx->nColumn; ii++){
|
| + jj = pIx->aiColumn[ii];
|
| + if( jj<0 ) continue;
|
| + if( jj>63 ) jj = 63;
|
| + if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue;
|
| + colUsed |= ((u64)1)<<(ii<63 ? ii : 63);
|
| + }
|
| + sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0,
|
| + (u8*)&colUsed, P4_INT64);
|
| + }
|
| +#endif /* SQLITE_ENABLE_COLUMN_USED_MASK */
|
| + }
|
| + }
|
| + if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
|
| + }
|
| + pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
|
| + if( db->mallocFailed ) goto whereBeginError;
|
| +
|
| + /* Generate the code to do the search. Each iteration of the for
|
| + ** loop below generates code for a single nested loop of the VM
|
| + ** program.
|
| + */
|
| + notReady = ~(Bitmask)0;
|
| + for(ii=0; ii<nTabList; ii++){
|
| + int addrExplain;
|
| + int wsFlags;
|
| + pLevel = &pWInfo->a[ii];
|
| + wsFlags = pLevel->pWLoop->wsFlags;
|
| +#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
|
| + if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
|
| + constructAutomaticIndex(pParse, &pWInfo->sWC,
|
| + &pTabList->a[pLevel->iFrom], notReady, pLevel);
|
| + if( db->mallocFailed ) goto whereBeginError;
|
| + }
|
| +#endif
|
| + addrExplain = sqlite3WhereExplainOneScan(
|
| + pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags
|
| + );
|
| + pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
|
| + notReady = sqlite3WhereCodeOneLoopStart(pWInfo, ii, notReady);
|
| + pWInfo->iContinue = pLevel->addrCont;
|
| + if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_ONETABLE_ONLY)==0 ){
|
| + sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain);
|
| + }
|
| + }
|
| +
|
| + /* Done. */
|
| + VdbeModuleComment((v, "Begin WHERE-core"));
|
| + return pWInfo;
|
| +
|
| + /* Jump here if malloc fails */
|
| +whereBeginError:
|
| + if( pWInfo ){
|
| + pParse->nQueryLoop = pWInfo->savedNQueryLoop;
|
| + whereInfoFree(db, pWInfo);
|
| + }
|
| + return 0;
|
| +}
|
| +
|
| +/*
|
| +** Generate the end of the WHERE loop. See comments on
|
| +** sqlite3WhereBegin() for additional information.
|
| +*/
|
| +SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
|
| + Parse *pParse = pWInfo->pParse;
|
| + Vdbe *v = pParse->pVdbe;
|
| + int i;
|
| + WhereLevel *pLevel;
|
| + WhereLoop *pLoop;
|
| + SrcList *pTabList = pWInfo->pTabList;
|
| + sqlite3 *db = pParse->db;
|
| +
|
| + /* Generate loop termination code.
|
| + */
|
| + VdbeModuleComment((v, "End WHERE-core"));
|
| + sqlite3ExprCacheClear(pParse);
|
| + for(i=pWInfo->nLevel-1; i>=0; i--){
|
| + int addr;
|
| + pLevel = &pWInfo->a[i];
|
| + pLoop = pLevel->pWLoop;
|
| + sqlite3VdbeResolveLabel(v, pLevel->addrCont);
|
| + if( pLevel->op!=OP_Noop ){
|
| + sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
|
| + sqlite3VdbeChangeP5(v, pLevel->p5);
|
| + VdbeCoverage(v);
|
| + VdbeCoverageIf(v, pLevel->op==OP_Next);
|
| + VdbeCoverageIf(v, pLevel->op==OP_Prev);
|
| + VdbeCoverageIf(v, pLevel->op==OP_VNext);
|
| + }
|
| + if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
|
| + struct InLoop *pIn;
|
| + int j;
|
| + sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
|
| + for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
|
| + sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
|
| + sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
|
| + VdbeCoverage(v);
|
| + VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen);
|
| + VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen);
|
| + sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
|
| + }
|
| + }
|
| + sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
|
| + if( pLevel->addrSkip ){
|
| + sqlite3VdbeGoto(v, pLevel->addrSkip);
|
| + VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
|
| + sqlite3VdbeJumpHere(v, pLevel->addrSkip);
|
| + sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
|
| + }
|
| +#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
|
| + if( pLevel->addrLikeRep ){
|
| + int op;
|
| + if( sqlite3VdbeGetOp(v, pLevel->addrLikeRep-1)->p1 ){
|
| + op = OP_DecrJumpZero;
|
| + }else{
|
| + op = OP_JumpZeroIncr;
|
| + }
|
| + sqlite3VdbeAddOp2(v, op, pLevel->iLikeRepCntr, pLevel->addrLikeRep);
|
| + VdbeCoverage(v);
|
| + }
|
| +#endif
|
| + if( pLevel->iLeftJoin ){
|
| + addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
|
| + assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
|
| + || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
|
| + if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
|
| + sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
|
| + }
|
| + if( pLoop->wsFlags & WHERE_INDEXED ){
|
| + sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
|
| + }
|
| + if( pLevel->op==OP_Return ){
|
| + sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
|
| + }else{
|
| + sqlite3VdbeGoto(v, pLevel->addrFirst);
|
| + }
|
| + sqlite3VdbeJumpHere(v, addr);
|
| + }
|
| + VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
|
| + pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
|
| + }
|
| +
|
| + /* The "break" point is here, just past the end of the outer loop.
|
| + ** Set it.
|
| + */
|
| + sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
|
| +
|
| + assert( pWInfo->nLevel<=pTabList->nSrc );
|
| + for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
|
| + int k, last;
|
| + VdbeOp *pOp;
|
| + Index *pIdx = 0;
|
| + struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
|
| + Table *pTab = pTabItem->pTab;
|
| + assert( pTab!=0 );
|
| + pLoop = pLevel->pWLoop;
|
| +
|
| + /* For a co-routine, change all OP_Column references to the table of
|
| + ** the co-routine into OP_Copy of result contained in a register.
|
| + ** OP_Rowid becomes OP_Null.
|
| + */
|
| + if( pTabItem->fg.viaCoroutine && !db->mallocFailed ){
|
| + translateColumnToCopy(v, pLevel->addrBody, pLevel->iTabCur,
|
| + pTabItem->regResult, 0);
|
| + continue;
|
| + }
|
| +
|
| + /* Close all of the cursors that were opened by sqlite3WhereBegin.
|
| + ** Except, do not close cursors that will be reused by the OR optimization
|
| + ** (WHERE_OMIT_OPEN_CLOSE). And do not close the OP_OpenWrite cursors
|
| + ** created for the ONEPASS optimization.
|
| + */
|
| + if( (pTab->tabFlags & TF_Ephemeral)==0
|
| + && pTab->pSelect==0
|
| + && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
|
| + ){
|
| + int ws = pLoop->wsFlags;
|
| + if( pWInfo->eOnePass==ONEPASS_OFF && (ws & WHERE_IDX_ONLY)==0 ){
|
| + sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
|
| + }
|
| + if( (ws & WHERE_INDEXED)!=0
|
| + && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0
|
| + && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1]
|
| + ){
|
| + sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
|
| + }
|
| + }
|
| +
|
| + /* If this scan uses an index, make VDBE code substitutions to read data
|
| + ** from the index instead of from the table where possible. In some cases
|
| + ** this optimization prevents the table from ever being read, which can
|
| + ** yield a significant performance boost.
|
| + **
|
| + ** Calls to the code generator in between sqlite3WhereBegin and
|
| + ** sqlite3WhereEnd will have created code that references the table
|
| + ** directly. This loop scans all that code looking for opcodes
|
| + ** that reference the table and converts them into opcodes that
|
| + ** reference the index.
|
| + */
|
| + if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
|
| + pIdx = pLoop->u.btree.pIndex;
|
| + }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
|
| + pIdx = pLevel->u.pCovidx;
|
| + }
|
| + if( pIdx
|
| + && (pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable))
|
| + && !db->mallocFailed
|
| + ){
|
| + last = sqlite3VdbeCurrentAddr(v);
|
| + k = pLevel->addrBody;
|
| + pOp = sqlite3VdbeGetOp(v, k);
|
| + for(; k<last; k++, pOp++){
|
| + if( pOp->p1!=pLevel->iTabCur ) continue;
|
| + if( pOp->opcode==OP_Column ){
|
| + int x = pOp->p2;
|
| + assert( pIdx->pTable==pTab );
|
| + if( !HasRowid(pTab) ){
|
| + Index *pPk = sqlite3PrimaryKeyIndex(pTab);
|
| + x = pPk->aiColumn[x];
|
| + assert( x>=0 );
|
| + }
|
| + x = sqlite3ColumnOfIndex(pIdx, x);
|
| + if( x>=0 ){
|
| + pOp->p2 = x;
|
| + pOp->p1 = pLevel->iIdxCur;
|
| + }
|
| + assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 );
|
| + }else if( pOp->opcode==OP_Rowid ){
|
| + pOp->p1 = pLevel->iIdxCur;
|
| + pOp->opcode = OP_IdxRowid;
|
| + }
|
| + }
|
| + }
|
| + }
|
| +
|
| + /* Final cleanup
|
| + */
|
| + pParse->nQueryLoop = pWInfo->savedNQueryLoop;
|
| + whereInfoFree(db, pWInfo);
|
| + return;
|
| +}
|
| +
|
| +/************** End of where.c ***********************************************/
|
| +/************** Begin file parse.c *******************************************/
|
| +/*
|
| +** 2000-05-29
|
| +**
|
| +** The author disclaims copyright to this source code. In place of
|
| +** a legal notice, here is a blessing:
|
| +**
|
| +** May you do good and not evil.
|
| +** May you find forgiveness for yourself and forgive others.
|
| +** May you share freely, never taking more than you give.
|
| +**
|
| +*************************************************************************
|
| +** Driver template for the LEMON parser generator.
|
| +**
|
| +** The "lemon" program processes an LALR(1) input grammar file, then uses
|
| +** this template to construct a parser. The "lemon" program inserts text
|
| +** at each "%%" line. Also, any "P-a-r-s-e" identifer prefix (without the
|
| +** interstitial "-" characters) contained in this template is changed into
|
| +** the value of the %name directive from the grammar. Otherwise, the content
|
| +** of this template is copied straight through into the generate parser
|
| +** source file.
|
| +**
|
| +** The following is the concatenation of all %include directives from the
|
| +** input grammar file:
|
| +*/
|
| +/* #include <stdio.h> */
|
| +/************ Begin %include sections from the grammar ************************/
|
| +
|
| +/* #include "sqliteInt.h" */
|
| +
|
| +/*
|
| +** Disable all error recovery processing in the parser push-down
|
| +** automaton.
|
| +*/
|
| +#define YYNOERRORRECOVERY 1
|
| +
|
| +/*
|
| +** Make yytestcase() the same as testcase()
|
| +*/
|
| +#define yytestcase(X) testcase(X)
|
| +
|
| +/*
|
| +** Indicate that sqlite3ParserFree() will never be called with a null
|
| +** pointer.
|
| +*/
|
| +#define YYPARSEFREENEVERNULL 1
|
| +
|
| +/*
|
| +** Alternative datatype for the argument to the malloc() routine passed
|
| +** into sqlite3ParserAlloc(). The default is size_t.
|
| +*/
|
| +#define YYMALLOCARGTYPE u64
|
| +
|
| +/*
|
| +** An instance of this structure holds information about the
|
| +** LIMIT clause of a SELECT statement.
|
| +*/
|
| +struct LimitVal {
|
| + Expr *pLimit; /* The LIMIT expression. NULL if there is no limit */
|
| + Expr *pOffset; /* The OFFSET expression. NULL if there is none */
|
| +};
|
| +
|
| +/*
|
| +** An instance of this structure is used to store the LIKE,
|
| +** GLOB, NOT LIKE, and NOT GLOB operators.
|
| +*/
|
| +struct LikeOp {
|
| + Token eOperator; /* "like" or "glob" or "regexp" */
|
| + int bNot; /* True if the NOT keyword is present */
|
| +};
|
| +
|
| +/*
|
| +** An instance of the following structure describes the event of a
|
| +** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
|
| +** TK_DELETE, or TK_INSTEAD. If the event is of the form
|
| +**
|
| +** UPDATE ON (a,b,c)
|
| +**
|
| +** Then the "b" IdList records the list "a,b,c".
|
| +*/
|
| +struct TrigEvent { int a; IdList * b; };
|
| +
|
| +/*
|
| +** An instance of this structure holds the ATTACH key and the key type.
|
| +*/
|
| +struct AttachKey { int type; Token key; };
|
| +
|
| +
|
| + /*
|
| + ** For a compound SELECT statement, make sure p->pPrior->pNext==p for
|
| + ** all elements in the list. And make sure list length does not exceed
|
| + ** SQLITE_LIMIT_COMPOUND_SELECT.
|
| + */
|
| + static void parserDoubleLinkSelect(Parse *pParse, Select *p){
|
| + if( p->pPrior ){
|
| + Select *pNext = 0, *pLoop;
|
| + int mxSelect, cnt = 0;
|
| + for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){
|
| + pLoop->pNext = pNext;
|
| + pLoop->selFlags |= SF_Compound;
|
| + }
|
| + if( (p->selFlags & SF_MultiValue)==0 &&
|
| + (mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT])>0 &&
|
| + cnt>mxSelect
|
| + ){
|
| + sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
|
| + }
|
| + }
|
| + }
|
| +
|
| + /* This is a utility routine used to set the ExprSpan.zStart and
|
| + ** ExprSpan.zEnd values of pOut so that the span covers the complete
|
| + ** range of text beginning with pStart and going to the end of pEnd.
|
| + */
|
| + static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
|
| + pOut->zStart = pStart->z;
|
| + pOut->zEnd = &pEnd->z[pEnd->n];
|
| + }
|
| +
|
| + /* Construct a new Expr object from a single identifier. Use the
|
| + ** new Expr to populate pOut. Set the span of pOut to be the identifier
|
| + ** that created the expression.
|
| + */
|
| + static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
|
| + pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
|
| + pOut->zStart = pValue->z;
|
| + pOut->zEnd = &pValue->z[pValue->n];
|
| + }
|
| +
|
| + /* This routine constructs a binary expression node out of two ExprSpan
|
| + ** objects and uses the result to populate a new ExprSpan object.
|
| + */
|
| + static void spanBinaryExpr(
|
| + ExprSpan *pOut, /* Write the result here */
|
| + Parse *pParse, /* The parsing context. Errors accumulate here */
|
| + int op, /* The binary operation */
|
| + ExprSpan *pLeft, /* The left operand */
|
| + ExprSpan *pRight /* The right operand */
|
| + ){
|
| + pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
|
| + pOut->zStart = pLeft->zStart;
|
| + pOut->zEnd = pRight->zEnd;
|
| + }
|
| +
|
| + /* If doNot is true, then add a TK_NOT Expr-node wrapper around the
|
| + ** outside of *ppExpr.
|
| + */
|
| + static void exprNot(Parse *pParse, int doNot, Expr **ppExpr){
|
| + if( doNot ) *ppExpr = sqlite3PExpr(pParse, TK_NOT, *ppExpr, 0, 0);
|
| + }
|
| +
|
| + /* Construct an expression node for a unary postfix operator
|
| + */
|
| + static void spanUnaryPostfix(
|
| + ExprSpan *pOut, /* Write the new expression node here */
|
| + Parse *pParse, /* Parsing context to record errors */
|
| + int op, /* The operator */
|
| + ExprSpan *pOperand, /* The operand */
|
| + Token *pPostOp /* The operand token for setting the span */
|
| + ){
|
| + pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
|
| + pOut->zStart = pOperand->zStart;
|
| + pOut->zEnd = &pPostOp->z[pPostOp->n];
|
| + }
|
| +
|
| + /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
|
| + ** unary TK_ISNULL or TK_NOTNULL expression. */
|
| + static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
|
| + sqlite3 *db = pParse->db;
|
| + if( pY && pA && pY->op==TK_NULL ){
|
| + pA->op = (u8)op;
|
| + sqlite3ExprDelete(db, pA->pRight);
|
| + pA->pRight = 0;
|
| + }
|
| + }
|
| +
|
| + /* Construct an expression node for a unary prefix operator
|
| + */
|
| + static void spanUnaryPrefix(
|
| + ExprSpan *pOut, /* Write the new expression node here */
|
| + Parse *pParse, /* Parsing context to record errors */
|
| + int op, /* The operator */
|
| + ExprSpan *pOperand, /* The operand */
|
| + Token *pPreOp /* The operand token for setting the span */
|
| + ){
|
| + pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
|
| + pOut->zStart = pPreOp->z;
|
| + pOut->zEnd = pOperand->zEnd;
|
| + }
|
| +
|
| + /* Add a single new term to an ExprList that is used to store a
|
| + ** list of identifiers. Report an error if the ID list contains
|
| + ** a COLLATE clause or an ASC or DESC keyword, except ignore the
|
| + ** error while parsing a legacy schema.
|
| + */
|
| + static ExprList *parserAddExprIdListTerm(
|
| + Parse *pParse,
|
| + ExprList *pPrior,
|
| + Token *pIdToken,
|
| + int hasCollate,
|
| + int sortOrder
|
| + ){
|
| + ExprList *p = sqlite3ExprListAppend(pParse, pPrior, 0);
|
| + if( (hasCollate || sortOrder!=SQLITE_SO_UNDEFINED)
|
| + && pParse->db->init.busy==0
|
| + ){
|
| + sqlite3ErrorMsg(pParse, "syntax error after column name \"%.*s\"",
|
| + pIdToken->n, pIdToken->z);
|
| + }
|
| + sqlite3ExprListSetName(pParse, p, pIdToken, 1);
|
| + return p;
|
| + }
|
| +/**************** End of %include directives **********************************/
|
| +/* These constants specify the various numeric values for terminal symbols
|
| +** in a format understandable to "makeheaders". This section is blank unless
|
| +** "lemon" is run with the "-m" command-line option.
|
| +***************** Begin makeheaders token definitions *************************/
|
| +/**************** End makeheaders token definitions ***************************/
|
| +
|
| +/* The next sections is a series of control #defines.
|
| +** various aspects of the generated parser.
|
| +** YYCODETYPE is the data type used to store the integer codes
|
| +** that represent terminal and non-terminal symbols.
|
| +** "unsigned char" is used if there are fewer than
|
| +** 256 symbols. Larger types otherwise.
|
| +** YYNOCODE is a number of type YYCODETYPE that is not used for
|
| +** any terminal or nonterminal symbol.
|
| +** YYFALLBACK If defined, this indicates that one or more tokens
|
| +** (also known as: "terminal symbols") have fall-back
|
| +** values which should be used if the original symbol
|
| +** would not parse. This permits keywords to sometimes
|
| +** be used as identifiers, for example.
|
| +** YYACTIONTYPE is the data type used for "action codes" - numbers
|
| +** that indicate what to do in response to the next
|
| +** token.
|
| +** sqlite3ParserTOKENTYPE is the data type used for minor type for terminal
|
| +** symbols. Background: A "minor type" is a semantic
|
| +** value associated with a terminal or non-terminal
|
| +** symbols. For example, for an "ID" terminal symbol,
|
| +** the minor type might be the name of the identifier.
|
| +** Each non-terminal can have a different minor type.
|
| +** Terminal symbols all have the same minor type, though.
|
| +** This macros defines the minor type for terminal
|
| +** symbols.
|
| +** YYMINORTYPE is the data type used for all minor types.
|
| +** This is typically a union of many types, one of
|
| +** which is sqlite3ParserTOKENTYPE. The entry in the union
|
| +** for terminal symbols is called "yy0".
|
| +** YYSTACKDEPTH is the maximum depth of the parser's stack. If
|
| +** zero the stack is dynamically sized using realloc()
|
| +** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument
|
| +** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument
|
| +** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser
|
| +** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser
|
| +** YYERRORSYMBOL is the code number of the error symbol. If not
|
| +** defined, then do no error processing.
|
| +** YYNSTATE the combined number of states.
|
| +** YYNRULE the number of rules in the grammar
|
| +** YY_MAX_SHIFT Maximum value for shift actions
|
| +** YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
|
| +** YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
|
| +** YY_MIN_REDUCE Maximum value for reduce actions
|
| +** YY_ERROR_ACTION The yy_action[] code for syntax error
|
| +** YY_ACCEPT_ACTION The yy_action[] code for accept
|
| +** YY_NO_ACTION The yy_action[] code for no-op
|
| +*/
|
| +#ifndef INTERFACE
|
| +# define INTERFACE 1
|
| +#endif
|
| +/************* Begin control #defines *****************************************/
|
| +#define YYCODETYPE unsigned char
|
| +#define YYNOCODE 253
|
| +#define YYACTIONTYPE unsigned short int
|
| +#define YYWILDCARD 70
|
| +#define sqlite3ParserTOKENTYPE Token
|
| +typedef union {
|
| + int yyinit;
|
| + sqlite3ParserTOKENTYPE yy0;
|
| + int yy4;
|
| + struct TrigEvent yy90;
|
| + ExprSpan yy118;
|
| + TriggerStep* yy203;
|
| + struct {int value; int mask;} yy215;
|
| + SrcList* yy259;
|
| + struct LimitVal yy292;
|
| + Expr* yy314;
|
| + ExprList* yy322;
|
| + struct LikeOp yy342;
|
| + IdList* yy384;
|
| + Select* yy387;
|
| + With* yy451;
|
| +} YYMINORTYPE;
|
| +#ifndef YYSTACKDEPTH
|
| +#define YYSTACKDEPTH 100
|
| +#endif
|
| +#define sqlite3ParserARG_SDECL Parse *pParse;
|
| +#define sqlite3ParserARG_PDECL ,Parse *pParse
|
| +#define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
|
| +#define sqlite3ParserARG_STORE yypParser->pParse = pParse
|
| +#define YYFALLBACK 1
|
| +#define YYNSTATE 436
|
| +#define YYNRULE 328
|
| +#define YY_MAX_SHIFT 435
|
| +#define YY_MIN_SHIFTREDUCE 649
|
| +#define YY_MAX_SHIFTREDUCE 976
|
| +#define YY_MIN_REDUCE 977
|
| +#define YY_MAX_REDUCE 1304
|
| +#define YY_ERROR_ACTION 1305
|
| +#define YY_ACCEPT_ACTION 1306
|
| +#define YY_NO_ACTION 1307
|
| +/************* End control #defines *******************************************/
|
| +
|
| +/* The yyzerominor constant is used to initialize instances of
|
| +** YYMINORTYPE objects to zero. */
|
| +static const YYMINORTYPE yyzerominor = { 0 };
|
| +
|
| +/* Define the yytestcase() macro to be a no-op if is not already defined
|
| +** otherwise.
|
| +**
|
| +** Applications can choose to define yytestcase() in the %include section
|
| +** to a macro that can assist in verifying code coverage. For production
|
| +** code the yytestcase() macro should be turned off. But it is useful
|
| +** for testing.
|
| +*/
|
| +#ifndef yytestcase
|
| +# define yytestcase(X)
|
| +#endif
|
| +
|
| +
|
| +/* Next are the tables used to determine what action to take based on the
|
| +** current state and lookahead token. These tables are used to implement
|
| +** functions that take a state number and lookahead value and return an
|
| +** action integer.
|
| +**
|
| +** Suppose the action integer is N. Then the action is determined as
|
| +** follows
|
| +**
|
| +** 0 <= N <= YY_MAX_SHIFT Shift N. That is, push the lookahead
|
| +** token onto the stack and goto state N.
|
| +**
|
| +** N between YY_MIN_SHIFTREDUCE Shift to an arbitrary state then
|
| +** and YY_MAX_SHIFTREDUCE reduce by rule N-YY_MIN_SHIFTREDUCE.
|
| +**
|
| +** N between YY_MIN_REDUCE Reduce by rule N-YY_MIN_REDUCE
|
| +** and YY_MAX_REDUCE
|
| +
|
| +** N == YY_ERROR_ACTION A syntax error has occurred.
|
| +**
|
| +** N == YY_ACCEPT_ACTION The parser accepts its input.
|
| +**
|
| +** N == YY_NO_ACTION No such action. Denotes unused
|
| +** slots in the yy_action[] table.
|
| +**
|
| +** The action table is constructed as a single large table named yy_action[].
|
| +** Given state S and lookahead X, the action is computed as
|
| +**
|
| +** yy_action[ yy_shift_ofst[S] + X ]
|
| +**
|
| +** If the index value yy_shift_ofst[S]+X is out of range or if the value
|
| +** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
|
| +** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
|
| +** and that yy_default[S] should be used instead.
|
| +**
|
| +** The formula above is for computing the action when the lookahead is
|
| +** a terminal symbol. If the lookahead is a non-terminal (as occurs after
|
| +** a reduce action) then the yy_reduce_ofst[] array is used in place of
|
| +** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
|
| +** YY_SHIFT_USE_DFLT.
|
| +**
|
| +** The following are the tables generated in this section:
|
| +**
|
| +** yy_action[] A single table containing all actions.
|
| +** yy_lookahead[] A table containing the lookahead for each entry in
|
| +** yy_action. Used to detect hash collisions.
|
| +** yy_shift_ofst[] For each state, the offset into yy_action for
|
| +** shifting terminals.
|
| +** yy_reduce_ofst[] For each state, the offset into yy_action for
|
| +** shifting non-terminals after a reduce.
|
| +** yy_default[] Default action for each state.
|
| +**
|
| +*********** Begin parsing tables **********************************************/
|
| +#define YY_ACTTAB_COUNT (1501)
|
| +static const YYACTIONTYPE yy_action[] = {
|
| + /* 0 */ 311, 1306, 145, 651, 2, 192, 652, 338, 780, 92,
|
| + /* 10 */ 92, 92, 92, 85, 90, 90, 90, 90, 89, 89,
|
| + /* 20 */ 88, 88, 88, 87, 335, 88, 88, 88, 87, 335,
|
| + /* 30 */ 327, 856, 856, 92, 92, 92, 92, 697, 90, 90,
|
| + /* 40 */ 90, 90, 89, 89, 88, 88, 88, 87, 335, 76,
|
| + /* 50 */ 807, 74, 93, 94, 84, 868, 871, 860, 860, 91,
|
| + /* 60 */ 91, 92, 92, 92, 92, 335, 90, 90, 90, 90,
|
| + /* 70 */ 89, 89, 88, 88, 88, 87, 335, 311, 780, 90,
|
| + /* 80 */ 90, 90, 90, 89, 89, 88, 88, 88, 87, 335,
|
| + /* 90 */ 356, 808, 776, 701, 689, 689, 86, 83, 166, 257,
|
| + /* 100 */ 809, 715, 430, 86, 83, 166, 324, 697, 856, 856,
|
| + /* 110 */ 201, 158, 276, 387, 271, 386, 188, 689, 689, 828,
|
| + /* 120 */ 86, 83, 166, 269, 833, 49, 123, 87, 335, 93,
|
| + /* 130 */ 94, 84, 868, 871, 860, 860, 91, 91, 92, 92,
|
| + /* 140 */ 92, 92, 239, 90, 90, 90, 90, 89, 89, 88,
|
| + /* 150 */ 88, 88, 87, 335, 311, 763, 333, 332, 216, 408,
|
| + /* 160 */ 394, 69, 231, 393, 690, 691, 396, 910, 251, 354,
|
| + /* 170 */ 250, 288, 315, 430, 908, 430, 909, 89, 89, 88,
|
| + /* 180 */ 88, 88, 87, 335, 391, 856, 856, 690, 691, 183,
|
| + /* 190 */ 95, 123, 384, 381, 380, 833, 31, 833, 49, 912,
|
| + /* 200 */ 912, 751, 752, 379, 123, 311, 93, 94, 84, 868,
|
| + /* 210 */ 871, 860, 860, 91, 91, 92, 92, 92, 92, 114,
|
| + /* 220 */ 90, 90, 90, 90, 89, 89, 88, 88, 88, 87,
|
| + /* 230 */ 335, 430, 408, 399, 435, 657, 856, 856, 346, 57,
|
| + /* 240 */ 232, 828, 109, 704, 366, 689, 689, 363, 825, 760,
|
| + /* 250 */ 97, 749, 752, 833, 49, 708, 708, 93, 94, 84,
|
| + /* 260 */ 868, 871, 860, 860, 91, 91, 92, 92, 92, 92,
|
| + /* 270 */ 423, 90, 90, 90, 90, 89, 89, 88, 88, 88,
|
| + /* 280 */ 87, 335, 311, 114, 22, 361, 688, 58, 408, 390,
|
| + /* 290 */ 251, 349, 240, 213, 762, 689, 689, 847, 685, 115,
|
| + /* 300 */ 361, 231, 393, 689, 689, 396, 183, 689, 689, 384,
|
| + /* 310 */ 381, 380, 361, 856, 856, 690, 691, 160, 159, 223,
|
| + /* 320 */ 379, 738, 25, 806, 707, 841, 143, 689, 689, 835,
|
| + /* 330 */ 392, 339, 766, 766, 93, 94, 84, 868, 871, 860,
|
| + /* 340 */ 860, 91, 91, 92, 92, 92, 92, 914, 90, 90,
|
| + /* 350 */ 90, 90, 89, 89, 88, 88, 88, 87, 335, 311,
|
| + /* 360 */ 840, 840, 840, 266, 257, 690, 691, 778, 706, 86,
|
| + /* 370 */ 83, 166, 219, 690, 691, 737, 1, 690, 691, 689,
|
| + /* 380 */ 689, 689, 689, 430, 86, 83, 166, 249, 688, 937,
|
| + /* 390 */ 856, 856, 427, 699, 700, 828, 298, 690, 691, 221,
|
| + /* 400 */ 686, 115, 123, 944, 795, 833, 48, 342, 305, 970,
|
| + /* 410 */ 847, 93, 94, 84, 868, 871, 860, 860, 91, 91,
|
| + /* 420 */ 92, 92, 92, 92, 114, 90, 90, 90, 90, 89,
|
| + /* 430 */ 89, 88, 88, 88, 87, 335, 311, 940, 841, 679,
|
| + /* 440 */ 713, 429, 835, 430, 251, 354, 250, 355, 288, 690,
|
| + /* 450 */ 691, 690, 691, 285, 941, 340, 971, 287, 210, 23,
|
| + /* 460 */ 174, 793, 832, 430, 353, 833, 10, 856, 856, 24,
|
| + /* 470 */ 942, 151, 753, 840, 840, 840, 794, 968, 1290, 321,
|
| + /* 480 */ 398, 1290, 356, 352, 754, 833, 49, 935, 93, 94,
|
| + /* 490 */ 84, 868, 871, 860, 860, 91, 91, 92, 92, 92,
|
| + /* 500 */ 92, 430, 90, 90, 90, 90, 89, 89, 88, 88,
|
| + /* 510 */ 88, 87, 335, 311, 376, 114, 907, 705, 430, 907,
|
| + /* 520 */ 328, 890, 114, 833, 10, 966, 430, 857, 857, 320,
|
| + /* 530 */ 189, 163, 832, 165, 430, 906, 344, 323, 906, 904,
|
| + /* 540 */ 833, 10, 965, 306, 856, 856, 187, 419, 833, 10,
|
| + /* 550 */ 220, 869, 872, 832, 222, 403, 833, 49, 1219, 793,
|
| + /* 560 */ 68, 937, 406, 245, 66, 93, 94, 84, 868, 871,
|
| + /* 570 */ 860, 860, 91, 91, 92, 92, 92, 92, 861, 90,
|
| + /* 580 */ 90, 90, 90, 89, 89, 88, 88, 88, 87, 335,
|
| + /* 590 */ 311, 404, 213, 762, 834, 345, 114, 940, 902, 368,
|
| + /* 600 */ 727, 5, 316, 192, 396, 772, 780, 269, 230, 242,
|
| + /* 610 */ 771, 244, 397, 164, 941, 385, 123, 347, 55, 355,
|
| + /* 620 */ 329, 856, 856, 728, 333, 332, 688, 968, 1291, 724,
|
| + /* 630 */ 942, 1291, 413, 214, 833, 9, 362, 286, 955, 115,
|
| + /* 640 */ 718, 311, 93, 94, 84, 868, 871, 860, 860, 91,
|
| + /* 650 */ 91, 92, 92, 92, 92, 430, 90, 90, 90, 90,
|
| + /* 660 */ 89, 89, 88, 88, 88, 87, 335, 912, 912, 1300,
|
| + /* 670 */ 1300, 758, 856, 856, 325, 966, 780, 833, 35, 747,
|
| + /* 680 */ 720, 334, 699, 700, 977, 652, 338, 243, 745, 920,
|
| + /* 690 */ 920, 369, 187, 93, 94, 84, 868, 871, 860, 860,
|
| + /* 700 */ 91, 91, 92, 92, 92, 92, 114, 90, 90, 90,
|
| + /* 710 */ 90, 89, 89, 88, 88, 88, 87, 335, 311, 430,
|
| + /* 720 */ 954, 430, 112, 310, 430, 693, 317, 698, 400, 430,
|
| + /* 730 */ 793, 359, 430, 1017, 430, 192, 430, 401, 780, 430,
|
| + /* 740 */ 360, 833, 36, 833, 12, 430, 833, 27, 316, 856,
|
| + /* 750 */ 856, 833, 37, 20, 833, 38, 833, 39, 833, 28,
|
| + /* 760 */ 72, 833, 29, 663, 664, 665, 264, 833, 40, 234,
|
| + /* 770 */ 93, 94, 84, 868, 871, 860, 860, 91, 91, 92,
|
| + /* 780 */ 92, 92, 92, 430, 90, 90, 90, 90, 89, 89,
|
| + /* 790 */ 88, 88, 88, 87, 335, 311, 430, 698, 430, 917,
|
| + /* 800 */ 147, 430, 165, 916, 275, 833, 41, 430, 780, 430,
|
| + /* 810 */ 21, 430, 259, 430, 262, 274, 430, 367, 833, 42,
|
| + /* 820 */ 833, 11, 430, 833, 43, 235, 856, 856, 793, 833,
|
| + /* 830 */ 99, 833, 44, 833, 45, 833, 32, 75, 833, 46,
|
| + /* 840 */ 305, 967, 257, 257, 833, 47, 311, 93, 94, 84,
|
| + /* 850 */ 868, 871, 860, 860, 91, 91, 92, 92, 92, 92,
|
| + /* 860 */ 430, 90, 90, 90, 90, 89, 89, 88, 88, 88,
|
| + /* 870 */ 87, 335, 430, 186, 185, 184, 238, 856, 856, 650,
|
| + /* 880 */ 2, 1064, 833, 33, 739, 217, 218, 257, 971, 257,
|
| + /* 890 */ 426, 317, 257, 774, 833, 117, 257, 311, 93, 94,
|
| + /* 900 */ 84, 868, 871, 860, 860, 91, 91, 92, 92, 92,
|
| + /* 910 */ 92, 430, 90, 90, 90, 90, 89, 89, 88, 88,
|
| + /* 920 */ 88, 87, 335, 430, 318, 124, 212, 163, 856, 856,
|
| + /* 930 */ 943, 900, 898, 833, 118, 759, 726, 725, 257, 755,
|
| + /* 940 */ 289, 289, 733, 734, 961, 833, 119, 682, 311, 93,
|
| + /* 950 */ 82, 84, 868, 871, 860, 860, 91, 91, 92, 92,
|
| + /* 960 */ 92, 92, 430, 90, 90, 90, 90, 89, 89, 88,
|
| + /* 970 */ 88, 88, 87, 335, 430, 716, 246, 322, 331, 856,
|
| + /* 980 */ 856, 256, 114, 357, 833, 53, 808, 913, 913, 932,
|
| + /* 990 */ 156, 416, 420, 424, 930, 809, 833, 34, 364, 311,
|
| + /* 1000 */ 253, 94, 84, 868, 871, 860, 860, 91, 91, 92,
|
| + /* 1010 */ 92, 92, 92, 430, 90, 90, 90, 90, 89, 89,
|
| + /* 1020 */ 88, 88, 88, 87, 335, 430, 114, 114, 114, 960,
|
| + /* 1030 */ 856, 856, 307, 258, 830, 833, 100, 191, 252, 377,
|
| + /* 1040 */ 267, 68, 197, 68, 261, 716, 769, 833, 50, 71,
|
| + /* 1050 */ 911, 911, 263, 84, 868, 871, 860, 860, 91, 91,
|
| + /* 1060 */ 92, 92, 92, 92, 430, 90, 90, 90, 90, 89,
|
| + /* 1070 */ 89, 88, 88, 88, 87, 335, 80, 425, 802, 3,
|
| + /* 1080 */ 1214, 191, 430, 265, 336, 336, 833, 101, 741, 80,
|
| + /* 1090 */ 425, 897, 3, 723, 722, 428, 721, 336, 336, 430,
|
| + /* 1100 */ 893, 270, 430, 197, 833, 102, 430, 800, 428, 430,
|
| + /* 1110 */ 695, 430, 843, 111, 414, 430, 784, 409, 430, 831,
|
| + /* 1120 */ 430, 833, 98, 123, 833, 116, 847, 414, 833, 49,
|
| + /* 1130 */ 779, 833, 113, 833, 106, 226, 123, 833, 105, 847,
|
| + /* 1140 */ 833, 103, 833, 104, 791, 411, 77, 78, 290, 412,
|
| + /* 1150 */ 430, 291, 114, 79, 432, 431, 389, 430, 835, 77,
|
| + /* 1160 */ 78, 897, 839, 408, 410, 430, 79, 432, 431, 372,
|
| + /* 1170 */ 703, 835, 833, 52, 430, 80, 425, 430, 3, 833,
|
| + /* 1180 */ 54, 772, 843, 336, 336, 684, 771, 833, 51, 840,
|
| + /* 1190 */ 840, 840, 842, 19, 428, 672, 833, 26, 671, 833,
|
| + /* 1200 */ 30, 673, 840, 840, 840, 842, 19, 207, 661, 278,
|
| + /* 1210 */ 304, 148, 280, 414, 282, 248, 358, 822, 382, 6,
|
| + /* 1220 */ 348, 161, 273, 80, 425, 847, 3, 934, 895, 720,
|
| + /* 1230 */ 894, 336, 336, 296, 157, 415, 241, 284, 674, 958,
|
| + /* 1240 */ 194, 953, 428, 951, 948, 77, 78, 777, 319, 56,
|
| + /* 1250 */ 59, 135, 79, 432, 431, 121, 66, 835, 146, 128,
|
| + /* 1260 */ 350, 414, 819, 130, 351, 131, 132, 133, 375, 173,
|
| + /* 1270 */ 107, 138, 149, 847, 365, 178, 62, 70, 425, 936,
|
| + /* 1280 */ 3, 827, 889, 371, 255, 336, 336, 792, 840, 840,
|
| + /* 1290 */ 840, 842, 19, 77, 78, 915, 428, 208, 179, 144,
|
| + /* 1300 */ 79, 432, 431, 373, 260, 835, 180, 326, 675, 181,
|
| + /* 1310 */ 308, 744, 388, 743, 731, 414, 718, 742, 730, 712,
|
| + /* 1320 */ 402, 309, 711, 272, 788, 65, 710, 847, 709, 277,
|
| + /* 1330 */ 193, 789, 787, 279, 876, 73, 840, 840, 840, 842,
|
| + /* 1340 */ 19, 786, 281, 418, 283, 422, 227, 77, 78, 330,
|
| + /* 1350 */ 228, 229, 96, 767, 79, 432, 431, 407, 67, 835,
|
| + /* 1360 */ 215, 292, 293, 405, 294, 303, 302, 301, 204, 299,
|
| + /* 1370 */ 295, 202, 676, 681, 7, 433, 669, 203, 205, 206,
|
| + /* 1380 */ 125, 110, 313, 434, 667, 666, 658, 168, 224, 237,
|
| + /* 1390 */ 840, 840, 840, 842, 19, 120, 656, 337, 236, 155,
|
| + /* 1400 */ 167, 341, 233, 314, 108, 905, 903, 826, 127, 126,
|
| + /* 1410 */ 756, 170, 129, 172, 247, 928, 134, 136, 171, 60,
|
| + /* 1420 */ 61, 123, 169, 137, 933, 175, 176, 927, 8, 13,
|
| + /* 1430 */ 177, 254, 918, 139, 191, 924, 140, 370, 678, 150,
|
| + /* 1440 */ 374, 182, 274, 268, 141, 122, 63, 14, 378, 15,
|
| + /* 1450 */ 383, 64, 225, 846, 845, 874, 16, 4, 729, 765,
|
| + /* 1460 */ 770, 162, 395, 209, 211, 142, 801, 878, 796, 312,
|
| + /* 1470 */ 71, 68, 875, 873, 939, 190, 417, 938, 17, 195,
|
| + /* 1480 */ 196, 152, 18, 975, 199, 976, 153, 198, 154, 421,
|
| + /* 1490 */ 877, 844, 696, 81, 200, 297, 343, 1019, 1018, 300,
|
| + /* 1500 */ 653,
|
| +};
|
| +static const YYCODETYPE yy_lookahead[] = {
|
| + /* 0 */ 19, 144, 145, 146, 147, 24, 1, 2, 27, 80,
|
| + /* 10 */ 81, 82, 83, 84, 85, 86, 87, 88, 89, 90,
|
| + /* 20 */ 91, 92, 93, 94, 95, 91, 92, 93, 94, 95,
|
| + /* 30 */ 19, 50, 51, 80, 81, 82, 83, 27, 85, 86,
|
| + /* 40 */ 87, 88, 89, 90, 91, 92, 93, 94, 95, 137,
|
| + /* 50 */ 177, 139, 71, 72, 73, 74, 75, 76, 77, 78,
|
| + /* 60 */ 79, 80, 81, 82, 83, 95, 85, 86, 87, 88,
|
| + /* 70 */ 89, 90, 91, 92, 93, 94, 95, 19, 97, 85,
|
| + /* 80 */ 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
|
| + /* 90 */ 152, 33, 212, 173, 27, 28, 223, 224, 225, 152,
|
| + /* 100 */ 42, 181, 152, 223, 224, 225, 95, 97, 50, 51,
|
| + /* 110 */ 99, 100, 101, 102, 103, 104, 105, 27, 28, 59,
|
| + /* 120 */ 223, 224, 225, 112, 174, 175, 66, 94, 95, 71,
|
| + /* 130 */ 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
|
| + /* 140 */ 82, 83, 195, 85, 86, 87, 88, 89, 90, 91,
|
| + /* 150 */ 92, 93, 94, 95, 19, 197, 89, 90, 220, 209,
|
| + /* 160 */ 210, 26, 119, 120, 97, 98, 208, 100, 108, 109,
|
| + /* 170 */ 110, 152, 157, 152, 107, 152, 109, 89, 90, 91,
|
| + /* 180 */ 92, 93, 94, 95, 163, 50, 51, 97, 98, 99,
|
| + /* 190 */ 55, 66, 102, 103, 104, 174, 175, 174, 175, 132,
|
| + /* 200 */ 133, 192, 193, 113, 66, 19, 71, 72, 73, 74,
|
| + /* 210 */ 75, 76, 77, 78, 79, 80, 81, 82, 83, 198,
|
| + /* 220 */ 85, 86, 87, 88, 89, 90, 91, 92, 93, 94,
|
| + /* 230 */ 95, 152, 209, 210, 148, 149, 50, 51, 100, 53,
|
| + /* 240 */ 154, 59, 156, 174, 229, 27, 28, 232, 163, 163,
|
| + /* 250 */ 22, 192, 193, 174, 175, 27, 28, 71, 72, 73,
|
| + /* 260 */ 74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
|
| + /* 270 */ 251, 85, 86, 87, 88, 89, 90, 91, 92, 93,
|
| + /* 280 */ 94, 95, 19, 198, 198, 152, 152, 24, 209, 210,
|
| + /* 290 */ 108, 109, 110, 196, 197, 27, 28, 69, 164, 165,
|
| + /* 300 */ 152, 119, 120, 27, 28, 208, 99, 27, 28, 102,
|
| + /* 310 */ 103, 104, 152, 50, 51, 97, 98, 89, 90, 185,
|
| + /* 320 */ 113, 187, 22, 177, 174, 97, 58, 27, 28, 101,
|
| + /* 330 */ 115, 245, 117, 118, 71, 72, 73, 74, 75, 76,
|
| + /* 340 */ 77, 78, 79, 80, 81, 82, 83, 11, 85, 86,
|
| + /* 350 */ 87, 88, 89, 90, 91, 92, 93, 94, 95, 19,
|
| + /* 360 */ 132, 133, 134, 23, 152, 97, 98, 91, 174, 223,
|
| + /* 370 */ 224, 225, 239, 97, 98, 187, 22, 97, 98, 27,
|
| + /* 380 */ 28, 27, 28, 152, 223, 224, 225, 239, 152, 163,
|
| + /* 390 */ 50, 51, 170, 171, 172, 59, 160, 97, 98, 239,
|
| + /* 400 */ 164, 165, 66, 242, 124, 174, 175, 195, 22, 23,
|
| + /* 410 */ 69, 71, 72, 73, 74, 75, 76, 77, 78, 79,
|
| + /* 420 */ 80, 81, 82, 83, 198, 85, 86, 87, 88, 89,
|
| + /* 430 */ 90, 91, 92, 93, 94, 95, 19, 12, 97, 21,
|
| + /* 440 */ 23, 152, 101, 152, 108, 109, 110, 221, 152, 97,
|
| + /* 450 */ 98, 97, 98, 152, 29, 243, 70, 226, 23, 233,
|
| + /* 460 */ 26, 26, 152, 152, 238, 174, 175, 50, 51, 22,
|
| + /* 470 */ 45, 24, 47, 132, 133, 134, 124, 22, 23, 188,
|
| + /* 480 */ 163, 26, 152, 65, 59, 174, 175, 163, 71, 72,
|
| + /* 490 */ 73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
|
| + /* 500 */ 83, 152, 85, 86, 87, 88, 89, 90, 91, 92,
|
| + /* 510 */ 93, 94, 95, 19, 19, 198, 152, 23, 152, 152,
|
| + /* 520 */ 209, 103, 198, 174, 175, 70, 152, 50, 51, 219,
|
| + /* 530 */ 213, 214, 152, 98, 152, 171, 172, 188, 171, 172,
|
| + /* 540 */ 174, 175, 248, 249, 50, 51, 51, 251, 174, 175,
|
| + /* 550 */ 220, 74, 75, 152, 188, 152, 174, 175, 140, 124,
|
| + /* 560 */ 26, 163, 188, 16, 130, 71, 72, 73, 74, 75,
|
| + /* 570 */ 76, 77, 78, 79, 80, 81, 82, 83, 101, 85,
|
| + /* 580 */ 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
|
| + /* 590 */ 19, 209, 196, 197, 23, 231, 198, 12, 231, 219,
|
| + /* 600 */ 37, 22, 107, 24, 208, 116, 27, 112, 201, 62,
|
| + /* 610 */ 121, 64, 152, 152, 29, 52, 66, 221, 211, 221,
|
| + /* 620 */ 219, 50, 51, 60, 89, 90, 152, 22, 23, 183,
|
| + /* 630 */ 45, 26, 47, 22, 174, 175, 238, 152, 164, 165,
|
| + /* 640 */ 106, 19, 71, 72, 73, 74, 75, 76, 77, 78,
|
| + /* 650 */ 79, 80, 81, 82, 83, 152, 85, 86, 87, 88,
|
| + /* 660 */ 89, 90, 91, 92, 93, 94, 95, 132, 133, 119,
|
| + /* 670 */ 120, 163, 50, 51, 111, 70, 97, 174, 175, 181,
|
| + /* 680 */ 182, 170, 171, 172, 0, 1, 2, 140, 190, 108,
|
| + /* 690 */ 109, 110, 51, 71, 72, 73, 74, 75, 76, 77,
|
| + /* 700 */ 78, 79, 80, 81, 82, 83, 198, 85, 86, 87,
|
| + /* 710 */ 88, 89, 90, 91, 92, 93, 94, 95, 19, 152,
|
| + /* 720 */ 152, 152, 22, 166, 152, 168, 169, 27, 19, 152,
|
| + /* 730 */ 26, 19, 152, 122, 152, 24, 152, 28, 27, 152,
|
| + /* 740 */ 28, 174, 175, 174, 175, 152, 174, 175, 107, 50,
|
| + /* 750 */ 51, 174, 175, 22, 174, 175, 174, 175, 174, 175,
|
| + /* 760 */ 138, 174, 175, 7, 8, 9, 16, 174, 175, 152,
|
| + /* 770 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
|
| + /* 780 */ 81, 82, 83, 152, 85, 86, 87, 88, 89, 90,
|
| + /* 790 */ 91, 92, 93, 94, 95, 19, 152, 97, 152, 31,
|
| + /* 800 */ 24, 152, 98, 35, 101, 174, 175, 152, 97, 152,
|
| + /* 810 */ 79, 152, 62, 152, 64, 112, 152, 49, 174, 175,
|
| + /* 820 */ 174, 175, 152, 174, 175, 152, 50, 51, 124, 174,
|
| + /* 830 */ 175, 174, 175, 174, 175, 174, 175, 138, 174, 175,
|
| + /* 840 */ 22, 23, 152, 152, 174, 175, 19, 71, 72, 73,
|
| + /* 850 */ 74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
|
| + /* 860 */ 152, 85, 86, 87, 88, 89, 90, 91, 92, 93,
|
| + /* 870 */ 94, 95, 152, 108, 109, 110, 152, 50, 51, 146,
|
| + /* 880 */ 147, 23, 174, 175, 26, 195, 195, 152, 70, 152,
|
| + /* 890 */ 168, 169, 152, 26, 174, 175, 152, 19, 71, 72,
|
| + /* 900 */ 73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
|
| + /* 910 */ 83, 152, 85, 86, 87, 88, 89, 90, 91, 92,
|
| + /* 920 */ 93, 94, 95, 152, 246, 247, 213, 214, 50, 51,
|
| + /* 930 */ 195, 152, 195, 174, 175, 195, 100, 101, 152, 195,
|
| + /* 940 */ 152, 152, 7, 8, 152, 174, 175, 163, 19, 71,
|
| + /* 950 */ 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
|
| + /* 960 */ 82, 83, 152, 85, 86, 87, 88, 89, 90, 91,
|
| + /* 970 */ 92, 93, 94, 95, 152, 27, 152, 189, 189, 50,
|
| + /* 980 */ 51, 195, 198, 152, 174, 175, 33, 132, 133, 152,
|
| + /* 990 */ 123, 163, 163, 163, 152, 42, 174, 175, 152, 19,
|
| + /* 1000 */ 152, 72, 73, 74, 75, 76, 77, 78, 79, 80,
|
| + /* 1010 */ 81, 82, 83, 152, 85, 86, 87, 88, 89, 90,
|
| + /* 1020 */ 91, 92, 93, 94, 95, 152, 198, 198, 198, 23,
|
| + /* 1030 */ 50, 51, 26, 152, 23, 174, 175, 26, 23, 23,
|
| + /* 1040 */ 23, 26, 26, 26, 152, 97, 23, 174, 175, 26,
|
| + /* 1050 */ 132, 133, 152, 73, 74, 75, 76, 77, 78, 79,
|
| + /* 1060 */ 80, 81, 82, 83, 152, 85, 86, 87, 88, 89,
|
| + /* 1070 */ 90, 91, 92, 93, 94, 95, 19, 20, 23, 22,
|
| + /* 1080 */ 23, 26, 152, 152, 27, 28, 174, 175, 152, 19,
|
| + /* 1090 */ 20, 27, 22, 183, 183, 38, 152, 27, 28, 152,
|
| + /* 1100 */ 23, 152, 152, 26, 174, 175, 152, 152, 38, 152,
|
| + /* 1110 */ 23, 152, 27, 26, 57, 152, 215, 163, 152, 152,
|
| + /* 1120 */ 152, 174, 175, 66, 174, 175, 69, 57, 174, 175,
|
| + /* 1130 */ 152, 174, 175, 174, 175, 212, 66, 174, 175, 69,
|
| + /* 1140 */ 174, 175, 174, 175, 152, 152, 89, 90, 152, 193,
|
| + /* 1150 */ 152, 152, 198, 96, 97, 98, 91, 152, 101, 89,
|
| + /* 1160 */ 90, 97, 152, 209, 210, 152, 96, 97, 98, 235,
|
| + /* 1170 */ 152, 101, 174, 175, 152, 19, 20, 152, 22, 174,
|
| + /* 1180 */ 175, 116, 97, 27, 28, 152, 121, 174, 175, 132,
|
| + /* 1190 */ 133, 134, 135, 136, 38, 152, 174, 175, 152, 174,
|
| + /* 1200 */ 175, 152, 132, 133, 134, 135, 136, 234, 152, 212,
|
| + /* 1210 */ 150, 199, 212, 57, 212, 240, 240, 203, 178, 200,
|
| + /* 1220 */ 216, 186, 177, 19, 20, 69, 22, 203, 177, 182,
|
| + /* 1230 */ 177, 27, 28, 202, 200, 228, 216, 216, 155, 39,
|
| + /* 1240 */ 122, 159, 38, 159, 41, 89, 90, 91, 159, 241,
|
| + /* 1250 */ 241, 22, 96, 97, 98, 71, 130, 101, 222, 191,
|
| + /* 1260 */ 18, 57, 203, 194, 159, 194, 194, 194, 18, 158,
|
| + /* 1270 */ 244, 191, 222, 69, 159, 158, 137, 19, 20, 203,
|
| + /* 1280 */ 22, 191, 203, 46, 236, 27, 28, 159, 132, 133,
|
| + /* 1290 */ 134, 135, 136, 89, 90, 237, 38, 159, 158, 22,
|
| + /* 1300 */ 96, 97, 98, 179, 159, 101, 158, 48, 159, 158,
|
| + /* 1310 */ 179, 176, 107, 176, 184, 57, 106, 176, 184, 176,
|
| + /* 1320 */ 125, 179, 178, 176, 218, 107, 176, 69, 176, 217,
|
| + /* 1330 */ 159, 218, 218, 217, 159, 137, 132, 133, 134, 135,
|
| + /* 1340 */ 136, 218, 217, 179, 217, 179, 227, 89, 90, 95,
|
| + /* 1350 */ 230, 230, 129, 207, 96, 97, 98, 126, 128, 101,
|
| + /* 1360 */ 5, 206, 205, 127, 204, 10, 11, 12, 13, 14,
|
| + /* 1370 */ 203, 25, 17, 162, 26, 161, 13, 153, 153, 6,
|
| + /* 1380 */ 247, 180, 250, 151, 151, 151, 151, 32, 180, 34,
|
| + /* 1390 */ 132, 133, 134, 135, 136, 167, 4, 3, 43, 22,
|
| + /* 1400 */ 15, 68, 142, 250, 16, 23, 23, 120, 111, 131,
|
| + /* 1410 */ 20, 56, 123, 125, 16, 1, 123, 131, 63, 79,
|
| + /* 1420 */ 79, 66, 67, 111, 28, 36, 122, 1, 5, 22,
|
| + /* 1430 */ 107, 140, 54, 54, 26, 61, 107, 44, 20, 24,
|
| + /* 1440 */ 19, 105, 112, 23, 22, 40, 22, 22, 53, 22,
|
| + /* 1450 */ 53, 22, 53, 23, 23, 23, 22, 22, 30, 116,
|
| + /* 1460 */ 23, 122, 26, 23, 23, 22, 28, 11, 124, 114,
|
| + /* 1470 */ 26, 26, 23, 23, 23, 36, 24, 23, 36, 26,
|
| + /* 1480 */ 22, 22, 36, 23, 122, 23, 22, 26, 22, 24,
|
| + /* 1490 */ 23, 23, 23, 22, 122, 23, 141, 122, 122, 15,
|
| + /* 1500 */ 1,
|
| +};
|
| +#define YY_SHIFT_USE_DFLT (-89)
|
| +#define YY_SHIFT_COUNT (435)
|
| +#define YY_SHIFT_MIN (-88)
|
| +#define YY_SHIFT_MAX (1499)
|
| +static const short yy_shift_ofst[] = {
|
| + /* 0 */ 5, 1057, 1355, 1070, 1204, 1204, 1204, 90, 60, -19,
|
| + /* 10 */ 58, 58, 186, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
|
| + /* 20 */ 67, 67, 182, 336, 218, 550, 135, 263, 340, 417,
|
| + /* 30 */ 494, 571, 622, 699, 776, 827, 827, 827, 827, 827,
|
| + /* 40 */ 827, 827, 827, 827, 827, 827, 827, 827, 827, 827,
|
| + /* 50 */ 878, 827, 929, 980, 980, 1156, 1204, 1204, 1204, 1204,
|
| + /* 60 */ 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
|
| + /* 70 */ 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
|
| + /* 80 */ 1204, 1204, 1204, 1204, 1258, 1204, 1204, 1204, 1204, 1204,
|
| + /* 90 */ 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, -71, -47,
|
| + /* 100 */ -47, -47, -47, -47, -6, 88, -66, 218, 218, 418,
|
| + /* 110 */ 495, 535, 535, 33, 43, 10, -30, -89, -89, -89,
|
| + /* 120 */ 11, 425, 425, 268, 455, 605, 218, 218, 218, 218,
|
| + /* 130 */ 218, 218, 218, 218, 218, 218, 218, 218, 218, 218,
|
| + /* 140 */ 218, 218, 218, 218, 218, 684, 138, 10, 43, 125,
|
| + /* 150 */ 125, 125, 125, 125, 125, -89, -89, -89, 228, 341,
|
| + /* 160 */ 341, 207, 276, 300, 280, 352, 354, 218, 218, 218,
|
| + /* 170 */ 218, 218, 218, 218, 218, 218, 218, 218, 218, 218,
|
| + /* 180 */ 218, 218, 218, 218, 563, 563, 563, 218, 218, 435,
|
| + /* 190 */ 218, 218, 218, 579, 218, 218, 585, 218, 218, 218,
|
| + /* 200 */ 218, 218, 218, 218, 218, 218, 218, 581, 768, 711,
|
| + /* 210 */ 711, 711, 704, 215, 1065, 756, 434, 709, 709, 712,
|
| + /* 220 */ 434, 712, 534, 858, 641, 953, 709, -88, 953, 953,
|
| + /* 230 */ 867, 489, 447, 1200, 1118, 1118, 1203, 1203, 1118, 1229,
|
| + /* 240 */ 1184, 1126, 1242, 1242, 1242, 1242, 1118, 1250, 1126, 1229,
|
| + /* 250 */ 1184, 1184, 1126, 1118, 1250, 1139, 1237, 1118, 1118, 1250,
|
| + /* 260 */ 1277, 1118, 1250, 1118, 1250, 1277, 1205, 1205, 1205, 1259,
|
| + /* 270 */ 1277, 1205, 1210, 1205, 1259, 1205, 1205, 1195, 1218, 1195,
|
| + /* 280 */ 1218, 1195, 1218, 1195, 1218, 1118, 1118, 1198, 1277, 1254,
|
| + /* 290 */ 1254, 1277, 1223, 1231, 1230, 1236, 1126, 1346, 1348, 1363,
|
| + /* 300 */ 1363, 1373, 1373, 1373, 1373, -89, -89, -89, -89, -89,
|
| + /* 310 */ -89, 477, 547, 386, 818, 750, 765, 700, 1006, 731,
|
| + /* 320 */ 1011, 1015, 1016, 1017, 948, 836, 935, 703, 1023, 1055,
|
| + /* 330 */ 1064, 1077, 855, 918, 1087, 1085, 611, 1392, 1394, 1377,
|
| + /* 340 */ 1260, 1385, 1333, 1388, 1382, 1383, 1287, 1278, 1297, 1289,
|
| + /* 350 */ 1390, 1288, 1398, 1414, 1293, 1286, 1340, 1341, 1312, 1396,
|
| + /* 360 */ 1389, 1304, 1426, 1423, 1407, 1323, 1291, 1378, 1408, 1379,
|
| + /* 370 */ 1374, 1393, 1329, 1415, 1418, 1421, 1330, 1336, 1422, 1395,
|
| + /* 380 */ 1424, 1425, 1420, 1427, 1397, 1428, 1429, 1399, 1405, 1430,
|
| + /* 390 */ 1431, 1432, 1343, 1434, 1437, 1435, 1436, 1339, 1440, 1441,
|
| + /* 400 */ 1438, 1439, 1443, 1344, 1444, 1442, 1445, 1446, 1444, 1449,
|
| + /* 410 */ 1450, 1451, 1453, 1454, 1458, 1456, 1460, 1459, 1452, 1461,
|
| + /* 420 */ 1462, 1464, 1465, 1461, 1467, 1466, 1468, 1469, 1471, 1362,
|
| + /* 430 */ 1372, 1375, 1376, 1472, 1484, 1499,
|
| +};
|
| +#define YY_REDUCE_USE_DFLT (-144)
|
| +#define YY_REDUCE_COUNT (310)
|
| +#define YY_REDUCE_MIN (-143)
|
| +#define YY_REDUCE_MAX (1235)
|
| +static const short yy_reduce_ofst[] = {
|
| + /* 0 */ -143, 954, 86, 21, -50, 23, 79, 134, 226, -120,
|
| + /* 10 */ -127, 146, 161, 291, 349, 366, 311, 382, 374, 231,
|
| + /* 20 */ 364, 367, 396, 398, 236, 317, -103, -103, -103, -103,
|
| + /* 30 */ -103, -103, -103, -103, -103, -103, -103, -103, -103, -103,
|
| + /* 40 */ -103, -103, -103, -103, -103, -103, -103, -103, -103, -103,
|
| + /* 50 */ -103, -103, -103, -103, -103, 460, 503, 567, 569, 572,
|
| + /* 60 */ 577, 580, 582, 584, 587, 593, 631, 644, 646, 649,
|
| + /* 70 */ 655, 657, 659, 661, 664, 670, 708, 720, 759, 771,
|
| + /* 80 */ 810, 822, 861, 873, 912, 930, 947, 950, 957, 959,
|
| + /* 90 */ 963, 966, 968, 998, 1005, 1013, 1022, 1025, -103, -103,
|
| + /* 100 */ -103, -103, -103, -103, -103, -103, -103, 474, 212, 15,
|
| + /* 110 */ 498, 222, 511, -103, 97, 557, -103, -103, -103, -103,
|
| + /* 120 */ -80, 9, 59, 19, 294, 294, -53, -62, 690, 691,
|
| + /* 130 */ 735, 737, 740, 744, 133, 310, 148, 330, 160, 380,
|
| + /* 140 */ 786, 788, 401, 296, 789, 733, 85, 722, -42, 324,
|
| + /* 150 */ 508, 784, 828, 829, 830, 678, 713, 407, 69, 150,
|
| + /* 160 */ 194, 188, 289, 301, 403, 461, 485, 568, 617, 673,
|
| + /* 170 */ 724, 779, 792, 824, 831, 837, 842, 846, 848, 881,
|
| + /* 180 */ 892, 900, 931, 936, 446, 910, 911, 944, 949, 901,
|
| + /* 190 */ 955, 967, 978, 923, 992, 993, 956, 996, 999, 1010,
|
| + /* 200 */ 289, 1018, 1033, 1043, 1046, 1049, 1056, 934, 973, 997,
|
| + /* 210 */ 1000, 1002, 901, 1012, 1019, 1060, 1014, 1004, 1020, 975,
|
| + /* 220 */ 1024, 976, 1040, 1035, 1047, 1045, 1021, 1007, 1051, 1053,
|
| + /* 230 */ 1031, 1034, 1083, 1026, 1082, 1084, 1008, 1009, 1089, 1036,
|
| + /* 240 */ 1068, 1059, 1069, 1071, 1072, 1073, 1105, 1111, 1076, 1050,
|
| + /* 250 */ 1080, 1090, 1079, 1115, 1117, 1058, 1048, 1128, 1138, 1140,
|
| + /* 260 */ 1124, 1145, 1148, 1149, 1151, 1131, 1135, 1137, 1141, 1130,
|
| + /* 270 */ 1142, 1143, 1144, 1147, 1134, 1150, 1152, 1106, 1112, 1113,
|
| + /* 280 */ 1116, 1114, 1125, 1123, 1127, 1171, 1175, 1119, 1164, 1120,
|
| + /* 290 */ 1121, 1166, 1146, 1155, 1157, 1160, 1167, 1211, 1214, 1224,
|
| + /* 300 */ 1225, 1232, 1233, 1234, 1235, 1132, 1153, 1133, 1201, 1208,
|
| + /* 310 */ 1228,
|
| +};
|
| +static const YYACTIONTYPE yy_default[] = {
|
| + /* 0 */ 982, 1300, 1300, 1300, 1214, 1214, 1214, 1305, 1300, 1109,
|
| + /* 10 */ 1138, 1138, 1274, 1305, 1305, 1305, 1305, 1305, 1305, 1212,
|
| + /* 20 */ 1305, 1305, 1305, 1300, 1305, 1113, 1144, 1305, 1305, 1305,
|
| + /* 30 */ 1305, 1305, 1305, 1305, 1305, 1273, 1275, 1152, 1151, 1254,
|
| + /* 40 */ 1125, 1149, 1142, 1146, 1215, 1208, 1209, 1207, 1211, 1216,
|
| + /* 50 */ 1305, 1145, 1177, 1192, 1176, 1305, 1305, 1305, 1305, 1305,
|
| + /* 60 */ 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
|
| + /* 70 */ 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
|
| + /* 80 */ 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
|
| + /* 90 */ 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1186, 1191,
|
| + /* 100 */ 1198, 1190, 1187, 1179, 1178, 1180, 1181, 1305, 1305, 1008,
|
| + /* 110 */ 1074, 1305, 1305, 1182, 1305, 1020, 1183, 1195, 1194, 1193,
|
| + /* 120 */ 1015, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
|
| + /* 130 */ 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
|
| + /* 140 */ 1305, 1305, 1305, 1305, 1305, 982, 1300, 1305, 1305, 1300,
|
| + /* 150 */ 1300, 1300, 1300, 1300, 1300, 1292, 1113, 1103, 1305, 1305,
|
| + /* 160 */ 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1280, 1278,
|
| + /* 170 */ 1305, 1227, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
|
| + /* 180 */ 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
|
| + /* 190 */ 1305, 1305, 1305, 1109, 1305, 1305, 1305, 1305, 1305, 1305,
|
| + /* 200 */ 1305, 1305, 1305, 1305, 1305, 1305, 988, 1305, 1247, 1109,
|
| + /* 210 */ 1109, 1109, 1111, 1089, 1101, 990, 1148, 1127, 1127, 1259,
|
| + /* 220 */ 1148, 1259, 1045, 1068, 1042, 1138, 1127, 1210, 1138, 1138,
|
| + /* 230 */ 1110, 1101, 1305, 1285, 1118, 1118, 1277, 1277, 1118, 1157,
|
| + /* 240 */ 1078, 1148, 1085, 1085, 1085, 1085, 1118, 1005, 1148, 1157,
|
| + /* 250 */ 1078, 1078, 1148, 1118, 1005, 1253, 1251, 1118, 1118, 1005,
|
| + /* 260 */ 1220, 1118, 1005, 1118, 1005, 1220, 1076, 1076, 1076, 1060,
|
| + /* 270 */ 1220, 1076, 1045, 1076, 1060, 1076, 1076, 1131, 1126, 1131,
|
| + /* 280 */ 1126, 1131, 1126, 1131, 1126, 1118, 1118, 1305, 1220, 1224,
|
| + /* 290 */ 1224, 1220, 1143, 1132, 1141, 1139, 1148, 1011, 1063, 998,
|
| + /* 300 */ 998, 987, 987, 987, 987, 1297, 1297, 1292, 1047, 1047,
|
| + /* 310 */ 1030, 1305, 1305, 1305, 1305, 1305, 1305, 1022, 1305, 1229,
|
| + /* 320 */ 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
|
| + /* 330 */ 1305, 1305, 1305, 1305, 1305, 1305, 1164, 1305, 983, 1287,
|
| + /* 340 */ 1305, 1305, 1284, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
|
| + /* 350 */ 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
|
| + /* 360 */ 1305, 1257, 1305, 1305, 1305, 1305, 1305, 1305, 1250, 1249,
|
| + /* 370 */ 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
|
| + /* 380 */ 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
|
| + /* 390 */ 1305, 1305, 1092, 1305, 1305, 1305, 1096, 1305, 1305, 1305,
|
| + /* 400 */ 1305, 1305, 1305, 1305, 1140, 1305, 1133, 1305, 1213, 1305,
|
| + /* 410 */ 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1302,
|
| + /* 420 */ 1305, 1305, 1305, 1301, 1305, 1305, 1305, 1305, 1305, 1166,
|
| + /* 430 */ 1305, 1165, 1169, 1305, 996, 1305,
|
| +};
|
| +/********** End of lemon-generated parsing tables *****************************/
|
| +
|
| +/* The next table maps tokens (terminal symbols) into fallback tokens.
|
| +** If a construct like the following:
|
| +**
|
| +** %fallback ID X Y Z.
|
| +**
|
| +** appears in the grammar, then ID becomes a fallback token for X, Y,
|
| +** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
|
| +** but it does not parse, the type of the token is changed to ID and
|
| +** the parse is retried before an error is thrown.
|
| +**
|
| +** This feature can be used, for example, to cause some keywords in a language
|
| +** to revert to identifiers if they keyword does not apply in the context where
|
| +** it appears.
|
| +*/
|
| +#ifdef YYFALLBACK
|
| +static const YYCODETYPE yyFallback[] = {
|
| + 0, /* $ => nothing */
|
| + 0, /* SEMI => nothing */
|
| + 27, /* EXPLAIN => ID */
|
| + 27, /* QUERY => ID */
|
| + 27, /* PLAN => ID */
|
| + 27, /* BEGIN => ID */
|
| + 0, /* TRANSACTION => nothing */
|
| + 27, /* DEFERRED => ID */
|
| + 27, /* IMMEDIATE => ID */
|
| + 27, /* EXCLUSIVE => ID */
|
| + 0, /* COMMIT => nothing */
|
| + 27, /* END => ID */
|
| + 27, /* ROLLBACK => ID */
|
| + 27, /* SAVEPOINT => ID */
|
| + 27, /* RELEASE => ID */
|
| + 0, /* TO => nothing */
|
| + 0, /* TABLE => nothing */
|
| + 0, /* CREATE => nothing */
|
| + 27, /* IF => ID */
|
| + 0, /* NOT => nothing */
|
| + 0, /* EXISTS => nothing */
|
| + 27, /* TEMP => ID */
|
| + 0, /* LP => nothing */
|
| + 0, /* RP => nothing */
|
| + 0, /* AS => nothing */
|
| + 27, /* WITHOUT => ID */
|
| + 0, /* COMMA => nothing */
|
| + 0, /* ID => nothing */
|
| + 0, /* INDEXED => nothing */
|
| + 27, /* ABORT => ID */
|
| + 27, /* ACTION => ID */
|
| + 27, /* AFTER => ID */
|
| + 27, /* ANALYZE => ID */
|
| + 27, /* ASC => ID */
|
| + 27, /* ATTACH => ID */
|
| + 27, /* BEFORE => ID */
|
| + 27, /* BY => ID */
|
| + 27, /* CASCADE => ID */
|
| + 27, /* CAST => ID */
|
| + 27, /* COLUMNKW => ID */
|
| + 27, /* CONFLICT => ID */
|
| + 27, /* DATABASE => ID */
|
| + 27, /* DESC => ID */
|
| + 27, /* DETACH => ID */
|
| + 27, /* EACH => ID */
|
| + 27, /* FAIL => ID */
|
| + 27, /* FOR => ID */
|
| + 27, /* IGNORE => ID */
|
| + 27, /* INITIALLY => ID */
|
| + 27, /* INSTEAD => ID */
|
| + 27, /* LIKE_KW => ID */
|
| + 27, /* MATCH => ID */
|
| + 27, /* NO => ID */
|
| + 27, /* KEY => ID */
|
| + 27, /* OF => ID */
|
| + 27, /* OFFSET => ID */
|
| + 27, /* PRAGMA => ID */
|
| + 27, /* RAISE => ID */
|
| + 27, /* RECURSIVE => ID */
|
| + 27, /* REPLACE => ID */
|
| + 27, /* RESTRICT => ID */
|
| + 27, /* ROW => ID */
|
| + 27, /* TRIGGER => ID */
|
| + 27, /* VACUUM => ID */
|
| + 27, /* VIEW => ID */
|
| + 27, /* VIRTUAL => ID */
|
| + 27, /* WITH => ID */
|
| + 27, /* REINDEX => ID */
|
| + 27, /* RENAME => ID */
|
| + 27, /* CTIME_KW => ID */
|
| +};
|
| +#endif /* YYFALLBACK */
|
| +
|
| +/* The following structure represents a single element of the
|
| +** parser's stack. Information stored includes:
|
| +**
|
| +** + The state number for the parser at this level of the stack.
|
| +**
|
| +** + The value of the token stored at this level of the stack.
|
| +** (In other words, the "major" token.)
|
| +**
|
| +** + The semantic value stored at this level of the stack. This is
|
| +** the information used by the action routines in the grammar.
|
| +** It is sometimes called the "minor" token.
|
| +**
|
| +** After the "shift" half of a SHIFTREDUCE action, the stateno field
|
| +** actually contains the reduce action for the second half of the
|
| +** SHIFTREDUCE.
|
| +*/
|
| +struct yyStackEntry {
|
| + YYACTIONTYPE stateno; /* The state-number, or reduce action in SHIFTREDUCE */
|
| + YYCODETYPE major; /* The major token value. This is the code
|
| + ** number for the token at this stack level */
|
| + YYMINORTYPE minor; /* The user-supplied minor token value. This
|
| + ** is the value of the token */
|
| +};
|
| +typedef struct yyStackEntry yyStackEntry;
|
| +
|
| +/* The state of the parser is completely contained in an instance of
|
| +** the following structure */
|
| +struct yyParser {
|
| + int yyidx; /* Index of top element in stack */
|
| +#ifdef YYTRACKMAXSTACKDEPTH
|
| + int yyidxMax; /* Maximum value of yyidx */
|
| +#endif
|
| + int yyerrcnt; /* Shifts left before out of the error */
|
| + sqlite3ParserARG_SDECL /* A place to hold %extra_argument */
|
| +#if YYSTACKDEPTH<=0
|
| + int yystksz; /* Current side of the stack */
|
| + yyStackEntry *yystack; /* The parser's stack */
|
| +#else
|
| + yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */
|
| +#endif
|
| +};
|
| +typedef struct yyParser yyParser;
|
| +
|
| +#ifndef NDEBUG
|
| +/* #include <stdio.h> */
|
| +static FILE *yyTraceFILE = 0;
|
| +static char *yyTracePrompt = 0;
|
| +#endif /* NDEBUG */
|
| +
|
| +#ifndef NDEBUG
|
| +/*
|
| +** Turn parser tracing on by giving a stream to which to write the trace
|
| +** and a prompt to preface each trace message. Tracing is turned off
|
| +** by making either argument NULL
|
| +**
|
| +** Inputs:
|
| +** <ul>
|
| +** <li> A FILE* to which trace output should be written.
|
| +** If NULL, then tracing is turned off.
|
| +** <li> A prefix string written at the beginning of every
|
| +** line of trace output. If NULL, then tracing is
|
| +** turned off.
|
| +** </ul>
|
| +**
|
| +** Outputs:
|
| +** None.
|
| +*/
|
| +SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
|
| + yyTraceFILE = TraceFILE;
|
| + yyTracePrompt = zTracePrompt;
|
| + if( yyTraceFILE==0 ) yyTracePrompt = 0;
|
| + else if( yyTracePrompt==0 ) yyTraceFILE = 0;
|
| +}
|
| +#endif /* NDEBUG */
|
| +
|
| +#ifndef NDEBUG
|
| +/* For tracing shifts, the names of all terminals and nonterminals
|
| +** are required. The following table supplies these names */
|
| +static const char *const yyTokenName[] = {
|
| + "$", "SEMI", "EXPLAIN", "QUERY",
|
| + "PLAN", "BEGIN", "TRANSACTION", "DEFERRED",
|
| + "IMMEDIATE", "EXCLUSIVE", "COMMIT", "END",
|
| + "ROLLBACK", "SAVEPOINT", "RELEASE", "TO",
|
| + "TABLE", "CREATE", "IF", "NOT",
|
| + "EXISTS", "TEMP", "LP", "RP",
|
| + "AS", "WITHOUT", "COMMA", "ID",
|
| + "INDEXED", "ABORT", "ACTION", "AFTER",
|
| + "ANALYZE", "ASC", "ATTACH", "BEFORE",
|
| + "BY", "CASCADE", "CAST", "COLUMNKW",
|
| + "CONFLICT", "DATABASE", "DESC", "DETACH",
|
| + "EACH", "FAIL", "FOR", "IGNORE",
|
| + "INITIALLY", "INSTEAD", "LIKE_KW", "MATCH",
|
| + "NO", "KEY", "OF", "OFFSET",
|
| + "PRAGMA", "RAISE", "RECURSIVE", "REPLACE",
|
| + "RESTRICT", "ROW", "TRIGGER", "VACUUM",
|
| + "VIEW", "VIRTUAL", "WITH", "REINDEX",
|
| + "RENAME", "CTIME_KW", "ANY", "OR",
|
| + "AND", "IS", "BETWEEN", "IN",
|
| + "ISNULL", "NOTNULL", "NE", "EQ",
|
| + "GT", "LE", "LT", "GE",
|
| + "ESCAPE", "BITAND", "BITOR", "LSHIFT",
|
| + "RSHIFT", "PLUS", "MINUS", "STAR",
|
| + "SLASH", "REM", "CONCAT", "COLLATE",
|
| + "BITNOT", "STRING", "JOIN_KW", "CONSTRAINT",
|
| + "DEFAULT", "NULL", "PRIMARY", "UNIQUE",
|
| + "CHECK", "REFERENCES", "AUTOINCR", "ON",
|
| + "INSERT", "DELETE", "UPDATE", "SET",
|
| + "DEFERRABLE", "FOREIGN", "DROP", "UNION",
|
| + "ALL", "EXCEPT", "INTERSECT", "SELECT",
|
| + "VALUES", "DISTINCT", "DOT", "FROM",
|
| + "JOIN", "USING", "ORDER", "GROUP",
|
| + "HAVING", "LIMIT", "WHERE", "INTO",
|
| + "INTEGER", "FLOAT", "BLOB", "VARIABLE",
|
| + "CASE", "WHEN", "THEN", "ELSE",
|
| + "INDEX", "ALTER", "ADD", "error",
|
| + "input", "cmdlist", "ecmd", "explain",
|
| + "cmdx", "cmd", "transtype", "trans_opt",
|
| + "nm", "savepoint_opt", "create_table", "create_table_args",
|
| + "createkw", "temp", "ifnotexists", "dbnm",
|
| + "columnlist", "conslist_opt", "table_options", "select",
|
| + "column", "columnid", "type", "carglist",
|
| + "typetoken", "typename", "signed", "plus_num",
|
| + "minus_num", "ccons", "term", "expr",
|
| + "onconf", "sortorder", "autoinc", "eidlist_opt",
|
| + "refargs", "defer_subclause", "refarg", "refact",
|
| + "init_deferred_pred_opt", "conslist", "tconscomma", "tcons",
|
| + "sortlist", "eidlist", "defer_subclause_opt", "orconf",
|
| + "resolvetype", "raisetype", "ifexists", "fullname",
|
| + "selectnowith", "oneselect", "with", "multiselect_op",
|
| + "distinct", "selcollist", "from", "where_opt",
|
| + "groupby_opt", "having_opt", "orderby_opt", "limit_opt",
|
| + "values", "nexprlist", "exprlist", "sclp",
|
| + "as", "seltablist", "stl_prefix", "joinop",
|
| + "indexed_opt", "on_opt", "using_opt", "idlist",
|
| + "setlist", "insert_cmd", "idlist_opt", "likeop",
|
| + "between_op", "in_op", "case_operand", "case_exprlist",
|
| + "case_else", "uniqueflag", "collate", "nmnum",
|
| + "trigger_decl", "trigger_cmd_list", "trigger_time", "trigger_event",
|
| + "foreach_clause", "when_clause", "trigger_cmd", "trnm",
|
| + "tridxby", "database_kw_opt", "key_opt", "add_column_fullname",
|
| + "kwcolumn_opt", "create_vtab", "vtabarglist", "vtabarg",
|
| + "vtabargtoken", "lp", "anylist", "wqlist",
|
| +};
|
| +#endif /* NDEBUG */
|
| +
|
| +#ifndef NDEBUG
|
| +/* For tracing reduce actions, the names of all rules are required.
|
| +*/
|
| +static const char *const yyRuleName[] = {
|
| + /* 0 */ "input ::= cmdlist",
|
| + /* 1 */ "cmdlist ::= cmdlist ecmd",
|
| + /* 2 */ "cmdlist ::= ecmd",
|
| + /* 3 */ "ecmd ::= SEMI",
|
| + /* 4 */ "ecmd ::= explain cmdx SEMI",
|
| + /* 5 */ "explain ::=",
|
| + /* 6 */ "explain ::= EXPLAIN",
|
| + /* 7 */ "explain ::= EXPLAIN QUERY PLAN",
|
| + /* 8 */ "cmdx ::= cmd",
|
| + /* 9 */ "cmd ::= BEGIN transtype trans_opt",
|
| + /* 10 */ "trans_opt ::=",
|
| + /* 11 */ "trans_opt ::= TRANSACTION",
|
| + /* 12 */ "trans_opt ::= TRANSACTION nm",
|
| + /* 13 */ "transtype ::=",
|
| + /* 14 */ "transtype ::= DEFERRED",
|
| + /* 15 */ "transtype ::= IMMEDIATE",
|
| + /* 16 */ "transtype ::= EXCLUSIVE",
|
| + /* 17 */ "cmd ::= COMMIT trans_opt",
|
| + /* 18 */ "cmd ::= END trans_opt",
|
| + /* 19 */ "cmd ::= ROLLBACK trans_opt",
|
| + /* 20 */ "savepoint_opt ::= SAVEPOINT",
|
| + /* 21 */ "savepoint_opt ::=",
|
| + /* 22 */ "cmd ::= SAVEPOINT nm",
|
| + /* 23 */ "cmd ::= RELEASE savepoint_opt nm",
|
| + /* 24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
|
| + /* 25 */ "cmd ::= create_table create_table_args",
|
| + /* 26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
|
| + /* 27 */ "createkw ::= CREATE",
|
| + /* 28 */ "ifnotexists ::=",
|
| + /* 29 */ "ifnotexists ::= IF NOT EXISTS",
|
| + /* 30 */ "temp ::= TEMP",
|
| + /* 31 */ "temp ::=",
|
| + /* 32 */ "create_table_args ::= LP columnlist conslist_opt RP table_options",
|
| + /* 33 */ "create_table_args ::= AS select",
|
| + /* 34 */ "table_options ::=",
|
| + /* 35 */ "table_options ::= WITHOUT nm",
|
| + /* 36 */ "columnlist ::= columnlist COMMA column",
|
| + /* 37 */ "columnlist ::= column",
|
| + /* 38 */ "column ::= columnid type carglist",
|
| + /* 39 */ "columnid ::= nm",
|
| + /* 40 */ "nm ::= ID|INDEXED",
|
| + /* 41 */ "nm ::= STRING",
|
| + /* 42 */ "nm ::= JOIN_KW",
|
| + /* 43 */ "type ::=",
|
| + /* 44 */ "type ::= typetoken",
|
| + /* 45 */ "typetoken ::= typename",
|
| + /* 46 */ "typetoken ::= typename LP signed RP",
|
| + /* 47 */ "typetoken ::= typename LP signed COMMA signed RP",
|
| + /* 48 */ "typename ::= ID|STRING",
|
| + /* 49 */ "typename ::= typename ID|STRING",
|
| + /* 50 */ "signed ::= plus_num",
|
| + /* 51 */ "signed ::= minus_num",
|
| + /* 52 */ "carglist ::= carglist ccons",
|
| + /* 53 */ "carglist ::=",
|
| + /* 54 */ "ccons ::= CONSTRAINT nm",
|
| + /* 55 */ "ccons ::= DEFAULT term",
|
| + /* 56 */ "ccons ::= DEFAULT LP expr RP",
|
| + /* 57 */ "ccons ::= DEFAULT PLUS term",
|
| + /* 58 */ "ccons ::= DEFAULT MINUS term",
|
| + /* 59 */ "ccons ::= DEFAULT ID|INDEXED",
|
| + /* 60 */ "ccons ::= NULL onconf",
|
| + /* 61 */ "ccons ::= NOT NULL onconf",
|
| + /* 62 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
|
| + /* 63 */ "ccons ::= UNIQUE onconf",
|
| + /* 64 */ "ccons ::= CHECK LP expr RP",
|
| + /* 65 */ "ccons ::= REFERENCES nm eidlist_opt refargs",
|
| + /* 66 */ "ccons ::= defer_subclause",
|
| + /* 67 */ "ccons ::= COLLATE ID|STRING",
|
| + /* 68 */ "autoinc ::=",
|
| + /* 69 */ "autoinc ::= AUTOINCR",
|
| + /* 70 */ "refargs ::=",
|
| + /* 71 */ "refargs ::= refargs refarg",
|
| + /* 72 */ "refarg ::= MATCH nm",
|
| + /* 73 */ "refarg ::= ON INSERT refact",
|
| + /* 74 */ "refarg ::= ON DELETE refact",
|
| + /* 75 */ "refarg ::= ON UPDATE refact",
|
| + /* 76 */ "refact ::= SET NULL",
|
| + /* 77 */ "refact ::= SET DEFAULT",
|
| + /* 78 */ "refact ::= CASCADE",
|
| + /* 79 */ "refact ::= RESTRICT",
|
| + /* 80 */ "refact ::= NO ACTION",
|
| + /* 81 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
|
| + /* 82 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
|
| + /* 83 */ "init_deferred_pred_opt ::=",
|
| + /* 84 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
|
| + /* 85 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
|
| + /* 86 */ "conslist_opt ::=",
|
| + /* 87 */ "conslist_opt ::= COMMA conslist",
|
| + /* 88 */ "conslist ::= conslist tconscomma tcons",
|
| + /* 89 */ "conslist ::= tcons",
|
| + /* 90 */ "tconscomma ::= COMMA",
|
| + /* 91 */ "tconscomma ::=",
|
| + /* 92 */ "tcons ::= CONSTRAINT nm",
|
| + /* 93 */ "tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf",
|
| + /* 94 */ "tcons ::= UNIQUE LP sortlist RP onconf",
|
| + /* 95 */ "tcons ::= CHECK LP expr RP onconf",
|
| + /* 96 */ "tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt",
|
| + /* 97 */ "defer_subclause_opt ::=",
|
| + /* 98 */ "defer_subclause_opt ::= defer_subclause",
|
| + /* 99 */ "onconf ::=",
|
| + /* 100 */ "onconf ::= ON CONFLICT resolvetype",
|
| + /* 101 */ "orconf ::=",
|
| + /* 102 */ "orconf ::= OR resolvetype",
|
| + /* 103 */ "resolvetype ::= raisetype",
|
| + /* 104 */ "resolvetype ::= IGNORE",
|
| + /* 105 */ "resolvetype ::= REPLACE",
|
| + /* 106 */ "cmd ::= DROP TABLE ifexists fullname",
|
| + /* 107 */ "ifexists ::= IF EXISTS",
|
| + /* 108 */ "ifexists ::=",
|
| + /* 109 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select",
|
| + /* 110 */ "cmd ::= DROP VIEW ifexists fullname",
|
| + /* 111 */ "cmd ::= select",
|
| + /* 112 */ "select ::= with selectnowith",
|
| + /* 113 */ "selectnowith ::= oneselect",
|
| + /* 114 */ "selectnowith ::= selectnowith multiselect_op oneselect",
|
| + /* 115 */ "multiselect_op ::= UNION",
|
| + /* 116 */ "multiselect_op ::= UNION ALL",
|
| + /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
|
| + /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
|
| + /* 119 */ "oneselect ::= values",
|
| + /* 120 */ "values ::= VALUES LP nexprlist RP",
|
| + /* 121 */ "values ::= values COMMA LP exprlist RP",
|
| + /* 122 */ "distinct ::= DISTINCT",
|
| + /* 123 */ "distinct ::= ALL",
|
| + /* 124 */ "distinct ::=",
|
| + /* 125 */ "sclp ::= selcollist COMMA",
|
| + /* 126 */ "sclp ::=",
|
| + /* 127 */ "selcollist ::= sclp expr as",
|
| + /* 128 */ "selcollist ::= sclp STAR",
|
| + /* 129 */ "selcollist ::= sclp nm DOT STAR",
|
| + /* 130 */ "as ::= AS nm",
|
| + /* 131 */ "as ::= ID|STRING",
|
| + /* 132 */ "as ::=",
|
| + /* 133 */ "from ::=",
|
| + /* 134 */ "from ::= FROM seltablist",
|
| + /* 135 */ "stl_prefix ::= seltablist joinop",
|
| + /* 136 */ "stl_prefix ::=",
|
| + /* 137 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
|
| + /* 138 */ "seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt",
|
| + /* 139 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
|
| + /* 140 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
|
| + /* 141 */ "dbnm ::=",
|
| + /* 142 */ "dbnm ::= DOT nm",
|
| + /* 143 */ "fullname ::= nm dbnm",
|
| + /* 144 */ "joinop ::= COMMA|JOIN",
|
| + /* 145 */ "joinop ::= JOIN_KW JOIN",
|
| + /* 146 */ "joinop ::= JOIN_KW nm JOIN",
|
| + /* 147 */ "joinop ::= JOIN_KW nm nm JOIN",
|
| + /* 148 */ "on_opt ::= ON expr",
|
| + /* 149 */ "on_opt ::=",
|
| + /* 150 */ "indexed_opt ::=",
|
| + /* 151 */ "indexed_opt ::= INDEXED BY nm",
|
| + /* 152 */ "indexed_opt ::= NOT INDEXED",
|
| + /* 153 */ "using_opt ::= USING LP idlist RP",
|
| + /* 154 */ "using_opt ::=",
|
| + /* 155 */ "orderby_opt ::=",
|
| + /* 156 */ "orderby_opt ::= ORDER BY sortlist",
|
| + /* 157 */ "sortlist ::= sortlist COMMA expr sortorder",
|
| + /* 158 */ "sortlist ::= expr sortorder",
|
| + /* 159 */ "sortorder ::= ASC",
|
| + /* 160 */ "sortorder ::= DESC",
|
| + /* 161 */ "sortorder ::=",
|
| + /* 162 */ "groupby_opt ::=",
|
| + /* 163 */ "groupby_opt ::= GROUP BY nexprlist",
|
| + /* 164 */ "having_opt ::=",
|
| + /* 165 */ "having_opt ::= HAVING expr",
|
| + /* 166 */ "limit_opt ::=",
|
| + /* 167 */ "limit_opt ::= LIMIT expr",
|
| + /* 168 */ "limit_opt ::= LIMIT expr OFFSET expr",
|
| + /* 169 */ "limit_opt ::= LIMIT expr COMMA expr",
|
| + /* 170 */ "cmd ::= with DELETE FROM fullname indexed_opt where_opt",
|
| + /* 171 */ "where_opt ::=",
|
| + /* 172 */ "where_opt ::= WHERE expr",
|
| + /* 173 */ "cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt",
|
| + /* 174 */ "setlist ::= setlist COMMA nm EQ expr",
|
| + /* 175 */ "setlist ::= nm EQ expr",
|
| + /* 176 */ "cmd ::= with insert_cmd INTO fullname idlist_opt select",
|
| + /* 177 */ "cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES",
|
| + /* 178 */ "insert_cmd ::= INSERT orconf",
|
| + /* 179 */ "insert_cmd ::= REPLACE",
|
| + /* 180 */ "idlist_opt ::=",
|
| + /* 181 */ "idlist_opt ::= LP idlist RP",
|
| + /* 182 */ "idlist ::= idlist COMMA nm",
|
| + /* 183 */ "idlist ::= nm",
|
| + /* 184 */ "expr ::= term",
|
| + /* 185 */ "expr ::= LP expr RP",
|
| + /* 186 */ "term ::= NULL",
|
| + /* 187 */ "expr ::= ID|INDEXED",
|
| + /* 188 */ "expr ::= JOIN_KW",
|
| + /* 189 */ "expr ::= nm DOT nm",
|
| + /* 190 */ "expr ::= nm DOT nm DOT nm",
|
| + /* 191 */ "term ::= INTEGER|FLOAT|BLOB",
|
| + /* 192 */ "term ::= STRING",
|
| + /* 193 */ "expr ::= VARIABLE",
|
| + /* 194 */ "expr ::= expr COLLATE ID|STRING",
|
| + /* 195 */ "expr ::= CAST LP expr AS typetoken RP",
|
| + /* 196 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
|
| + /* 197 */ "expr ::= ID|INDEXED LP STAR RP",
|
| + /* 198 */ "term ::= CTIME_KW",
|
| + /* 199 */ "expr ::= expr AND expr",
|
| + /* 200 */ "expr ::= expr OR expr",
|
| + /* 201 */ "expr ::= expr LT|GT|GE|LE expr",
|
| + /* 202 */ "expr ::= expr EQ|NE expr",
|
| + /* 203 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
|
| + /* 204 */ "expr ::= expr PLUS|MINUS expr",
|
| + /* 205 */ "expr ::= expr STAR|SLASH|REM expr",
|
| + /* 206 */ "expr ::= expr CONCAT expr",
|
| + /* 207 */ "likeop ::= LIKE_KW|MATCH",
|
| + /* 208 */ "likeop ::= NOT LIKE_KW|MATCH",
|
| + /* 209 */ "expr ::= expr likeop expr",
|
| + /* 210 */ "expr ::= expr likeop expr ESCAPE expr",
|
| + /* 211 */ "expr ::= expr ISNULL|NOTNULL",
|
| + /* 212 */ "expr ::= expr NOT NULL",
|
| + /* 213 */ "expr ::= expr IS expr",
|
| + /* 214 */ "expr ::= expr IS NOT expr",
|
| + /* 215 */ "expr ::= NOT expr",
|
| + /* 216 */ "expr ::= BITNOT expr",
|
| + /* 217 */ "expr ::= MINUS expr",
|
| + /* 218 */ "expr ::= PLUS expr",
|
| + /* 219 */ "between_op ::= BETWEEN",
|
| + /* 220 */ "between_op ::= NOT BETWEEN",
|
| + /* 221 */ "expr ::= expr between_op expr AND expr",
|
| + /* 222 */ "in_op ::= IN",
|
| + /* 223 */ "in_op ::= NOT IN",
|
| + /* 224 */ "expr ::= expr in_op LP exprlist RP",
|
| + /* 225 */ "expr ::= LP select RP",
|
| + /* 226 */ "expr ::= expr in_op LP select RP",
|
| + /* 227 */ "expr ::= expr in_op nm dbnm",
|
| + /* 228 */ "expr ::= EXISTS LP select RP",
|
| + /* 229 */ "expr ::= CASE case_operand case_exprlist case_else END",
|
| + /* 230 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
|
| + /* 231 */ "case_exprlist ::= WHEN expr THEN expr",
|
| + /* 232 */ "case_else ::= ELSE expr",
|
| + /* 233 */ "case_else ::=",
|
| + /* 234 */ "case_operand ::= expr",
|
| + /* 235 */ "case_operand ::=",
|
| + /* 236 */ "exprlist ::= nexprlist",
|
| + /* 237 */ "exprlist ::=",
|
| + /* 238 */ "nexprlist ::= nexprlist COMMA expr",
|
| + /* 239 */ "nexprlist ::= expr",
|
| + /* 240 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt",
|
| + /* 241 */ "uniqueflag ::= UNIQUE",
|
| + /* 242 */ "uniqueflag ::=",
|
| + /* 243 */ "eidlist_opt ::=",
|
| + /* 244 */ "eidlist_opt ::= LP eidlist RP",
|
| + /* 245 */ "eidlist ::= eidlist COMMA nm collate sortorder",
|
| + /* 246 */ "eidlist ::= nm collate sortorder",
|
| + /* 247 */ "collate ::=",
|
| + /* 248 */ "collate ::= COLLATE ID|STRING",
|
| + /* 249 */ "cmd ::= DROP INDEX ifexists fullname",
|
| + /* 250 */ "cmd ::= VACUUM",
|
| + /* 251 */ "cmd ::= VACUUM nm",
|
| + /* 252 */ "cmd ::= PRAGMA nm dbnm",
|
| + /* 253 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
|
| + /* 254 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
|
| + /* 255 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
|
| + /* 256 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
|
| + /* 257 */ "nmnum ::= plus_num",
|
| + /* 258 */ "nmnum ::= nm",
|
| + /* 259 */ "nmnum ::= ON",
|
| + /* 260 */ "nmnum ::= DELETE",
|
| + /* 261 */ "nmnum ::= DEFAULT",
|
| + /* 262 */ "plus_num ::= PLUS INTEGER|FLOAT",
|
| + /* 263 */ "plus_num ::= INTEGER|FLOAT",
|
| + /* 264 */ "minus_num ::= MINUS INTEGER|FLOAT",
|
| + /* 265 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
|
| + /* 266 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
|
| + /* 267 */ "trigger_time ::= BEFORE",
|
| + /* 268 */ "trigger_time ::= AFTER",
|
| + /* 269 */ "trigger_time ::= INSTEAD OF",
|
| + /* 270 */ "trigger_time ::=",
|
| + /* 271 */ "trigger_event ::= DELETE|INSERT",
|
| + /* 272 */ "trigger_event ::= UPDATE",
|
| + /* 273 */ "trigger_event ::= UPDATE OF idlist",
|
| + /* 274 */ "foreach_clause ::=",
|
| + /* 275 */ "foreach_clause ::= FOR EACH ROW",
|
| + /* 276 */ "when_clause ::=",
|
| + /* 277 */ "when_clause ::= WHEN expr",
|
| + /* 278 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
|
| + /* 279 */ "trigger_cmd_list ::= trigger_cmd SEMI",
|
| + /* 280 */ "trnm ::= nm",
|
| + /* 281 */ "trnm ::= nm DOT nm",
|
| + /* 282 */ "tridxby ::=",
|
| + /* 283 */ "tridxby ::= INDEXED BY nm",
|
| + /* 284 */ "tridxby ::= NOT INDEXED",
|
| + /* 285 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
|
| + /* 286 */ "trigger_cmd ::= insert_cmd INTO trnm idlist_opt select",
|
| + /* 287 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
|
| + /* 288 */ "trigger_cmd ::= select",
|
| + /* 289 */ "expr ::= RAISE LP IGNORE RP",
|
| + /* 290 */ "expr ::= RAISE LP raisetype COMMA nm RP",
|
| + /* 291 */ "raisetype ::= ROLLBACK",
|
| + /* 292 */ "raisetype ::= ABORT",
|
| + /* 293 */ "raisetype ::= FAIL",
|
| + /* 294 */ "cmd ::= DROP TRIGGER ifexists fullname",
|
| + /* 295 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
|
| + /* 296 */ "cmd ::= DETACH database_kw_opt expr",
|
| + /* 297 */ "key_opt ::=",
|
| + /* 298 */ "key_opt ::= KEY expr",
|
| + /* 299 */ "database_kw_opt ::= DATABASE",
|
| + /* 300 */ "database_kw_opt ::=",
|
| + /* 301 */ "cmd ::= REINDEX",
|
| + /* 302 */ "cmd ::= REINDEX nm dbnm",
|
| + /* 303 */ "cmd ::= ANALYZE",
|
| + /* 304 */ "cmd ::= ANALYZE nm dbnm",
|
| + /* 305 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
|
| + /* 306 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
|
| + /* 307 */ "add_column_fullname ::= fullname",
|
| + /* 308 */ "kwcolumn_opt ::=",
|
| + /* 309 */ "kwcolumn_opt ::= COLUMNKW",
|
| + /* 310 */ "cmd ::= create_vtab",
|
| + /* 311 */ "cmd ::= create_vtab LP vtabarglist RP",
|
| + /* 312 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
|
| + /* 313 */ "vtabarglist ::= vtabarg",
|
| + /* 314 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
|
| + /* 315 */ "vtabarg ::=",
|
| + /* 316 */ "vtabarg ::= vtabarg vtabargtoken",
|
| + /* 317 */ "vtabargtoken ::= ANY",
|
| + /* 318 */ "vtabargtoken ::= lp anylist RP",
|
| + /* 319 */ "lp ::= LP",
|
| + /* 320 */ "anylist ::=",
|
| + /* 321 */ "anylist ::= anylist LP anylist RP",
|
| + /* 322 */ "anylist ::= anylist ANY",
|
| + /* 323 */ "with ::=",
|
| + /* 324 */ "with ::= WITH wqlist",
|
| + /* 325 */ "with ::= WITH RECURSIVE wqlist",
|
| + /* 326 */ "wqlist ::= nm eidlist_opt AS LP select RP",
|
| + /* 327 */ "wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP",
|
| +};
|
| +#endif /* NDEBUG */
|
| +
|
| +
|
| +#if YYSTACKDEPTH<=0
|
| +/*
|
| +** Try to increase the size of the parser stack.
|
| +*/
|
| +static void yyGrowStack(yyParser *p){
|
| + int newSize;
|
| + yyStackEntry *pNew;
|
| +
|
| + newSize = p->yystksz*2 + 100;
|
| + pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
|
| + if( pNew ){
|
| + p->yystack = pNew;
|
| + p->yystksz = newSize;
|
| +#ifndef NDEBUG
|
| + if( yyTraceFILE ){
|
| + fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
|
| + yyTracePrompt, p->yystksz);
|
| + }
|
| +#endif
|
| + }
|
| +}
|
| +#endif
|
| +
|
| +/* Datatype of the argument to the memory allocated passed as the
|
| +** second argument to sqlite3ParserAlloc() below. This can be changed by
|
| +** putting an appropriate #define in the %include section of the input
|
| +** grammar.
|
| +*/
|
| +#ifndef YYMALLOCARGTYPE
|
| +# define YYMALLOCARGTYPE size_t
|
| +#endif
|
| +
|
| +/*
|
| +** This function allocates a new parser.
|
| +** The only argument is a pointer to a function which works like
|
| +** malloc.
|
| +**
|
| +** Inputs:
|
| +** A pointer to the function used to allocate memory.
|
| +**
|
| +** Outputs:
|
| +** A pointer to a parser. This pointer is used in subsequent calls
|
| +** to sqlite3Parser and sqlite3ParserFree.
|
| +*/
|
| +SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(YYMALLOCARGTYPE)){
|
| + yyParser *pParser;
|
| + pParser = (yyParser*)(*mallocProc)( (YYMALLOCARGTYPE)sizeof(yyParser) );
|
| + if( pParser ){
|
| + pParser->yyidx = -1;
|
| +#ifdef YYTRACKMAXSTACKDEPTH
|
| + pParser->yyidxMax = 0;
|
| +#endif
|
| +#if YYSTACKDEPTH<=0
|
| + pParser->yystack = NULL;
|
| + pParser->yystksz = 0;
|
| + yyGrowStack(pParser);
|
| +#endif
|
| + }
|
| + return pParser;
|
| +}
|
| +
|
| +/* The following function deletes the "minor type" or semantic value
|
| +** associated with a symbol. The symbol can be either a terminal
|
| +** or nonterminal. "yymajor" is the symbol code, and "yypminor" is
|
| +** a pointer to the value to be deleted. The code used to do the
|
| +** deletions is derived from the %destructor and/or %token_destructor
|
| +** directives of the input grammar.
|
| +*/
|
| +static void yy_destructor(
|
| + yyParser *yypParser, /* The parser */
|
| + YYCODETYPE yymajor, /* Type code for object to destroy */
|
| + YYMINORTYPE *yypminor /* The object to be destroyed */
|
| +){
|
| + sqlite3ParserARG_FETCH;
|
| + switch( yymajor ){
|
| + /* Here is inserted the actions which take place when a
|
| + ** terminal or non-terminal is destroyed. This can happen
|
| + ** when the symbol is popped from the stack during a
|
| + ** reduce or during error processing or when a parser is
|
| + ** being destroyed before it is finished parsing.
|
| + **
|
| + ** Note: during a reduce, the only symbols destroyed are those
|
| + ** which appear on the RHS of the rule, but which are *not* used
|
| + ** inside the C code.
|
| + */
|
| +/********* Begin destructor definitions ***************************************/
|
| + case 163: /* select */
|
| + case 196: /* selectnowith */
|
| + case 197: /* oneselect */
|
| + case 208: /* values */
|
| +{
|
| +sqlite3SelectDelete(pParse->db, (yypminor->yy387));
|
| +}
|
| + break;
|
| + case 174: /* term */
|
| + case 175: /* expr */
|
| +{
|
| +sqlite3ExprDelete(pParse->db, (yypminor->yy118).pExpr);
|
| +}
|
| + break;
|
| + case 179: /* eidlist_opt */
|
| + case 188: /* sortlist */
|
| + case 189: /* eidlist */
|
| + case 201: /* selcollist */
|
| + case 204: /* groupby_opt */
|
| + case 206: /* orderby_opt */
|
| + case 209: /* nexprlist */
|
| + case 210: /* exprlist */
|
| + case 211: /* sclp */
|
| + case 220: /* setlist */
|
| + case 227: /* case_exprlist */
|
| +{
|
| +sqlite3ExprListDelete(pParse->db, (yypminor->yy322));
|
| +}
|
| + break;
|
| + case 195: /* fullname */
|
| + case 202: /* from */
|
| + case 213: /* seltablist */
|
| + case 214: /* stl_prefix */
|
| +{
|
| +sqlite3SrcListDelete(pParse->db, (yypminor->yy259));
|
| +}
|
| + break;
|
| + case 198: /* with */
|
| + case 251: /* wqlist */
|
| +{
|
| +sqlite3WithDelete(pParse->db, (yypminor->yy451));
|
| +}
|
| + break;
|
| + case 203: /* where_opt */
|
| + case 205: /* having_opt */
|
| + case 217: /* on_opt */
|
| + case 226: /* case_operand */
|
| + case 228: /* case_else */
|
| + case 237: /* when_clause */
|
| + case 242: /* key_opt */
|
| +{
|
| +sqlite3ExprDelete(pParse->db, (yypminor->yy314));
|
| +}
|
| + break;
|
| + case 218: /* using_opt */
|
| + case 219: /* idlist */
|
| + case 222: /* idlist_opt */
|
| +{
|
| +sqlite3IdListDelete(pParse->db, (yypminor->yy384));
|
| +}
|
| + break;
|
| + case 233: /* trigger_cmd_list */
|
| + case 238: /* trigger_cmd */
|
| +{
|
| +sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy203));
|
| +}
|
| + break;
|
| + case 235: /* trigger_event */
|
| +{
|
| +sqlite3IdListDelete(pParse->db, (yypminor->yy90).b);
|
| +}
|
| + break;
|
| +/********* End destructor definitions *****************************************/
|
| + default: break; /* If no destructor action specified: do nothing */
|
| + }
|
| +}
|
| +
|
| +/*
|
| +** Pop the parser's stack once.
|
| +**
|
| +** If there is a destructor routine associated with the token which
|
| +** is popped from the stack, then call it.
|
| +*/
|
| +static void yy_pop_parser_stack(yyParser *pParser){
|
| + yyStackEntry *yytos;
|
| + assert( pParser->yyidx>=0 );
|
| + yytos = &pParser->yystack[pParser->yyidx--];
|
| +#ifndef NDEBUG
|
| + if( yyTraceFILE ){
|
| + fprintf(yyTraceFILE,"%sPopping %s\n",
|
| + yyTracePrompt,
|
| + yyTokenName[yytos->major]);
|
| + }
|
| +#endif
|
| + yy_destructor(pParser, yytos->major, &yytos->minor);
|
| +}
|
| +
|
| +/*
|
| +** Deallocate and destroy a parser. Destructors are called for
|
| +** all stack elements before shutting the parser down.
|
| +**
|
| +** If the YYPARSEFREENEVERNULL macro exists (for example because it
|
| +** is defined in a %include section of the input grammar) then it is
|
| +** assumed that the input pointer is never NULL.
|
| +*/
|
| +SQLITE_PRIVATE void sqlite3ParserFree(
|
| + void *p, /* The parser to be deleted */
|
| + void (*freeProc)(void*) /* Function used to reclaim memory */
|
| +){
|
| + yyParser *pParser = (yyParser*)p;
|
| +#ifndef YYPARSEFREENEVERNULL
|
| + if( pParser==0 ) return;
|
| +#endif
|
| + while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
|
| +#if YYSTACKDEPTH<=0
|
| + free(pParser->yystack);
|
| +#endif
|
| + (*freeProc)((void*)pParser);
|
| +}
|
| +
|
| +/*
|
| +** Return the peak depth of the stack for a parser.
|
| +*/
|
| +#ifdef YYTRACKMAXSTACKDEPTH
|
| +SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
|
| + yyParser *pParser = (yyParser*)p;
|
| + return pParser->yyidxMax;
|
| +}
|
| +#endif
|
| +
|
| +/*
|
| +** Find the appropriate action for a parser given the terminal
|
| +** look-ahead token iLookAhead.
|
| +*/
|
| +static int yy_find_shift_action(
|
| + yyParser *pParser, /* The parser */
|
| + YYCODETYPE iLookAhead /* The look-ahead token */
|
| +){
|
| + int i;
|
| + int stateno = pParser->yystack[pParser->yyidx].stateno;
|
| +
|
| + if( stateno>=YY_MIN_REDUCE ) return stateno;
|
| + assert( stateno <= YY_SHIFT_COUNT );
|
| + do{
|
| + i = yy_shift_ofst[stateno];
|
| + if( i==YY_SHIFT_USE_DFLT ) return yy_default[stateno];
|
| + assert( iLookAhead!=YYNOCODE );
|
| + i += iLookAhead;
|
| + if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
|
| + if( iLookAhead>0 ){
|
| +#ifdef YYFALLBACK
|
| + YYCODETYPE iFallback; /* Fallback token */
|
| + if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
|
| + && (iFallback = yyFallback[iLookAhead])!=0 ){
|
| +#ifndef NDEBUG
|
| + if( yyTraceFILE ){
|
| + fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
|
| + yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
|
| + }
|
| +#endif
|
| + assert( yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
|
| + iLookAhead = iFallback;
|
| + continue;
|
| + }
|
| +#endif
|
| +#ifdef YYWILDCARD
|
| + {
|
| + int j = i - iLookAhead + YYWILDCARD;
|
| + if(
|
| +#if YY_SHIFT_MIN+YYWILDCARD<0
|
| + j>=0 &&
|
| +#endif
|
| +#if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
|
| + j<YY_ACTTAB_COUNT &&
|
| +#endif
|
| + yy_lookahead[j]==YYWILDCARD
|
| + ){
|
| +#ifndef NDEBUG
|
| + if( yyTraceFILE ){
|
| + fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
|
| + yyTracePrompt, yyTokenName[iLookAhead],
|
| + yyTokenName[YYWILDCARD]);
|
| + }
|
| +#endif /* NDEBUG */
|
| + return yy_action[j];
|
| + }
|
| + }
|
| +#endif /* YYWILDCARD */
|
| + }
|
| + return yy_default[stateno];
|
| + }else{
|
| + return yy_action[i];
|
| + }
|
| + }while(1);
|
| +}
|
| +
|
| +/*
|
| +** Find the appropriate action for a parser given the non-terminal
|
| +** look-ahead token iLookAhead.
|
| +*/
|
| +static int yy_find_reduce_action(
|
| + int stateno, /* Current state number */
|
| + YYCODETYPE iLookAhead /* The look-ahead token */
|
| +){
|
| + int i;
|
| +#ifdef YYERRORSYMBOL
|
| + if( stateno>YY_REDUCE_COUNT ){
|
| + return yy_default[stateno];
|
| + }
|
| +#else
|
| + assert( stateno<=YY_REDUCE_COUNT );
|
| +#endif
|
| + i = yy_reduce_ofst[stateno];
|
| + assert( i!=YY_REDUCE_USE_DFLT );
|
| + assert( iLookAhead!=YYNOCODE );
|
| + i += iLookAhead;
|
| +#ifdef YYERRORSYMBOL
|
| + if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
|
| + return yy_default[stateno];
|
| + }
|
| +#else
|
| + assert( i>=0 && i<YY_ACTTAB_COUNT );
|
| + assert( yy_lookahead[i]==iLookAhead );
|
| +#endif
|
| + return yy_action[i];
|
| +}
|
| +
|
| +/*
|
| +** The following routine is called if the stack overflows.
|
| +*/
|
| +static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
|
| + sqlite3ParserARG_FETCH;
|
| + yypParser->yyidx--;
|
| +#ifndef NDEBUG
|
| + if( yyTraceFILE ){
|
| + fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
|
| + }
|
| +#endif
|
| + while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
|
| + /* Here code is inserted which will execute if the parser
|
| + ** stack every overflows */
|
| +/******** Begin %stack_overflow code ******************************************/
|
| +
|
| + UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
|
| + sqlite3ErrorMsg(pParse, "parser stack overflow");
|
| +/******** End %stack_overflow code ********************************************/
|
| + sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
|
| +}
|
| +
|
| +/*
|
| +** Print tracing information for a SHIFT action
|
| +*/
|
| +#ifndef NDEBUG
|
| +static void yyTraceShift(yyParser *yypParser, int yyNewState){
|
| + if( yyTraceFILE ){
|
| + if( yyNewState<YYNSTATE ){
|
| + fprintf(yyTraceFILE,"%sShift '%s', go to state %d\n",
|
| + yyTracePrompt,yyTokenName[yypParser->yystack[yypParser->yyidx].major],
|
| + yyNewState);
|
| + }else{
|
| + fprintf(yyTraceFILE,"%sShift '%s'\n",
|
| + yyTracePrompt,yyTokenName[yypParser->yystack[yypParser->yyidx].major]);
|
| + }
|
| + }
|
| +}
|
| +#else
|
| +# define yyTraceShift(X,Y)
|
| +#endif
|
| +
|
| +/*
|
| +** Perform a shift action.
|
| +*/
|
| +static void yy_shift(
|
| + yyParser *yypParser, /* The parser to be shifted */
|
| + int yyNewState, /* The new state to shift in */
|
| + int yyMajor, /* The major token to shift in */
|
| + YYMINORTYPE *yypMinor /* Pointer to the minor token to shift in */
|
| +){
|
| + yyStackEntry *yytos;
|
| + yypParser->yyidx++;
|
| +#ifdef YYTRACKMAXSTACKDEPTH
|
| + if( yypParser->yyidx>yypParser->yyidxMax ){
|
| + yypParser->yyidxMax = yypParser->yyidx;
|
| + }
|
| +#endif
|
| +#if YYSTACKDEPTH>0
|
| + if( yypParser->yyidx>=YYSTACKDEPTH ){
|
| + yyStackOverflow(yypParser, yypMinor);
|
| + return;
|
| + }
|
| +#else
|
| + if( yypParser->yyidx>=yypParser->yystksz ){
|
| + yyGrowStack(yypParser);
|
| + if( yypParser->yyidx>=yypParser->yystksz ){
|
| + yyStackOverflow(yypParser, yypMinor);
|
| + return;
|
| + }
|
| + }
|
| +#endif
|
| + yytos = &yypParser->yystack[yypParser->yyidx];
|
| + yytos->stateno = (YYACTIONTYPE)yyNewState;
|
| + yytos->major = (YYCODETYPE)yyMajor;
|
| + yytos->minor = *yypMinor;
|
| + yyTraceShift(yypParser, yyNewState);
|
| +}
|
| +
|
| +/* The following table contains information about every rule that
|
| +** is used during the reduce.
|
| +*/
|
| +static const struct {
|
| + YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
|
| + unsigned char nrhs; /* Number of right-hand side symbols in the rule */
|
| +} yyRuleInfo[] = {
|
| + { 144, 1 },
|
| + { 145, 2 },
|
| + { 145, 1 },
|
| + { 146, 1 },
|
| + { 146, 3 },
|
| + { 147, 0 },
|
| + { 147, 1 },
|
| + { 147, 3 },
|
| + { 148, 1 },
|
| + { 149, 3 },
|
| + { 151, 0 },
|
| + { 151, 1 },
|
| + { 151, 2 },
|
| + { 150, 0 },
|
| + { 150, 1 },
|
| + { 150, 1 },
|
| + { 150, 1 },
|
| + { 149, 2 },
|
| + { 149, 2 },
|
| + { 149, 2 },
|
| + { 153, 1 },
|
| + { 153, 0 },
|
| + { 149, 2 },
|
| + { 149, 3 },
|
| + { 149, 5 },
|
| + { 149, 2 },
|
| + { 154, 6 },
|
| + { 156, 1 },
|
| + { 158, 0 },
|
| + { 158, 3 },
|
| + { 157, 1 },
|
| + { 157, 0 },
|
| + { 155, 5 },
|
| + { 155, 2 },
|
| + { 162, 0 },
|
| + { 162, 2 },
|
| + { 160, 3 },
|
| + { 160, 1 },
|
| + { 164, 3 },
|
| + { 165, 1 },
|
| + { 152, 1 },
|
| + { 152, 1 },
|
| + { 152, 1 },
|
| + { 166, 0 },
|
| + { 166, 1 },
|
| + { 168, 1 },
|
| + { 168, 4 },
|
| + { 168, 6 },
|
| + { 169, 1 },
|
| + { 169, 2 },
|
| + { 170, 1 },
|
| + { 170, 1 },
|
| + { 167, 2 },
|
| + { 167, 0 },
|
| + { 173, 2 },
|
| + { 173, 2 },
|
| + { 173, 4 },
|
| + { 173, 3 },
|
| + { 173, 3 },
|
| + { 173, 2 },
|
| + { 173, 2 },
|
| + { 173, 3 },
|
| + { 173, 5 },
|
| + { 173, 2 },
|
| + { 173, 4 },
|
| + { 173, 4 },
|
| + { 173, 1 },
|
| + { 173, 2 },
|
| + { 178, 0 },
|
| + { 178, 1 },
|
| + { 180, 0 },
|
| + { 180, 2 },
|
| + { 182, 2 },
|
| + { 182, 3 },
|
| + { 182, 3 },
|
| + { 182, 3 },
|
| + { 183, 2 },
|
| + { 183, 2 },
|
| + { 183, 1 },
|
| + { 183, 1 },
|
| + { 183, 2 },
|
| + { 181, 3 },
|
| + { 181, 2 },
|
| + { 184, 0 },
|
| + { 184, 2 },
|
| + { 184, 2 },
|
| + { 161, 0 },
|
| + { 161, 2 },
|
| + { 185, 3 },
|
| + { 185, 1 },
|
| + { 186, 1 },
|
| + { 186, 0 },
|
| + { 187, 2 },
|
| + { 187, 7 },
|
| + { 187, 5 },
|
| + { 187, 5 },
|
| + { 187, 10 },
|
| + { 190, 0 },
|
| + { 190, 1 },
|
| + { 176, 0 },
|
| + { 176, 3 },
|
| + { 191, 0 },
|
| + { 191, 2 },
|
| + { 192, 1 },
|
| + { 192, 1 },
|
| + { 192, 1 },
|
| + { 149, 4 },
|
| + { 194, 2 },
|
| + { 194, 0 },
|
| + { 149, 9 },
|
| + { 149, 4 },
|
| + { 149, 1 },
|
| + { 163, 2 },
|
| + { 196, 1 },
|
| + { 196, 3 },
|
| + { 199, 1 },
|
| + { 199, 2 },
|
| + { 199, 1 },
|
| + { 197, 9 },
|
| + { 197, 1 },
|
| + { 208, 4 },
|
| + { 208, 5 },
|
| + { 200, 1 },
|
| + { 200, 1 },
|
| + { 200, 0 },
|
| + { 211, 2 },
|
| + { 211, 0 },
|
| + { 201, 3 },
|
| + { 201, 2 },
|
| + { 201, 4 },
|
| + { 212, 2 },
|
| + { 212, 1 },
|
| + { 212, 0 },
|
| + { 202, 0 },
|
| + { 202, 2 },
|
| + { 214, 2 },
|
| + { 214, 0 },
|
| + { 213, 7 },
|
| + { 213, 9 },
|
| + { 213, 7 },
|
| + { 213, 7 },
|
| + { 159, 0 },
|
| + { 159, 2 },
|
| + { 195, 2 },
|
| + { 215, 1 },
|
| + { 215, 2 },
|
| + { 215, 3 },
|
| + { 215, 4 },
|
| + { 217, 2 },
|
| + { 217, 0 },
|
| + { 216, 0 },
|
| + { 216, 3 },
|
| + { 216, 2 },
|
| + { 218, 4 },
|
| + { 218, 0 },
|
| + { 206, 0 },
|
| + { 206, 3 },
|
| + { 188, 4 },
|
| + { 188, 2 },
|
| + { 177, 1 },
|
| + { 177, 1 },
|
| + { 177, 0 },
|
| + { 204, 0 },
|
| + { 204, 3 },
|
| + { 205, 0 },
|
| + { 205, 2 },
|
| + { 207, 0 },
|
| + { 207, 2 },
|
| + { 207, 4 },
|
| + { 207, 4 },
|
| + { 149, 6 },
|
| + { 203, 0 },
|
| + { 203, 2 },
|
| + { 149, 8 },
|
| + { 220, 5 },
|
| + { 220, 3 },
|
| + { 149, 6 },
|
| + { 149, 7 },
|
| + { 221, 2 },
|
| + { 221, 1 },
|
| + { 222, 0 },
|
| + { 222, 3 },
|
| + { 219, 3 },
|
| + { 219, 1 },
|
| + { 175, 1 },
|
| + { 175, 3 },
|
| + { 174, 1 },
|
| + { 175, 1 },
|
| + { 175, 1 },
|
| + { 175, 3 },
|
| + { 175, 5 },
|
| + { 174, 1 },
|
| + { 174, 1 },
|
| + { 175, 1 },
|
| + { 175, 3 },
|
| + { 175, 6 },
|
| + { 175, 5 },
|
| + { 175, 4 },
|
| + { 174, 1 },
|
| + { 175, 3 },
|
| + { 175, 3 },
|
| + { 175, 3 },
|
| + { 175, 3 },
|
| + { 175, 3 },
|
| + { 175, 3 },
|
| + { 175, 3 },
|
| + { 175, 3 },
|
| + { 223, 1 },
|
| + { 223, 2 },
|
| + { 175, 3 },
|
| + { 175, 5 },
|
| + { 175, 2 },
|
| + { 175, 3 },
|
| + { 175, 3 },
|
| + { 175, 4 },
|
| + { 175, 2 },
|
| + { 175, 2 },
|
| + { 175, 2 },
|
| + { 175, 2 },
|
| + { 224, 1 },
|
| + { 224, 2 },
|
| + { 175, 5 },
|
| + { 225, 1 },
|
| + { 225, 2 },
|
| + { 175, 5 },
|
| + { 175, 3 },
|
| + { 175, 5 },
|
| + { 175, 4 },
|
| + { 175, 4 },
|
| + { 175, 5 },
|
| + { 227, 5 },
|
| + { 227, 4 },
|
| + { 228, 2 },
|
| + { 228, 0 },
|
| + { 226, 1 },
|
| + { 226, 0 },
|
| + { 210, 1 },
|
| + { 210, 0 },
|
| + { 209, 3 },
|
| + { 209, 1 },
|
| + { 149, 12 },
|
| + { 229, 1 },
|
| + { 229, 0 },
|
| + { 179, 0 },
|
| + { 179, 3 },
|
| + { 189, 5 },
|
| + { 189, 3 },
|
| + { 230, 0 },
|
| + { 230, 2 },
|
| + { 149, 4 },
|
| + { 149, 1 },
|
| + { 149, 2 },
|
| + { 149, 3 },
|
| + { 149, 5 },
|
| + { 149, 6 },
|
| + { 149, 5 },
|
| + { 149, 6 },
|
| + { 231, 1 },
|
| + { 231, 1 },
|
| + { 231, 1 },
|
| + { 231, 1 },
|
| + { 231, 1 },
|
| + { 171, 2 },
|
| + { 171, 1 },
|
| + { 172, 2 },
|
| + { 149, 5 },
|
| + { 232, 11 },
|
| + { 234, 1 },
|
| + { 234, 1 },
|
| + { 234, 2 },
|
| + { 234, 0 },
|
| + { 235, 1 },
|
| + { 235, 1 },
|
| + { 235, 3 },
|
| + { 236, 0 },
|
| + { 236, 3 },
|
| + { 237, 0 },
|
| + { 237, 2 },
|
| + { 233, 3 },
|
| + { 233, 2 },
|
| + { 239, 1 },
|
| + { 239, 3 },
|
| + { 240, 0 },
|
| + { 240, 3 },
|
| + { 240, 2 },
|
| + { 238, 7 },
|
| + { 238, 5 },
|
| + { 238, 5 },
|
| + { 238, 1 },
|
| + { 175, 4 },
|
| + { 175, 6 },
|
| + { 193, 1 },
|
| + { 193, 1 },
|
| + { 193, 1 },
|
| + { 149, 4 },
|
| + { 149, 6 },
|
| + { 149, 3 },
|
| + { 242, 0 },
|
| + { 242, 2 },
|
| + { 241, 1 },
|
| + { 241, 0 },
|
| + { 149, 1 },
|
| + { 149, 3 },
|
| + { 149, 1 },
|
| + { 149, 3 },
|
| + { 149, 6 },
|
| + { 149, 6 },
|
| + { 243, 1 },
|
| + { 244, 0 },
|
| + { 244, 1 },
|
| + { 149, 1 },
|
| + { 149, 4 },
|
| + { 245, 8 },
|
| + { 246, 1 },
|
| + { 246, 3 },
|
| + { 247, 0 },
|
| + { 247, 2 },
|
| + { 248, 1 },
|
| + { 248, 3 },
|
| + { 249, 1 },
|
| + { 250, 0 },
|
| + { 250, 4 },
|
| + { 250, 2 },
|
| + { 198, 0 },
|
| + { 198, 2 },
|
| + { 198, 3 },
|
| + { 251, 6 },
|
| + { 251, 8 },
|
| +};
|
| +
|
| +static void yy_accept(yyParser*); /* Forward Declaration */
|
| +
|
| +/*
|
| +** Perform a reduce action and the shift that must immediately
|
| +** follow the reduce.
|
| +*/
|
| +static void yy_reduce(
|
| + yyParser *yypParser, /* The parser */
|
| + int yyruleno /* Number of the rule by which to reduce */
|
| +){
|
| + int yygoto; /* The next state */
|
| + int yyact; /* The next action */
|
| + YYMINORTYPE yygotominor; /* The LHS of the rule reduced */
|
| + yyStackEntry *yymsp; /* The top of the parser's stack */
|
| + int yysize; /* Amount to pop the stack */
|
| + sqlite3ParserARG_FETCH;
|
| + yymsp = &yypParser->yystack[yypParser->yyidx];
|
| +#ifndef NDEBUG
|
| + if( yyTraceFILE && yyruleno>=0
|
| + && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
|
| + yysize = yyRuleInfo[yyruleno].nrhs;
|
| + fprintf(yyTraceFILE, "%sReduce [%s], go to state %d.\n", yyTracePrompt,
|
| + yyRuleName[yyruleno], yymsp[-yysize].stateno);
|
| + }
|
| +#endif /* NDEBUG */
|
| + yygotominor = yyzerominor;
|
| +
|
| + switch( yyruleno ){
|
| + /* Beginning here are the reduction cases. A typical example
|
| + ** follows:
|
| + ** case 0:
|
| + ** #line <lineno> <grammarfile>
|
| + ** { ... } // User supplied code
|
| + ** #line <lineno> <thisfile>
|
| + ** break;
|
| + */
|
| +/********** Begin reduce actions **********************************************/
|
| + case 5: /* explain ::= */
|
| +{ sqlite3BeginParse(pParse, 0); }
|
| + break;
|
| + case 6: /* explain ::= EXPLAIN */
|
| +{ sqlite3BeginParse(pParse, 1); }
|
| + break;
|
| + case 7: /* explain ::= EXPLAIN QUERY PLAN */
|
| +{ sqlite3BeginParse(pParse, 2); }
|
| + break;
|
| + case 8: /* cmdx ::= cmd */
|
| +{ sqlite3FinishCoding(pParse); }
|
| + break;
|
| + case 9: /* cmd ::= BEGIN transtype trans_opt */
|
| +{sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy4);}
|
| + break;
|
| + case 13: /* transtype ::= */
|
| +{yygotominor.yy4 = TK_DEFERRED;}
|
| + break;
|
| + case 14: /* transtype ::= DEFERRED */
|
| + case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
|
| + case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
|
| + case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
|
| + case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
|
| +{yygotominor.yy4 = yymsp[0].major;}
|
| + break;
|
| + case 17: /* cmd ::= COMMIT trans_opt */
|
| + case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
|
| +{sqlite3CommitTransaction(pParse);}
|
| + break;
|
| + case 19: /* cmd ::= ROLLBACK trans_opt */
|
| +{sqlite3RollbackTransaction(pParse);}
|
| + break;
|
| + case 22: /* cmd ::= SAVEPOINT nm */
|
| +{
|
| + sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
|
| +}
|
| + break;
|
| + case 23: /* cmd ::= RELEASE savepoint_opt nm */
|
| +{
|
| + sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
|
| +}
|
| + break;
|
| + case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
|
| +{
|
| + sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
|
| +}
|
| + break;
|
| + case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
|
| +{
|
| + sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy4,0,0,yymsp[-2].minor.yy4);
|
| +}
|
| + break;
|
| + case 27: /* createkw ::= CREATE */
|
| +{
|
| + pParse->db->lookaside.bEnabled = 0;
|
| + yygotominor.yy0 = yymsp[0].minor.yy0;
|
| +}
|
| + break;
|
| + case 28: /* ifnotexists ::= */
|
| + case 31: /* temp ::= */ yytestcase(yyruleno==31);
|
| + case 34: /* table_options ::= */ yytestcase(yyruleno==34);
|
| + case 68: /* autoinc ::= */ yytestcase(yyruleno==68);
|
| + case 81: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==81);
|
| + case 83: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==83);
|
| + case 85: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==85);
|
| + case 97: /* defer_subclause_opt ::= */ yytestcase(yyruleno==97);
|
| + case 108: /* ifexists ::= */ yytestcase(yyruleno==108);
|
| + case 124: /* distinct ::= */ yytestcase(yyruleno==124);
|
| + case 219: /* between_op ::= BETWEEN */ yytestcase(yyruleno==219);
|
| + case 222: /* in_op ::= IN */ yytestcase(yyruleno==222);
|
| + case 247: /* collate ::= */ yytestcase(yyruleno==247);
|
| +{yygotominor.yy4 = 0;}
|
| + break;
|
| + case 29: /* ifnotexists ::= IF NOT EXISTS */
|
| + case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
|
| + case 69: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==69);
|
| + case 84: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==84);
|
| + case 107: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==107);
|
| + case 220: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==220);
|
| + case 223: /* in_op ::= NOT IN */ yytestcase(yyruleno==223);
|
| + case 248: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==248);
|
| +{yygotominor.yy4 = 1;}
|
| + break;
|
| + case 32: /* create_table_args ::= LP columnlist conslist_opt RP table_options */
|
| +{
|
| + sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy4,0);
|
| +}
|
| + break;
|
| + case 33: /* create_table_args ::= AS select */
|
| +{
|
| + sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy387);
|
| + sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy387);
|
| +}
|
| + break;
|
| + case 35: /* table_options ::= WITHOUT nm */
|
| +{
|
| + if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){
|
| + yygotominor.yy4 = TF_WithoutRowid | TF_NoVisibleRowid;
|
| + }else{
|
| + yygotominor.yy4 = 0;
|
| + sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
|
| + }
|
| +}
|
| + break;
|
| + case 38: /* column ::= columnid type carglist */
|
| +{
|
| + yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
|
| + yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
|
| +}
|
| + break;
|
| + case 39: /* columnid ::= nm */
|
| +{
|
| + sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
|
| + yygotominor.yy0 = yymsp[0].minor.yy0;
|
| + pParse->constraintName.n = 0;
|
| +}
|
| + break;
|
| + case 40: /* nm ::= ID|INDEXED */
|
| + case 41: /* nm ::= STRING */ yytestcase(yyruleno==41);
|
| + case 42: /* nm ::= JOIN_KW */ yytestcase(yyruleno==42);
|
| + case 45: /* typetoken ::= typename */ yytestcase(yyruleno==45);
|
| + case 48: /* typename ::= ID|STRING */ yytestcase(yyruleno==48);
|
| + case 130: /* as ::= AS nm */ yytestcase(yyruleno==130);
|
| + case 131: /* as ::= ID|STRING */ yytestcase(yyruleno==131);
|
| + case 142: /* dbnm ::= DOT nm */ yytestcase(yyruleno==142);
|
| + case 151: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==151);
|
| + case 257: /* nmnum ::= plus_num */ yytestcase(yyruleno==257);
|
| + case 258: /* nmnum ::= nm */ yytestcase(yyruleno==258);
|
| + case 259: /* nmnum ::= ON */ yytestcase(yyruleno==259);
|
| + case 260: /* nmnum ::= DELETE */ yytestcase(yyruleno==260);
|
| + case 261: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==261);
|
| + case 262: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==262);
|
| + case 263: /* plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==263);
|
| + case 264: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==264);
|
| + case 280: /* trnm ::= nm */ yytestcase(yyruleno==280);
|
| +{yygotominor.yy0 = yymsp[0].minor.yy0;}
|
| + break;
|
| + case 44: /* type ::= typetoken */
|
| +{sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
|
| + break;
|
| + case 46: /* typetoken ::= typename LP signed RP */
|
| +{
|
| + yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
|
| + yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
|
| +}
|
| + break;
|
| + case 47: /* typetoken ::= typename LP signed COMMA signed RP */
|
| +{
|
| + yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
|
| + yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
|
| +}
|
| + break;
|
| + case 49: /* typename ::= typename ID|STRING */
|
| +{yygotominor.yy0.z=yymsp[-1].minor.yy0.z; yygotominor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);}
|
| + break;
|
| + case 54: /* ccons ::= CONSTRAINT nm */
|
| + case 92: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==92);
|
| +{pParse->constraintName = yymsp[0].minor.yy0;}
|
| + break;
|
| + case 55: /* ccons ::= DEFAULT term */
|
| + case 57: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==57);
|
| +{sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy118);}
|
| + break;
|
| + case 56: /* ccons ::= DEFAULT LP expr RP */
|
| +{sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy118);}
|
| + break;
|
| + case 58: /* ccons ::= DEFAULT MINUS term */
|
| +{
|
| + ExprSpan v;
|
| + v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy118.pExpr, 0, 0);
|
| + v.zStart = yymsp[-1].minor.yy0.z;
|
| + v.zEnd = yymsp[0].minor.yy118.zEnd;
|
| + sqlite3AddDefaultValue(pParse,&v);
|
| +}
|
| + break;
|
| + case 59: /* ccons ::= DEFAULT ID|INDEXED */
|
| +{
|
| + ExprSpan v;
|
| + spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
|
| + sqlite3AddDefaultValue(pParse,&v);
|
| +}
|
| + break;
|
| + case 61: /* ccons ::= NOT NULL onconf */
|
| +{sqlite3AddNotNull(pParse, yymsp[0].minor.yy4);}
|
| + break;
|
| + case 62: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
|
| +{sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy4,yymsp[0].minor.yy4,yymsp[-2].minor.yy4);}
|
| + break;
|
| + case 63: /* ccons ::= UNIQUE onconf */
|
| +{sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy4,0,0,0,0);}
|
| + break;
|
| + case 64: /* ccons ::= CHECK LP expr RP */
|
| +{sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy118.pExpr);}
|
| + break;
|
| + case 65: /* ccons ::= REFERENCES nm eidlist_opt refargs */
|
| +{sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy322,yymsp[0].minor.yy4);}
|
| + break;
|
| + case 66: /* ccons ::= defer_subclause */
|
| +{sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy4);}
|
| + break;
|
| + case 67: /* ccons ::= COLLATE ID|STRING */
|
| +{sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
|
| + break;
|
| + case 70: /* refargs ::= */
|
| +{ yygotominor.yy4 = OE_None*0x0101; /* EV: R-19803-45884 */}
|
| + break;
|
| + case 71: /* refargs ::= refargs refarg */
|
| +{ yygotominor.yy4 = (yymsp[-1].minor.yy4 & ~yymsp[0].minor.yy215.mask) | yymsp[0].minor.yy215.value; }
|
| + break;
|
| + case 72: /* refarg ::= MATCH nm */
|
| + case 73: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==73);
|
| +{ yygotominor.yy215.value = 0; yygotominor.yy215.mask = 0x000000; }
|
| + break;
|
| + case 74: /* refarg ::= ON DELETE refact */
|
| +{ yygotominor.yy215.value = yymsp[0].minor.yy4; yygotominor.yy215.mask = 0x0000ff; }
|
| + break;
|
| + case 75: /* refarg ::= ON UPDATE refact */
|
| +{ yygotominor.yy215.value = yymsp[0].minor.yy4<<8; yygotominor.yy215.mask = 0x00ff00; }
|
| + break;
|
| + case 76: /* refact ::= SET NULL */
|
| +{ yygotominor.yy4 = OE_SetNull; /* EV: R-33326-45252 */}
|
| + break;
|
| + case 77: /* refact ::= SET DEFAULT */
|
| +{ yygotominor.yy4 = OE_SetDflt; /* EV: R-33326-45252 */}
|
| + break;
|
| + case 78: /* refact ::= CASCADE */
|
| +{ yygotominor.yy4 = OE_Cascade; /* EV: R-33326-45252 */}
|
| + break;
|
| + case 79: /* refact ::= RESTRICT */
|
| +{ yygotominor.yy4 = OE_Restrict; /* EV: R-33326-45252 */}
|
| + break;
|
| + case 80: /* refact ::= NO ACTION */
|
| +{ yygotominor.yy4 = OE_None; /* EV: R-33326-45252 */}
|
| + break;
|
| + case 82: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
|
| + case 98: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==98);
|
| + case 100: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==100);
|
| + case 102: /* orconf ::= OR resolvetype */ yytestcase(yyruleno==102);
|
| + case 103: /* resolvetype ::= raisetype */ yytestcase(yyruleno==103);
|
| + case 178: /* insert_cmd ::= INSERT orconf */ yytestcase(yyruleno==178);
|
| +{yygotominor.yy4 = yymsp[0].minor.yy4;}
|
| + break;
|
| + case 86: /* conslist_opt ::= */
|
| +{yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
|
| + break;
|
| + case 87: /* conslist_opt ::= COMMA conslist */
|
| +{yygotominor.yy0 = yymsp[-1].minor.yy0;}
|
| + break;
|
| + case 90: /* tconscomma ::= COMMA */
|
| +{pParse->constraintName.n = 0;}
|
| + break;
|
| + case 93: /* tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
|
| +{sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy322,yymsp[0].minor.yy4,yymsp[-2].minor.yy4,0);}
|
| + break;
|
| + case 94: /* tcons ::= UNIQUE LP sortlist RP onconf */
|
| +{sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy322,yymsp[0].minor.yy4,0,0,0,0);}
|
| + break;
|
| + case 95: /* tcons ::= CHECK LP expr RP onconf */
|
| +{sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy118.pExpr);}
|
| + break;
|
| + case 96: /* tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
|
| +{
|
| + sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy322, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy322, yymsp[-1].minor.yy4);
|
| + sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy4);
|
| +}
|
| + break;
|
| + case 99: /* onconf ::= */
|
| + case 101: /* orconf ::= */ yytestcase(yyruleno==101);
|
| +{yygotominor.yy4 = OE_Default;}
|
| + break;
|
| + case 104: /* resolvetype ::= IGNORE */
|
| +{yygotominor.yy4 = OE_Ignore;}
|
| + break;
|
| + case 105: /* resolvetype ::= REPLACE */
|
| + case 179: /* insert_cmd ::= REPLACE */ yytestcase(yyruleno==179);
|
| +{yygotominor.yy4 = OE_Replace;}
|
| + break;
|
| + case 106: /* cmd ::= DROP TABLE ifexists fullname */
|
| +{
|
| + sqlite3DropTable(pParse, yymsp[0].minor.yy259, 0, yymsp[-1].minor.yy4);
|
| +}
|
| + break;
|
| + case 109: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
|
| +{
|
| + sqlite3CreateView(pParse, &yymsp[-8].minor.yy0, &yymsp[-4].minor.yy0, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy322, yymsp[0].minor.yy387, yymsp[-7].minor.yy4, yymsp[-5].minor.yy4);
|
| +}
|
| + break;
|
| + case 110: /* cmd ::= DROP VIEW ifexists fullname */
|
| +{
|
| + sqlite3DropTable(pParse, yymsp[0].minor.yy259, 1, yymsp[-1].minor.yy4);
|
| +}
|
| + break;
|
| + case 111: /* cmd ::= select */
|
| +{
|
| + SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0};
|
| + sqlite3Select(pParse, yymsp[0].minor.yy387, &dest);
|
| + sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy387);
|
| +}
|
| + break;
|
| + case 112: /* select ::= with selectnowith */
|
| +{
|
| + Select *p = yymsp[0].minor.yy387;
|
| + if( p ){
|
| + p->pWith = yymsp[-1].minor.yy451;
|
| + parserDoubleLinkSelect(pParse, p);
|
| + }else{
|
| + sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy451);
|
| + }
|
| + yygotominor.yy387 = p;
|
| +}
|
| + break;
|
| + case 113: /* selectnowith ::= oneselect */
|
| + case 119: /* oneselect ::= values */ yytestcase(yyruleno==119);
|
| +{yygotominor.yy387 = yymsp[0].minor.yy387;}
|
| + break;
|
| + case 114: /* selectnowith ::= selectnowith multiselect_op oneselect */
|
| +{
|
| + Select *pRhs = yymsp[0].minor.yy387;
|
| + Select *pLhs = yymsp[-2].minor.yy387;
|
| + if( pRhs && pRhs->pPrior ){
|
| + SrcList *pFrom;
|
| + Token x;
|
| + x.n = 0;
|
| + parserDoubleLinkSelect(pParse, pRhs);
|
| + pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);
|
| + pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0,0);
|
| + }
|
| + if( pRhs ){
|
| + pRhs->op = (u8)yymsp[-1].minor.yy4;
|
| + pRhs->pPrior = pLhs;
|
| + if( ALWAYS(pLhs) ) pLhs->selFlags &= ~SF_MultiValue;
|
| + pRhs->selFlags &= ~SF_MultiValue;
|
| + if( yymsp[-1].minor.yy4!=TK_ALL ) pParse->hasCompound = 1;
|
| + }else{
|
| + sqlite3SelectDelete(pParse->db, pLhs);
|
| + }
|
| + yygotominor.yy387 = pRhs;
|
| +}
|
| + break;
|
| + case 116: /* multiselect_op ::= UNION ALL */
|
| +{yygotominor.yy4 = TK_ALL;}
|
| + break;
|
| + case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
|
| +{
|
| + yygotominor.yy387 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy322,yymsp[-5].minor.yy259,yymsp[-4].minor.yy314,yymsp[-3].minor.yy322,yymsp[-2].minor.yy314,yymsp[-1].minor.yy322,yymsp[-7].minor.yy4,yymsp[0].minor.yy292.pLimit,yymsp[0].minor.yy292.pOffset);
|
| +#if SELECTTRACE_ENABLED
|
| + /* Populate the Select.zSelName[] string that is used to help with
|
| + ** query planner debugging, to differentiate between multiple Select
|
| + ** objects in a complex query.
|
| + **
|
| + ** If the SELECT keyword is immediately followed by a C-style comment
|
| + ** then extract the first few alphanumeric characters from within that
|
| + ** comment to be the zSelName value. Otherwise, the label is #N where
|
| + ** is an integer that is incremented with each SELECT statement seen.
|
| + */
|
| + if( yygotominor.yy387!=0 ){
|
| + const char *z = yymsp[-8].minor.yy0.z+6;
|
| + int i;
|
| + sqlite3_snprintf(sizeof(yygotominor.yy387->zSelName), yygotominor.yy387->zSelName, "#%d",
|
| + ++pParse->nSelect);
|
| + while( z[0]==' ' ) z++;
|
| + if( z[0]=='/' && z[1]=='*' ){
|
| + z += 2;
|
| + while( z[0]==' ' ) z++;
|
| + for(i=0; sqlite3Isalnum(z[i]); i++){}
|
| + sqlite3_snprintf(sizeof(yygotominor.yy387->zSelName), yygotominor.yy387->zSelName, "%.*s", i, z);
|
| + }
|
| + }
|
| +#endif /* SELECTRACE_ENABLED */
|
| +}
|
| + break;
|
| + case 120: /* values ::= VALUES LP nexprlist RP */
|
| +{
|
| + yygotominor.yy387 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy322,0,0,0,0,0,SF_Values,0,0);
|
| +}
|
| + break;
|
| + case 121: /* values ::= values COMMA LP exprlist RP */
|
| +{
|
| + Select *pRight, *pLeft = yymsp[-4].minor.yy387;
|
| + pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy322,0,0,0,0,0,SF_Values|SF_MultiValue,0,0);
|
| + if( ALWAYS(pLeft) ) pLeft->selFlags &= ~SF_MultiValue;
|
| + if( pRight ){
|
| + pRight->op = TK_ALL;
|
| + pLeft = yymsp[-4].minor.yy387;
|
| + pRight->pPrior = pLeft;
|
| + yygotominor.yy387 = pRight;
|
| + }else{
|
| + yygotominor.yy387 = pLeft;
|
| + }
|
| +}
|
| + break;
|
| + case 122: /* distinct ::= DISTINCT */
|
| +{yygotominor.yy4 = SF_Distinct;}
|
| + break;
|
| + case 123: /* distinct ::= ALL */
|
| +{yygotominor.yy4 = SF_All;}
|
| + break;
|
| + case 125: /* sclp ::= selcollist COMMA */
|
| + case 244: /* eidlist_opt ::= LP eidlist RP */ yytestcase(yyruleno==244);
|
| +{yygotominor.yy322 = yymsp[-1].minor.yy322;}
|
| + break;
|
| + case 126: /* sclp ::= */
|
| + case 155: /* orderby_opt ::= */ yytestcase(yyruleno==155);
|
| + case 162: /* groupby_opt ::= */ yytestcase(yyruleno==162);
|
| + case 237: /* exprlist ::= */ yytestcase(yyruleno==237);
|
| + case 243: /* eidlist_opt ::= */ yytestcase(yyruleno==243);
|
| +{yygotominor.yy322 = 0;}
|
| + break;
|
| + case 127: /* selcollist ::= sclp expr as */
|
| +{
|
| + yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy322, yymsp[-1].minor.yy118.pExpr);
|
| + if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[0].minor.yy0, 1);
|
| + sqlite3ExprListSetSpan(pParse,yygotominor.yy322,&yymsp[-1].minor.yy118);
|
| +}
|
| + break;
|
| + case 128: /* selcollist ::= sclp STAR */
|
| +{
|
| + Expr *p = sqlite3Expr(pParse->db, TK_ASTERISK, 0);
|
| + yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy322, p);
|
| +}
|
| + break;
|
| + case 129: /* selcollist ::= sclp nm DOT STAR */
|
| +{
|
| + Expr *pRight = sqlite3PExpr(pParse, TK_ASTERISK, 0, 0, &yymsp[0].minor.yy0);
|
| + Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
|
| + Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
|
| + yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322, pDot);
|
| +}
|
| + break;
|
| + case 132: /* as ::= */
|
| +{yygotominor.yy0.n = 0;}
|
| + break;
|
| + case 133: /* from ::= */
|
| +{yygotominor.yy259 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy259));}
|
| + break;
|
| + case 134: /* from ::= FROM seltablist */
|
| +{
|
| + yygotominor.yy259 = yymsp[0].minor.yy259;
|
| + sqlite3SrcListShiftJoinType(yygotominor.yy259);
|
| +}
|
| + break;
|
| + case 135: /* stl_prefix ::= seltablist joinop */
|
| +{
|
| + yygotominor.yy259 = yymsp[-1].minor.yy259;
|
| + if( ALWAYS(yygotominor.yy259 && yygotominor.yy259->nSrc>0) ) yygotominor.yy259->a[yygotominor.yy259->nSrc-1].fg.jointype = (u8)yymsp[0].minor.yy4;
|
| +}
|
| + break;
|
| + case 136: /* stl_prefix ::= */
|
| +{yygotominor.yy259 = 0;}
|
| + break;
|
| + case 137: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
|
| +{
|
| + yygotominor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
|
| + sqlite3SrcListIndexedBy(pParse, yygotominor.yy259, &yymsp[-2].minor.yy0);
|
| +}
|
| + break;
|
| + case 138: /* seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
|
| +{
|
| + yygotominor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-8].minor.yy259,&yymsp[-7].minor.yy0,&yymsp[-6].minor.yy0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
|
| + sqlite3SrcListFuncArgs(pParse, yygotominor.yy259, yymsp[-4].minor.yy322);
|
| +}
|
| + break;
|
| + case 139: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
|
| +{
|
| + yygotominor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy387,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
|
| + }
|
| + break;
|
| + case 140: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
|
| +{
|
| + if( yymsp[-6].minor.yy259==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy314==0 && yymsp[0].minor.yy384==0 ){
|
| + yygotominor.yy259 = yymsp[-4].minor.yy259;
|
| + }else if( yymsp[-4].minor.yy259->nSrc==1 ){
|
| + yygotominor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
|
| + if( yygotominor.yy259 ){
|
| + struct SrcList_item *pNew = &yygotominor.yy259->a[yygotominor.yy259->nSrc-1];
|
| + struct SrcList_item *pOld = yymsp[-4].minor.yy259->a;
|
| + pNew->zName = pOld->zName;
|
| + pNew->zDatabase = pOld->zDatabase;
|
| + pNew->pSelect = pOld->pSelect;
|
| + pOld->zName = pOld->zDatabase = 0;
|
| + pOld->pSelect = 0;
|
| + }
|
| + sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy259);
|
| + }else{
|
| + Select *pSubquery;
|
| + sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy259);
|
| + pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy259,0,0,0,0,SF_NestedFrom,0,0);
|
| + yygotominor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
|
| + }
|
| + }
|
| + break;
|
| + case 141: /* dbnm ::= */
|
| + case 150: /* indexed_opt ::= */ yytestcase(yyruleno==150);
|
| +{yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
|
| + break;
|
| + case 143: /* fullname ::= nm dbnm */
|
| +{yygotominor.yy259 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
|
| + break;
|
| + case 144: /* joinop ::= COMMA|JOIN */
|
| +{ yygotominor.yy4 = JT_INNER; }
|
| + break;
|
| + case 145: /* joinop ::= JOIN_KW JOIN */
|
| +{ yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
|
| + break;
|
| + case 146: /* joinop ::= JOIN_KW nm JOIN */
|
| +{ yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
|
| + break;
|
| + case 147: /* joinop ::= JOIN_KW nm nm JOIN */
|
| +{ yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
|
| + break;
|
| + case 148: /* on_opt ::= ON expr */
|
| + case 165: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==165);
|
| + case 172: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==172);
|
| + case 232: /* case_else ::= ELSE expr */ yytestcase(yyruleno==232);
|
| + case 234: /* case_operand ::= expr */ yytestcase(yyruleno==234);
|
| +{yygotominor.yy314 = yymsp[0].minor.yy118.pExpr;}
|
| + break;
|
| + case 149: /* on_opt ::= */
|
| + case 164: /* having_opt ::= */ yytestcase(yyruleno==164);
|
| + case 171: /* where_opt ::= */ yytestcase(yyruleno==171);
|
| + case 233: /* case_else ::= */ yytestcase(yyruleno==233);
|
| + case 235: /* case_operand ::= */ yytestcase(yyruleno==235);
|
| +{yygotominor.yy314 = 0;}
|
| + break;
|
| + case 152: /* indexed_opt ::= NOT INDEXED */
|
| +{yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
|
| + break;
|
| + case 153: /* using_opt ::= USING LP idlist RP */
|
| + case 181: /* idlist_opt ::= LP idlist RP */ yytestcase(yyruleno==181);
|
| +{yygotominor.yy384 = yymsp[-1].minor.yy384;}
|
| + break;
|
| + case 154: /* using_opt ::= */
|
| + case 180: /* idlist_opt ::= */ yytestcase(yyruleno==180);
|
| +{yygotominor.yy384 = 0;}
|
| + break;
|
| + case 156: /* orderby_opt ::= ORDER BY sortlist */
|
| + case 163: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==163);
|
| + case 236: /* exprlist ::= nexprlist */ yytestcase(yyruleno==236);
|
| +{yygotominor.yy322 = yymsp[0].minor.yy322;}
|
| + break;
|
| + case 157: /* sortlist ::= sortlist COMMA expr sortorder */
|
| +{
|
| + yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322,yymsp[-1].minor.yy118.pExpr);
|
| + sqlite3ExprListSetSortOrder(yygotominor.yy322,yymsp[0].minor.yy4);
|
| +}
|
| + break;
|
| + case 158: /* sortlist ::= expr sortorder */
|
| +{
|
| + yygotominor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy118.pExpr);
|
| + sqlite3ExprListSetSortOrder(yygotominor.yy322,yymsp[0].minor.yy4);
|
| +}
|
| + break;
|
| + case 159: /* sortorder ::= ASC */
|
| +{yygotominor.yy4 = SQLITE_SO_ASC;}
|
| + break;
|
| + case 160: /* sortorder ::= DESC */
|
| +{yygotominor.yy4 = SQLITE_SO_DESC;}
|
| + break;
|
| + case 161: /* sortorder ::= */
|
| +{yygotominor.yy4 = SQLITE_SO_UNDEFINED;}
|
| + break;
|
| + case 166: /* limit_opt ::= */
|
| +{yygotominor.yy292.pLimit = 0; yygotominor.yy292.pOffset = 0;}
|
| + break;
|
| + case 167: /* limit_opt ::= LIMIT expr */
|
| +{yygotominor.yy292.pLimit = yymsp[0].minor.yy118.pExpr; yygotominor.yy292.pOffset = 0;}
|
| + break;
|
| + case 168: /* limit_opt ::= LIMIT expr OFFSET expr */
|
| +{yygotominor.yy292.pLimit = yymsp[-2].minor.yy118.pExpr; yygotominor.yy292.pOffset = yymsp[0].minor.yy118.pExpr;}
|
| + break;
|
| + case 169: /* limit_opt ::= LIMIT expr COMMA expr */
|
| +{yygotominor.yy292.pOffset = yymsp[-2].minor.yy118.pExpr; yygotominor.yy292.pLimit = yymsp[0].minor.yy118.pExpr;}
|
| + break;
|
| + case 170: /* cmd ::= with DELETE FROM fullname indexed_opt where_opt */
|
| +{
|
| + sqlite3WithPush(pParse, yymsp[-5].minor.yy451, 1);
|
| + sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy259, &yymsp[-1].minor.yy0);
|
| + sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy259,yymsp[0].minor.yy314);
|
| +}
|
| + break;
|
| + case 173: /* cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt */
|
| +{
|
| + sqlite3WithPush(pParse, yymsp[-7].minor.yy451, 1);
|
| + sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy259, &yymsp[-3].minor.yy0);
|
| + sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy322,"set list");
|
| + sqlite3Update(pParse,yymsp[-4].minor.yy259,yymsp[-1].minor.yy322,yymsp[0].minor.yy314,yymsp[-5].minor.yy4);
|
| +}
|
| + break;
|
| + case 174: /* setlist ::= setlist COMMA nm EQ expr */
|
| +{
|
| + yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy322, yymsp[0].minor.yy118.pExpr);
|
| + sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
|
| +}
|
| + break;
|
| + case 175: /* setlist ::= nm EQ expr */
|
| +{
|
| + yygotominor.yy322 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy118.pExpr);
|
| + sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
|
| +}
|
| + break;
|
| + case 176: /* cmd ::= with insert_cmd INTO fullname idlist_opt select */
|
| +{
|
| + sqlite3WithPush(pParse, yymsp[-5].minor.yy451, 1);
|
| + sqlite3Insert(pParse, yymsp[-2].minor.yy259, yymsp[0].minor.yy387, yymsp[-1].minor.yy384, yymsp[-4].minor.yy4);
|
| +}
|
| + break;
|
| + case 177: /* cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES */
|
| +{
|
| + sqlite3WithPush(pParse, yymsp[-6].minor.yy451, 1);
|
| + sqlite3Insert(pParse, yymsp[-3].minor.yy259, 0, yymsp[-2].minor.yy384, yymsp[-5].minor.yy4);
|
| +}
|
| + break;
|
| + case 182: /* idlist ::= idlist COMMA nm */
|
| +{yygotominor.yy384 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy384,&yymsp[0].minor.yy0);}
|
| + break;
|
| + case 183: /* idlist ::= nm */
|
| +{yygotominor.yy384 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
|
| + break;
|
| + case 184: /* expr ::= term */
|
| +{yygotominor.yy118 = yymsp[0].minor.yy118;}
|
| + break;
|
| + case 185: /* expr ::= LP expr RP */
|
| +{yygotominor.yy118.pExpr = yymsp[-1].minor.yy118.pExpr; spanSet(&yygotominor.yy118,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
|
| + break;
|
| + case 186: /* term ::= NULL */
|
| + case 191: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==191);
|
| + case 192: /* term ::= STRING */ yytestcase(yyruleno==192);
|
| +{spanExpr(&yygotominor.yy118, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
|
| + break;
|
| + case 187: /* expr ::= ID|INDEXED */
|
| + case 188: /* expr ::= JOIN_KW */ yytestcase(yyruleno==188);
|
| +{spanExpr(&yygotominor.yy118, pParse, TK_ID, &yymsp[0].minor.yy0);}
|
| + break;
|
| + case 189: /* expr ::= nm DOT nm */
|
| +{
|
| + Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
|
| + Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
|
| + yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
|
| + spanSet(&yygotominor.yy118,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
|
| +}
|
| + break;
|
| + case 190: /* expr ::= nm DOT nm DOT nm */
|
| +{
|
| + Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
|
| + Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
|
| + Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
|
| + Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
|
| + yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
|
| + spanSet(&yygotominor.yy118,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
|
| +}
|
| + break;
|
| + case 193: /* expr ::= VARIABLE */
|
| +{
|
| + if( yymsp[0].minor.yy0.n>=2 && yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1]) ){
|
| + /* When doing a nested parse, one can include terms in an expression
|
| + ** that look like this: #1 #2 ... These terms refer to registers
|
| + ** in the virtual machine. #N is the N-th register. */
|
| + if( pParse->nested==0 ){
|
| + sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
|
| + yygotominor.yy118.pExpr = 0;
|
| + }else{
|
| + yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
|
| + if( yygotominor.yy118.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy118.pExpr->iTable);
|
| + }
|
| + }else{
|
| + spanExpr(&yygotominor.yy118, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
|
| + sqlite3ExprAssignVarNumber(pParse, yygotominor.yy118.pExpr);
|
| + }
|
| + spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
|
| +}
|
| + break;
|
| + case 194: /* expr ::= expr COLLATE ID|STRING */
|
| +{
|
| + yygotominor.yy118.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy118.pExpr, &yymsp[0].minor.yy0, 1);
|
| + yygotominor.yy118.zStart = yymsp[-2].minor.yy118.zStart;
|
| + yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
|
| +}
|
| + break;
|
| + case 195: /* expr ::= CAST LP expr AS typetoken RP */
|
| +{
|
| + yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy118.pExpr, 0, &yymsp[-1].minor.yy0);
|
| + spanSet(&yygotominor.yy118,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
|
| +}
|
| + break;
|
| + case 196: /* expr ::= ID|INDEXED LP distinct exprlist RP */
|
| +{
|
| + if( yymsp[-1].minor.yy322 && yymsp[-1].minor.yy322->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
|
| + sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
|
| + }
|
| + yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy322, &yymsp[-4].minor.yy0);
|
| + spanSet(&yygotominor.yy118,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
|
| + if( yymsp[-2].minor.yy4==SF_Distinct && yygotominor.yy118.pExpr ){
|
| + yygotominor.yy118.pExpr->flags |= EP_Distinct;
|
| + }
|
| +}
|
| + break;
|
| + case 197: /* expr ::= ID|INDEXED LP STAR RP */
|
| +{
|
| + yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
|
| + spanSet(&yygotominor.yy118,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
|
| +}
|
| + break;
|
| + case 198: /* term ::= CTIME_KW */
|
| +{
|
| + yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0);
|
| + spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
|
| +}
|
| + break;
|
| + case 199: /* expr ::= expr AND expr */
|
| + case 200: /* expr ::= expr OR expr */ yytestcase(yyruleno==200);
|
| + case 201: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==201);
|
| + case 202: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==202);
|
| + case 203: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==203);
|
| + case 204: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==204);
|
| + case 205: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==205);
|
| + case 206: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==206);
|
| +{spanBinaryExpr(&yygotominor.yy118,pParse,yymsp[-1].major,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy118);}
|
| + break;
|
| + case 207: /* likeop ::= LIKE_KW|MATCH */
|
| +{yygotominor.yy342.eOperator = yymsp[0].minor.yy0; yygotominor.yy342.bNot = 0;}
|
| + break;
|
| + case 208: /* likeop ::= NOT LIKE_KW|MATCH */
|
| +{yygotominor.yy342.eOperator = yymsp[0].minor.yy0; yygotominor.yy342.bNot = 1;}
|
| + break;
|
| + case 209: /* expr ::= expr likeop expr */
|
| +{
|
| + ExprList *pList;
|
| + pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy118.pExpr);
|
| + pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy118.pExpr);
|
| + yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy342.eOperator);
|
| + exprNot(pParse, yymsp[-1].minor.yy342.bNot, &yygotominor.yy118.pExpr);
|
| + yygotominor.yy118.zStart = yymsp[-2].minor.yy118.zStart;
|
| + yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
|
| + if( yygotominor.yy118.pExpr ) yygotominor.yy118.pExpr->flags |= EP_InfixFunc;
|
| +}
|
| + break;
|
| + case 210: /* expr ::= expr likeop expr ESCAPE expr */
|
| +{
|
| + ExprList *pList;
|
| + pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
|
| + pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy118.pExpr);
|
| + pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy118.pExpr);
|
| + yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy342.eOperator);
|
| + exprNot(pParse, yymsp[-3].minor.yy342.bNot, &yygotominor.yy118.pExpr);
|
| + yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
|
| + yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
|
| + if( yygotominor.yy118.pExpr ) yygotominor.yy118.pExpr->flags |= EP_InfixFunc;
|
| +}
|
| + break;
|
| + case 211: /* expr ::= expr ISNULL|NOTNULL */
|
| +{spanUnaryPostfix(&yygotominor.yy118,pParse,yymsp[0].major,&yymsp[-1].minor.yy118,&yymsp[0].minor.yy0);}
|
| + break;
|
| + case 212: /* expr ::= expr NOT NULL */
|
| +{spanUnaryPostfix(&yygotominor.yy118,pParse,TK_NOTNULL,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy0);}
|
| + break;
|
| + case 213: /* expr ::= expr IS expr */
|
| +{
|
| + spanBinaryExpr(&yygotominor.yy118,pParse,TK_IS,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy118);
|
| + binaryToUnaryIfNull(pParse, yymsp[0].minor.yy118.pExpr, yygotominor.yy118.pExpr, TK_ISNULL);
|
| +}
|
| + break;
|
| + case 214: /* expr ::= expr IS NOT expr */
|
| +{
|
| + spanBinaryExpr(&yygotominor.yy118,pParse,TK_ISNOT,&yymsp[-3].minor.yy118,&yymsp[0].minor.yy118);
|
| + binaryToUnaryIfNull(pParse, yymsp[0].minor.yy118.pExpr, yygotominor.yy118.pExpr, TK_NOTNULL);
|
| +}
|
| + break;
|
| + case 215: /* expr ::= NOT expr */
|
| + case 216: /* expr ::= BITNOT expr */ yytestcase(yyruleno==216);
|
| +{spanUnaryPrefix(&yygotominor.yy118,pParse,yymsp[-1].major,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
|
| + break;
|
| + case 217: /* expr ::= MINUS expr */
|
| +{spanUnaryPrefix(&yygotominor.yy118,pParse,TK_UMINUS,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
|
| + break;
|
| + case 218: /* expr ::= PLUS expr */
|
| +{spanUnaryPrefix(&yygotominor.yy118,pParse,TK_UPLUS,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
|
| + break;
|
| + case 221: /* expr ::= expr between_op expr AND expr */
|
| +{
|
| + ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
|
| + pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy118.pExpr);
|
| + yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy118.pExpr, 0, 0);
|
| + if( yygotominor.yy118.pExpr ){
|
| + yygotominor.yy118.pExpr->x.pList = pList;
|
| + }else{
|
| + sqlite3ExprListDelete(pParse->db, pList);
|
| + }
|
| + exprNot(pParse, yymsp[-3].minor.yy4, &yygotominor.yy118.pExpr);
|
| + yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
|
| + yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
|
| +}
|
| + break;
|
| + case 224: /* expr ::= expr in_op LP exprlist RP */
|
| +{
|
| + if( yymsp[-1].minor.yy322==0 ){
|
| + /* Expressions of the form
|
| + **
|
| + ** expr1 IN ()
|
| + ** expr1 NOT IN ()
|
| + **
|
| + ** simplify to constants 0 (false) and 1 (true), respectively,
|
| + ** regardless of the value of expr1.
|
| + */
|
| + yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy4]);
|
| + sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy118.pExpr);
|
| + }else if( yymsp[-1].minor.yy322->nExpr==1 ){
|
| + /* Expressions of the form:
|
| + **
|
| + ** expr1 IN (?1)
|
| + ** expr1 NOT IN (?2)
|
| + **
|
| + ** with exactly one value on the RHS can be simplified to something
|
| + ** like this:
|
| + **
|
| + ** expr1 == ?1
|
| + ** expr1 <> ?2
|
| + **
|
| + ** But, the RHS of the == or <> is marked with the EP_Generic flag
|
| + ** so that it may not contribute to the computation of comparison
|
| + ** affinity or the collating sequence to use for comparison. Otherwise,
|
| + ** the semantics would be subtly different from IN or NOT IN.
|
| + */
|
| + Expr *pRHS = yymsp[-1].minor.yy322->a[0].pExpr;
|
| + yymsp[-1].minor.yy322->a[0].pExpr = 0;
|
| + sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy322);
|
| + /* pRHS cannot be NULL because a malloc error would have been detected
|
| + ** before now and control would have never reached this point */
|
| + if( ALWAYS(pRHS) ){
|
| + pRHS->flags &= ~EP_Collate;
|
| + pRHS->flags |= EP_Generic;
|
| + }
|
| + yygotominor.yy118.pExpr = sqlite3PExpr(pParse, yymsp[-3].minor.yy4 ? TK_NE : TK_EQ, yymsp[-4].minor.yy118.pExpr, pRHS, 0);
|
| + }else{
|
| + yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy118.pExpr, 0, 0);
|
| + if( yygotominor.yy118.pExpr ){
|
| + yygotominor.yy118.pExpr->x.pList = yymsp[-1].minor.yy322;
|
| + sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy118.pExpr);
|
| + }else{
|
| + sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy322);
|
| + }
|
| + exprNot(pParse, yymsp[-3].minor.yy4, &yygotominor.yy118.pExpr);
|
| + }
|
| + yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
|
| + yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
|
| + }
|
| + break;
|
| + case 225: /* expr ::= LP select RP */
|
| +{
|
| + yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
|
| + if( yygotominor.yy118.pExpr ){
|
| + yygotominor.yy118.pExpr->x.pSelect = yymsp[-1].minor.yy387;
|
| + ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect|EP_Subquery);
|
| + sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy118.pExpr);
|
| + }else{
|
| + sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
|
| + }
|
| + yygotominor.yy118.zStart = yymsp[-2].minor.yy0.z;
|
| + yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
|
| + }
|
| + break;
|
| + case 226: /* expr ::= expr in_op LP select RP */
|
| +{
|
| + yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy118.pExpr, 0, 0);
|
| + if( yygotominor.yy118.pExpr ){
|
| + yygotominor.yy118.pExpr->x.pSelect = yymsp[-1].minor.yy387;
|
| + ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect|EP_Subquery);
|
| + sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy118.pExpr);
|
| + }else{
|
| + sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
|
| + }
|
| + exprNot(pParse, yymsp[-3].minor.yy4, &yygotominor.yy118.pExpr);
|
| + yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
|
| + yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
|
| + }
|
| + break;
|
| + case 227: /* expr ::= expr in_op nm dbnm */
|
| +{
|
| + SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
|
| + yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy118.pExpr, 0, 0);
|
| + if( yygotominor.yy118.pExpr ){
|
| + yygotominor.yy118.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
|
| + ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect|EP_Subquery);
|
| + sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy118.pExpr);
|
| + }else{
|
| + sqlite3SrcListDelete(pParse->db, pSrc);
|
| + }
|
| + exprNot(pParse, yymsp[-2].minor.yy4, &yygotominor.yy118.pExpr);
|
| + yygotominor.yy118.zStart = yymsp[-3].minor.yy118.zStart;
|
| + yygotominor.yy118.zEnd = yymsp[0].minor.yy0.z ? &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] : &yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n];
|
| + }
|
| + break;
|
| + case 228: /* expr ::= EXISTS LP select RP */
|
| +{
|
| + Expr *p = yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
|
| + if( p ){
|
| + p->x.pSelect = yymsp[-1].minor.yy387;
|
| + ExprSetProperty(p, EP_xIsSelect|EP_Subquery);
|
| + sqlite3ExprSetHeightAndFlags(pParse, p);
|
| + }else{
|
| + sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
|
| + }
|
| + yygotominor.yy118.zStart = yymsp[-3].minor.yy0.z;
|
| + yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
|
| + }
|
| + break;
|
| + case 229: /* expr ::= CASE case_operand case_exprlist case_else END */
|
| +{
|
| + yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy314, 0, 0);
|
| + if( yygotominor.yy118.pExpr ){
|
| + yygotominor.yy118.pExpr->x.pList = yymsp[-1].minor.yy314 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy322,yymsp[-1].minor.yy314) : yymsp[-2].minor.yy322;
|
| + sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy118.pExpr);
|
| + }else{
|
| + sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy322);
|
| + sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy314);
|
| + }
|
| + yygotominor.yy118.zStart = yymsp[-4].minor.yy0.z;
|
| + yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
|
| +}
|
| + break;
|
| + case 230: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
|
| +{
|
| + yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, yymsp[-2].minor.yy118.pExpr);
|
| + yygotominor.yy322 = sqlite3ExprListAppend(pParse,yygotominor.yy322, yymsp[0].minor.yy118.pExpr);
|
| +}
|
| + break;
|
| + case 231: /* case_exprlist ::= WHEN expr THEN expr */
|
| +{
|
| + yygotominor.yy322 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
|
| + yygotominor.yy322 = sqlite3ExprListAppend(pParse,yygotominor.yy322, yymsp[0].minor.yy118.pExpr);
|
| +}
|
| + break;
|
| + case 238: /* nexprlist ::= nexprlist COMMA expr */
|
| +{yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy322,yymsp[0].minor.yy118.pExpr);}
|
| + break;
|
| + case 239: /* nexprlist ::= expr */
|
| +{yygotominor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy118.pExpr);}
|
| + break;
|
| + case 240: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
|
| +{
|
| + sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
|
| + sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy322, yymsp[-10].minor.yy4,
|
| + &yymsp[-11].minor.yy0, yymsp[0].minor.yy314, SQLITE_SO_ASC, yymsp[-8].minor.yy4);
|
| +}
|
| + break;
|
| + case 241: /* uniqueflag ::= UNIQUE */
|
| + case 292: /* raisetype ::= ABORT */ yytestcase(yyruleno==292);
|
| +{yygotominor.yy4 = OE_Abort;}
|
| + break;
|
| + case 242: /* uniqueflag ::= */
|
| +{yygotominor.yy4 = OE_None;}
|
| + break;
|
| + case 245: /* eidlist ::= eidlist COMMA nm collate sortorder */
|
| +{
|
| + yygotominor.yy322 = parserAddExprIdListTerm(pParse, yymsp[-4].minor.yy322, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy4, yymsp[0].minor.yy4);
|
| +}
|
| + break;
|
| + case 246: /* eidlist ::= nm collate sortorder */
|
| +{
|
| + yygotominor.yy322 = parserAddExprIdListTerm(pParse, 0, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy4, yymsp[0].minor.yy4);
|
| +}
|
| + break;
|
| + case 249: /* cmd ::= DROP INDEX ifexists fullname */
|
| +{sqlite3DropIndex(pParse, yymsp[0].minor.yy259, yymsp[-1].minor.yy4);}
|
| + break;
|
| + case 250: /* cmd ::= VACUUM */
|
| + case 251: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==251);
|
| +{sqlite3Vacuum(pParse);}
|
| + break;
|
| + case 252: /* cmd ::= PRAGMA nm dbnm */
|
| +{sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
|
| + break;
|
| + case 253: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
|
| +{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
|
| + break;
|
| + case 254: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
|
| +{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
|
| + break;
|
| + case 255: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
|
| +{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
|
| + break;
|
| + case 256: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
|
| +{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
|
| + break;
|
| + case 265: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
|
| +{
|
| + Token all;
|
| + all.z = yymsp[-3].minor.yy0.z;
|
| + all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
|
| + sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy203, &all);
|
| +}
|
| + break;
|
| + case 266: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
|
| +{
|
| + sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy4, yymsp[-4].minor.yy90.a, yymsp[-4].minor.yy90.b, yymsp[-2].minor.yy259, yymsp[0].minor.yy314, yymsp[-10].minor.yy4, yymsp[-8].minor.yy4);
|
| + yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
|
| +}
|
| + break;
|
| + case 267: /* trigger_time ::= BEFORE */
|
| + case 270: /* trigger_time ::= */ yytestcase(yyruleno==270);
|
| +{ yygotominor.yy4 = TK_BEFORE; }
|
| + break;
|
| + case 268: /* trigger_time ::= AFTER */
|
| +{ yygotominor.yy4 = TK_AFTER; }
|
| + break;
|
| + case 269: /* trigger_time ::= INSTEAD OF */
|
| +{ yygotominor.yy4 = TK_INSTEAD;}
|
| + break;
|
| + case 271: /* trigger_event ::= DELETE|INSERT */
|
| + case 272: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==272);
|
| +{yygotominor.yy90.a = yymsp[0].major; yygotominor.yy90.b = 0;}
|
| + break;
|
| + case 273: /* trigger_event ::= UPDATE OF idlist */
|
| +{yygotominor.yy90.a = TK_UPDATE; yygotominor.yy90.b = yymsp[0].minor.yy384;}
|
| + break;
|
| + case 276: /* when_clause ::= */
|
| + case 297: /* key_opt ::= */ yytestcase(yyruleno==297);
|
| +{ yygotominor.yy314 = 0; }
|
| + break;
|
| + case 277: /* when_clause ::= WHEN expr */
|
| + case 298: /* key_opt ::= KEY expr */ yytestcase(yyruleno==298);
|
| +{ yygotominor.yy314 = yymsp[0].minor.yy118.pExpr; }
|
| + break;
|
| + case 278: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
|
| +{
|
| + assert( yymsp[-2].minor.yy203!=0 );
|
| + yymsp[-2].minor.yy203->pLast->pNext = yymsp[-1].minor.yy203;
|
| + yymsp[-2].minor.yy203->pLast = yymsp[-1].minor.yy203;
|
| + yygotominor.yy203 = yymsp[-2].minor.yy203;
|
| +}
|
| + break;
|
| + case 279: /* trigger_cmd_list ::= trigger_cmd SEMI */
|
| +{
|
| + assert( yymsp[-1].minor.yy203!=0 );
|
| + yymsp[-1].minor.yy203->pLast = yymsp[-1].minor.yy203;
|
| + yygotominor.yy203 = yymsp[-1].minor.yy203;
|
| +}
|
| + break;
|
| + case 281: /* trnm ::= nm DOT nm */
|
| +{
|
| + yygotominor.yy0 = yymsp[0].minor.yy0;
|
| + sqlite3ErrorMsg(pParse,
|
| + "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
|
| + "statements within triggers");
|
| +}
|
| + break;
|
| + case 283: /* tridxby ::= INDEXED BY nm */
|
| +{
|
| + sqlite3ErrorMsg(pParse,
|
| + "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
|
| + "within triggers");
|
| +}
|
| + break;
|
| + case 284: /* tridxby ::= NOT INDEXED */
|
| +{
|
| + sqlite3ErrorMsg(pParse,
|
| + "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
|
| + "within triggers");
|
| +}
|
| + break;
|
| + case 285: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
|
| +{ yygotominor.yy203 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy322, yymsp[0].minor.yy314, yymsp[-5].minor.yy4); }
|
| + break;
|
| + case 286: /* trigger_cmd ::= insert_cmd INTO trnm idlist_opt select */
|
| +{yygotominor.yy203 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy384, yymsp[0].minor.yy387, yymsp[-4].minor.yy4);}
|
| + break;
|
| + case 287: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
|
| +{yygotominor.yy203 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy314);}
|
| + break;
|
| + case 288: /* trigger_cmd ::= select */
|
| +{yygotominor.yy203 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy387); }
|
| + break;
|
| + case 289: /* expr ::= RAISE LP IGNORE RP */
|
| +{
|
| + yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
|
| + if( yygotominor.yy118.pExpr ){
|
| + yygotominor.yy118.pExpr->affinity = OE_Ignore;
|
| + }
|
| + yygotominor.yy118.zStart = yymsp[-3].minor.yy0.z;
|
| + yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
|
| +}
|
| + break;
|
| + case 290: /* expr ::= RAISE LP raisetype COMMA nm RP */
|
| +{
|
| + yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
|
| + if( yygotominor.yy118.pExpr ) {
|
| + yygotominor.yy118.pExpr->affinity = (char)yymsp[-3].minor.yy4;
|
| + }
|
| + yygotominor.yy118.zStart = yymsp[-5].minor.yy0.z;
|
| + yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
|
| +}
|
| + break;
|
| + case 291: /* raisetype ::= ROLLBACK */
|
| +{yygotominor.yy4 = OE_Rollback;}
|
| + break;
|
| + case 293: /* raisetype ::= FAIL */
|
| +{yygotominor.yy4 = OE_Fail;}
|
| + break;
|
| + case 294: /* cmd ::= DROP TRIGGER ifexists fullname */
|
| +{
|
| + sqlite3DropTrigger(pParse,yymsp[0].minor.yy259,yymsp[-1].minor.yy4);
|
| +}
|
| + break;
|
| + case 295: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
|
| +{
|
| + sqlite3Attach(pParse, yymsp[-3].minor.yy118.pExpr, yymsp[-1].minor.yy118.pExpr, yymsp[0].minor.yy314);
|
| +}
|
| + break;
|
| + case 296: /* cmd ::= DETACH database_kw_opt expr */
|
| +{
|
| + sqlite3Detach(pParse, yymsp[0].minor.yy118.pExpr);
|
| +}
|
| + break;
|
| + case 301: /* cmd ::= REINDEX */
|
| +{sqlite3Reindex(pParse, 0, 0);}
|
| + break;
|
| + case 302: /* cmd ::= REINDEX nm dbnm */
|
| +{sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
|
| + break;
|
| + case 303: /* cmd ::= ANALYZE */
|
| +{sqlite3Analyze(pParse, 0, 0);}
|
| + break;
|
| + case 304: /* cmd ::= ANALYZE nm dbnm */
|
| +{sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
|
| + break;
|
| + case 305: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
|
| +{
|
| + sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy259,&yymsp[0].minor.yy0);
|
| +}
|
| + break;
|
| + case 306: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
|
| +{
|
| + sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
|
| +}
|
| + break;
|
| + case 307: /* add_column_fullname ::= fullname */
|
| +{
|
| + pParse->db->lookaside.bEnabled = 0;
|
| + sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy259);
|
| +}
|
| + break;
|
| + case 310: /* cmd ::= create_vtab */
|
| +{sqlite3VtabFinishParse(pParse,0);}
|
| + break;
|
| + case 311: /* cmd ::= create_vtab LP vtabarglist RP */
|
| +{sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
|
| + break;
|
| + case 312: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
|
| +{
|
| + sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy4);
|
| +}
|
| + break;
|
| + case 315: /* vtabarg ::= */
|
| +{sqlite3VtabArgInit(pParse);}
|
| + break;
|
| + case 317: /* vtabargtoken ::= ANY */
|
| + case 318: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==318);
|
| + case 319: /* lp ::= LP */ yytestcase(yyruleno==319);
|
| +{sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
|
| + break;
|
| + case 323: /* with ::= */
|
| +{yygotominor.yy451 = 0;}
|
| + break;
|
| + case 324: /* with ::= WITH wqlist */
|
| + case 325: /* with ::= WITH RECURSIVE wqlist */ yytestcase(yyruleno==325);
|
| +{ yygotominor.yy451 = yymsp[0].minor.yy451; }
|
| + break;
|
| + case 326: /* wqlist ::= nm eidlist_opt AS LP select RP */
|
| +{
|
| + yygotominor.yy451 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy322, yymsp[-1].minor.yy387);
|
| +}
|
| + break;
|
| + case 327: /* wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
|
| +{
|
| + yygotominor.yy451 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy451, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy322, yymsp[-1].minor.yy387);
|
| +}
|
| + break;
|
| + default:
|
| + /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
|
| + /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
|
| + /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
|
| + /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
|
| + /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
|
| + /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
|
| + /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
|
| + /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
|
| + /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
|
| + /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
|
| + /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
|
| + /* (36) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==36);
|
| + /* (37) columnlist ::= column */ yytestcase(yyruleno==37);
|
| + /* (43) type ::= */ yytestcase(yyruleno==43);
|
| + /* (50) signed ::= plus_num */ yytestcase(yyruleno==50);
|
| + /* (51) signed ::= minus_num */ yytestcase(yyruleno==51);
|
| + /* (52) carglist ::= carglist ccons */ yytestcase(yyruleno==52);
|
| + /* (53) carglist ::= */ yytestcase(yyruleno==53);
|
| + /* (60) ccons ::= NULL onconf */ yytestcase(yyruleno==60);
|
| + /* (88) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==88);
|
| + /* (89) conslist ::= tcons */ yytestcase(yyruleno==89);
|
| + /* (91) tconscomma ::= */ yytestcase(yyruleno==91);
|
| + /* (274) foreach_clause ::= */ yytestcase(yyruleno==274);
|
| + /* (275) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==275);
|
| + /* (282) tridxby ::= */ yytestcase(yyruleno==282);
|
| + /* (299) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==299);
|
| + /* (300) database_kw_opt ::= */ yytestcase(yyruleno==300);
|
| + /* (308) kwcolumn_opt ::= */ yytestcase(yyruleno==308);
|
| + /* (309) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==309);
|
| + /* (313) vtabarglist ::= vtabarg */ yytestcase(yyruleno==313);
|
| + /* (314) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==314);
|
| + /* (316) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==316);
|
| + /* (320) anylist ::= */ yytestcase(yyruleno==320);
|
| + /* (321) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==321);
|
| + /* (322) anylist ::= anylist ANY */ yytestcase(yyruleno==322);
|
| + break;
|
| +/********** End reduce actions ************************************************/
|
| + };
|
| + assert( yyruleno>=0 && yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
|
| + yygoto = yyRuleInfo[yyruleno].lhs;
|
| + yysize = yyRuleInfo[yyruleno].nrhs;
|
| + yypParser->yyidx -= yysize;
|
| + yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
|
| + if( yyact <= YY_MAX_SHIFTREDUCE ){
|
| + if( yyact>YY_MAX_SHIFT ) yyact += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE;
|
| + /* If the reduce action popped at least
|
| + ** one element off the stack, then we can push the new element back
|
| + ** onto the stack here, and skip the stack overflow test in yy_shift().
|
| + ** That gives a significant speed improvement. */
|
| + if( yysize ){
|
| + yypParser->yyidx++;
|
| + yymsp -= yysize-1;
|
| + yymsp->stateno = (YYACTIONTYPE)yyact;
|
| + yymsp->major = (YYCODETYPE)yygoto;
|
| + yymsp->minor = yygotominor;
|
| + yyTraceShift(yypParser, yyact);
|
| + }else{
|
| + yy_shift(yypParser,yyact,yygoto,&yygotominor);
|
| + }
|
| + }else{
|
| + assert( yyact == YY_ACCEPT_ACTION );
|
| + yy_accept(yypParser);
|
| + }
|
| +}
|
| +
|
| +/*
|
| +** The following code executes when the parse fails
|
| +*/
|
| +#ifndef YYNOERRORRECOVERY
|
| +static void yy_parse_failed(
|
| + yyParser *yypParser /* The parser */
|
| +){
|
| + sqlite3ParserARG_FETCH;
|
| +#ifndef NDEBUG
|
| + if( yyTraceFILE ){
|
| + fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
|
| + }
|
| +#endif
|
| + while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
|
| + /* Here code is inserted which will be executed whenever the
|
| + ** parser fails */
|
| +/************ Begin %parse_failure code ***************************************/
|
| +/************ End %parse_failure code *****************************************/
|
| + sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
|
| +}
|
| +#endif /* YYNOERRORRECOVERY */
|
| +
|
| +/*
|
| +** The following code executes when a syntax error first occurs.
|
| +*/
|
| +static void yy_syntax_error(
|
| + yyParser *yypParser, /* The parser */
|
| + int yymajor, /* The major type of the error token */
|
| + YYMINORTYPE yyminor /* The minor type of the error token */
|
| +){
|
| + sqlite3ParserARG_FETCH;
|
| +#define TOKEN (yyminor.yy0)
|
| +/************ Begin %syntax_error code ****************************************/
|
| +
|
| + UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */
|
| + assert( TOKEN.z[0] ); /* The tokenizer always gives us a token */
|
| + sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
|
| +/************ End %syntax_error code ******************************************/
|
| + sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
|
| +}
|
| +
|
| +/*
|
| +** The following is executed when the parser accepts
|
| +*/
|
| +static void yy_accept(
|
| + yyParser *yypParser /* The parser */
|
| +){
|
| + sqlite3ParserARG_FETCH;
|
| +#ifndef NDEBUG
|
| + if( yyTraceFILE ){
|
| + fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
|
| + }
|
| +#endif
|
| + while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
|
| + /* Here code is inserted which will be executed whenever the
|
| + ** parser accepts */
|
| +/*********** Begin %parse_accept code *****************************************/
|
| +/*********** End %parse_accept code *******************************************/
|
| + sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
|
| +}
|
| +
|
| +/* The main parser program.
|
| +** The first argument is a pointer to a structure obtained from
|
| +** "sqlite3ParserAlloc" which describes the current state of the parser.
|
| +** The second argument is the major token number. The third is
|
| +** the minor token. The fourth optional argument is whatever the
|
| +** user wants (and specified in the grammar) and is available for
|
| +** use by the action routines.
|
| +**
|
| +** Inputs:
|
| +** <ul>
|
| +** <li> A pointer to the parser (an opaque structure.)
|
| +** <li> The major token number.
|
| +** <li> The minor token number.
|
| +** <li> An option argument of a grammar-specified type.
|
| +** </ul>
|
| +**
|
| +** Outputs:
|
| +** None.
|
| +*/
|
| +SQLITE_PRIVATE void sqlite3Parser(
|
| + void *yyp, /* The parser */
|
| + int yymajor, /* The major token code number */
|
| + sqlite3ParserTOKENTYPE yyminor /* The value for the token */
|
| + sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */
|
| +){
|
| + YYMINORTYPE yyminorunion;
|
| + int yyact; /* The parser action. */
|
| +#if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
|
| + int yyendofinput; /* True if we are at the end of input */
|
| +#endif
|
| +#ifdef YYERRORSYMBOL
|
| + int yyerrorhit = 0; /* True if yymajor has invoked an error */
|
| +#endif
|
| + yyParser *yypParser; /* The parser */
|
| +
|
| + /* (re)initialize the parser, if necessary */
|
| + yypParser = (yyParser*)yyp;
|
| + if( yypParser->yyidx<0 ){
|
| +#if YYSTACKDEPTH<=0
|
| + if( yypParser->yystksz <=0 ){
|
| + /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
|
| + yyminorunion = yyzerominor;
|
| + yyStackOverflow(yypParser, &yyminorunion);
|
| + return;
|
| + }
|
| +#endif
|
| + yypParser->yyidx = 0;
|
| + yypParser->yyerrcnt = -1;
|
| + yypParser->yystack[0].stateno = 0;
|
| + yypParser->yystack[0].major = 0;
|
| +#ifndef NDEBUG
|
| + if( yyTraceFILE ){
|
| + fprintf(yyTraceFILE,"%sInitialize. Empty stack. State 0\n",
|
| + yyTracePrompt);
|
| + }
|
| +#endif
|
| + }
|
| + yyminorunion.yy0 = yyminor;
|
| +#if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
|
| + yyendofinput = (yymajor==0);
|
| +#endif
|
| + sqlite3ParserARG_STORE;
|
| +
|
| +#ifndef NDEBUG
|
| + if( yyTraceFILE ){
|
| + fprintf(yyTraceFILE,"%sInput '%s'\n",yyTracePrompt,yyTokenName[yymajor]);
|
| + }
|
| +#endif
|
| +
|
| + do{
|
| + yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
|
| + if( yyact <= YY_MAX_SHIFTREDUCE ){
|
| + if( yyact > YY_MAX_SHIFT ) yyact += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE;
|
| + yy_shift(yypParser,yyact,yymajor,&yyminorunion);
|
| + yypParser->yyerrcnt--;
|
| + yymajor = YYNOCODE;
|
| + }else if( yyact <= YY_MAX_REDUCE ){
|
| + yy_reduce(yypParser,yyact-YY_MIN_REDUCE);
|
| + }else{
|
| + assert( yyact == YY_ERROR_ACTION );
|
| +#ifdef YYERRORSYMBOL
|
| + int yymx;
|
| +#endif
|
| +#ifndef NDEBUG
|
| + if( yyTraceFILE ){
|
| + fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
|
| + }
|
| +#endif
|
| +#ifdef YYERRORSYMBOL
|
| + /* A syntax error has occurred.
|
| + ** The response to an error depends upon whether or not the
|
| + ** grammar defines an error token "ERROR".
|
| + **
|
| + ** This is what we do if the grammar does define ERROR:
|
| + **
|
| + ** * Call the %syntax_error function.
|
| + **
|
| + ** * Begin popping the stack until we enter a state where
|
| + ** it is legal to shift the error symbol, then shift
|
| + ** the error symbol.
|
| + **
|
| + ** * Set the error count to three.
|
| + **
|
| + ** * Begin accepting and shifting new tokens. No new error
|
| + ** processing will occur until three tokens have been
|
| + ** shifted successfully.
|
| + **
|
| + */
|
| + if( yypParser->yyerrcnt<0 ){
|
| + yy_syntax_error(yypParser,yymajor,yyminorunion);
|
| + }
|
| + yymx = yypParser->yystack[yypParser->yyidx].major;
|
| + if( yymx==YYERRORSYMBOL || yyerrorhit ){
|
| +#ifndef NDEBUG
|
| + if( yyTraceFILE ){
|
| + fprintf(yyTraceFILE,"%sDiscard input token %s\n",
|
| + yyTracePrompt,yyTokenName[yymajor]);
|
| + }
|
| +#endif
|
| + yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
|
| + yymajor = YYNOCODE;
|
| + }else{
|
| + while(
|
| + yypParser->yyidx >= 0 &&
|
| + yymx != YYERRORSYMBOL &&
|
| + (yyact = yy_find_reduce_action(
|
| + yypParser->yystack[yypParser->yyidx].stateno,
|
| + YYERRORSYMBOL)) >= YY_MIN_REDUCE
|
| + ){
|
| + yy_pop_parser_stack(yypParser);
|
| + }
|
| + if( yypParser->yyidx < 0 || yymajor==0 ){
|
| + yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
|
| + yy_parse_failed(yypParser);
|
| + yymajor = YYNOCODE;
|
| + }else if( yymx!=YYERRORSYMBOL ){
|
| + YYMINORTYPE u2;
|
| + u2.YYERRSYMDT = 0;
|
| + yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
|
| + }
|
| + }
|
| + yypParser->yyerrcnt = 3;
|
| + yyerrorhit = 1;
|
| +#elif defined(YYNOERRORRECOVERY)
|
| + /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
|
| + ** do any kind of error recovery. Instead, simply invoke the syntax
|
| + ** error routine and continue going as if nothing had happened.
|
| + **
|
| + ** Applications can set this macro (for example inside %include) if
|
| + ** they intend to abandon the parse upon the first syntax error seen.
|
| + */
|
| + yy_syntax_error(yypParser,yymajor,yyminorunion);
|
| + yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
|
| + yymajor = YYNOCODE;
|
| +
|
| +#else /* YYERRORSYMBOL is not defined */
|
| + /* This is what we do if the grammar does not define ERROR:
|
| + **
|
| + ** * Report an error message, and throw away the input token.
|
| + **
|
| + ** * If the input token is $, then fail the parse.
|
| + **
|
| + ** As before, subsequent error messages are suppressed until
|
| + ** three input tokens have been successfully shifted.
|
| + */
|
| + if( yypParser->yyerrcnt<=0 ){
|
| + yy_syntax_error(yypParser,yymajor,yyminorunion);
|
| + }
|
| + yypParser->yyerrcnt = 3;
|
| + yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
|
| + if( yyendofinput ){
|
| + yy_parse_failed(yypParser);
|
| + }
|
| + yymajor = YYNOCODE;
|
| +#endif
|
| + }
|
| + }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
|
| +#ifndef NDEBUG
|
| + if( yyTraceFILE ){
|
| + int i;
|
| + fprintf(yyTraceFILE,"%sReturn. Stack=",yyTracePrompt);
|
| + for(i=1; i<=yypParser->yyidx; i++)
|
| + fprintf(yyTraceFILE,"%c%s", i==1 ? '[' : ' ',
|
| + yyTokenName[yypParser->yystack[i].major]);
|
| + fprintf(yyTraceFILE,"]\n");
|
| + }
|
| +#endif
|
| + return;
|
| +}
|
| +
|
| +/************** End of parse.c ***********************************************/
|
| +/************** Begin file tokenize.c ****************************************/
|
| +/*
|
| +** 2001 September 15
|
| +**
|
| +** The author disclaims copyright to this source code. In place of
|
| +** a legal notice, here is a blessing:
|
| +**
|
| +** May you do good and not evil.
|
| +** May you find forgiveness for yourself and forgive others.
|
| +** May you share freely, never taking more than you give.
|
| +**
|
| +*************************************************************************
|
| +** An tokenizer for SQL
|
| +**
|
| +** This file contains C code that splits an SQL input string up into
|
| +** individual tokens and sends those tokens one-by-one over to the
|
| +** parser for analysis.
|
| +*/
|
| +/* #include "sqliteInt.h" */
|
| +/* #include <stdlib.h> */
|
| +
|
| +/*
|
| +** The charMap() macro maps alphabetic characters into their
|
| +** lower-case ASCII equivalent. On ASCII machines, this is just
|
| +** an upper-to-lower case map. On EBCDIC machines we also need
|
| +** to adjust the encoding. Only alphabetic characters and underscores
|
| +** need to be translated.
|
| +*/
|
| +#ifdef SQLITE_ASCII
|
| +# define charMap(X) sqlite3UpperToLower[(unsigned char)X]
|
| +#endif
|
| +#ifdef SQLITE_EBCDIC
|
| +# define charMap(X) ebcdicToAscii[(unsigned char)X]
|
| +const unsigned char ebcdicToAscii[] = {
|
| +/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
|
| + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
|
| + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
|
| + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
|
| + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */
|
| + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */
|
| + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */
|
| + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */
|
| + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */
|
| + 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */
|
| + 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */
|
| + 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */
|
| + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
|
| + 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */
|
| + 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */
|
| + 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */
|
| + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */
|
| +};
|
| +#endif
|
| +
|
| +/*
|
| +** The sqlite3KeywordCode function looks up an identifier to determine if
|
| +** it is a keyword. If it is a keyword, the token code of that keyword is
|
| +** returned. If the input is not a keyword, TK_ID is returned.
|
| +**
|
| +** The implementation of this routine was generated by a program,
|
| +** mkkeywordhash.h, located in the tool subdirectory of the distribution.
|
| +** The output of the mkkeywordhash.c program is written into a file
|
| +** named keywordhash.h and then included into this source file by
|
| +** the #include below.
|
| +*/
|
| +/************** Include keywordhash.h in the middle of tokenize.c ************/
|
| +/************** Begin file keywordhash.h *************************************/
|
| +/***** This file contains automatically generated code ******
|
| +**
|
| +** The code in this file has been automatically generated by
|
| +**
|
| +** sqlite/tool/mkkeywordhash.c
|
| +**
|
| +** The code in this file implements a function that determines whether
|
| +** or not a given identifier is really an SQL keyword. The same thing
|
| +** might be implemented more directly using a hand-written hash table.
|
| +** But by using this automatically generated code, the size of the code
|
| +** is substantially reduced. This is important for embedded applications
|
| +** on platforms with limited memory.
|
| +*/
|
| +/* Hash score: 182 */
|
| +static int keywordCode(const char *z, int n, int *pType){
|
| + /* zText[] encodes 834 bytes of keywords in 554 bytes */
|
| + /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */
|
| + /* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */
|
| + /* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */
|
| + /* UNIQUERYWITHOUTERELEASEATTACHAVINGROUPDATEBEGINNERECURSIVE */
|
| + /* BETWEENOTNULLIKECASCADELETECASECOLLATECREATECURRENT_DATEDETACH */
|
| + /* IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN */
|
| + /* WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMIT */
|
| + /* CONFLICTCROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAIL */
|
| + /* FROMFULLGLOBYIFISNULLORDERESTRICTRIGHTROLLBACKROWUNIONUSING */
|
| + /* VACUUMVIEWINITIALLY */
|
| + static const char zText[553] = {
|
| + 'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
|
| + 'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
|
| + 'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
|
| + 'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
|
| + 'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
|
| + 'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
|
| + 'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
|
| + 'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
|
| + 'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
|
| + 'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
|
| + 'U','E','R','Y','W','I','T','H','O','U','T','E','R','E','L','E','A','S',
|
| + 'E','A','T','T','A','C','H','A','V','I','N','G','R','O','U','P','D','A',
|
| + 'T','E','B','E','G','I','N','N','E','R','E','C','U','R','S','I','V','E',
|
| + 'B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C','A',
|
| + 'S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L','A',
|
| + 'T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A',
|
| + 'T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E','J',
|
| + 'O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A','L',
|
| + 'Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U','E',
|
| + 'S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W','H',
|
| + 'E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C','E',
|
| + 'A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R','E',
|
| + 'M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M','M',
|
| + 'I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U','R',
|
| + 'R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M','A',
|
| + 'R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','D',
|
| + 'R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L','O',
|
| + 'B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S','T',
|
| + 'R','I','C','T','R','I','G','H','T','R','O','L','L','B','A','C','K','R',
|
| + 'O','W','U','N','I','O','N','U','S','I','N','G','V','A','C','U','U','M',
|
| + 'V','I','E','W','I','N','I','T','I','A','L','L','Y',
|
| + };
|
| + static const unsigned char aHash[127] = {
|
| + 76, 105, 117, 74, 0, 45, 0, 0, 82, 0, 77, 0, 0,
|
| + 42, 12, 78, 15, 0, 116, 85, 54, 112, 0, 19, 0, 0,
|
| + 121, 0, 119, 115, 0, 22, 93, 0, 9, 0, 0, 70, 71,
|
| + 0, 69, 6, 0, 48, 90, 102, 0, 118, 101, 0, 0, 44,
|
| + 0, 103, 24, 0, 17, 0, 122, 53, 23, 0, 5, 110, 25,
|
| + 96, 0, 0, 124, 106, 60, 123, 57, 28, 55, 0, 91, 0,
|
| + 100, 26, 0, 99, 0, 0, 0, 95, 92, 97, 88, 109, 14,
|
| + 39, 108, 0, 81, 0, 18, 89, 111, 32, 0, 120, 80, 113,
|
| + 62, 46, 84, 0, 0, 94, 40, 59, 114, 0, 36, 0, 0,
|
| + 29, 0, 86, 63, 64, 0, 20, 61, 0, 56,
|
| + };
|
| + static const unsigned char aNext[124] = {
|
| + 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0,
|
| + 0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0,
|
| + 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
| + 0, 0, 0, 0, 33, 0, 21, 0, 0, 0, 0, 0, 50,
|
| + 0, 43, 3, 47, 0, 0, 0, 0, 30, 0, 58, 0, 38,
|
| + 0, 0, 0, 1, 66, 0, 0, 67, 0, 41, 0, 0, 0,
|
| + 0, 0, 0, 49, 65, 0, 0, 0, 0, 31, 52, 16, 34,
|
| + 10, 0, 0, 0, 0, 0, 0, 0, 11, 72, 79, 0, 8,
|
| + 0, 104, 98, 0, 107, 0, 87, 0, 75, 51, 0, 27, 37,
|
| + 73, 83, 0, 35, 68, 0, 0,
|
| + };
|
| + static const unsigned char aLen[124] = {
|
| + 7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6,
|
| + 7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6,
|
| + 11, 6, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10,
|
| + 4, 6, 2, 3, 9, 4, 2, 6, 5, 7, 4, 5, 7,
|
| + 6, 6, 5, 6, 5, 5, 9, 7, 7, 3, 2, 4, 4,
|
| + 7, 3, 6, 4, 7, 6, 12, 6, 9, 4, 6, 5, 4,
|
| + 7, 6, 5, 6, 7, 5, 4, 5, 6, 5, 7, 3, 7,
|
| + 13, 2, 2, 4, 6, 6, 8, 5, 17, 12, 7, 8, 8,
|
| + 2, 4, 4, 4, 4, 4, 2, 2, 6, 5, 8, 5, 8,
|
| + 3, 5, 5, 6, 4, 9, 3,
|
| + };
|
| + static const unsigned short int aOffset[124] = {
|
| + 0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33,
|
| + 36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81,
|
| + 86, 91, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
|
| + 159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 184, 188, 192,
|
| + 199, 204, 209, 212, 218, 221, 225, 234, 240, 240, 240, 243, 246,
|
| + 250, 251, 255, 261, 265, 272, 278, 290, 296, 305, 307, 313, 318,
|
| + 320, 327, 332, 337, 343, 349, 354, 358, 361, 367, 371, 378, 380,
|
| + 387, 389, 391, 400, 404, 410, 416, 424, 429, 429, 445, 452, 459,
|
| + 460, 467, 471, 475, 479, 483, 486, 488, 490, 496, 500, 508, 513,
|
| + 521, 524, 529, 534, 540, 544, 549,
|
| + };
|
| + static const unsigned char aCode[124] = {
|
| + TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE,
|
| + TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN,
|
| + TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD,
|
| + TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE,
|
| + TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE,
|
| + TK_EXCEPT, TK_TRANSACTION,TK_ACTION, TK_ON, TK_JOIN_KW,
|
| + TK_ALTER, TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_SAVEPOINT,
|
| + TK_INTERSECT, TK_TRIGGER, TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
|
| + TK_OFFSET, TK_OF, TK_SET, TK_TEMP, TK_TEMP,
|
| + TK_OR, TK_UNIQUE, TK_QUERY, TK_WITHOUT, TK_WITH,
|
| + TK_JOIN_KW, TK_RELEASE, TK_ATTACH, TK_HAVING, TK_GROUP,
|
| + TK_UPDATE, TK_BEGIN, TK_JOIN_KW, TK_RECURSIVE, TK_BETWEEN,
|
| + TK_NOTNULL, TK_NOT, TK_NO, TK_NULL, TK_LIKE_KW,
|
| + TK_CASCADE, TK_ASC, TK_DELETE, TK_CASE, TK_COLLATE,
|
| + TK_CREATE, TK_CTIME_KW, TK_DETACH, TK_IMMEDIATE, TK_JOIN,
|
| + TK_INSERT, TK_MATCH, TK_PLAN, TK_ANALYZE, TK_PRAGMA,
|
| + TK_ABORT, TK_VALUES, TK_VIRTUAL, TK_LIMIT, TK_WHEN,
|
| + TK_WHERE, TK_RENAME, TK_AFTER, TK_REPLACE, TK_AND,
|
| + TK_DEFAULT, TK_AUTOINCR, TK_TO, TK_IN, TK_CAST,
|
| + TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, TK_JOIN_KW, TK_CTIME_KW,
|
| + TK_CTIME_KW, TK_PRIMARY, TK_DEFERRED, TK_DISTINCT, TK_IS,
|
| + TK_DROP, TK_FAIL, TK_FROM, TK_JOIN_KW, TK_LIKE_KW,
|
| + TK_BY, TK_IF, TK_ISNULL, TK_ORDER, TK_RESTRICT,
|
| + TK_JOIN_KW, TK_ROLLBACK, TK_ROW, TK_UNION, TK_USING,
|
| + TK_VACUUM, TK_VIEW, TK_INITIALLY, TK_ALL,
|
| + };
|
| + int h, i;
|
| + if( n>=2 ){
|
| + h = ((charMap(z[0])*4) ^ (charMap(z[n-1])*3) ^ n) % 127;
|
| + for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
|
| + if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
|
| + testcase( i==0 ); /* REINDEX */
|
| + testcase( i==1 ); /* INDEXED */
|
| + testcase( i==2 ); /* INDEX */
|
| + testcase( i==3 ); /* DESC */
|
| + testcase( i==4 ); /* ESCAPE */
|
| + testcase( i==5 ); /* EACH */
|
| + testcase( i==6 ); /* CHECK */
|
| + testcase( i==7 ); /* KEY */
|
| + testcase( i==8 ); /* BEFORE */
|
| + testcase( i==9 ); /* FOREIGN */
|
| + testcase( i==10 ); /* FOR */
|
| + testcase( i==11 ); /* IGNORE */
|
| + testcase( i==12 ); /* REGEXP */
|
| + testcase( i==13 ); /* EXPLAIN */
|
| + testcase( i==14 ); /* INSTEAD */
|
| + testcase( i==15 ); /* ADD */
|
| + testcase( i==16 ); /* DATABASE */
|
| + testcase( i==17 ); /* AS */
|
| + testcase( i==18 ); /* SELECT */
|
| + testcase( i==19 ); /* TABLE */
|
| + testcase( i==20 ); /* LEFT */
|
| + testcase( i==21 ); /* THEN */
|
| + testcase( i==22 ); /* END */
|
| + testcase( i==23 ); /* DEFERRABLE */
|
| + testcase( i==24 ); /* ELSE */
|
| + testcase( i==25 ); /* EXCEPT */
|
| + testcase( i==26 ); /* TRANSACTION */
|
| + testcase( i==27 ); /* ACTION */
|
| + testcase( i==28 ); /* ON */
|
| + testcase( i==29 ); /* NATURAL */
|
| + testcase( i==30 ); /* ALTER */
|
| + testcase( i==31 ); /* RAISE */
|
| + testcase( i==32 ); /* EXCLUSIVE */
|
| + testcase( i==33 ); /* EXISTS */
|
| + testcase( i==34 ); /* SAVEPOINT */
|
| + testcase( i==35 ); /* INTERSECT */
|
| + testcase( i==36 ); /* TRIGGER */
|
| + testcase( i==37 ); /* REFERENCES */
|
| + testcase( i==38 ); /* CONSTRAINT */
|
| + testcase( i==39 ); /* INTO */
|
| + testcase( i==40 ); /* OFFSET */
|
| + testcase( i==41 ); /* OF */
|
| + testcase( i==42 ); /* SET */
|
| + testcase( i==43 ); /* TEMPORARY */
|
| + testcase( i==44 ); /* TEMP */
|
| + testcase( i==45 ); /* OR */
|
| + testcase( i==46 ); /* UNIQUE */
|
| + testcase( i==47 ); /* QUERY */
|
| + testcase( i==48 ); /* WITHOUT */
|
| + testcase( i==49 ); /* WITH */
|
| + testcase( i==50 ); /* OUTER */
|
| + testcase( i==51 ); /* RELEASE */
|
| + testcase( i==52 ); /* ATTACH */
|
| + testcase( i==53 ); /* HAVING */
|
| + testcase( i==54 ); /* GROUP */
|
| + testcase( i==55 ); /* UPDATE */
|
| + testcase( i==56 ); /* BEGIN */
|
| + testcase( i==57 ); /* INNER */
|
| + testcase( i==58 ); /* RECURSIVE */
|
| + testcase( i==59 ); /* BETWEEN */
|
| + testcase( i==60 ); /* NOTNULL */
|
| + testcase( i==61 ); /* NOT */
|
| + testcase( i==62 ); /* NO */
|
| + testcase( i==63 ); /* NULL */
|
| + testcase( i==64 ); /* LIKE */
|
| + testcase( i==65 ); /* CASCADE */
|
| + testcase( i==66 ); /* ASC */
|
| + testcase( i==67 ); /* DELETE */
|
| + testcase( i==68 ); /* CASE */
|
| + testcase( i==69 ); /* COLLATE */
|
| + testcase( i==70 ); /* CREATE */
|
| + testcase( i==71 ); /* CURRENT_DATE */
|
| + testcase( i==72 ); /* DETACH */
|
| + testcase( i==73 ); /* IMMEDIATE */
|
| + testcase( i==74 ); /* JOIN */
|
| + testcase( i==75 ); /* INSERT */
|
| + testcase( i==76 ); /* MATCH */
|
| + testcase( i==77 ); /* PLAN */
|
| + testcase( i==78 ); /* ANALYZE */
|
| + testcase( i==79 ); /* PRAGMA */
|
| + testcase( i==80 ); /* ABORT */
|
| + testcase( i==81 ); /* VALUES */
|
| + testcase( i==82 ); /* VIRTUAL */
|
| + testcase( i==83 ); /* LIMIT */
|
| + testcase( i==84 ); /* WHEN */
|
| + testcase( i==85 ); /* WHERE */
|
| + testcase( i==86 ); /* RENAME */
|
| + testcase( i==87 ); /* AFTER */
|
| + testcase( i==88 ); /* REPLACE */
|
| + testcase( i==89 ); /* AND */
|
| + testcase( i==90 ); /* DEFAULT */
|
| + testcase( i==91 ); /* AUTOINCREMENT */
|
| + testcase( i==92 ); /* TO */
|
| + testcase( i==93 ); /* IN */
|
| + testcase( i==94 ); /* CAST */
|
| + testcase( i==95 ); /* COLUMN */
|
| + testcase( i==96 ); /* COMMIT */
|
| + testcase( i==97 ); /* CONFLICT */
|
| + testcase( i==98 ); /* CROSS */
|
| + testcase( i==99 ); /* CURRENT_TIMESTAMP */
|
| + testcase( i==100 ); /* CURRENT_TIME */
|
| + testcase( i==101 ); /* PRIMARY */
|
| + testcase( i==102 ); /* DEFERRED */
|
| + testcase( i==103 ); /* DISTINCT */
|
| + testcase( i==104 ); /* IS */
|
| + testcase( i==105 ); /* DROP */
|
| + testcase( i==106 ); /* FAIL */
|
| + testcase( i==107 ); /* FROM */
|
| + testcase( i==108 ); /* FULL */
|
| + testcase( i==109 ); /* GLOB */
|
| + testcase( i==110 ); /* BY */
|
| + testcase( i==111 ); /* IF */
|
| + testcase( i==112 ); /* ISNULL */
|
| + testcase( i==113 ); /* ORDER */
|
| + testcase( i==114 ); /* RESTRICT */
|
| + testcase( i==115 ); /* RIGHT */
|
| + testcase( i==116 ); /* ROLLBACK */
|
| + testcase( i==117 ); /* ROW */
|
| + testcase( i==118 ); /* UNION */
|
| + testcase( i==119 ); /* USING */
|
| + testcase( i==120 ); /* VACUUM */
|
| + testcase( i==121 ); /* VIEW */
|
| + testcase( i==122 ); /* INITIALLY */
|
| + testcase( i==123 ); /* ALL */
|
| + *pType = aCode[i];
|
| + break;
|
| + }
|
| + }
|
| + }
|
| + return n;
|
| +}
|
| +SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
|
| + int id = TK_ID;
|
| + keywordCode((char*)z, n, &id);
|
| + return id;
|
| +}
|
| +#define SQLITE_N_KEYWORD 124
|
| +
|
| +/************** End of keywordhash.h *****************************************/
|
| +/************** Continuing where we left off in tokenize.c *******************/
|
| +
|
| +
|
| +/*
|
| +** If X is a character that can be used in an identifier then
|
| +** IdChar(X) will be true. Otherwise it is false.
|
| +**
|
| +** For ASCII, any character with the high-order bit set is
|
| +** allowed in an identifier. For 7-bit characters,
|
| +** sqlite3IsIdChar[X] must be 1.
|
| +**
|
| +** For EBCDIC, the rules are more complex but have the same
|
| +** end result.
|
| +**
|
| +** Ticket #1066. the SQL standard does not allow '$' in the
|
| +** middle of identifiers. But many SQL implementations do.
|
| +** SQLite will allow '$' in identifiers for compatibility.
|
| +** But the feature is undocumented.
|
| +*/
|
| +#ifdef SQLITE_ASCII
|
| +#define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
|
| +#endif
|
| +#ifdef SQLITE_EBCDIC
|
| +SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
|
| +/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
|
| + 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */
|
| + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */
|
| + 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */
|
| + 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */
|
| + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */
|
| + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */
|
| + 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */
|
| + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
|
| + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */
|
| + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */
|
| + 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */
|
| + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */
|
| +};
|
| +#define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
|
| +#endif
|
| +
|
| +/* Make the IdChar function accessible from ctime.c */
|
| +#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
|
| +SQLITE_PRIVATE int sqlite3IsIdChar(u8 c){ return IdChar(c); }
|
| +#endif
|
| +
|
| +
|
| +/*
|
| +** Return the length of the token that begins at z[0].
|
| +** Store the token type in *tokenType before returning.
|
| +*/
|
| +SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
|
| + int i, c;
|
| + switch( *z ){
|
| + case ' ': case '\t': case '\n': case '\f': case '\r': {
|
| + testcase( z[0]==' ' );
|
| + testcase( z[0]=='\t' );
|
| + testcase( z[0]=='\n' );
|
| + testcase( z[0]=='\f' );
|
| + testcase( z[0]=='\r' );
|
| + for(i=1; sqlite3Isspace(z[i]); i++){}
|
| + *tokenType = TK_SPACE;
|
| + return i;
|
| + }
|
| + case '-': {
|
| + if( z[1]=='-' ){
|
| + for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
|
| + *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
|
| + return i;
|
| + }
|
| + *tokenType = TK_MINUS;
|
| + return 1;
|
| + }
|
| + case '(': {
|
| + *tokenType = TK_LP;
|
| + return 1;
|
| + }
|
| + case ')': {
|
| + *tokenType = TK_RP;
|
| + return 1;
|
| + }
|
| + case ';': {
|
| + *tokenType = TK_SEMI;
|
| + return 1;
|
| + }
|
| + case '+': {
|
| + *tokenType = TK_PLUS;
|
| + return 1;
|
| + }
|
| + case '*': {
|
| + *tokenType = TK_STAR;
|
| + return 1;
|
| + }
|
| + case '/': {
|
| + if( z[1]!='*' || z[2]==0 ){
|
| + *tokenType = TK_SLASH;
|
| + return 1;
|
| + }
|
| + for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
|
| + if( c ) i++;
|
| + *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
|
| + return i;
|
| + }
|
| + case '%': {
|
| + *tokenType = TK_REM;
|
| + return 1;
|
| + }
|
| + case '=': {
|
| + *tokenType = TK_EQ;
|
| + return 1 + (z[1]=='=');
|
| + }
|
| + case '<': {
|
| + if( (c=z[1])=='=' ){
|
| + *tokenType = TK_LE;
|
| + return 2;
|
| + }else if( c=='>' ){
|
| + *tokenType = TK_NE;
|
| + return 2;
|
| + }else if( c=='<' ){
|
| + *tokenType = TK_LSHIFT;
|
| + return 2;
|
| + }else{
|
| + *tokenType = TK_LT;
|
| + return 1;
|
| + }
|
| + }
|
| + case '>': {
|
| + if( (c=z[1])=='=' ){
|
| + *tokenType = TK_GE;
|
| + return 2;
|
| + }else if( c=='>' ){
|
| + *tokenType = TK_RSHIFT;
|
| + return 2;
|
| + }else{
|
| + *tokenType = TK_GT;
|
| + return 1;
|
| + }
|
| + }
|
| + case '!': {
|
| + if( z[1]!='=' ){
|
| + *tokenType = TK_ILLEGAL;
|
| + return 2;
|
| + }else{
|
| + *tokenType = TK_NE;
|
| + return 2;
|
| + }
|
| + }
|
| + case '|': {
|
| + if( z[1]!='|' ){
|
| + *tokenType = TK_BITOR;
|
| + return 1;
|
| + }else{
|
| + *tokenType = TK_CONCAT;
|
| + return 2;
|
| + }
|
| + }
|
| + case ',': {
|
| + *tokenType = TK_COMMA;
|
| + return 1;
|
| + }
|
| + case '&': {
|
| + *tokenType = TK_BITAND;
|
| + return 1;
|
| + }
|
| + case '~': {
|
| + *tokenType = TK_BITNOT;
|
| + return 1;
|
| + }
|
| + case '`':
|
| + case '\'':
|
| + case '"': {
|
| + int delim = z[0];
|
| + testcase( delim=='`' );
|
| + testcase( delim=='\'' );
|
| + testcase( delim=='"' );
|
| + for(i=1; (c=z[i])!=0; i++){
|
| + if( c==delim ){
|
| + if( z[i+1]==delim ){
|
| + i++;
|
| + }else{
|
| + break;
|
| + }
|
| + }
|
| + }
|
| + if( c=='\'' ){
|
| + *tokenType = TK_STRING;
|
| + return i+1;
|
| + }else if( c!=0 ){
|
| + *tokenType = TK_ID;
|
| + return i+1;
|
| + }else{
|
| + *tokenType = TK_ILLEGAL;
|
| + return i;
|
| + }
|
| + }
|
| + case '.': {
|
| +#ifndef SQLITE_OMIT_FLOATING_POINT
|
| + if( !sqlite3Isdigit(z[1]) )
|
| +#endif
|
| + {
|
| + *tokenType = TK_DOT;
|
| + return 1;
|
| + }
|
| + /* If the next character is a digit, this is a floating point
|
| + ** number that begins with ".". Fall thru into the next case */
|
| + }
|
| + case '0': case '1': case '2': case '3': case '4':
|
| + case '5': case '6': case '7': case '8': case '9': {
|
| + testcase( z[0]=='0' ); testcase( z[0]=='1' ); testcase( z[0]=='2' );
|
| + testcase( z[0]=='3' ); testcase( z[0]=='4' ); testcase( z[0]=='5' );
|
| + testcase( z[0]=='6' ); testcase( z[0]=='7' ); testcase( z[0]=='8' );
|
| + testcase( z[0]=='9' );
|
| + *tokenType = TK_INTEGER;
|
| +#ifndef SQLITE_OMIT_HEX_INTEGER
|
| + if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && sqlite3Isxdigit(z[2]) ){
|
| + for(i=3; sqlite3Isxdigit(z[i]); i++){}
|
| + return i;
|
| + }
|
| +#endif
|
| + for(i=0; sqlite3Isdigit(z[i]); i++){}
|
| +#ifndef SQLITE_OMIT_FLOATING_POINT
|
| + if( z[i]=='.' ){
|
| + i++;
|
| + while( sqlite3Isdigit(z[i]) ){ i++; }
|
| + *tokenType = TK_FLOAT;
|
| + }
|
| + if( (z[i]=='e' || z[i]=='E') &&
|
| + ( sqlite3Isdigit(z[i+1])
|
| + || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
|
| + )
|
| + ){
|
| + i += 2;
|
| + while( sqlite3Isdigit(z[i]) ){ i++; }
|
| + *tokenType = TK_FLOAT;
|
| + }
|
| +#endif
|
| + while( IdChar(z[i]) ){
|
| + *tokenType = TK_ILLEGAL;
|
| + i++;
|
| + }
|
| + return i;
|
| + }
|
| + case '[': {
|
| + for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
|
| + *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
|
| + return i;
|
| + }
|
| + case '?': {
|
| + *tokenType = TK_VARIABLE;
|
| + for(i=1; sqlite3Isdigit(z[i]); i++){}
|
| + return i;
|
| + }
|
| +#ifndef SQLITE_OMIT_TCL_VARIABLE
|
| + case '$':
|
| +#endif
|
| + case '@': /* For compatibility with MS SQL Server */
|
| + case '#':
|
| + case ':': {
|
| + int n = 0;
|
| + testcase( z[0]=='$' ); testcase( z[0]=='@' );
|
| + testcase( z[0]==':' ); testcase( z[0]=='#' );
|
| + *tokenType = TK_VARIABLE;
|
| + for(i=1; (c=z[i])!=0; i++){
|
| + if( IdChar(c) ){
|
| + n++;
|
| +#ifndef SQLITE_OMIT_TCL_VARIABLE
|
| + }else if( c=='(' && n>0 ){
|
| + do{
|
| + i++;
|
| + }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
|
| + if( c==')' ){
|
| + i++;
|
| + }else{
|
| + *tokenType = TK_ILLEGAL;
|
| + }
|
| + break;
|
| + }else if( c==':' && z[i+1]==':' ){
|
| + i++;
|
| +#endif
|
| + }else{
|
| + break;
|
| + }
|
| + }
|
| + if( n==0 ) *tokenType = TK_ILLEGAL;
|
| + return i;
|
| + }
|
| +#ifndef SQLITE_OMIT_BLOB_LITERAL
|
| + case 'x': case 'X': {
|
| + testcase( z[0]=='x' ); testcase( z[0]=='X' );
|
| + if( z[1]=='\'' ){
|
| + *tokenType = TK_BLOB;
|
| + for(i=2; sqlite3Isxdigit(z[i]); i++){}
|
| + if( z[i]!='\'' || i%2 ){
|
| + *tokenType = TK_ILLEGAL;
|
| + while( z[i] && z[i]!='\'' ){ i++; }
|
| + }
|
| + if( z[i] ) i++;
|
| + return i;
|
| + }
|
| + /* Otherwise fall through to the next case */
|
| + }
|
| +#endif
|
| + default: {
|
| + if( !IdChar(*z) ){
|
| + break;
|
| + }
|
| + for(i=1; IdChar(z[i]); i++){}
|
| + *tokenType = TK_ID;
|
| + return keywordCode((char*)z, i, tokenType);
|
| + }
|
| + }
|
| + *tokenType = TK_ILLEGAL;
|
| + return 1;
|
| +}
|
| +
|
| +/*
|
| +** Run the parser on the given SQL string. The parser structure is
|
| +** passed in. An SQLITE_ status code is returned. If an error occurs
|
| +** then an and attempt is made to write an error message into
|
| +** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
|
| +** error message.
|
| +*/
|
| +SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
|
| + int nErr = 0; /* Number of errors encountered */
|
| + int i; /* Loop counter */
|
| + void *pEngine; /* The LEMON-generated LALR(1) parser */
|
| + int tokenType; /* type of the next token */
|
| + int lastTokenParsed = -1; /* type of the previous token */
|
| + u8 enableLookaside; /* Saved value of db->lookaside.bEnabled */
|
| + sqlite3 *db = pParse->db; /* The database connection */
|
| + int mxSqlLen; /* Max length of an SQL string */
|
| +
|
| + assert( zSql!=0 );
|
| + mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
|
| + if( db->nVdbeActive==0 ){
|
| + db->u1.isInterrupted = 0;
|
| + }
|
| + pParse->rc = SQLITE_OK;
|
| + pParse->zTail = zSql;
|
| + i = 0;
|
| + assert( pzErrMsg!=0 );
|
| + /* sqlite3ParserTrace(stdout, "parser: "); */
|
| + pEngine = sqlite3ParserAlloc(sqlite3Malloc);
|
| + if( pEngine==0 ){
|
| + db->mallocFailed = 1;
|
| + return SQLITE_NOMEM;
|
| + }
|
| + assert( pParse->pNewTable==0 );
|
| + assert( pParse->pNewTrigger==0 );
|
| + assert( pParse->nVar==0 );
|
| + assert( pParse->nzVar==0 );
|
| + assert( pParse->azVar==0 );
|
| + enableLookaside = db->lookaside.bEnabled;
|
| + if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
|
| + while( zSql[i]!=0 ){
|
| + assert( i>=0 );
|
| + pParse->sLastToken.z = &zSql[i];
|
| + pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
|
| + i += pParse->sLastToken.n;
|
| + if( i>mxSqlLen ){
|
| + pParse->rc = SQLITE_TOOBIG;
|
| + break;
|
| + }
|
| + if( tokenType>=TK_SPACE ){
|
| + assert( tokenType==TK_SPACE || tokenType==TK_ILLEGAL );
|
| + if( db->u1.isInterrupted ){
|
| + sqlite3ErrorMsg(pParse, "interrupt");
|
| + pParse->rc = SQLITE_INTERRUPT;
|
| + break;
|
| + }
|
| + if( tokenType==TK_ILLEGAL ){
|
| + sqlite3ErrorMsg(pParse, "unrecognized token: \"%T\"",
|
| + &pParse->sLastToken);
|
| + break;
|
| + }
|
| + }else{
|
| + if( tokenType==TK_SEMI ) pParse->zTail = &zSql[i];
|
| + sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
|
| + lastTokenParsed = tokenType;
|
| + if( pParse->rc!=SQLITE_OK || db->mallocFailed ) break;
|
| + }
|
| + }
|
| + assert( nErr==0 );
|
| + if( pParse->rc==SQLITE_OK && db->mallocFailed==0 ){
|
| + assert( zSql[i]==0 );
|
| + if( lastTokenParsed!=TK_SEMI ){
|
| + sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
|
| + pParse->zTail = &zSql[i];
|
| + }
|
| + if( pParse->rc==SQLITE_OK && db->mallocFailed==0 ){
|
| + sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
|
| + }
|
| + }
|
| +#ifdef YYTRACKMAXSTACKDEPTH
|
| + sqlite3_mutex_enter(sqlite3MallocMutex());
|
| + sqlite3StatusHighwater(SQLITE_STATUS_PARSER_STACK,
|
| + sqlite3ParserStackPeak(pEngine)
|
| + );
|
| + sqlite3_mutex_leave(sqlite3MallocMutex());
|
| +#endif /* YYDEBUG */
|
| + sqlite3ParserFree(pEngine, sqlite3_free);
|
| + db->lookaside.bEnabled = enableLookaside;
|
| + if( db->mallocFailed ){
|
| + pParse->rc = SQLITE_NOMEM;
|
| + }
|
| + if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
|
| + pParse->zErrMsg = sqlite3MPrintf(db, "%s", sqlite3ErrStr(pParse->rc));
|
| + }
|
| + assert( pzErrMsg!=0 );
|
| + if( pParse->zErrMsg ){
|
| + *pzErrMsg = pParse->zErrMsg;
|
| + sqlite3_log(pParse->rc, "%s", *pzErrMsg);
|
| + pParse->zErrMsg = 0;
|
| + nErr++;
|
| + }
|
| + if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
|
| + sqlite3VdbeDelete(pParse->pVdbe);
|
| + pParse->pVdbe = 0;
|
| + }
|
| +#ifndef SQLITE_OMIT_SHARED_CACHE
|
| + if( pParse->nested==0 ){
|
| + sqlite3DbFree(db, pParse->aTableLock);
|
| + pParse->aTableLock = 0;
|
| + pParse->nTableLock = 0;
|
| + }
|
| +#endif
|
| +#ifndef SQLITE_OMIT_VIRTUALTABLE
|
| + sqlite3_free(pParse->apVtabLock);
|
| +#endif
|
| +
|
| + if( !IN_DECLARE_VTAB ){
|
| + /* If the pParse->declareVtab flag is set, do not delete any table
|
| + ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
|
| + ** will take responsibility for freeing the Table structure.
|
| + */
|
| + sqlite3DeleteTable(db, pParse->pNewTable);
|
| + }
|
| +
|
| + sqlite3WithDelete(db, pParse->pWithToFree);
|
| + sqlite3DeleteTrigger(db, pParse->pNewTrigger);
|
| + for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
|
| + sqlite3DbFree(db, pParse->azVar);
|
| + while( pParse->pAinc ){
|
| + AutoincInfo *p = pParse->pAinc;
|
| + pParse->pAinc = p->pNext;
|
| + sqlite3DbFree(db, p);
|
| + }
|
| + while( pParse->pZombieTab ){
|
| + Table *p = pParse->pZombieTab;
|
| + pParse->pZombieTab = p->pNextZombie;
|
| + sqlite3DeleteTable(db, p);
|
| + }
|
| + assert( nErr==0 || pParse->rc!=SQLITE_OK );
|
| + return nErr;
|
| +}
|
| +
|
| +/************** End of tokenize.c ********************************************/
|
| +/************** Begin file complete.c ****************************************/
|
| +/*
|
| +** 2001 September 15
|
| +**
|
| +** The author disclaims copyright to this source code. In place of
|
| +** a legal notice, here is a blessing:
|
| +**
|
| +** May you do good and not evil.
|
| +** May you find forgiveness for yourself and forgive others.
|
| +** May you share freely, never taking more than you give.
|
| +**
|
| +*************************************************************************
|
| +** An tokenizer for SQL
|
| +**
|
| +** This file contains C code that implements the sqlite3_complete() API.
|
| +** This code used to be part of the tokenizer.c source file. But by
|
| +** separating it out, the code will be automatically omitted from
|
| +** static links that do not use it.
|
| +*/
|
| +/* #include "sqliteInt.h" */
|
| +#ifndef SQLITE_OMIT_COMPLETE
|
| +
|
| +/*
|
| +** This is defined in tokenize.c. We just have to import the definition.
|
| +*/
|
| +#ifndef SQLITE_AMALGAMATION
|
| +#ifdef SQLITE_ASCII
|
| +#define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
|
| +#endif
|
| +#ifdef SQLITE_EBCDIC
|
| +SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
|
| +#define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
|
| +#endif
|
| +#endif /* SQLITE_AMALGAMATION */
|
| +
|
| +
|
| +/*
|
| +** Token types used by the sqlite3_complete() routine. See the header
|
| +** comments on that procedure for additional information.
|
| +*/
|
| +#define tkSEMI 0
|
| +#define tkWS 1
|
| +#define tkOTHER 2
|
| +#ifndef SQLITE_OMIT_TRIGGER
|
| +#define tkEXPLAIN 3
|
| +#define tkCREATE 4
|
| +#define tkTEMP 5
|
| +#define tkTRIGGER 6
|
| +#define tkEND 7
|
| +#endif
|
| +
|
| +/*
|
| +** Return TRUE if the given SQL string ends in a semicolon.
|
| +**
|
| +** Special handling is require for CREATE TRIGGER statements.
|
| +** Whenever the CREATE TRIGGER keywords are seen, the statement
|
| +** must end with ";END;".
|
| +**
|
| +** This implementation uses a state machine with 8 states:
|
| +**
|
| +** (0) INVALID We have not yet seen a non-whitespace character.
|
| +**
|
| +** (1) START At the beginning or end of an SQL statement. This routine
|
| +** returns 1 if it ends in the START state and 0 if it ends
|
| +** in any other state.
|
| +**
|
| +** (2) NORMAL We are in the middle of statement which ends with a single
|
| +** semicolon.
|
| +**
|
| +** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of
|
| +** a statement.
|
| +**
|
| +** (4) CREATE The keyword CREATE has been seen at the beginning of a
|
| +** statement, possibly preceded by EXPLAIN and/or followed by
|
| +** TEMP or TEMPORARY
|
| +**
|
| +** (5) TRIGGER We are in the middle of a trigger definition that must be
|
| +** ended by a semicolon, the keyword END, and another semicolon.
|
| +**
|
| +** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at
|
| +** the end of a trigger definition.
|
| +**
|
| +** (7) END We've seen the ";END" of the ";END;" that occurs at the end
|
| +** of a trigger definition.
|
| +**
|
| +** Transitions between states above are determined by tokens extracted
|
| +** from the input. The following tokens are significant:
|
| +**
|
| +** (0) tkSEMI A semicolon.
|
| +** (1) tkWS Whitespace.
|
| +** (2) tkOTHER Any other SQL token.
|
| +** (3) tkEXPLAIN The "explain" keyword.
|
| +** (4) tkCREATE The "create" keyword.
|
| +** (5) tkTEMP The "temp" or "temporary" keyword.
|
| +** (6) tkTRIGGER The "trigger" keyword.
|
| +** (7) tkEND The "end" keyword.
|
| +**
|
| +** Whitespace never causes a state transition and is always ignored.
|
| +** This means that a SQL string of all whitespace is invalid.
|
| +**
|
| +** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
|
| +** to recognize the end of a trigger can be omitted. All we have to do
|
| +** is look for a semicolon that is not part of an string or comment.
|
| +*/
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_complete(const char *zSql){
|
| + u8 state = 0; /* Current state, using numbers defined in header comment */
|
| + u8 token; /* Value of the next token */
|
| +
|
| +#ifndef SQLITE_OMIT_TRIGGER
|
| + /* A complex statement machine used to detect the end of a CREATE TRIGGER
|
| + ** statement. This is the normal case.
|
| + */
|
| + static const u8 trans[8][8] = {
|
| + /* Token: */
|
| + /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
|
| + /* 0 INVALID: */ { 1, 0, 2, 3, 4, 2, 2, 2, },
|
| + /* 1 START: */ { 1, 1, 2, 3, 4, 2, 2, 2, },
|
| + /* 2 NORMAL: */ { 1, 2, 2, 2, 2, 2, 2, 2, },
|
| + /* 3 EXPLAIN: */ { 1, 3, 3, 2, 4, 2, 2, 2, },
|
| + /* 4 CREATE: */ { 1, 4, 2, 2, 2, 4, 5, 2, },
|
| + /* 5 TRIGGER: */ { 6, 5, 5, 5, 5, 5, 5, 5, },
|
| + /* 6 SEMI: */ { 6, 6, 5, 5, 5, 5, 5, 7, },
|
| + /* 7 END: */ { 1, 7, 5, 5, 5, 5, 5, 5, },
|
| + };
|
| +#else
|
| + /* If triggers are not supported by this compile then the statement machine
|
| + ** used to detect the end of a statement is much simpler
|
| + */
|
| + static const u8 trans[3][3] = {
|
| + /* Token: */
|
| + /* State: ** SEMI WS OTHER */
|
| + /* 0 INVALID: */ { 1, 0, 2, },
|
| + /* 1 START: */ { 1, 1, 2, },
|
| + /* 2 NORMAL: */ { 1, 2, 2, },
|
| + };
|
| +#endif /* SQLITE_OMIT_TRIGGER */
|
| +
|
| +#ifdef SQLITE_ENABLE_API_ARMOR
|
| + if( zSql==0 ){
|
| + (void)SQLITE_MISUSE_BKPT;
|
| + return 0;
|
| + }
|
| +#endif
|
| +
|
| + while( *zSql ){
|
| + switch( *zSql ){
|
| + case ';': { /* A semicolon */
|
| + token = tkSEMI;
|
| + break;
|
| + }
|
| + case ' ':
|
| + case '\r':
|
| + case '\t':
|
| + case '\n':
|
| + case '\f': { /* White space is ignored */
|
| + token = tkWS;
|
| + break;
|
| + }
|
| + case '/': { /* C-style comments */
|
| + if( zSql[1]!='*' ){
|
| + token = tkOTHER;
|
| + break;
|
| + }
|
| + zSql += 2;
|
| + while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
|
| + if( zSql[0]==0 ) return 0;
|
| + zSql++;
|
| + token = tkWS;
|
| + break;
|
| + }
|
| + case '-': { /* SQL-style comments from "--" to end of line */
|
| + if( zSql[1]!='-' ){
|
| + token = tkOTHER;
|
| + break;
|
| + }
|
| + while( *zSql && *zSql!='\n' ){ zSql++; }
|
| + if( *zSql==0 ) return state==1;
|
| + token = tkWS;
|
| + break;
|
| + }
|
| + case '[': { /* Microsoft-style identifiers in [...] */
|
| + zSql++;
|
| + while( *zSql && *zSql!=']' ){ zSql++; }
|
| + if( *zSql==0 ) return 0;
|
| + token = tkOTHER;
|
| + break;
|
| + }
|
| + case '`': /* Grave-accent quoted symbols used by MySQL */
|
| + case '"': /* single- and double-quoted strings */
|
| + case '\'': {
|
| + int c = *zSql;
|
| + zSql++;
|
| + while( *zSql && *zSql!=c ){ zSql++; }
|
| + if( *zSql==0 ) return 0;
|
| + token = tkOTHER;
|
| + break;
|
| + }
|
| + default: {
|
| +#ifdef SQLITE_EBCDIC
|
| + unsigned char c;
|
| +#endif
|
| + if( IdChar((u8)*zSql) ){
|
| + /* Keywords and unquoted identifiers */
|
| + int nId;
|
| + for(nId=1; IdChar(zSql[nId]); nId++){}
|
| +#ifdef SQLITE_OMIT_TRIGGER
|
| + token = tkOTHER;
|
| +#else
|
| + switch( *zSql ){
|
| + case 'c': case 'C': {
|
| + if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
|
| + token = tkCREATE;
|
| + }else{
|
| + token = tkOTHER;
|
| + }
|
| + break;
|
| + }
|
| + case 't': case 'T': {
|
| + if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
|
| + token = tkTRIGGER;
|
| + }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
|
| + token = tkTEMP;
|
| + }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
|
| + token = tkTEMP;
|
| + }else{
|
| + token = tkOTHER;
|
| + }
|
| + break;
|
| + }
|
| + case 'e': case 'E': {
|
| + if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
|
| + token = tkEND;
|
| + }else
|
| +#ifndef SQLITE_OMIT_EXPLAIN
|
| + if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
|
| + token = tkEXPLAIN;
|
| + }else
|
| +#endif
|
| + {
|
| + token = tkOTHER;
|
| + }
|
| + break;
|
| + }
|
| + default: {
|
| + token = tkOTHER;
|
| + break;
|
| + }
|
| + }
|
| +#endif /* SQLITE_OMIT_TRIGGER */
|
| + zSql += nId-1;
|
| + }else{
|
| + /* Operators and special symbols */
|
| + token = tkOTHER;
|
| + }
|
| + break;
|
| + }
|
| + }
|
| + state = trans[state][token];
|
| + zSql++;
|
| + }
|
| + return state==1;
|
| +}
|
| +
|
| +#ifndef SQLITE_OMIT_UTF16
|
| +/*
|
| +** This routine is the same as the sqlite3_complete() routine described
|
| +** above, except that the parameter is required to be UTF-16 encoded, not
|
| +** UTF-8.
|
| +*/
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_complete16(const void *zSql){
|
| + sqlite3_value *pVal;
|
| + char const *zSql8;
|
| + int rc;
|
| +
|
| +#ifndef SQLITE_OMIT_AUTOINIT
|
| + rc = sqlite3_initialize();
|
| + if( rc ) return rc;
|
| +#endif
|
| + pVal = sqlite3ValueNew(0);
|
| + sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
|
| + zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
|
| + if( zSql8 ){
|
| + rc = sqlite3_complete(zSql8);
|
| + }else{
|
| + rc = SQLITE_NOMEM;
|
| + }
|
| + sqlite3ValueFree(pVal);
|
| + return rc & 0xff;
|
| +}
|
| +#endif /* SQLITE_OMIT_UTF16 */
|
| +#endif /* SQLITE_OMIT_COMPLETE */
|
| +
|
| +/************** End of complete.c ********************************************/
|
| +/************** Begin file main.c ********************************************/
|
| +/*
|
| +** 2001 September 15
|
| +**
|
| +** The author disclaims copyright to this source code. In place of
|
| +** a legal notice, here is a blessing:
|
| +**
|
| +** May you do good and not evil.
|
| +** May you find forgiveness for yourself and forgive others.
|
| +** May you share freely, never taking more than you give.
|
| +**
|
| +*************************************************************************
|
| +** Main file for the SQLite library. The routines in this file
|
| +** implement the programmer interface to the library. Routines in
|
| +** other files are for internal use by SQLite and should not be
|
| +** accessed by users of the library.
|
| +*/
|
| +/* #include "sqliteInt.h" */
|
| +
|
| +#ifdef SQLITE_ENABLE_FTS3
|
| +/************** Include fts3.h in the middle of main.c ***********************/
|
| +/************** Begin file fts3.h ********************************************/
|
| +/*
|
| +** 2006 Oct 10
|
| +**
|
| +** The author disclaims copyright to this source code. In place of
|
| +** a legal notice, here is a blessing:
|
| +**
|
| +** May you do good and not evil.
|
| +** May you find forgiveness for yourself and forgive others.
|
| +** May you share freely, never taking more than you give.
|
| +**
|
| +******************************************************************************
|
| +**
|
| +** This header file is used by programs that want to link against the
|
| +** FTS3 library. All it does is declare the sqlite3Fts3Init() interface.
|
| +*/
|
| +/* #include "sqlite3.h" */
|
| +
|
| +#if 0
|
| +extern "C" {
|
| +#endif /* __cplusplus */
|
| +
|
| +SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
|
| +
|
| +#if 0
|
| +} /* extern "C" */
|
| +#endif /* __cplusplus */
|
| +
|
| +/************** End of fts3.h ************************************************/
|
| +/************** Continuing where we left off in main.c ***********************/
|
| +#endif
|
| +#ifdef SQLITE_ENABLE_RTREE
|
| +/************** Include rtree.h in the middle of main.c **********************/
|
| +/************** Begin file rtree.h *******************************************/
|
| +/*
|
| +** 2008 May 26
|
| +**
|
| +** The author disclaims copyright to this source code. In place of
|
| +** a legal notice, here is a blessing:
|
| +**
|
| +** May you do good and not evil.
|
| +** May you find forgiveness for yourself and forgive others.
|
| +** May you share freely, never taking more than you give.
|
| +**
|
| +******************************************************************************
|
| +**
|
| +** This header file is used by programs that want to link against the
|
| +** RTREE library. All it does is declare the sqlite3RtreeInit() interface.
|
| +*/
|
| +/* #include "sqlite3.h" */
|
| +
|
| +#if 0
|
| +extern "C" {
|
| +#endif /* __cplusplus */
|
| +
|
| +SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
|
| +
|
| +#if 0
|
| +} /* extern "C" */
|
| +#endif /* __cplusplus */
|
| +
|
| +/************** End of rtree.h ***********************************************/
|
| +/************** Continuing where we left off in main.c ***********************/
|
| +#endif
|
| +#ifdef SQLITE_ENABLE_ICU
|
| +/************** Include sqliteicu.h in the middle of main.c ******************/
|
| +/************** Begin file sqliteicu.h ***************************************/
|
| +/*
|
| +** 2008 May 26
|
| +**
|
| +** The author disclaims copyright to this source code. In place of
|
| +** a legal notice, here is a blessing:
|
| +**
|
| +** May you do good and not evil.
|
| +** May you find forgiveness for yourself and forgive others.
|
| +** May you share freely, never taking more than you give.
|
| +**
|
| +******************************************************************************
|
| +**
|
| +** This header file is used by programs that want to link against the
|
| +** ICU extension. All it does is declare the sqlite3IcuInit() interface.
|
| +*/
|
| +/* #include "sqlite3.h" */
|
| +
|
| +#if 0
|
| +extern "C" {
|
| +#endif /* __cplusplus */
|
| +
|
| +SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
|
| +
|
| +#if 0
|
| +} /* extern "C" */
|
| +#endif /* __cplusplus */
|
| +
|
| +
|
| +/************** End of sqliteicu.h *******************************************/
|
| +/************** Continuing where we left off in main.c ***********************/
|
| +#endif
|
| +#ifdef SQLITE_ENABLE_JSON1
|
| +SQLITE_PRIVATE int sqlite3Json1Init(sqlite3*);
|
| +#endif
|
| +#ifdef SQLITE_ENABLE_FTS5
|
| +SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3*);
|
| +#endif
|
| +
|
| +#ifndef SQLITE_AMALGAMATION
|
| +/* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
|
| +** contains the text of SQLITE_VERSION macro.
|
| +*/
|
| +SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
|
| +#endif
|
| +
|
| +/* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
|
| +** a pointer to the to the sqlite3_version[] string constant.
|
| +*/
|
| +SQLITE_API const char *SQLITE_STDCALL sqlite3_libversion(void){ return sqlite3_version; }
|
| +
|
| +/* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
|
| +** pointer to a string constant whose value is the same as the
|
| +** SQLITE_SOURCE_ID C preprocessor macro.
|
| +*/
|
| +SQLITE_API const char *SQLITE_STDCALL sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
|
| +
|
| +/* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
|
| +** returns an integer equal to SQLITE_VERSION_NUMBER.
|
| +*/
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
|
| +
|
| +/* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
|
| +** zero if and only if SQLite was compiled with mutexing code omitted due to
|
| +** the SQLITE_THREADSAFE compile-time option being set to 0.
|
| +*/
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
|
| +
|
| +/*
|
| +** When compiling the test fixture or with debugging enabled (on Win32),
|
| +** this variable being set to non-zero will cause OSTRACE macros to emit
|
| +** extra diagnostic information.
|
| +*/
|
| +#ifdef SQLITE_HAVE_OS_TRACE
|
| +# ifndef SQLITE_DEBUG_OS_TRACE
|
| +# define SQLITE_DEBUG_OS_TRACE 0
|
| +# endif
|
| + int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
|
| +#endif
|
| +
|
| +#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
|
| +/*
|
| +** If the following function pointer is not NULL and if
|
| +** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
|
| +** I/O active are written using this function. These messages
|
| +** are intended for debugging activity only.
|
| +*/
|
| +SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0;
|
| +#endif
|
| +
|
| +/*
|
| +** If the following global variable points to a string which is the
|
| +** name of a directory, then that directory will be used to store
|
| +** temporary files.
|
| +**
|
| +** See also the "PRAGMA temp_store_directory" SQL command.
|
| +*/
|
| +SQLITE_API char *sqlite3_temp_directory = 0;
|
| +
|
| +/*
|
| +** If the following global variable points to a string which is the
|
| +** name of a directory, then that directory will be used to store
|
| +** all database files specified with a relative pathname.
|
| +**
|
| +** See also the "PRAGMA data_store_directory" SQL command.
|
| +*/
|
| +SQLITE_API char *sqlite3_data_directory = 0;
|
| +
|
| +/*
|
| +** Initialize SQLite.
|
| +**
|
| +** This routine must be called to initialize the memory allocation,
|
| +** VFS, and mutex subsystems prior to doing any serious work with
|
| +** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
|
| +** this routine will be called automatically by key routines such as
|
| +** sqlite3_open().
|
| +**
|
| +** This routine is a no-op except on its very first call for the process,
|
| +** or for the first call after a call to sqlite3_shutdown.
|
| +**
|
| +** The first thread to call this routine runs the initialization to
|
| +** completion. If subsequent threads call this routine before the first
|
| +** thread has finished the initialization process, then the subsequent
|
| +** threads must block until the first thread finishes with the initialization.
|
| +**
|
| +** The first thread might call this routine recursively. Recursive
|
| +** calls to this routine should not block, of course. Otherwise the
|
| +** initialization process would never complete.
|
| +**
|
| +** Let X be the first thread to enter this routine. Let Y be some other
|
| +** thread. Then while the initial invocation of this routine by X is
|
| +** incomplete, it is required that:
|
| +**
|
| +** * Calls to this routine from Y must block until the outer-most
|
| +** call by X completes.
|
| +**
|
| +** * Recursive calls to this routine from thread X return immediately
|
| +** without blocking.
|
| +*/
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_initialize(void){
|
| + MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
|
| + int rc; /* Result code */
|
| +#ifdef SQLITE_EXTRA_INIT
|
| + int bRunExtraInit = 0; /* Extra initialization needed */
|
| +#endif
|
| +
|
| +#ifdef SQLITE_OMIT_WSD
|
| + rc = sqlite3_wsd_init(4096, 24);
|
| + if( rc!=SQLITE_OK ){
|
| + return rc;
|
| + }
|
| +#endif
|
| +
|
| + /* If the following assert() fails on some obscure processor/compiler
|
| + ** combination, the work-around is to set the correct pointer
|
| + ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */
|
| + assert( SQLITE_PTRSIZE==sizeof(char*) );
|
| +
|
| + /* If SQLite is already completely initialized, then this call
|
| + ** to sqlite3_initialize() should be a no-op. But the initialization
|
| + ** must be complete. So isInit must not be set until the very end
|
| + ** of this routine.
|
| + */
|
| + if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
|
| +
|
| + /* Make sure the mutex subsystem is initialized. If unable to
|
| + ** initialize the mutex subsystem, return early with the error.
|
| + ** If the system is so sick that we are unable to allocate a mutex,
|
| + ** there is not much SQLite is going to be able to do.
|
| + **
|
| + ** The mutex subsystem must take care of serializing its own
|
| + ** initialization.
|
| + */
|
| + rc = sqlite3MutexInit();
|
| + if( rc ) return rc;
|
| +
|
| + /* Initialize the malloc() system and the recursive pInitMutex mutex.
|
| + ** This operation is protected by the STATIC_MASTER mutex. Note that
|
| + ** MutexAlloc() is called for a static mutex prior to initializing the
|
| + ** malloc subsystem - this implies that the allocation of a static
|
| + ** mutex must not require support from the malloc subsystem.
|
| + */
|
| + MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
|
| + sqlite3_mutex_enter(pMaster);
|
| + sqlite3GlobalConfig.isMutexInit = 1;
|
| + if( !sqlite3GlobalConfig.isMallocInit ){
|
| + rc = sqlite3MallocInit();
|
| + }
|
| + if( rc==SQLITE_OK ){
|
| + sqlite3GlobalConfig.isMallocInit = 1;
|
| + if( !sqlite3GlobalConfig.pInitMutex ){
|
| + sqlite3GlobalConfig.pInitMutex =
|
| + sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
|
| + if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
|
| + rc = SQLITE_NOMEM;
|
| + }
|
| + }
|
| + }
|
| + if( rc==SQLITE_OK ){
|
| + sqlite3GlobalConfig.nRefInitMutex++;
|
| + }
|
| + sqlite3_mutex_leave(pMaster);
|
| +
|
| + /* If rc is not SQLITE_OK at this point, then either the malloc
|
| + ** subsystem could not be initialized or the system failed to allocate
|
| + ** the pInitMutex mutex. Return an error in either case. */
|
| + if( rc!=SQLITE_OK ){
|
| + return rc;
|
| + }
|
| +
|
| + /* Do the rest of the initialization under the recursive mutex so
|
| + ** that we will be able to handle recursive calls into
|
| + ** sqlite3_initialize(). The recursive calls normally come through
|
| + ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
|
| + ** recursive calls might also be possible.
|
| + **
|
| + ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
|
| + ** to the xInit method, so the xInit method need not be threadsafe.
|
| + **
|
| + ** The following mutex is what serializes access to the appdef pcache xInit
|
| + ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
|
| + ** call to sqlite3PcacheInitialize().
|
| + */
|
| + sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
|
| + if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
|
| + FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
|
| + sqlite3GlobalConfig.inProgress = 1;
|
| +#ifdef SQLITE_ENABLE_SQLLOG
|
| + {
|
| + extern void sqlite3_init_sqllog(void);
|
| + sqlite3_init_sqllog();
|
| + }
|
| +#endif
|
| + memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
|
| + sqlite3RegisterGlobalFunctions();
|
| + if( sqlite3GlobalConfig.isPCacheInit==0 ){
|
| + rc = sqlite3PcacheInitialize();
|
| + }
|
| + if( rc==SQLITE_OK ){
|
| + sqlite3GlobalConfig.isPCacheInit = 1;
|
| + rc = sqlite3OsInit();
|
| + }
|
| + if( rc==SQLITE_OK ){
|
| + sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
|
| + sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
|
| + sqlite3GlobalConfig.isInit = 1;
|
| +#ifdef SQLITE_EXTRA_INIT
|
| + bRunExtraInit = 1;
|
| +#endif
|
| + }
|
| + sqlite3GlobalConfig.inProgress = 0;
|
| + }
|
| + sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
|
| +
|
| + /* Go back under the static mutex and clean up the recursive
|
| + ** mutex to prevent a resource leak.
|
| + */
|
| + sqlite3_mutex_enter(pMaster);
|
| + sqlite3GlobalConfig.nRefInitMutex--;
|
| + if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
|
| + assert( sqlite3GlobalConfig.nRefInitMutex==0 );
|
| + sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
|
| + sqlite3GlobalConfig.pInitMutex = 0;
|
| + }
|
| + sqlite3_mutex_leave(pMaster);
|
| +
|
| + /* The following is just a sanity check to make sure SQLite has
|
| + ** been compiled correctly. It is important to run this code, but
|
| + ** we don't want to run it too often and soak up CPU cycles for no
|
| + ** reason. So we run it once during initialization.
|
| + */
|
| +#ifndef NDEBUG
|
| +#ifndef SQLITE_OMIT_FLOATING_POINT
|
| + /* This section of code's only "output" is via assert() statements. */
|
| + if ( rc==SQLITE_OK ){
|
| + u64 x = (((u64)1)<<63)-1;
|
| + double y;
|
| + assert(sizeof(x)==8);
|
| + assert(sizeof(x)==sizeof(y));
|
| + memcpy(&y, &x, 8);
|
| + assert( sqlite3IsNaN(y) );
|
| + }
|
| +#endif
|
| +#endif
|
| +
|
| + /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
|
| + ** compile-time option.
|
| + */
|
| +#ifdef SQLITE_EXTRA_INIT
|
| + if( bRunExtraInit ){
|
| + int SQLITE_EXTRA_INIT(const char*);
|
| + rc = SQLITE_EXTRA_INIT(0);
|
| + }
|
| +#endif
|
| +
|
| + return rc;
|
| +}
|
| +
|
| +/*
|
| +** Undo the effects of sqlite3_initialize(). Must not be called while
|
| +** there are outstanding database connections or memory allocations or
|
| +** while any part of SQLite is otherwise in use in any thread. This
|
| +** routine is not threadsafe. But it is safe to invoke this routine
|
| +** on when SQLite is already shut down. If SQLite is already shut down
|
| +** when this routine is invoked, then this routine is a harmless no-op.
|
| +*/
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_shutdown(void){
|
| +#ifdef SQLITE_OMIT_WSD
|
| + int rc = sqlite3_wsd_init(4096, 24);
|
| + if( rc!=SQLITE_OK ){
|
| + return rc;
|
| + }
|
| +#endif
|
| +
|
| + if( sqlite3GlobalConfig.isInit ){
|
| +#ifdef SQLITE_EXTRA_SHUTDOWN
|
| + void SQLITE_EXTRA_SHUTDOWN(void);
|
| + SQLITE_EXTRA_SHUTDOWN();
|
| +#endif
|
| + sqlite3_os_end();
|
| + sqlite3_reset_auto_extension();
|
| + sqlite3GlobalConfig.isInit = 0;
|
| + }
|
| + if( sqlite3GlobalConfig.isPCacheInit ){
|
| + sqlite3PcacheShutdown();
|
| + sqlite3GlobalConfig.isPCacheInit = 0;
|
| + }
|
| + if( sqlite3GlobalConfig.isMallocInit ){
|
| + sqlite3MallocEnd();
|
| + sqlite3GlobalConfig.isMallocInit = 0;
|
| +
|
| +#ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
|
| + /* The heap subsystem has now been shutdown and these values are supposed
|
| + ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
|
| + ** which would rely on that heap subsystem; therefore, make sure these
|
| + ** values cannot refer to heap memory that was just invalidated when the
|
| + ** heap subsystem was shutdown. This is only done if the current call to
|
| + ** this function resulted in the heap subsystem actually being shutdown.
|
| + */
|
| + sqlite3_data_directory = 0;
|
| + sqlite3_temp_directory = 0;
|
| +#endif
|
| + }
|
| + if( sqlite3GlobalConfig.isMutexInit ){
|
| + sqlite3MutexEnd();
|
| + sqlite3GlobalConfig.isMutexInit = 0;
|
| + }
|
| +
|
| + return SQLITE_OK;
|
| +}
|
| +
|
| +/*
|
| +** This API allows applications to modify the global configuration of
|
| +** the SQLite library at run-time.
|
| +**
|
| +** This routine should only be called when there are no outstanding
|
| +** database connections or memory allocations. This routine is not
|
| +** threadsafe. Failure to heed these warnings can lead to unpredictable
|
| +** behavior.
|
| +*/
|
| +SQLITE_API int SQLITE_CDECL sqlite3_config(int op, ...){
|
| + va_list ap;
|
| + int rc = SQLITE_OK;
|
| +
|
| + /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
|
| + ** the SQLite library is in use. */
|
| + if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
|
| +
|
| + va_start(ap, op);
|
| + switch( op ){
|
| +
|
| + /* Mutex configuration options are only available in a threadsafe
|
| + ** compile.
|
| + */
|
| +#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-54466-46756 */
|
| + case SQLITE_CONFIG_SINGLETHREAD: {
|
| + /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to
|
| + ** Single-thread. */
|
| + sqlite3GlobalConfig.bCoreMutex = 0; /* Disable mutex on core */
|
| + sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
|
| + break;
|
| + }
|
| +#endif
|
| +#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */
|
| + case SQLITE_CONFIG_MULTITHREAD: {
|
| + /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to
|
| + ** Multi-thread. */
|
| + sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
|
| + sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
|
| + break;
|
| + }
|
| +#endif
|
| +#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */
|
| + case SQLITE_CONFIG_SERIALIZED: {
|
| + /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to
|
| + ** Serialized. */
|
| + sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
|
| + sqlite3GlobalConfig.bFullMutex = 1; /* Enable mutex on connections */
|
| + break;
|
| + }
|
| +#endif
|
| +#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */
|
| + case SQLITE_CONFIG_MUTEX: {
|
| + /* Specify an alternative mutex implementation */
|
| + sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
|
| + break;
|
| + }
|
| +#endif
|
| +#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */
|
| + case SQLITE_CONFIG_GETMUTEX: {
|
| + /* Retrieve the current mutex implementation */
|
| + *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
|
| + break;
|
| + }
|
| +#endif
|
| +
|
| + case SQLITE_CONFIG_MALLOC: {
|
| + /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
|
| + ** single argument which is a pointer to an instance of the
|
| + ** sqlite3_mem_methods structure. The argument specifies alternative
|
| + ** low-level memory allocation routines to be used in place of the memory
|
| + ** allocation routines built into SQLite. */
|
| + sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
|
| + break;
|
| + }
|
| + case SQLITE_CONFIG_GETMALLOC: {
|
| + /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
|
| + ** single argument which is a pointer to an instance of the
|
| + ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
|
| + ** filled with the currently defined memory allocation routines. */
|
| + if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
|
| + *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
|
| + break;
|
| + }
|
| + case SQLITE_CONFIG_MEMSTATUS: {
|
| + /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
|
| + ** single argument of type int, interpreted as a boolean, which enables
|
| + ** or disables the collection of memory allocation statistics. */
|
| + sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
|
| + break;
|
| + }
|
| + case SQLITE_CONFIG_SCRATCH: {
|
| + /* EVIDENCE-OF: R-08404-60887 There are three arguments to
|
| + ** SQLITE_CONFIG_SCRATCH: A pointer an 8-byte aligned memory buffer from
|
| + ** which the scratch allocations will be drawn, the size of each scratch
|
| + ** allocation (sz), and the maximum number of scratch allocations (N). */
|
| + sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
|
| + sqlite3GlobalConfig.szScratch = va_arg(ap, int);
|
| + sqlite3GlobalConfig.nScratch = va_arg(ap, int);
|
| + break;
|
| + }
|
| + case SQLITE_CONFIG_PAGECACHE: {
|
| + /* EVIDENCE-OF: R-18761-36601 There are three arguments to
|
| + ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem),
|
| + ** the size of each page cache line (sz), and the number of cache lines
|
| + ** (N). */
|
| + sqlite3GlobalConfig.pPage = va_arg(ap, void*);
|
| + sqlite3GlobalConfig.szPage = va_arg(ap, int);
|
| + sqlite3GlobalConfig.nPage = va_arg(ap, int);
|
| + break;
|
| + }
|
| + case SQLITE_CONFIG_PCACHE_HDRSZ: {
|
| + /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
|
| + ** a single parameter which is a pointer to an integer and writes into
|
| + ** that integer the number of extra bytes per page required for each page
|
| + ** in SQLITE_CONFIG_PAGECACHE. */
|
| + *va_arg(ap, int*) =
|
| + sqlite3HeaderSizeBtree() +
|
| + sqlite3HeaderSizePcache() +
|
| + sqlite3HeaderSizePcache1();
|
| + break;
|
| + }
|
| +
|
| + case SQLITE_CONFIG_PCACHE: {
|
| + /* no-op */
|
| + break;
|
| + }
|
| + case SQLITE_CONFIG_GETPCACHE: {
|
| + /* now an error */
|
| + rc = SQLITE_ERROR;
|
| + break;
|
| + }
|
| +
|
| + case SQLITE_CONFIG_PCACHE2: {
|
| + /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
|
| + ** single argument which is a pointer to an sqlite3_pcache_methods2
|
| + ** object. This object specifies the interface to a custom page cache
|
| + ** implementation. */
|
| + sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
|
| + break;
|
| + }
|
| + case SQLITE_CONFIG_GETPCACHE2: {
|
| + /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
|
| + ** single argument which is a pointer to an sqlite3_pcache_methods2
|
| + ** object. SQLite copies of the current page cache implementation into
|
| + ** that object. */
|
| + if( sqlite3GlobalConfig.pcache2.xInit==0 ){
|
| + sqlite3PCacheSetDefault();
|
| + }
|
| + *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
|
| + break;
|
| + }
|
| +
|
| +/* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
|
| +** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or
|
| +** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */
|
| +#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
|
| + case SQLITE_CONFIG_HEAP: {
|
| + /* EVIDENCE-OF: R-19854-42126 There are three arguments to
|
| + ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the
|
| + ** number of bytes in the memory buffer, and the minimum allocation size.
|
| + */
|
| + sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
|
| + sqlite3GlobalConfig.nHeap = va_arg(ap, int);
|
| + sqlite3GlobalConfig.mnReq = va_arg(ap, int);
|
| +
|
| + if( sqlite3GlobalConfig.mnReq<1 ){
|
| + sqlite3GlobalConfig.mnReq = 1;
|
| + }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
|
| + /* cap min request size at 2^12 */
|
| + sqlite3GlobalConfig.mnReq = (1<<12);
|
| + }
|
| +
|
| + if( sqlite3GlobalConfig.pHeap==0 ){
|
| + /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)
|
| + ** is NULL, then SQLite reverts to using its default memory allocator
|
| + ** (the system malloc() implementation), undoing any prior invocation of
|
| + ** SQLITE_CONFIG_MALLOC.
|
| + **
|
| + ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to
|
| + ** revert to its default implementation when sqlite3_initialize() is run
|
| + */
|
| + memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
|
| + }else{
|
| + /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the
|
| + ** alternative memory allocator is engaged to handle all of SQLites
|
| + ** memory allocation needs. */
|
| +#ifdef SQLITE_ENABLE_MEMSYS3
|
| + sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
|
| +#endif
|
| +#ifdef SQLITE_ENABLE_MEMSYS5
|
| + sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
|
| +#endif
|
| + }
|
| + break;
|
| + }
|
| +#endif
|
| +
|
| + case SQLITE_CONFIG_LOOKASIDE: {
|
| + sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
|
| + sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
|
| + break;
|
| + }
|
| +
|
| + /* Record a pointer to the logger function and its first argument.
|
| + ** The default is NULL. Logging is disabled if the function pointer is
|
| + ** NULL.
|
| + */
|
| + case SQLITE_CONFIG_LOG: {
|
| + /* MSVC is picky about pulling func ptrs from va lists.
|
| + ** http://support.microsoft.com/kb/47961
|
| + ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
|
| + */
|
| + typedef void(*LOGFUNC_t)(void*,int,const char*);
|
| + sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
|
| + sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
|
| + break;
|
| + }
|
| +
|
| + /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
|
| + ** can be changed at start-time using the
|
| + ** sqlite3_config(SQLITE_CONFIG_URI,1) or
|
| + ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
|
| + */
|
| + case SQLITE_CONFIG_URI: {
|
| + /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
|
| + ** argument of type int. If non-zero, then URI handling is globally
|
| + ** enabled. If the parameter is zero, then URI handling is globally
|
| + ** disabled. */
|
| + sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
|
| + break;
|
| + }
|
| +
|
| + case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
|
| + /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
|
| + ** option takes a single integer argument which is interpreted as a
|
| + ** boolean in order to enable or disable the use of covering indices for
|
| + ** full table scans in the query optimizer. */
|
| + sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
|
| + break;
|
| + }
|
| +
|
| +#ifdef SQLITE_ENABLE_SQLLOG
|
| + case SQLITE_CONFIG_SQLLOG: {
|
| + typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
|
| + sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
|
| + sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
|
| + break;
|
| + }
|
| +#endif
|
| +
|
| + case SQLITE_CONFIG_MMAP_SIZE: {
|
| + /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
|
| + ** integer (sqlite3_int64) values that are the default mmap size limit
|
| + ** (the default setting for PRAGMA mmap_size) and the maximum allowed
|
| + ** mmap size limit. */
|
| + sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
|
| + sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
|
| + /* EVIDENCE-OF: R-53367-43190 If either argument to this option is
|
| + ** negative, then that argument is changed to its compile-time default.
|
| + **
|
| + ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
|
| + ** silently truncated if necessary so that it does not exceed the
|
| + ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
|
| + ** compile-time option.
|
| + */
|
| + if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
|
| + mxMmap = SQLITE_MAX_MMAP_SIZE;
|
| + }
|
| + if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
|
| + if( szMmap>mxMmap) szMmap = mxMmap;
|
| + sqlite3GlobalConfig.mxMmap = mxMmap;
|
| + sqlite3GlobalConfig.szMmap = szMmap;
|
| + break;
|
| + }
|
| +
|
| +#if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */
|
| + case SQLITE_CONFIG_WIN32_HEAPSIZE: {
|
| + /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit
|
| + ** unsigned integer value that specifies the maximum size of the created
|
| + ** heap. */
|
| + sqlite3GlobalConfig.nHeap = va_arg(ap, int);
|
| + break;
|
| + }
|
| +#endif
|
| +
|
| + case SQLITE_CONFIG_PMASZ: {
|
| + sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int);
|
| + break;
|
| + }
|
| +
|
| + default: {
|
| + rc = SQLITE_ERROR;
|
| + break;
|
| + }
|
| + }
|
| + va_end(ap);
|
| + return rc;
|
| +}
|
| +
|
| +/*
|
| +** Set up the lookaside buffers for a database connection.
|
| +** Return SQLITE_OK on success.
|
| +** If lookaside is already active, return SQLITE_BUSY.
|
| +**
|
| +** The sz parameter is the number of bytes in each lookaside slot.
|
| +** The cnt parameter is the number of slots. If pStart is NULL the
|
| +** space for the lookaside memory is obtained from sqlite3_malloc().
|
| +** If pStart is not NULL then it is sz*cnt bytes of memory to use for
|
| +** the lookaside memory.
|
| +*/
|
| +static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
|
| +#ifndef SQLITE_OMIT_LOOKASIDE
|
| + void *pStart;
|
| + if( db->lookaside.nOut ){
|
| + return SQLITE_BUSY;
|
| + }
|
| + /* Free any existing lookaside buffer for this handle before
|
| + ** allocating a new one so we don't have to have space for
|
| + ** both at the same time.
|
| + */
|
| + if( db->lookaside.bMalloced ){
|
| + sqlite3_free(db->lookaside.pStart);
|
| + }
|
| + /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
|
| + ** than a pointer to be useful.
|
| + */
|
| + sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
|
| + if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
|
| + if( cnt<0 ) cnt = 0;
|
| + if( sz==0 || cnt==0 ){
|
| + sz = 0;
|
| + pStart = 0;
|
| + }else if( pBuf==0 ){
|
| + sqlite3BeginBenignMalloc();
|
| + pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */
|
| + sqlite3EndBenignMalloc();
|
| + if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
|
| + }else{
|
| + pStart = pBuf;
|
| + }
|
| + db->lookaside.pStart = pStart;
|
| + db->lookaside.pFree = 0;
|
| + db->lookaside.sz = (u16)sz;
|
| + if( pStart ){
|
| + int i;
|
| + LookasideSlot *p;
|
| + assert( sz > (int)sizeof(LookasideSlot*) );
|
| + p = (LookasideSlot*)pStart;
|
| + for(i=cnt-1; i>=0; i--){
|
| + p->pNext = db->lookaside.pFree;
|
| + db->lookaside.pFree = p;
|
| + p = (LookasideSlot*)&((u8*)p)[sz];
|
| + }
|
| + db->lookaside.pEnd = p;
|
| + db->lookaside.bEnabled = 1;
|
| + db->lookaside.bMalloced = pBuf==0 ?1:0;
|
| + }else{
|
| + db->lookaside.pStart = db;
|
| + db->lookaside.pEnd = db;
|
| + db->lookaside.bEnabled = 0;
|
| + db->lookaside.bMalloced = 0;
|
| + }
|
| +#endif /* SQLITE_OMIT_LOOKASIDE */
|
| + return SQLITE_OK;
|
| +}
|
| +
|
| +/*
|
| +** Return the mutex associated with a database connection.
|
| +*/
|
| +SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_db_mutex(sqlite3 *db){
|
| +#ifdef SQLITE_ENABLE_API_ARMOR
|
| + if( !sqlite3SafetyCheckOk(db) ){
|
| + (void)SQLITE_MISUSE_BKPT;
|
| + return 0;
|
| + }
|
| +#endif
|
| + return db->mutex;
|
| +}
|
| +
|
| +/*
|
| +** Free up as much memory as we can from the given database
|
| +** connection.
|
| +*/
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_db_release_memory(sqlite3 *db){
|
| + int i;
|
| +
|
| +#ifdef SQLITE_ENABLE_API_ARMOR
|
| + if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
|
| +#endif
|
| + sqlite3_mutex_enter(db->mutex);
|
| + sqlite3BtreeEnterAll(db);
|
| + for(i=0; i<db->nDb; i++){
|
| + Btree *pBt = db->aDb[i].pBt;
|
| + if( pBt ){
|
| + Pager *pPager = sqlite3BtreePager(pBt);
|
| + sqlite3PagerShrink(pPager);
|
| + }
|
| + }
|
| + sqlite3BtreeLeaveAll(db);
|
| + sqlite3_mutex_leave(db->mutex);
|
| + return SQLITE_OK;
|
| +}
|
| +
|
| +/*
|
| +** Flush any dirty pages in the pager-cache for any attached database
|
| +** to disk.
|
| +*/
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_db_cacheflush(sqlite3 *db){
|
| + int i;
|
| + int rc = SQLITE_OK;
|
| + int bSeenBusy = 0;
|
| +
|
| +#ifdef SQLITE_ENABLE_API_ARMOR
|
| + if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
|
| +#endif
|
| + sqlite3_mutex_enter(db->mutex);
|
| + sqlite3BtreeEnterAll(db);
|
| + for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
|
| + Btree *pBt = db->aDb[i].pBt;
|
| + if( pBt && sqlite3BtreeIsInTrans(pBt) ){
|
| + Pager *pPager = sqlite3BtreePager(pBt);
|
| + rc = sqlite3PagerFlush(pPager);
|
| + if( rc==SQLITE_BUSY ){
|
| + bSeenBusy = 1;
|
| + rc = SQLITE_OK;
|
| + }
|
| + }
|
| + }
|
| + sqlite3BtreeLeaveAll(db);
|
| + sqlite3_mutex_leave(db->mutex);
|
| + return ((rc==SQLITE_OK && bSeenBusy) ? SQLITE_BUSY : rc);
|
| +}
|
| +
|
| +/*
|
| +** Configuration settings for an individual database connection
|
| +*/
|
| +SQLITE_API int SQLITE_CDECL sqlite3_db_config(sqlite3 *db, int op, ...){
|
| + va_list ap;
|
| + int rc;
|
| + va_start(ap, op);
|
| + switch( op ){
|
| + case SQLITE_DBCONFIG_LOOKASIDE: {
|
| + void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
|
| + int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
|
| + int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
|
| + rc = setupLookaside(db, pBuf, sz, cnt);
|
| + break;
|
| + }
|
| + default: {
|
| + static const struct {
|
| + int op; /* The opcode */
|
| + u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */
|
| + } aFlagOp[] = {
|
| + { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys },
|
| + { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger },
|
| + };
|
| + unsigned int i;
|
| + rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
|
| + for(i=0; i<ArraySize(aFlagOp); i++){
|
| + if( aFlagOp[i].op==op ){
|
| + int onoff = va_arg(ap, int);
|
| + int *pRes = va_arg(ap, int*);
|
| + int oldFlags = db->flags;
|
| + if( onoff>0 ){
|
| + db->flags |= aFlagOp[i].mask;
|
| + }else if( onoff==0 ){
|
| + db->flags &= ~aFlagOp[i].mask;
|
| + }
|
| + if( oldFlags!=db->flags ){
|
| + sqlite3ExpirePreparedStatements(db);
|
| + }
|
| + if( pRes ){
|
| + *pRes = (db->flags & aFlagOp[i].mask)!=0;
|
| + }
|
| + rc = SQLITE_OK;
|
| + break;
|
| + }
|
| + }
|
| + break;
|
| + }
|
| + }
|
| + va_end(ap);
|
| + return rc;
|
| +}
|
| +
|
| +
|
| +/*
|
| +** Return true if the buffer z[0..n-1] contains all spaces.
|
| +*/
|
| +static int allSpaces(const char *z, int n){
|
| + while( n>0 && z[n-1]==' ' ){ n--; }
|
| + return n==0;
|
| +}
|
| +
|
| +/*
|
| +** This is the default collating function named "BINARY" which is always
|
| +** available.
|
| +**
|
| +** If the padFlag argument is not NULL then space padding at the end
|
| +** of strings is ignored. This implements the RTRIM collation.
|
| +*/
|
| +static int binCollFunc(
|
| + void *padFlag,
|
| + int nKey1, const void *pKey1,
|
| + int nKey2, const void *pKey2
|
| +){
|
| + int rc, n;
|
| + n = nKey1<nKey2 ? nKey1 : nKey2;
|
| + /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
|
| + ** strings byte by byte using the memcmp() function from the standard C
|
| + ** library. */
|
| + rc = memcmp(pKey1, pKey2, n);
|
| + if( rc==0 ){
|
| + if( padFlag
|
| + && allSpaces(((char*)pKey1)+n, nKey1-n)
|
| + && allSpaces(((char*)pKey2)+n, nKey2-n)
|
| + ){
|
| + /* EVIDENCE-OF: R-31624-24737 RTRIM is like BINARY except that extra
|
| + ** spaces at the end of either string do not change the result. In other
|
| + ** words, strings will compare equal to one another as long as they
|
| + ** differ only in the number of spaces at the end.
|
| + */
|
| + }else{
|
| + rc = nKey1 - nKey2;
|
| + }
|
| + }
|
| + return rc;
|
| +}
|
| +
|
| +/*
|
| +** Another built-in collating sequence: NOCASE.
|
| +**
|
| +** This collating sequence is intended to be used for "case independent
|
| +** comparison". SQLite's knowledge of upper and lower case equivalents
|
| +** extends only to the 26 characters used in the English language.
|
| +**
|
| +** At the moment there is only a UTF-8 implementation.
|
| +*/
|
| +static int nocaseCollatingFunc(
|
| + void *NotUsed,
|
| + int nKey1, const void *pKey1,
|
| + int nKey2, const void *pKey2
|
| +){
|
| + int r = sqlite3StrNICmp(
|
| + (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
|
| + UNUSED_PARAMETER(NotUsed);
|
| + if( 0==r ){
|
| + r = nKey1-nKey2;
|
| + }
|
| + return r;
|
| +}
|
| +
|
| +/*
|
| +** Return the ROWID of the most recent insert
|
| +*/
|
| +SQLITE_API sqlite_int64 SQLITE_STDCALL sqlite3_last_insert_rowid(sqlite3 *db){
|
| +#ifdef SQLITE_ENABLE_API_ARMOR
|
| + if( !sqlite3SafetyCheckOk(db) ){
|
| + (void)SQLITE_MISUSE_BKPT;
|
| + return 0;
|
| + }
|
| +#endif
|
| + return db->lastRowid;
|
| +}
|
| +
|
| +/*
|
| +** Return the number of changes in the most recent call to sqlite3_exec().
|
| +*/
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_changes(sqlite3 *db){
|
| +#ifdef SQLITE_ENABLE_API_ARMOR
|
| + if( !sqlite3SafetyCheckOk(db) ){
|
| + (void)SQLITE_MISUSE_BKPT;
|
| + return 0;
|
| + }
|
| +#endif
|
| + return db->nChange;
|
| +}
|
| +
|
| +/*
|
| +** Return the number of changes since the database handle was opened.
|
| +*/
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_total_changes(sqlite3 *db){
|
| +#ifdef SQLITE_ENABLE_API_ARMOR
|
| + if( !sqlite3SafetyCheckOk(db) ){
|
| + (void)SQLITE_MISUSE_BKPT;
|
| + return 0;
|
| + }
|
| +#endif
|
| + return db->nTotalChange;
|
| +}
|
| +
|
| +/*
|
| +** Close all open savepoints. This function only manipulates fields of the
|
| +** database handle object, it does not close any savepoints that may be open
|
| +** at the b-tree/pager level.
|
| +*/
|
| +SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
|
| + while( db->pSavepoint ){
|
| + Savepoint *pTmp = db->pSavepoint;
|
| + db->pSavepoint = pTmp->pNext;
|
| + sqlite3DbFree(db, pTmp);
|
| + }
|
| + db->nSavepoint = 0;
|
| + db->nStatement = 0;
|
| + db->isTransactionSavepoint = 0;
|
| +}
|
| +
|
| +/*
|
| +** Invoke the destructor function associated with FuncDef p, if any. Except,
|
| +** if this is not the last copy of the function, do not invoke it. Multiple
|
| +** copies of a single function are created when create_function() is called
|
| +** with SQLITE_ANY as the encoding.
|
| +*/
|
| +static void functionDestroy(sqlite3 *db, FuncDef *p){
|
| + FuncDestructor *pDestructor = p->pDestructor;
|
| + if( pDestructor ){
|
| + pDestructor->nRef--;
|
| + if( pDestructor->nRef==0 ){
|
| + pDestructor->xDestroy(pDestructor->pUserData);
|
| + sqlite3DbFree(db, pDestructor);
|
| + }
|
| + }
|
| +}
|
| +
|
| +/*
|
| +** Disconnect all sqlite3_vtab objects that belong to database connection
|
| +** db. This is called when db is being closed.
|
| +*/
|
| +static void disconnectAllVtab(sqlite3 *db){
|
| +#ifndef SQLITE_OMIT_VIRTUALTABLE
|
| + int i;
|
| + HashElem *p;
|
| + sqlite3BtreeEnterAll(db);
|
| + for(i=0; i<db->nDb; i++){
|
| + Schema *pSchema = db->aDb[i].pSchema;
|
| + if( db->aDb[i].pSchema ){
|
| + for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
|
| + Table *pTab = (Table *)sqliteHashData(p);
|
| + if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
|
| + }
|
| + }
|
| + }
|
| + for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){
|
| + Module *pMod = (Module *)sqliteHashData(p);
|
| + if( pMod->pEpoTab ){
|
| + sqlite3VtabDisconnect(db, pMod->pEpoTab);
|
| + }
|
| + }
|
| + sqlite3VtabUnlockList(db);
|
| + sqlite3BtreeLeaveAll(db);
|
| +#else
|
| + UNUSED_PARAMETER(db);
|
| +#endif
|
| +}
|
| +
|
| +/*
|
| +** Return TRUE if database connection db has unfinalized prepared
|
| +** statements or unfinished sqlite3_backup objects.
|
| +*/
|
| +static int connectionIsBusy(sqlite3 *db){
|
| + int j;
|
| + assert( sqlite3_mutex_held(db->mutex) );
|
| + if( db->pVdbe ) return 1;
|
| + for(j=0; j<db->nDb; j++){
|
| + Btree *pBt = db->aDb[j].pBt;
|
| + if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
|
| + }
|
| + return 0;
|
| +}
|
| +
|
| +/*
|
| +** Close an existing SQLite database
|
| +*/
|
| +static int sqlite3Close(sqlite3 *db, int forceZombie){
|
| + if( !db ){
|
| + /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
|
| + ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
|
| + return SQLITE_OK;
|
| + }
|
| + if( !sqlite3SafetyCheckSickOrOk(db) ){
|
| + return SQLITE_MISUSE_BKPT;
|
| + }
|
| + sqlite3_mutex_enter(db->mutex);
|
| +
|
| + /* Force xDisconnect calls on all virtual tables */
|
| + disconnectAllVtab(db);
|
| +
|
| + /* If a transaction is open, the disconnectAllVtab() call above
|
| + ** will not have called the xDisconnect() method on any virtual
|
| + ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
|
| + ** call will do so. We need to do this before the check for active
|
| + ** SQL statements below, as the v-table implementation may be storing
|
| + ** some prepared statements internally.
|
| + */
|
| + sqlite3VtabRollback(db);
|
| +
|
| + /* Legacy behavior (sqlite3_close() behavior) is to return
|
| + ** SQLITE_BUSY if the connection can not be closed immediately.
|
| + */
|
| + if( !forceZombie && connectionIsBusy(db) ){
|
| + sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
|
| + "statements or unfinished backups");
|
| + sqlite3_mutex_leave(db->mutex);
|
| + return SQLITE_BUSY;
|
| + }
|
| +
|
| +#ifdef SQLITE_ENABLE_SQLLOG
|
| + if( sqlite3GlobalConfig.xSqllog ){
|
| + /* Closing the handle. Fourth parameter is passed the value 2. */
|
| + sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
|
| + }
|
| +#endif
|
| +
|
| + /* Convert the connection into a zombie and then close it.
|
| + */
|
| + db->magic = SQLITE_MAGIC_ZOMBIE;
|
| + sqlite3LeaveMutexAndCloseZombie(db);
|
| + return SQLITE_OK;
|
| +}
|
| +
|
| +/*
|
| +** Two variations on the public interface for closing a database
|
| +** connection. The sqlite3_close() version returns SQLITE_BUSY and
|
| +** leaves the connection option if there are unfinalized prepared
|
| +** statements or unfinished sqlite3_backups. The sqlite3_close_v2()
|
| +** version forces the connection to become a zombie if there are
|
| +** unclosed resources, and arranges for deallocation when the last
|
| +** prepare statement or sqlite3_backup closes.
|
| +*/
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
|
| +
|
| +
|
| +/*
|
| +** Close the mutex on database connection db.
|
| +**
|
| +** Furthermore, if database connection db is a zombie (meaning that there
|
| +** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
|
| +** every sqlite3_stmt has now been finalized and every sqlite3_backup has
|
| +** finished, then free all resources.
|
| +*/
|
| +SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
|
| + HashElem *i; /* Hash table iterator */
|
| + int j;
|
| +
|
| + /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
|
| + ** or if the connection has not yet been closed by sqlite3_close_v2(),
|
| + ** then just leave the mutex and return.
|
| + */
|
| + if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
|
| + sqlite3_mutex_leave(db->mutex);
|
| + return;
|
| + }
|
| +
|
| + /* If we reach this point, it means that the database connection has
|
| + ** closed all sqlite3_stmt and sqlite3_backup objects and has been
|
| + ** passed to sqlite3_close (meaning that it is a zombie). Therefore,
|
| + ** go ahead and free all resources.
|
| + */
|
| +
|
| + /* If a transaction is open, roll it back. This also ensures that if
|
| + ** any database schemas have been modified by an uncommitted transaction
|
| + ** they are reset. And that the required b-tree mutex is held to make
|
| + ** the pager rollback and schema reset an atomic operation. */
|
| + sqlite3RollbackAll(db, SQLITE_OK);
|
| +
|
| + /* Free any outstanding Savepoint structures. */
|
| + sqlite3CloseSavepoints(db);
|
| +
|
| + /* Close all database connections */
|
| + for(j=0; j<db->nDb; j++){
|
| + struct Db *pDb = &db->aDb[j];
|
| + if( pDb->pBt ){
|
| + sqlite3BtreeClose(pDb->pBt);
|
| + pDb->pBt = 0;
|
| + if( j!=1 ){
|
| + pDb->pSchema = 0;
|
| + }
|
| + }
|
| + }
|
| + /* Clear the TEMP schema separately and last */
|
| + if( db->aDb[1].pSchema ){
|
| + sqlite3SchemaClear(db->aDb[1].pSchema);
|
| + }
|
| + sqlite3VtabUnlockList(db);
|
| +
|
| + /* Free up the array of auxiliary databases */
|
| + sqlite3CollapseDatabaseArray(db);
|
| + assert( db->nDb<=2 );
|
| + assert( db->aDb==db->aDbStatic );
|
| +
|
| + /* Tell the code in notify.c that the connection no longer holds any
|
| + ** locks and does not require any further unlock-notify callbacks.
|
| + */
|
| + sqlite3ConnectionClosed(db);
|
| +
|
| + for(j=0; j<ArraySize(db->aFunc.a); j++){
|
| + FuncDef *pNext, *pHash, *p;
|
| + for(p=db->aFunc.a[j]; p; p=pHash){
|
| + pHash = p->pHash;
|
| + while( p ){
|
| + functionDestroy(db, p);
|
| + pNext = p->pNext;
|
| + sqlite3DbFree(db, p);
|
| + p = pNext;
|
| + }
|
| + }
|
| + }
|
| + for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
|
| + CollSeq *pColl = (CollSeq *)sqliteHashData(i);
|
| + /* Invoke any destructors registered for collation sequence user data. */
|
| + for(j=0; j<3; j++){
|
| + if( pColl[j].xDel ){
|
| + pColl[j].xDel(pColl[j].pUser);
|
| + }
|
| + }
|
| + sqlite3DbFree(db, pColl);
|
| + }
|
| + sqlite3HashClear(&db->aCollSeq);
|
| +#ifndef SQLITE_OMIT_VIRTUALTABLE
|
| + for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
|
| + Module *pMod = (Module *)sqliteHashData(i);
|
| + if( pMod->xDestroy ){
|
| + pMod->xDestroy(pMod->pAux);
|
| + }
|
| + sqlite3VtabEponymousTableClear(db, pMod);
|
| + sqlite3DbFree(db, pMod);
|
| + }
|
| + sqlite3HashClear(&db->aModule);
|
| +#endif
|
| +
|
| + sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
|
| + sqlite3ValueFree(db->pErr);
|
| + sqlite3CloseExtensions(db);
|
| +#if SQLITE_USER_AUTHENTICATION
|
| + sqlite3_free(db->auth.zAuthUser);
|
| + sqlite3_free(db->auth.zAuthPW);
|
| +#endif
|
| +
|
| + db->magic = SQLITE_MAGIC_ERROR;
|
| +
|
| + /* The temp-database schema is allocated differently from the other schema
|
| + ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
|
| + ** So it needs to be freed here. Todo: Why not roll the temp schema into
|
| + ** the same sqliteMalloc() as the one that allocates the database
|
| + ** structure?
|
| + */
|
| + sqlite3DbFree(db, db->aDb[1].pSchema);
|
| + sqlite3_mutex_leave(db->mutex);
|
| + db->magic = SQLITE_MAGIC_CLOSED;
|
| + sqlite3_mutex_free(db->mutex);
|
| + assert( db->lookaside.nOut==0 ); /* Fails on a lookaside memory leak */
|
| + if( db->lookaside.bMalloced ){
|
| + sqlite3_free(db->lookaside.pStart);
|
| + }
|
| + sqlite3_free(db);
|
| +}
|
| +
|
| +/*
|
| +** Rollback all database files. If tripCode is not SQLITE_OK, then
|
| +** any write cursors are invalidated ("tripped" - as in "tripping a circuit
|
| +** breaker") and made to return tripCode if there are any further
|
| +** attempts to use that cursor. Read cursors remain open and valid
|
| +** but are "saved" in case the table pages are moved around.
|
| +*/
|
| +SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
|
| + int i;
|
| + int inTrans = 0;
|
| + int schemaChange;
|
| + assert( sqlite3_mutex_held(db->mutex) );
|
| + sqlite3BeginBenignMalloc();
|
| +
|
| + /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
|
| + ** This is important in case the transaction being rolled back has
|
| + ** modified the database schema. If the b-tree mutexes are not taken
|
| + ** here, then another shared-cache connection might sneak in between
|
| + ** the database rollback and schema reset, which can cause false
|
| + ** corruption reports in some cases. */
|
| + sqlite3BtreeEnterAll(db);
|
| + schemaChange = (db->flags & SQLITE_InternChanges)!=0 && db->init.busy==0;
|
| +
|
| + for(i=0; i<db->nDb; i++){
|
| + Btree *p = db->aDb[i].pBt;
|
| + if( p ){
|
| + if( sqlite3BtreeIsInTrans(p) ){
|
| + inTrans = 1;
|
| + }
|
| + sqlite3BtreeRollback(p, tripCode, !schemaChange);
|
| + }
|
| + }
|
| + sqlite3VtabRollback(db);
|
| + sqlite3EndBenignMalloc();
|
| +
|
| + if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){
|
| + sqlite3ExpirePreparedStatements(db);
|
| + sqlite3ResetAllSchemasOfConnection(db);
|
| + }
|
| + sqlite3BtreeLeaveAll(db);
|
| +
|
| + /* Any deferred constraint violations have now been resolved. */
|
| + db->nDeferredCons = 0;
|
| + db->nDeferredImmCons = 0;
|
| + db->flags &= ~SQLITE_DeferFKs;
|
| +
|
| + /* If one has been configured, invoke the rollback-hook callback */
|
| + if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
|
| + db->xRollbackCallback(db->pRollbackArg);
|
| + }
|
| +}
|
| +
|
| +/*
|
| +** Return a static string containing the name corresponding to the error code
|
| +** specified in the argument.
|
| +*/
|
| +#if defined(SQLITE_NEED_ERR_NAME)
|
| +SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
|
| + const char *zName = 0;
|
| + int i, origRc = rc;
|
| + for(i=0; i<2 && zName==0; i++, rc &= 0xff){
|
| + switch( rc ){
|
| + case SQLITE_OK: zName = "SQLITE_OK"; break;
|
| + case SQLITE_ERROR: zName = "SQLITE_ERROR"; break;
|
| + case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break;
|
| + case SQLITE_PERM: zName = "SQLITE_PERM"; break;
|
| + case SQLITE_ABORT: zName = "SQLITE_ABORT"; break;
|
| + case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break;
|
| + case SQLITE_BUSY: zName = "SQLITE_BUSY"; break;
|
| + case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break;
|
| + case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break;
|
| + case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break;
|
| + case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
|
| + case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break;
|
| + case SQLITE_READONLY: zName = "SQLITE_READONLY"; break;
|
| + case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break;
|
| + case SQLITE_READONLY_CANTLOCK: zName = "SQLITE_READONLY_CANTLOCK"; break;
|
| + case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break;
|
| + case SQLITE_READONLY_DBMOVED: zName = "SQLITE_READONLY_DBMOVED"; break;
|
| + case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break;
|
| + case SQLITE_IOERR: zName = "SQLITE_IOERR"; break;
|
| + case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break;
|
| + case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break;
|
| + case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break;
|
| + case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break;
|
| + case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break;
|
| + case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break;
|
| + case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break;
|
| + case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break;
|
| + case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break;
|
| + case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break;
|
| + case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break;
|
| + case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break;
|
| + case SQLITE_IOERR_CHECKRESERVEDLOCK:
|
| + zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
|
| + case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break;
|
| + case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break;
|
| + case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break;
|
| + case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break;
|
| + case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break;
|
| + case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break;
|
| + case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break;
|
| + case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break;
|
| + case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
|
| + case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break;
|
| + case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break;
|
| + case SQLITE_IOERR_CONVPATH: zName = "SQLITE_IOERR_CONVPATH"; break;
|
| + case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break;
|
| + case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break;
|
| + case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break;
|
| + case SQLITE_FULL: zName = "SQLITE_FULL"; break;
|
| + case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break;
|
| + case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
|
| + case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break;
|
| + case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break;
|
| + case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break;
|
| + case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break;
|
| + case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break;
|
| + case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break;
|
| + case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break;
|
| + case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break;
|
| + case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
|
| + case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
|
| + case SQLITE_CONSTRAINT_FOREIGNKEY:
|
| + zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break;
|
| + case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break;
|
| + case SQLITE_CONSTRAINT_PRIMARYKEY:
|
| + zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break;
|
| + case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
|
| + case SQLITE_CONSTRAINT_COMMITHOOK:
|
| + zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break;
|
| + case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break;
|
| + case SQLITE_CONSTRAINT_FUNCTION:
|
| + zName = "SQLITE_CONSTRAINT_FUNCTION"; break;
|
| + case SQLITE_CONSTRAINT_ROWID: zName = "SQLITE_CONSTRAINT_ROWID"; break;
|
| + case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break;
|
| + case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break;
|
| + case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break;
|
| + case SQLITE_AUTH: zName = "SQLITE_AUTH"; break;
|
| + case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break;
|
| + case SQLITE_RANGE: zName = "SQLITE_RANGE"; break;
|
| + case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break;
|
| + case SQLITE_ROW: zName = "SQLITE_ROW"; break;
|
| + case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break;
|
| + case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
|
| + case SQLITE_NOTICE_RECOVER_ROLLBACK:
|
| + zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
|
| + case SQLITE_WARNING: zName = "SQLITE_WARNING"; break;
|
| + case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break;
|
| + case SQLITE_DONE: zName = "SQLITE_DONE"; break;
|
| + }
|
| + }
|
| + if( zName==0 ){
|
| + static char zBuf[50];
|
| + sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
|
| + zName = zBuf;
|
| + }
|
| + return zName;
|
| +}
|
| +#endif
|
| +
|
| +/*
|
| +** Return a static string that describes the kind of error specified in the
|
| +** argument.
|
| +*/
|
| +SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
|
| + static const char* const aMsg[] = {
|
| + /* SQLITE_OK */ "not an error",
|
| + /* SQLITE_ERROR */ "SQL logic error or missing database",
|
| + /* SQLITE_INTERNAL */ 0,
|
| + /* SQLITE_PERM */ "access permission denied",
|
| + /* SQLITE_ABORT */ "callback requested query abort",
|
| + /* SQLITE_BUSY */ "database is locked",
|
| + /* SQLITE_LOCKED */ "database table is locked",
|
| + /* SQLITE_NOMEM */ "out of memory",
|
| + /* SQLITE_READONLY */ "attempt to write a readonly database",
|
| + /* SQLITE_INTERRUPT */ "interrupted",
|
| + /* SQLITE_IOERR */ "disk I/O error",
|
| + /* SQLITE_CORRUPT */ "database disk image is malformed",
|
| + /* SQLITE_NOTFOUND */ "unknown operation",
|
| + /* SQLITE_FULL */ "database or disk is full",
|
| + /* SQLITE_CANTOPEN */ "unable to open database file",
|
| + /* SQLITE_PROTOCOL */ "locking protocol",
|
| + /* SQLITE_EMPTY */ "table contains no data",
|
| + /* SQLITE_SCHEMA */ "database schema has changed",
|
| + /* SQLITE_TOOBIG */ "string or blob too big",
|
| + /* SQLITE_CONSTRAINT */ "constraint failed",
|
| + /* SQLITE_MISMATCH */ "datatype mismatch",
|
| + /* SQLITE_MISUSE */ "library routine called out of sequence",
|
| + /* SQLITE_NOLFS */ "large file support is disabled",
|
| + /* SQLITE_AUTH */ "authorization denied",
|
| + /* SQLITE_FORMAT */ "auxiliary database format error",
|
| + /* SQLITE_RANGE */ "bind or column index out of range",
|
| + /* SQLITE_NOTADB */ "file is encrypted or is not a database",
|
| + };
|
| + const char *zErr = "unknown error";
|
| + switch( rc ){
|
| + case SQLITE_ABORT_ROLLBACK: {
|
| + zErr = "abort due to ROLLBACK";
|
| + break;
|
| + }
|
| + default: {
|
| + rc &= 0xff;
|
| + if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
|
| + zErr = aMsg[rc];
|
| + }
|
| + break;
|
| + }
|
| + }
|
| + return zErr;
|
| +}
|
| +
|
| +/*
|
| +** This routine implements a busy callback that sleeps and tries
|
| +** again until a timeout value is reached. The timeout value is
|
| +** an integer number of milliseconds passed in as the first
|
| +** argument.
|
| +*/
|
| +static int sqliteDefaultBusyCallback(
|
| + void *ptr, /* Database connection */
|
| + int count /* Number of times table has been busy */
|
| +){
|
| +#if SQLITE_OS_WIN || HAVE_USLEEP
|
| + static const u8 delays[] =
|
| + { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
|
| + static const u8 totals[] =
|
| + { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
|
| +# define NDELAY ArraySize(delays)
|
| + sqlite3 *db = (sqlite3 *)ptr;
|
| + int timeout = db->busyTimeout;
|
| + int delay, prior;
|
| +
|
| + assert( count>=0 );
|
| + if( count < NDELAY ){
|
| + delay = delays[count];
|
| + prior = totals[count];
|
| + }else{
|
| + delay = delays[NDELAY-1];
|
| + prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
|
| + }
|
| + if( prior + delay > timeout ){
|
| + delay = timeout - prior;
|
| + if( delay<=0 ) return 0;
|
| + }
|
| + sqlite3OsSleep(db->pVfs, delay*1000);
|
| + return 1;
|
| +#else
|
| + sqlite3 *db = (sqlite3 *)ptr;
|
| + int timeout = ((sqlite3 *)ptr)->busyTimeout;
|
| + if( (count+1)*1000 > timeout ){
|
| + return 0;
|
| + }
|
| + sqlite3OsSleep(db->pVfs, 1000000);
|
| + return 1;
|
| +#endif
|
| +}
|
| +
|
| +/*
|
| +** Invoke the given busy handler.
|
| +**
|
| +** This routine is called when an operation failed with a lock.
|
| +** If this routine returns non-zero, the lock is retried. If it
|
| +** returns 0, the operation aborts with an SQLITE_BUSY error.
|
| +*/
|
| +SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
|
| + int rc;
|
| + if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
|
| + rc = p->xFunc(p->pArg, p->nBusy);
|
| + if( rc==0 ){
|
| + p->nBusy = -1;
|
| + }else{
|
| + p->nBusy++;
|
| + }
|
| + return rc;
|
| +}
|
| +
|
| +/*
|
| +** This routine sets the busy callback for an Sqlite database to the
|
| +** given callback function with the given argument.
|
| +*/
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_busy_handler(
|
| + sqlite3 *db,
|
| + int (*xBusy)(void*,int),
|
| + void *pArg
|
| +){
|
| +#ifdef SQLITE_ENABLE_API_ARMOR
|
| + if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
|
| +#endif
|
| + sqlite3_mutex_enter(db->mutex);
|
| + db->busyHandler.xFunc = xBusy;
|
| + db->busyHandler.pArg = pArg;
|
| + db->busyHandler.nBusy = 0;
|
| + db->busyTimeout = 0;
|
| + sqlite3_mutex_leave(db->mutex);
|
| + return SQLITE_OK;
|
| +}
|
| +
|
| +#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
|
| +/*
|
| +** This routine sets the progress callback for an Sqlite database to the
|
| +** given callback function with the given argument. The progress callback will
|
| +** be invoked every nOps opcodes.
|
| +*/
|
| +SQLITE_API void SQLITE_STDCALL sqlite3_progress_handler(
|
| + sqlite3 *db,
|
| + int nOps,
|
| + int (*xProgress)(void*),
|
| + void *pArg
|
| +){
|
| +#ifdef SQLITE_ENABLE_API_ARMOR
|
| + if( !sqlite3SafetyCheckOk(db) ){
|
| + (void)SQLITE_MISUSE_BKPT;
|
| + return;
|
| + }
|
| +#endif
|
| + sqlite3_mutex_enter(db->mutex);
|
| + if( nOps>0 ){
|
| + db->xProgress = xProgress;
|
| + db->nProgressOps = (unsigned)nOps;
|
| + db->pProgressArg = pArg;
|
| + }else{
|
| + db->xProgress = 0;
|
| + db->nProgressOps = 0;
|
| + db->pProgressArg = 0;
|
| + }
|
| + sqlite3_mutex_leave(db->mutex);
|
| +}
|
| +#endif
|
| +
|
| +
|
| +/*
|
| +** This routine installs a default busy handler that waits for the
|
| +** specified number of milliseconds before returning 0.
|
| +*/
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_busy_timeout(sqlite3 *db, int ms){
|
| +#ifdef SQLITE_ENABLE_API_ARMOR
|
| + if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
|
| +#endif
|
| + if( ms>0 ){
|
| + sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
|
| + db->busyTimeout = ms;
|
| + }else{
|
| + sqlite3_busy_handler(db, 0, 0);
|
| + }
|
| + return SQLITE_OK;
|
| +}
|
| +
|
| +/*
|
| +** Cause any pending operation to stop at its earliest opportunity.
|
| +*/
|
| +SQLITE_API void SQLITE_STDCALL sqlite3_interrupt(sqlite3 *db){
|
| +#ifdef SQLITE_ENABLE_API_ARMOR
|
| + if( !sqlite3SafetyCheckOk(db) ){
|
| + (void)SQLITE_MISUSE_BKPT;
|
| + return;
|
| + }
|
| +#endif
|
| + db->u1.isInterrupted = 1;
|
| +}
|
| +
|
| +
|
| +/*
|
| +** This function is exactly the same as sqlite3_create_function(), except
|
| +** that it is designed to be called by internal code. The difference is
|
| +** that if a malloc() fails in sqlite3_create_function(), an error code
|
| +** is returned and the mallocFailed flag cleared.
|
| +*/
|
| +SQLITE_PRIVATE int sqlite3CreateFunc(
|
| + sqlite3 *db,
|
| + const char *zFunctionName,
|
| + int nArg,
|
| + int enc,
|
| + void *pUserData,
|
| + void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
|
| + void (*xStep)(sqlite3_context*,int,sqlite3_value **),
|
| + void (*xFinal)(sqlite3_context*),
|
| + FuncDestructor *pDestructor
|
| +){
|
| + FuncDef *p;
|
| + int nName;
|
| + int extraFlags;
|
| +
|
| + assert( sqlite3_mutex_held(db->mutex) );
|
| + if( zFunctionName==0 ||
|
| + (xFunc && (xFinal || xStep)) ||
|
| + (!xFunc && (xFinal && !xStep)) ||
|
| + (!xFunc && (!xFinal && xStep)) ||
|
| + (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
|
| + (255<(nName = sqlite3Strlen30( zFunctionName))) ){
|
| + return SQLITE_MISUSE_BKPT;
|
| + }
|
| +
|
| + assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
|
| + extraFlags = enc & SQLITE_DETERMINISTIC;
|
| + enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
|
| +
|
| +#ifndef SQLITE_OMIT_UTF16
|
| + /* If SQLITE_UTF16 is specified as the encoding type, transform this
|
| + ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
|
| + ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
|
| + **
|
| + ** If SQLITE_ANY is specified, add three versions of the function
|
| + ** to the hash table.
|
| + */
|
| + if( enc==SQLITE_UTF16 ){
|
| + enc = SQLITE_UTF16NATIVE;
|
| + }else if( enc==SQLITE_ANY ){
|
| + int rc;
|
| + rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags,
|
| + pUserData, xFunc, xStep, xFinal, pDestructor);
|
| + if( rc==SQLITE_OK ){
|
| + rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags,
|
| + pUserData, xFunc, xStep, xFinal, pDestructor);
|
| + }
|
| + if( rc!=SQLITE_OK ){
|
| + return rc;
|
| + }
|
| + enc = SQLITE_UTF16BE;
|
| + }
|
| +#else
|
| + enc = SQLITE_UTF8;
|
| +#endif
|
| +
|
| + /* Check if an existing function is being overridden or deleted. If so,
|
| + ** and there are active VMs, then return SQLITE_BUSY. If a function
|
| + ** is being overridden/deleted but there are no active VMs, allow the
|
| + ** operation to continue but invalidate all precompiled statements.
|
| + */
|
| + p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
|
| + if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){
|
| + if( db->nVdbeActive ){
|
| + sqlite3ErrorWithMsg(db, SQLITE_BUSY,
|
| + "unable to delete/modify user-function due to active statements");
|
| + assert( !db->mallocFailed );
|
| + return SQLITE_BUSY;
|
| + }else{
|
| + sqlite3ExpirePreparedStatements(db);
|
| + }
|
| + }
|
| +
|
| + p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
|
| + assert(p || db->mallocFailed);
|
| + if( !p ){
|
| + return SQLITE_NOMEM;
|
| + }
|
| +
|
| + /* If an older version of the function with a configured destructor is
|
| + ** being replaced invoke the destructor function here. */
|
| + functionDestroy(db, p);
|
| +
|
| + if( pDestructor ){
|
| + pDestructor->nRef++;
|
| + }
|
| + p->pDestructor = pDestructor;
|
| + p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
|
| + testcase( p->funcFlags & SQLITE_DETERMINISTIC );
|
| + p->xFunc = xFunc;
|
| + p->xStep = xStep;
|
| + p->xFinalize = xFinal;
|
| + p->pUserData = pUserData;
|
| + p->nArg = (u16)nArg;
|
| + return SQLITE_OK;
|
| +}
|
| +
|
| +/*
|
| +** Create new user functions.
|
| +*/
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_create_function(
|
| + sqlite3 *db,
|
| + const char *zFunc,
|
| + int nArg,
|
| + int enc,
|
| + void *p,
|
| + void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
|
| + void (*xStep)(sqlite3_context*,int,sqlite3_value **),
|
| + void (*xFinal)(sqlite3_context*)
|
| +){
|
| + return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
|
| + xFinal, 0);
|
| +}
|
| +
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_create_function_v2(
|
| + sqlite3 *db,
|
| + const char *zFunc,
|
| + int nArg,
|
| + int enc,
|
| + void *p,
|
| + void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
|
| + void (*xStep)(sqlite3_context*,int,sqlite3_value **),
|
| + void (*xFinal)(sqlite3_context*),
|
| + void (*xDestroy)(void *)
|
| +){
|
| + int rc = SQLITE_ERROR;
|
| + FuncDestructor *pArg = 0;
|
| +
|
| +#ifdef SQLITE_ENABLE_API_ARMOR
|
| + if( !sqlite3SafetyCheckOk(db) ){
|
| + return SQLITE_MISUSE_BKPT;
|
| + }
|
| +#endif
|
| + sqlite3_mutex_enter(db->mutex);
|
| + if( xDestroy ){
|
| + pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
|
| + if( !pArg ){
|
| + xDestroy(p);
|
| + goto out;
|
| + }
|
| + pArg->xDestroy = xDestroy;
|
| + pArg->pUserData = p;
|
| + }
|
| + rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
|
| + if( pArg && pArg->nRef==0 ){
|
| + assert( rc!=SQLITE_OK );
|
| + xDestroy(p);
|
| + sqlite3DbFree(db, pArg);
|
| + }
|
| +
|
| + out:
|
| + rc = sqlite3ApiExit(db, rc);
|
| + sqlite3_mutex_leave(db->mutex);
|
| + return rc;
|
| +}
|
| +
|
| +#ifndef SQLITE_OMIT_UTF16
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_create_function16(
|
| + sqlite3 *db,
|
| + const void *zFunctionName,
|
| + int nArg,
|
| + int eTextRep,
|
| + void *p,
|
| + void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
|
| + void (*xStep)(sqlite3_context*,int,sqlite3_value**),
|
| + void (*xFinal)(sqlite3_context*)
|
| +){
|
| + int rc;
|
| + char *zFunc8;
|
| +
|
| +#ifdef SQLITE_ENABLE_API_ARMOR
|
| + if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;
|
| +#endif
|
| + sqlite3_mutex_enter(db->mutex);
|
| + assert( !db->mallocFailed );
|
| + zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
|
| + rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
|
| + sqlite3DbFree(db, zFunc8);
|
| + rc = sqlite3ApiExit(db, rc);
|
| + sqlite3_mutex_leave(db->mutex);
|
| + return rc;
|
| +}
|
| +#endif
|
| +
|
| +
|
| +/*
|
| +** Declare that a function has been overloaded by a virtual table.
|
| +**
|
| +** If the function already exists as a regular global function, then
|
| +** this routine is a no-op. If the function does not exist, then create
|
| +** a new one that always throws a run-time error.
|
| +**
|
| +** When virtual tables intend to provide an overloaded function, they
|
| +** should call this routine to make sure the global function exists.
|
| +** A global function must exist in order for name resolution to work
|
| +** properly.
|
| +*/
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_overload_function(
|
| + sqlite3 *db,
|
| + const char *zName,
|
| + int nArg
|
| +){
|
| + int nName = sqlite3Strlen30(zName);
|
| + int rc = SQLITE_OK;
|
| +
|
| +#ifdef SQLITE_ENABLE_API_ARMOR
|
| + if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
|
| + return SQLITE_MISUSE_BKPT;
|
| + }
|
| +#endif
|
| + sqlite3_mutex_enter(db->mutex);
|
| + if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
|
| + rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
|
| + 0, sqlite3InvalidFunction, 0, 0, 0);
|
| + }
|
| + rc = sqlite3ApiExit(db, rc);
|
| + sqlite3_mutex_leave(db->mutex);
|
| + return rc;
|
| +}
|
| +
|
| +#ifndef SQLITE_OMIT_TRACE
|
| +/*
|
| +** Register a trace function. The pArg from the previously registered trace
|
| +** is returned.
|
| +**
|
| +** A NULL trace function means that no tracing is executes. A non-NULL
|
| +** trace is a pointer to a function that is invoked at the start of each
|
| +** SQL statement.
|
| +*/
|
| +SQLITE_API void *SQLITE_STDCALL sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
|
| + void *pOld;
|
| +
|
| +#ifdef SQLITE_ENABLE_API_ARMOR
|
| + if( !sqlite3SafetyCheckOk(db) ){
|
| + (void)SQLITE_MISUSE_BKPT;
|
| + return 0;
|
| + }
|
| +#endif
|
| + sqlite3_mutex_enter(db->mutex);
|
| + pOld = db->pTraceArg;
|
| + db->xTrace = xTrace;
|
| + db->pTraceArg = pArg;
|
| + sqlite3_mutex_leave(db->mutex);
|
| + return pOld;
|
| +}
|
| +/*
|
| +** Register a profile function. The pArg from the previously registered
|
| +** profile function is returned.
|
| +**
|
| +** A NULL profile function means that no profiling is executes. A non-NULL
|
| +** profile is a pointer to a function that is invoked at the conclusion of
|
| +** each SQL statement that is run.
|
| +*/
|
| +SQLITE_API void *SQLITE_STDCALL sqlite3_profile(
|
| + sqlite3 *db,
|
| + void (*xProfile)(void*,const char*,sqlite_uint64),
|
| + void *pArg
|
| +){
|
| + void *pOld;
|
| +
|
| +#ifdef SQLITE_ENABLE_API_ARMOR
|
| + if( !sqlite3SafetyCheckOk(db) ){
|
| + (void)SQLITE_MISUSE_BKPT;
|
| + return 0;
|
| + }
|
| +#endif
|
| + sqlite3_mutex_enter(db->mutex);
|
| + pOld = db->pProfileArg;
|
| + db->xProfile = xProfile;
|
| + db->pProfileArg = pArg;
|
| + sqlite3_mutex_leave(db->mutex);
|
| + return pOld;
|
| +}
|
| +#endif /* SQLITE_OMIT_TRACE */
|
| +
|
| +/*
|
| +** Register a function to be invoked when a transaction commits.
|
| +** If the invoked function returns non-zero, then the commit becomes a
|
| +** rollback.
|
| +*/
|
| +SQLITE_API void *SQLITE_STDCALL sqlite3_commit_hook(
|
| + sqlite3 *db, /* Attach the hook to this database */
|
| + int (*xCallback)(void*), /* Function to invoke on each commit */
|
| + void *pArg /* Argument to the function */
|
| +){
|
| + void *pOld;
|
| +
|
| +#ifdef SQLITE_ENABLE_API_ARMOR
|
| + if( !sqlite3SafetyCheckOk(db) ){
|
| + (void)SQLITE_MISUSE_BKPT;
|
| + return 0;
|
| + }
|
| +#endif
|
| + sqlite3_mutex_enter(db->mutex);
|
| + pOld = db->pCommitArg;
|
| + db->xCommitCallback = xCallback;
|
| + db->pCommitArg = pArg;
|
| + sqlite3_mutex_leave(db->mutex);
|
| + return pOld;
|
| +}
|
| +
|
| +/*
|
| +** Register a callback to be invoked each time a row is updated,
|
| +** inserted or deleted using this database connection.
|
| +*/
|
| +SQLITE_API void *SQLITE_STDCALL sqlite3_update_hook(
|
| + sqlite3 *db, /* Attach the hook to this database */
|
| + void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
|
| + void *pArg /* Argument to the function */
|
| +){
|
| + void *pRet;
|
| +
|
| +#ifdef SQLITE_ENABLE_API_ARMOR
|
| + if( !sqlite3SafetyCheckOk(db) ){
|
| + (void)SQLITE_MISUSE_BKPT;
|
| + return 0;
|
| + }
|
| +#endif
|
| + sqlite3_mutex_enter(db->mutex);
|
| + pRet = db->pUpdateArg;
|
| + db->xUpdateCallback = xCallback;
|
| + db->pUpdateArg = pArg;
|
| + sqlite3_mutex_leave(db->mutex);
|
| + return pRet;
|
| +}
|
| +
|
| +/*
|
| +** Register a callback to be invoked each time a transaction is rolled
|
| +** back by this database connection.
|
| +*/
|
| +SQLITE_API void *SQLITE_STDCALL sqlite3_rollback_hook(
|
| + sqlite3 *db, /* Attach the hook to this database */
|
| + void (*xCallback)(void*), /* Callback function */
|
| + void *pArg /* Argument to the function */
|
| +){
|
| + void *pRet;
|
| +
|
| +#ifdef SQLITE_ENABLE_API_ARMOR
|
| + if( !sqlite3SafetyCheckOk(db) ){
|
| + (void)SQLITE_MISUSE_BKPT;
|
| + return 0;
|
| + }
|
| +#endif
|
| + sqlite3_mutex_enter(db->mutex);
|
| + pRet = db->pRollbackArg;
|
| + db->xRollbackCallback = xCallback;
|
| + db->pRollbackArg = pArg;
|
| + sqlite3_mutex_leave(db->mutex);
|
| + return pRet;
|
| +}
|
| +
|
| +#ifndef SQLITE_OMIT_WAL
|
| +/*
|
| +** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
|
| +** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
|
| +** is greater than sqlite3.pWalArg cast to an integer (the value configured by
|
| +** wal_autocheckpoint()).
|
| +*/
|
| +SQLITE_PRIVATE int sqlite3WalDefaultHook(
|
| + void *pClientData, /* Argument */
|
| + sqlite3 *db, /* Connection */
|
| + const char *zDb, /* Database */
|
| + int nFrame /* Size of WAL */
|
| +){
|
| + if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
|
| + sqlite3BeginBenignMalloc();
|
| + sqlite3_wal_checkpoint(db, zDb);
|
| + sqlite3EndBenignMalloc();
|
| + }
|
| + return SQLITE_OK;
|
| +}
|
| +#endif /* SQLITE_OMIT_WAL */
|
| +
|
| +/*
|
| +** Configure an sqlite3_wal_hook() callback to automatically checkpoint
|
| +** a database after committing a transaction if there are nFrame or
|
| +** more frames in the log file. Passing zero or a negative value as the
|
| +** nFrame parameter disables automatic checkpoints entirely.
|
| +**
|
| +** The callback registered by this function replaces any existing callback
|
| +** registered using sqlite3_wal_hook(). Likewise, registering a callback
|
| +** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
|
| +** configured by this function.
|
| +*/
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
|
| +#ifdef SQLITE_OMIT_WAL
|
| + UNUSED_PARAMETER(db);
|
| + UNUSED_PARAMETER(nFrame);
|
| +#else
|
| +#ifdef SQLITE_ENABLE_API_ARMOR
|
| + if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
|
| +#endif
|
| + if( nFrame>0 ){
|
| + sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
|
| + }else{
|
| + sqlite3_wal_hook(db, 0, 0);
|
| + }
|
| +#endif
|
| + return SQLITE_OK;
|
| +}
|
| +
|
| +/*
|
| +** Register a callback to be invoked each time a transaction is written
|
| +** into the write-ahead-log by this database connection.
|
| +*/
|
| +SQLITE_API void *SQLITE_STDCALL sqlite3_wal_hook(
|
| + sqlite3 *db, /* Attach the hook to this db handle */
|
| + int(*xCallback)(void *, sqlite3*, const char*, int),
|
| + void *pArg /* First argument passed to xCallback() */
|
| +){
|
| +#ifndef SQLITE_OMIT_WAL
|
| + void *pRet;
|
| +#ifdef SQLITE_ENABLE_API_ARMOR
|
| + if( !sqlite3SafetyCheckOk(db) ){
|
| + (void)SQLITE_MISUSE_BKPT;
|
| + return 0;
|
| + }
|
| +#endif
|
| + sqlite3_mutex_enter(db->mutex);
|
| + pRet = db->pWalArg;
|
| + db->xWalCallback = xCallback;
|
| + db->pWalArg = pArg;
|
| + sqlite3_mutex_leave(db->mutex);
|
| + return pRet;
|
| +#else
|
| + return 0;
|
| +#endif
|
| +}
|
| +
|
| +/*
|
| +** Checkpoint database zDb.
|
| +*/
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint_v2(
|
| + sqlite3 *db, /* Database handle */
|
| + const char *zDb, /* Name of attached database (or NULL) */
|
| + int eMode, /* SQLITE_CHECKPOINT_* value */
|
| + int *pnLog, /* OUT: Size of WAL log in frames */
|
| + int *pnCkpt /* OUT: Total number of frames checkpointed */
|
| +){
|
| +#ifdef SQLITE_OMIT_WAL
|
| + return SQLITE_OK;
|
| +#else
|
| + int rc; /* Return code */
|
| + int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */
|
| +
|
| +#ifdef SQLITE_ENABLE_API_ARMOR
|
| + if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
|
| +#endif
|
| +
|
| + /* Initialize the output variables to -1 in case an error occurs. */
|
| + if( pnLog ) *pnLog = -1;
|
| + if( pnCkpt ) *pnCkpt = -1;
|
| +
|
| + assert( SQLITE_CHECKPOINT_PASSIVE==0 );
|
| + assert( SQLITE_CHECKPOINT_FULL==1 );
|
| + assert( SQLITE_CHECKPOINT_RESTART==2 );
|
| + assert( SQLITE_CHECKPOINT_TRUNCATE==3 );
|
| + if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){
|
| + /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
|
| + ** mode: */
|
| + return SQLITE_MISUSE;
|
| + }
|
| +
|
| + sqlite3_mutex_enter(db->mutex);
|
| + if( zDb && zDb[0] ){
|
| + iDb = sqlite3FindDbName(db, zDb);
|
| + }
|
| + if( iDb<0 ){
|
| + rc = SQLITE_ERROR;
|
| + sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
|
| + }else{
|
| + db->busyHandler.nBusy = 0;
|
| + rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
|
| + sqlite3Error(db, rc);
|
| + }
|
| + rc = sqlite3ApiExit(db, rc);
|
| + sqlite3_mutex_leave(db->mutex);
|
| + return rc;
|
| +#endif
|
| +}
|
| +
|
| +
|
| +/*
|
| +** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
|
| +** to contains a zero-length string, all attached databases are
|
| +** checkpointed.
|
| +*/
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
|
| + /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
|
| + ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
|
| + return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0);
|
| +}
|
| +
|
| +#ifndef SQLITE_OMIT_WAL
|
| +/*
|
| +** Run a checkpoint on database iDb. This is a no-op if database iDb is
|
| +** not currently open in WAL mode.
|
| +**
|
| +** If a transaction is open on the database being checkpointed, this
|
| +** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
|
| +** an error occurs while running the checkpoint, an SQLite error code is
|
| +** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
|
| +**
|
| +** The mutex on database handle db should be held by the caller. The mutex
|
| +** associated with the specific b-tree being checkpointed is taken by
|
| +** this function while the checkpoint is running.
|
| +**
|
| +** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
|
| +** checkpointed. If an error is encountered it is returned immediately -
|
| +** no attempt is made to checkpoint any remaining databases.
|
| +**
|
| +** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
|
| +*/
|
| +SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
|
| + int rc = SQLITE_OK; /* Return code */
|
| + int i; /* Used to iterate through attached dbs */
|
| + int bBusy = 0; /* True if SQLITE_BUSY has been encountered */
|
| +
|
| + assert( sqlite3_mutex_held(db->mutex) );
|
| + assert( !pnLog || *pnLog==-1 );
|
| + assert( !pnCkpt || *pnCkpt==-1 );
|
| +
|
| + for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
|
| + if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
|
| + rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
|
| + pnLog = 0;
|
| + pnCkpt = 0;
|
| + if( rc==SQLITE_BUSY ){
|
| + bBusy = 1;
|
| + rc = SQLITE_OK;
|
| + }
|
| + }
|
| + }
|
| +
|
| + return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
|
| +}
|
| +#endif /* SQLITE_OMIT_WAL */
|
| +
|
| +/*
|
| +** This function returns true if main-memory should be used instead of
|
| +** a temporary file for transient pager files and statement journals.
|
| +** The value returned depends on the value of db->temp_store (runtime
|
| +** parameter) and the compile time value of SQLITE_TEMP_STORE. The
|
| +** following table describes the relationship between these two values
|
| +** and this functions return value.
|
| +**
|
| +** SQLITE_TEMP_STORE db->temp_store Location of temporary database
|
| +** ----------------- -------------- ------------------------------
|
| +** 0 any file (return 0)
|
| +** 1 1 file (return 0)
|
| +** 1 2 memory (return 1)
|
| +** 1 0 file (return 0)
|
| +** 2 1 file (return 0)
|
| +** 2 2 memory (return 1)
|
| +** 2 0 memory (return 1)
|
| +** 3 any memory (return 1)
|
| +*/
|
| +SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
|
| +#if SQLITE_TEMP_STORE==1
|
| + return ( db->temp_store==2 );
|
| +#endif
|
| +#if SQLITE_TEMP_STORE==2
|
| + return ( db->temp_store!=1 );
|
| +#endif
|
| +#if SQLITE_TEMP_STORE==3
|
| + UNUSED_PARAMETER(db);
|
| + return 1;
|
| +#endif
|
| +#if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
|
| + UNUSED_PARAMETER(db);
|
| + return 0;
|
| +#endif
|
| +}
|
| +
|
| +/*
|
| +** Return UTF-8 encoded English language explanation of the most recent
|
| +** error.
|
| +*/
|
| +SQLITE_API const char *SQLITE_STDCALL sqlite3_errmsg(sqlite3 *db){
|
| + const char *z;
|
| + if( !db ){
|
| + return sqlite3ErrStr(SQLITE_NOMEM);
|
| + }
|
| + if( !sqlite3SafetyCheckSickOrOk(db) ){
|
| + return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
|
| + }
|
| + sqlite3_mutex_enter(db->mutex);
|
| + if( db->mallocFailed ){
|
| + z = sqlite3ErrStr(SQLITE_NOMEM);
|
| + }else{
|
| + testcase( db->pErr==0 );
|
| + z = (char*)sqlite3_value_text(db->pErr);
|
| + assert( !db->mallocFailed );
|
| + if( z==0 ){
|
| + z = sqlite3ErrStr(db->errCode);
|
| + }
|
| + }
|
| + sqlite3_mutex_leave(db->mutex);
|
| + return z;
|
| +}
|
| +
|
| +#ifndef SQLITE_OMIT_UTF16
|
| +/*
|
| +** Return UTF-16 encoded English language explanation of the most recent
|
| +** error.
|
| +*/
|
| +SQLITE_API const void *SQLITE_STDCALL sqlite3_errmsg16(sqlite3 *db){
|
| + static const u16 outOfMem[] = {
|
| + 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
|
| + };
|
| + static const u16 misuse[] = {
|
| + 'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
|
| + 'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
|
| + 'c', 'a', 'l', 'l', 'e', 'd', ' ',
|
| + 'o', 'u', 't', ' ',
|
| + 'o', 'f', ' ',
|
| + 's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
|
| + };
|
| +
|
| + const void *z;
|
| + if( !db ){
|
| + return (void *)outOfMem;
|
| + }
|
| + if( !sqlite3SafetyCheckSickOrOk(db) ){
|
| + return (void *)misuse;
|
| + }
|
| + sqlite3_mutex_enter(db->mutex);
|
| + if( db->mallocFailed ){
|
| + z = (void *)outOfMem;
|
| + }else{
|
| + z = sqlite3_value_text16(db->pErr);
|
| + if( z==0 ){
|
| + sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
|
| + z = sqlite3_value_text16(db->pErr);
|
| + }
|
| + /* A malloc() may have failed within the call to sqlite3_value_text16()
|
| + ** above. If this is the case, then the db->mallocFailed flag needs to
|
| + ** be cleared before returning. Do this directly, instead of via
|
| + ** sqlite3ApiExit(), to avoid setting the database handle error message.
|
| + */
|
| + db->mallocFailed = 0;
|
| + }
|
| + sqlite3_mutex_leave(db->mutex);
|
| + return z;
|
| +}
|
| +#endif /* SQLITE_OMIT_UTF16 */
|
| +
|
| +/*
|
| +** Return the most recent error code generated by an SQLite routine. If NULL is
|
| +** passed to this function, we assume a malloc() failed during sqlite3_open().
|
| +*/
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_errcode(sqlite3 *db){
|
| + if( db && !sqlite3SafetyCheckSickOrOk(db) ){
|
| + return SQLITE_MISUSE_BKPT;
|
| + }
|
| + if( !db || db->mallocFailed ){
|
| + return SQLITE_NOMEM;
|
| + }
|
| + return db->errCode & db->errMask;
|
| +}
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_extended_errcode(sqlite3 *db){
|
| + if( db && !sqlite3SafetyCheckSickOrOk(db) ){
|
| + return SQLITE_MISUSE_BKPT;
|
| + }
|
| + if( !db || db->mallocFailed ){
|
| + return SQLITE_NOMEM;
|
| + }
|
| + return db->errCode;
|
| +}
|
| +
|
| +/*
|
| +** Return a string that describes the kind of error specified in the
|
| +** argument. For now, this simply calls the internal sqlite3ErrStr()
|
| +** function.
|
| +*/
|
| +SQLITE_API const char *SQLITE_STDCALL sqlite3_errstr(int rc){
|
| + return sqlite3ErrStr(rc);
|
| +}
|
| +
|
| +/*
|
| +** Create a new collating function for database "db". The name is zName
|
| +** and the encoding is enc.
|
| +*/
|
| +static int createCollation(
|
| + sqlite3* db,
|
| + const char *zName,
|
| + u8 enc,
|
| + void* pCtx,
|
| + int(*xCompare)(void*,int,const void*,int,const void*),
|
| + void(*xDel)(void*)
|
| +){
|
| + CollSeq *pColl;
|
| + int enc2;
|
| +
|
| + assert( sqlite3_mutex_held(db->mutex) );
|
| +
|
| + /* If SQLITE_UTF16 is specified as the encoding type, transform this
|
| + ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
|
| + ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
|
| + */
|
| + enc2 = enc;
|
| + testcase( enc2==SQLITE_UTF16 );
|
| + testcase( enc2==SQLITE_UTF16_ALIGNED );
|
| + if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
|
| + enc2 = SQLITE_UTF16NATIVE;
|
| + }
|
| + if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
|
| + return SQLITE_MISUSE_BKPT;
|
| + }
|
| +
|
| + /* Check if this call is removing or replacing an existing collation
|
| + ** sequence. If so, and there are active VMs, return busy. If there
|
| + ** are no active VMs, invalidate any pre-compiled statements.
|
| + */
|
| + pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
|
| + if( pColl && pColl->xCmp ){
|
| + if( db->nVdbeActive ){
|
| + sqlite3ErrorWithMsg(db, SQLITE_BUSY,
|
| + "unable to delete/modify collation sequence due to active statements");
|
| + return SQLITE_BUSY;
|
| + }
|
| + sqlite3ExpirePreparedStatements(db);
|
| +
|
| + /* If collation sequence pColl was created directly by a call to
|
| + ** sqlite3_create_collation, and not generated by synthCollSeq(),
|
| + ** then any copies made by synthCollSeq() need to be invalidated.
|
| + ** Also, collation destructor - CollSeq.xDel() - function may need
|
| + ** to be called.
|
| + */
|
| + if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
|
| + CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
|
| + int j;
|
| + for(j=0; j<3; j++){
|
| + CollSeq *p = &aColl[j];
|
| + if( p->enc==pColl->enc ){
|
| + if( p->xDel ){
|
| + p->xDel(p->pUser);
|
| + }
|
| + p->xCmp = 0;
|
| + }
|
| + }
|
| + }
|
| + }
|
| +
|
| + pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
|
| + if( pColl==0 ) return SQLITE_NOMEM;
|
| + pColl->xCmp = xCompare;
|
| + pColl->pUser = pCtx;
|
| + pColl->xDel = xDel;
|
| + pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
|
| + sqlite3Error(db, SQLITE_OK);
|
| + return SQLITE_OK;
|
| +}
|
| +
|
| +
|
| +/*
|
| +** This array defines hard upper bounds on limit values. The
|
| +** initializer must be kept in sync with the SQLITE_LIMIT_*
|
| +** #defines in sqlite3.h.
|
| +*/
|
| +static const int aHardLimit[] = {
|
| + SQLITE_MAX_LENGTH,
|
| + SQLITE_MAX_SQL_LENGTH,
|
| + SQLITE_MAX_COLUMN,
|
| + SQLITE_MAX_EXPR_DEPTH,
|
| + SQLITE_MAX_COMPOUND_SELECT,
|
| + SQLITE_MAX_VDBE_OP,
|
| + SQLITE_MAX_FUNCTION_ARG,
|
| + SQLITE_MAX_ATTACHED,
|
| + SQLITE_MAX_LIKE_PATTERN_LENGTH,
|
| + SQLITE_MAX_VARIABLE_NUMBER, /* IMP: R-38091-32352 */
|
| + SQLITE_MAX_TRIGGER_DEPTH,
|
| + SQLITE_MAX_WORKER_THREADS,
|
| +};
|
| +
|
| +/*
|
| +** Make sure the hard limits are set to reasonable values
|
| +*/
|
| +#if SQLITE_MAX_LENGTH<100
|
| +# error SQLITE_MAX_LENGTH must be at least 100
|
| +#endif
|
| +#if SQLITE_MAX_SQL_LENGTH<100
|
| +# error SQLITE_MAX_SQL_LENGTH must be at least 100
|
| +#endif
|
| +#if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
|
| +# error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
|
| +#endif
|
| +#if SQLITE_MAX_COMPOUND_SELECT<2
|
| +# error SQLITE_MAX_COMPOUND_SELECT must be at least 2
|
| +#endif
|
| +#if SQLITE_MAX_VDBE_OP<40
|
| +# error SQLITE_MAX_VDBE_OP must be at least 40
|
| +#endif
|
| +#if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
|
| +# error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
|
| +#endif
|
| +#if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
|
| +# error SQLITE_MAX_ATTACHED must be between 0 and 125
|
| +#endif
|
| +#if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
|
| +# error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
|
| +#endif
|
| +#if SQLITE_MAX_COLUMN>32767
|
| +# error SQLITE_MAX_COLUMN must not exceed 32767
|
| +#endif
|
| +#if SQLITE_MAX_TRIGGER_DEPTH<1
|
| +# error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
|
| +#endif
|
| +#if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
|
| +# error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
|
| +#endif
|
| +
|
| +
|
| +/*
|
| +** Change the value of a limit. Report the old value.
|
| +** If an invalid limit index is supplied, report -1.
|
| +** Make no changes but still report the old value if the
|
| +** new limit is negative.
|
| +**
|
| +** A new lower limit does not shrink existing constructs.
|
| +** It merely prevents new constructs that exceed the limit
|
| +** from forming.
|
| +*/
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
|
| + int oldLimit;
|
| +
|
| +#ifdef SQLITE_ENABLE_API_ARMOR
|
| + if( !sqlite3SafetyCheckOk(db) ){
|
| + (void)SQLITE_MISUSE_BKPT;
|
| + return -1;
|
| + }
|
| +#endif
|
| +
|
| + /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
|
| + ** there is a hard upper bound set at compile-time by a C preprocessor
|
| + ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
|
| + ** "_MAX_".)
|
| + */
|
| + assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
|
| + assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
|
| + assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
|
| + assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
|
| + assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
|
| + assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
|
| + assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
|
| + assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
|
| + assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
|
| + SQLITE_MAX_LIKE_PATTERN_LENGTH );
|
| + assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
|
| + assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
|
| + assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
|
| + assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
|
| +
|
| +
|
| + if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
|
| + return -1;
|
| + }
|
| + oldLimit = db->aLimit[limitId];
|
| + if( newLimit>=0 ){ /* IMP: R-52476-28732 */
|
| + if( newLimit>aHardLimit[limitId] ){
|
| + newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
|
| + }
|
| + db->aLimit[limitId] = newLimit;
|
| + }
|
| + return oldLimit; /* IMP: R-53341-35419 */
|
| +}
|
| +
|
| +/*
|
| +** This function is used to parse both URIs and non-URI filenames passed by the
|
| +** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
|
| +** URIs specified as part of ATTACH statements.
|
| +**
|
| +** The first argument to this function is the name of the VFS to use (or
|
| +** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
|
| +** query parameter. The second argument contains the URI (or non-URI filename)
|
| +** itself. When this function is called the *pFlags variable should contain
|
| +** the default flags to open the database handle with. The value stored in
|
| +** *pFlags may be updated before returning if the URI filename contains
|
| +** "cache=xxx" or "mode=xxx" query parameters.
|
| +**
|
| +** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
|
| +** the VFS that should be used to open the database file. *pzFile is set to
|
| +** point to a buffer containing the name of the file to open. It is the
|
| +** responsibility of the caller to eventually call sqlite3_free() to release
|
| +** this buffer.
|
| +**
|
| +** If an error occurs, then an SQLite error code is returned and *pzErrMsg
|
| +** may be set to point to a buffer containing an English language error
|
| +** message. It is the responsibility of the caller to eventually release
|
| +** this buffer by calling sqlite3_free().
|
| +*/
|
| +SQLITE_PRIVATE int sqlite3ParseUri(
|
| + const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */
|
| + const char *zUri, /* Nul-terminated URI to parse */
|
| + unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */
|
| + sqlite3_vfs **ppVfs, /* OUT: VFS to use */
|
| + char **pzFile, /* OUT: Filename component of URI */
|
| + char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */
|
| +){
|
| + int rc = SQLITE_OK;
|
| + unsigned int flags = *pFlags;
|
| + const char *zVfs = zDefaultVfs;
|
| + char *zFile;
|
| + char c;
|
| + int nUri = sqlite3Strlen30(zUri);
|
| +
|
| + assert( *pzErrMsg==0 );
|
| +
|
| + if( ((flags & SQLITE_OPEN_URI) /* IMP: R-48725-32206 */
|
| + || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */
|
| + && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
|
| + ){
|
| + char *zOpt;
|
| + int eState; /* Parser state when parsing URI */
|
| + int iIn; /* Input character index */
|
| + int iOut = 0; /* Output character index */
|
| + u64 nByte = nUri+2; /* Bytes of space to allocate */
|
| +
|
| + /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
|
| + ** method that there may be extra parameters following the file-name. */
|
| + flags |= SQLITE_OPEN_URI;
|
| +
|
| + for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
|
| + zFile = sqlite3_malloc64(nByte);
|
| + if( !zFile ) return SQLITE_NOMEM;
|
| +
|
| + iIn = 5;
|
| +#ifdef SQLITE_ALLOW_URI_AUTHORITY
|
| + if( strncmp(zUri+5, "///", 3)==0 ){
|
| + iIn = 7;
|
| + /* The following condition causes URIs with five leading / characters
|
| + ** like file://///host/path to be converted into UNCs like //host/path.
|
| + ** The correct URI for that UNC has only two or four leading / characters
|
| + ** file://host/path or file:////host/path. But 5 leading slashes is a
|
| + ** common error, we are told, so we handle it as a special case. */
|
| + if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; }
|
| + }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){
|
| + iIn = 16;
|
| + }
|
| +#else
|
| + /* Discard the scheme and authority segments of the URI. */
|
| + if( zUri[5]=='/' && zUri[6]=='/' ){
|
| + iIn = 7;
|
| + while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
|
| + if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
|
| + *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
|
| + iIn-7, &zUri[7]);
|
| + rc = SQLITE_ERROR;
|
| + goto parse_uri_out;
|
| + }
|
| + }
|
| +#endif
|
| +
|
| + /* Copy the filename and any query parameters into the zFile buffer.
|
| + ** Decode %HH escape codes along the way.
|
| + **
|
| + ** Within this loop, variable eState may be set to 0, 1 or 2, depending
|
| + ** on the parsing context. As follows:
|
| + **
|
| + ** 0: Parsing file-name.
|
| + ** 1: Parsing name section of a name=value query parameter.
|
| + ** 2: Parsing value section of a name=value query parameter.
|
| + */
|
| + eState = 0;
|
| + while( (c = zUri[iIn])!=0 && c!='#' ){
|
| + iIn++;
|
| + if( c=='%'
|
| + && sqlite3Isxdigit(zUri[iIn])
|
| + && sqlite3Isxdigit(zUri[iIn+1])
|
| + ){
|
| + int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
|
| + octet += sqlite3HexToInt(zUri[iIn++]);
|
| +
|
| + assert( octet>=0 && octet<256 );
|
| + if( octet==0 ){
|
| + /* This branch is taken when "%00" appears within the URI. In this
|
| + ** case we ignore all text in the remainder of the path, name or
|
| + ** value currently being parsed. So ignore the current character
|
| + ** and skip to the next "?", "=" or "&", as appropriate. */
|
| + while( (c = zUri[iIn])!=0 && c!='#'
|
| + && (eState!=0 || c!='?')
|
| + && (eState!=1 || (c!='=' && c!='&'))
|
| + && (eState!=2 || c!='&')
|
| + ){
|
| + iIn++;
|
| + }
|
| + continue;
|
| + }
|
| + c = octet;
|
| + }else if( eState==1 && (c=='&' || c=='=') ){
|
| + if( zFile[iOut-1]==0 ){
|
| + /* An empty option name. Ignore this option altogether. */
|
| + while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
|
| + continue;
|
| + }
|
| + if( c=='&' ){
|
| + zFile[iOut++] = '\0';
|
| + }else{
|
| + eState = 2;
|
| + }
|
| + c = 0;
|
| + }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
|
| + c = 0;
|
| + eState = 1;
|
| + }
|
| + zFile[iOut++] = c;
|
| + }
|
| + if( eState==1 ) zFile[iOut++] = '\0';
|
| + zFile[iOut++] = '\0';
|
| + zFile[iOut++] = '\0';
|
| +
|
| + /* Check if there were any options specified that should be interpreted
|
| + ** here. Options that are interpreted here include "vfs" and those that
|
| + ** correspond to flags that may be passed to the sqlite3_open_v2()
|
| + ** method. */
|
| + zOpt = &zFile[sqlite3Strlen30(zFile)+1];
|
| + while( zOpt[0] ){
|
| + int nOpt = sqlite3Strlen30(zOpt);
|
| + char *zVal = &zOpt[nOpt+1];
|
| + int nVal = sqlite3Strlen30(zVal);
|
| +
|
| + if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
|
| + zVfs = zVal;
|
| + }else{
|
| + struct OpenMode {
|
| + const char *z;
|
| + int mode;
|
| + } *aMode = 0;
|
| + char *zModeType = 0;
|
| + int mask = 0;
|
| + int limit = 0;
|
| +
|
| + if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
|
| + static struct OpenMode aCacheMode[] = {
|
| + { "shared", SQLITE_OPEN_SHAREDCACHE },
|
| + { "private", SQLITE_OPEN_PRIVATECACHE },
|
| + { 0, 0 }
|
| + };
|
| +
|
| + mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
|
| + aMode = aCacheMode;
|
| + limit = mask;
|
| + zModeType = "cache";
|
| + }
|
| + if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
|
| + static struct OpenMode aOpenMode[] = {
|
| + { "ro", SQLITE_OPEN_READONLY },
|
| + { "rw", SQLITE_OPEN_READWRITE },
|
| + { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
|
| + { "memory", SQLITE_OPEN_MEMORY },
|
| + { 0, 0 }
|
| + };
|
| +
|
| + mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
|
| + | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
|
| + aMode = aOpenMode;
|
| + limit = mask & flags;
|
| + zModeType = "access";
|
| + }
|
| +
|
| + if( aMode ){
|
| + int i;
|
| + int mode = 0;
|
| + for(i=0; aMode[i].z; i++){
|
| + const char *z = aMode[i].z;
|
| + if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
|
| + mode = aMode[i].mode;
|
| + break;
|
| + }
|
| + }
|
| + if( mode==0 ){
|
| + *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
|
| + rc = SQLITE_ERROR;
|
| + goto parse_uri_out;
|
| + }
|
| + if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
|
| + *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
|
| + zModeType, zVal);
|
| + rc = SQLITE_PERM;
|
| + goto parse_uri_out;
|
| + }
|
| + flags = (flags & ~mask) | mode;
|
| + }
|
| + }
|
| +
|
| + zOpt = &zVal[nVal+1];
|
| + }
|
| +
|
| + }else{
|
| + zFile = sqlite3_malloc64(nUri+2);
|
| + if( !zFile ) return SQLITE_NOMEM;
|
| + memcpy(zFile, zUri, nUri);
|
| + zFile[nUri] = '\0';
|
| + zFile[nUri+1] = '\0';
|
| + flags &= ~SQLITE_OPEN_URI;
|
| + }
|
| +
|
| + *ppVfs = sqlite3_vfs_find(zVfs);
|
| + if( *ppVfs==0 ){
|
| + *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
|
| + rc = SQLITE_ERROR;
|
| + }
|
| + parse_uri_out:
|
| + if( rc!=SQLITE_OK ){
|
| + sqlite3_free(zFile);
|
| + zFile = 0;
|
| + }
|
| + *pFlags = flags;
|
| + *pzFile = zFile;
|
| + return rc;
|
| +}
|
| +
|
| +
|
| +/*
|
| +** This routine does the work of opening a database on behalf of
|
| +** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
|
| +** is UTF-8 encoded.
|
| +*/
|
| +static int openDatabase(
|
| + const char *zFilename, /* Database filename UTF-8 encoded */
|
| + sqlite3 **ppDb, /* OUT: Returned database handle */
|
| + unsigned int flags, /* Operational flags */
|
| + const char *zVfs /* Name of the VFS to use */
|
| +){
|
| + sqlite3 *db; /* Store allocated handle here */
|
| + int rc; /* Return code */
|
| + int isThreadsafe; /* True for threadsafe connections */
|
| + char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */
|
| + char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */
|
| +
|
| +#ifdef SQLITE_ENABLE_API_ARMOR
|
| + if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
|
| +#endif
|
| + *ppDb = 0;
|
| +#ifndef SQLITE_OMIT_AUTOINIT
|
| + rc = sqlite3_initialize();
|
| + if( rc ) return rc;
|
| +#endif
|
| +
|
| + /* Only allow sensible combinations of bits in the flags argument.
|
| + ** Throw an error if any non-sense combination is used. If we
|
| + ** do not block illegal combinations here, it could trigger
|
| + ** assert() statements in deeper layers. Sensible combinations
|
| + ** are:
|
| + **
|
| + ** 1: SQLITE_OPEN_READONLY
|
| + ** 2: SQLITE_OPEN_READWRITE
|
| + ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
|
| + */
|
| + assert( SQLITE_OPEN_READONLY == 0x01 );
|
| + assert( SQLITE_OPEN_READWRITE == 0x02 );
|
| + assert( SQLITE_OPEN_CREATE == 0x04 );
|
| + testcase( (1<<(flags&7))==0x02 ); /* READONLY */
|
| + testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
|
| + testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
|
| + if( ((1<<(flags&7)) & 0x46)==0 ){
|
| + return SQLITE_MISUSE_BKPT; /* IMP: R-65497-44594 */
|
| + }
|
| +
|
| + if( sqlite3GlobalConfig.bCoreMutex==0 ){
|
| + isThreadsafe = 0;
|
| + }else if( flags & SQLITE_OPEN_NOMUTEX ){
|
| + isThreadsafe = 0;
|
| + }else if( flags & SQLITE_OPEN_FULLMUTEX ){
|
| + isThreadsafe = 1;
|
| + }else{
|
| + isThreadsafe = sqlite3GlobalConfig.bFullMutex;
|
| + }
|
| + if( flags & SQLITE_OPEN_PRIVATECACHE ){
|
| + flags &= ~SQLITE_OPEN_SHAREDCACHE;
|
| + }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
|
| + flags |= SQLITE_OPEN_SHAREDCACHE;
|
| + }
|
| +
|
| + /* Remove harmful bits from the flags parameter
|
| + **
|
| + ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
|
| + ** dealt with in the previous code block. Besides these, the only
|
| + ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
|
| + ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
|
| + ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask
|
| + ** off all other flags.
|
| + */
|
| + flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
|
| + SQLITE_OPEN_EXCLUSIVE |
|
| + SQLITE_OPEN_MAIN_DB |
|
| + SQLITE_OPEN_TEMP_DB |
|
| + SQLITE_OPEN_TRANSIENT_DB |
|
| + SQLITE_OPEN_MAIN_JOURNAL |
|
| + SQLITE_OPEN_TEMP_JOURNAL |
|
| + SQLITE_OPEN_SUBJOURNAL |
|
| + SQLITE_OPEN_MASTER_JOURNAL |
|
| + SQLITE_OPEN_NOMUTEX |
|
| + SQLITE_OPEN_FULLMUTEX |
|
| + SQLITE_OPEN_WAL
|
| + );
|
| +
|
| + /* Allocate the sqlite data structure */
|
| + db = sqlite3MallocZero( sizeof(sqlite3) );
|
| + if( db==0 ) goto opendb_out;
|
| + if( isThreadsafe ){
|
| + db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
|
| + if( db->mutex==0 ){
|
| + sqlite3_free(db);
|
| + db = 0;
|
| + goto opendb_out;
|
| + }
|
| + }
|
| + sqlite3_mutex_enter(db->mutex);
|
| + db->errMask = 0xff;
|
| + db->nDb = 2;
|
| + db->magic = SQLITE_MAGIC_BUSY;
|
| + db->aDb = db->aDbStatic;
|
| +
|
| + assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
|
| + memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
|
| + db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
|
| + db->autoCommit = 1;
|
| + db->nextAutovac = -1;
|
| + db->szMmap = sqlite3GlobalConfig.szMmap;
|
| + db->nextPagesize = 0;
|
| + db->nMaxSorterMmap = 0x7FFFFFFF;
|
| + db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
|
| +#if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
|
| + | SQLITE_AutoIndex
|
| +#endif
|
| +#if SQLITE_DEFAULT_CKPTFULLFSYNC
|
| + | SQLITE_CkptFullFSync
|
| +#endif
|
| +#if SQLITE_DEFAULT_FILE_FORMAT<4
|
| + | SQLITE_LegacyFileFmt
|
| +#endif
|
| +#ifdef SQLITE_ENABLE_LOAD_EXTENSION
|
| + | SQLITE_LoadExtension
|
| +#endif
|
| +#if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
|
| + | SQLITE_RecTriggers
|
| +#endif
|
| +#if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
|
| + | SQLITE_ForeignKeys
|
| +#endif
|
| +#if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
|
| + | SQLITE_ReverseOrder
|
| +#endif
|
| +#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
|
| + | SQLITE_CellSizeCk
|
| +#endif
|
| + ;
|
| + sqlite3HashInit(&db->aCollSeq);
|
| +#ifndef SQLITE_OMIT_VIRTUALTABLE
|
| + sqlite3HashInit(&db->aModule);
|
| +#endif
|
| +
|
| + /* Add the default collation sequence BINARY. BINARY works for both UTF-8
|
| + ** and UTF-16, so add a version for each to avoid any unnecessary
|
| + ** conversions. The only error that can occur here is a malloc() failure.
|
| + **
|
| + ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
|
| + ** functions:
|
| + */
|
| + createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0);
|
| + createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0);
|
| + createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0);
|
| + createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
|
| + createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
|
| + if( db->mallocFailed ){
|
| + goto opendb_out;
|
| + }
|
| + /* EVIDENCE-OF: R-08308-17224 The default collating function for all
|
| + ** strings is BINARY.
|
| + */
|
| + db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, sqlite3StrBINARY, 0);
|
| + assert( db->pDfltColl!=0 );
|
| +
|
| + /* Parse the filename/URI argument. */
|
| + db->openFlags = flags;
|
| + rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
|
| + if( rc!=SQLITE_OK ){
|
| + if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
|
| + sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
|
| + sqlite3_free(zErrMsg);
|
| + goto opendb_out;
|
| + }
|
| +
|
| + /* Open the backend database driver */
|
| + rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
|
| + flags | SQLITE_OPEN_MAIN_DB);
|
| + if( rc!=SQLITE_OK ){
|
| + if( rc==SQLITE_IOERR_NOMEM ){
|
| + rc = SQLITE_NOMEM;
|
| + }
|
| + sqlite3Error(db, rc);
|
| + goto opendb_out;
|
| + }
|
| + sqlite3BtreeEnter(db->aDb[0].pBt);
|
| + db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
|
| + if( !db->mallocFailed ) ENC(db) = SCHEMA_ENC(db);
|
| + sqlite3BtreeLeave(db->aDb[0].pBt);
|
| + db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
|
| +
|
| + /* The default safety_level for the main database is 'full'; for the temp
|
| + ** database it is 'NONE'. This matches the pager layer defaults.
|
| + */
|
| + db->aDb[0].zName = "main";
|
| + db->aDb[0].safety_level = 3;
|
| + db->aDb[1].zName = "temp";
|
| + db->aDb[1].safety_level = 1;
|
| +
|
| + db->magic = SQLITE_MAGIC_OPEN;
|
| + if( db->mallocFailed ){
|
| + goto opendb_out;
|
| + }
|
| +
|
| + /* Register all built-in functions, but do not attempt to read the
|
| + ** database schema yet. This is delayed until the first time the database
|
| + ** is accessed.
|
| + */
|
| + sqlite3Error(db, SQLITE_OK);
|
| + sqlite3RegisterBuiltinFunctions(db);
|
| +
|
| + /* Load automatic extensions - extensions that have been registered
|
| + ** using the sqlite3_automatic_extension() API.
|
| + */
|
| + rc = sqlite3_errcode(db);
|
| + if( rc==SQLITE_OK ){
|
| + sqlite3AutoLoadExtensions(db);
|
| + rc = sqlite3_errcode(db);
|
| + if( rc!=SQLITE_OK ){
|
| + goto opendb_out;
|
| + }
|
| + }
|
| +
|
| +#ifdef SQLITE_ENABLE_FTS1
|
| + if( !db->mallocFailed ){
|
| + extern int sqlite3Fts1Init(sqlite3*);
|
| + rc = sqlite3Fts1Init(db);
|
| + }
|
| +#endif
|
| +
|
| +#ifdef SQLITE_ENABLE_FTS2
|
| + if( !db->mallocFailed && rc==SQLITE_OK ){
|
| + extern int sqlite3Fts2Init(sqlite3*);
|
| + rc = sqlite3Fts2Init(db);
|
| + }
|
| +#endif
|
| +
|
| +#ifdef SQLITE_ENABLE_FTS3 /* automatically defined by SQLITE_ENABLE_FTS4 */
|
| + if( !db->mallocFailed && rc==SQLITE_OK ){
|
| + rc = sqlite3Fts3Init(db);
|
| + }
|
| +#endif
|
| +
|
| +#ifdef SQLITE_ENABLE_FTS5
|
| + if( !db->mallocFailed && rc==SQLITE_OK ){
|
| + rc = sqlite3Fts5Init(db);
|
| + }
|
| +#endif
|
| +
|
| +#ifdef DEFAULT_ENABLE_RECOVER
|
| + /* Initialize recover virtual table for testing. */
|
| + extern int recoverVtableInit(sqlite3 *db);
|
| + if( !db->mallocFailed && rc==SQLITE_OK ){
|
| + rc = recoverVtableInit(db);
|
| + }
|
| +#endif
|
| +
|
| +#ifdef SQLITE_ENABLE_ICU
|
| + if( !db->mallocFailed && rc==SQLITE_OK ){
|
| + rc = sqlite3IcuInit(db);
|
| + }
|
| +#endif
|
| +
|
| +#ifdef SQLITE_ENABLE_RTREE
|
| + if( !db->mallocFailed && rc==SQLITE_OK){
|
| + rc = sqlite3RtreeInit(db);
|
| + }
|
| +#endif
|
| +
|
| +#ifdef SQLITE_ENABLE_DBSTAT_VTAB
|
| + if( !db->mallocFailed && rc==SQLITE_OK){
|
| + rc = sqlite3DbstatRegister(db);
|
| + }
|
| +#endif
|
| +
|
| +#ifdef SQLITE_ENABLE_JSON1
|
| + if( !db->mallocFailed && rc==SQLITE_OK){
|
| + rc = sqlite3Json1Init(db);
|
| + }
|
| +#endif
|
| +
|
| + /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
|
| + ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
|
| + ** mode. Doing nothing at all also makes NORMAL the default.
|
| + */
|
| +#ifdef SQLITE_DEFAULT_LOCKING_MODE
|
| + db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
|
| + sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
|
| + SQLITE_DEFAULT_LOCKING_MODE);
|
| +#endif
|
| +
|
| + if( rc ) sqlite3Error(db, rc);
|
| +
|
| + /* Enable the lookaside-malloc subsystem */
|
| + setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
|
| + sqlite3GlobalConfig.nLookaside);
|
| +
|
| + sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
|
| +
|
| +opendb_out:
|
| + if( db ){
|
| + assert( db->mutex!=0 || isThreadsafe==0
|
| + || sqlite3GlobalConfig.bFullMutex==0 );
|
| + sqlite3_mutex_leave(db->mutex);
|
| + }
|
| + rc = sqlite3_errcode(db);
|
| + assert( db!=0 || rc==SQLITE_NOMEM );
|
| + if( rc==SQLITE_NOMEM ){
|
| + sqlite3_close(db);
|
| + db = 0;
|
| + }else if( rc!=SQLITE_OK ){
|
| + db->magic = SQLITE_MAGIC_SICK;
|
| + }
|
| + *ppDb = db;
|
| +#ifdef SQLITE_ENABLE_SQLLOG
|
| + if( sqlite3GlobalConfig.xSqllog ){
|
| + /* Opening a db handle. Fourth parameter is passed 0. */
|
| + void *pArg = sqlite3GlobalConfig.pSqllogArg;
|
| + sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
|
| + }
|
| +#endif
|
| +#if defined(SQLITE_HAS_CODEC)
|
| + if( rc==SQLITE_OK ){
|
| + const char *zHexKey = sqlite3_uri_parameter(zOpen, "hexkey");
|
| + if( zHexKey && zHexKey[0] ){
|
| + u8 iByte;
|
| + int i;
|
| + char zKey[40];
|
| + for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zHexKey[i]); i++){
|
| + iByte = (iByte<<4) + sqlite3HexToInt(zHexKey[i]);
|
| + if( (i&1)!=0 ) zKey[i/2] = iByte;
|
| + }
|
| + sqlite3_key_v2(db, 0, zKey, i/2);
|
| + }
|
| + }
|
| +#endif
|
| + sqlite3_free(zOpen);
|
| + return rc & 0xff;
|
| +}
|
| +
|
| +/*
|
| +** Open a new database handle.
|
| +*/
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_open(
|
| + const char *zFilename,
|
| + sqlite3 **ppDb
|
| +){
|
| + return openDatabase(zFilename, ppDb,
|
| + SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
|
| +}
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_open_v2(
|
| + const char *filename, /* Database filename (UTF-8) */
|
| + sqlite3 **ppDb, /* OUT: SQLite db handle */
|
| + int flags, /* Flags */
|
| + const char *zVfs /* Name of VFS module to use */
|
| +){
|
| + return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
|
| +}
|
| +
|
| +#ifndef SQLITE_OMIT_UTF16
|
| +/*
|
| +** Open a new database handle.
|
| +*/
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_open16(
|
| + const void *zFilename,
|
| + sqlite3 **ppDb
|
| +){
|
| + char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
|
| + sqlite3_value *pVal;
|
| + int rc;
|
| +
|
| +#ifdef SQLITE_ENABLE_API_ARMOR
|
| + if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
|
| +#endif
|
| + *ppDb = 0;
|
| +#ifndef SQLITE_OMIT_AUTOINIT
|
| + rc = sqlite3_initialize();
|
| + if( rc ) return rc;
|
| +#endif
|
| + if( zFilename==0 ) zFilename = "\000\000";
|
| + pVal = sqlite3ValueNew(0);
|
| + sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
|
| + zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
|
| + if( zFilename8 ){
|
| + rc = openDatabase(zFilename8, ppDb,
|
| + SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
|
| + assert( *ppDb || rc==SQLITE_NOMEM );
|
| + if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
|
| + SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
|
| + }
|
| + }else{
|
| + rc = SQLITE_NOMEM;
|
| + }
|
| + sqlite3ValueFree(pVal);
|
| +
|
| + return rc & 0xff;
|
| +}
|
| +#endif /* SQLITE_OMIT_UTF16 */
|
| +
|
| +/*
|
| +** Register a new collation sequence with the database handle db.
|
| +*/
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_create_collation(
|
| + sqlite3* db,
|
| + const char *zName,
|
| + int enc,
|
| + void* pCtx,
|
| + int(*xCompare)(void*,int,const void*,int,const void*)
|
| +){
|
| + return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
|
| +}
|
| +
|
| +/*
|
| +** Register a new collation sequence with the database handle db.
|
| +*/
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_create_collation_v2(
|
| + sqlite3* db,
|
| + const char *zName,
|
| + int enc,
|
| + void* pCtx,
|
| + int(*xCompare)(void*,int,const void*,int,const void*),
|
| + void(*xDel)(void*)
|
| +){
|
| + int rc;
|
| +
|
| +#ifdef SQLITE_ENABLE_API_ARMOR
|
| + if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
|
| +#endif
|
| + sqlite3_mutex_enter(db->mutex);
|
| + assert( !db->mallocFailed );
|
| + rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
|
| + rc = sqlite3ApiExit(db, rc);
|
| + sqlite3_mutex_leave(db->mutex);
|
| + return rc;
|
| +}
|
| +
|
| +#ifndef SQLITE_OMIT_UTF16
|
| +/*
|
| +** Register a new collation sequence with the database handle db.
|
| +*/
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_create_collation16(
|
| + sqlite3* db,
|
| + const void *zName,
|
| + int enc,
|
| + void* pCtx,
|
| + int(*xCompare)(void*,int,const void*,int,const void*)
|
| +){
|
| + int rc = SQLITE_OK;
|
| + char *zName8;
|
| +
|
| +#ifdef SQLITE_ENABLE_API_ARMOR
|
| + if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
|
| +#endif
|
| + sqlite3_mutex_enter(db->mutex);
|
| + assert( !db->mallocFailed );
|
| + zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
|
| + if( zName8 ){
|
| + rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
|
| + sqlite3DbFree(db, zName8);
|
| + }
|
| + rc = sqlite3ApiExit(db, rc);
|
| + sqlite3_mutex_leave(db->mutex);
|
| + return rc;
|
| +}
|
| +#endif /* SQLITE_OMIT_UTF16 */
|
| +
|
| +/*
|
| +** Register a collation sequence factory callback with the database handle
|
| +** db. Replace any previously installed collation sequence factory.
|
| +*/
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed(
|
| + sqlite3 *db,
|
| + void *pCollNeededArg,
|
| + void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
|
| +){
|
| +#ifdef SQLITE_ENABLE_API_ARMOR
|
| + if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
|
| +#endif
|
| + sqlite3_mutex_enter(db->mutex);
|
| + db->xCollNeeded = xCollNeeded;
|
| + db->xCollNeeded16 = 0;
|
| + db->pCollNeededArg = pCollNeededArg;
|
| + sqlite3_mutex_leave(db->mutex);
|
| + return SQLITE_OK;
|
| +}
|
| +
|
| +#ifndef SQLITE_OMIT_UTF16
|
| +/*
|
| +** Register a collation sequence factory callback with the database handle
|
| +** db. Replace any previously installed collation sequence factory.
|
| +*/
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed16(
|
| + sqlite3 *db,
|
| + void *pCollNeededArg,
|
| + void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
|
| +){
|
| +#ifdef SQLITE_ENABLE_API_ARMOR
|
| + if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
|
| +#endif
|
| + sqlite3_mutex_enter(db->mutex);
|
| + db->xCollNeeded = 0;
|
| + db->xCollNeeded16 = xCollNeeded16;
|
| + db->pCollNeededArg = pCollNeededArg;
|
| + sqlite3_mutex_leave(db->mutex);
|
| + return SQLITE_OK;
|
| +}
|
| +#endif /* SQLITE_OMIT_UTF16 */
|
| +
|
| +#ifndef SQLITE_OMIT_DEPRECATED
|
| +/*
|
| +** This function is now an anachronism. It used to be used to recover from a
|
| +** malloc() failure, but SQLite now does this automatically.
|
| +*/
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_global_recover(void){
|
| + return SQLITE_OK;
|
| +}
|
| +#endif
|
| +
|
| +/*
|
| +** Test to see whether or not the database connection is in autocommit
|
| +** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
|
| +** by default. Autocommit is disabled by a BEGIN statement and reenabled
|
| +** by the next COMMIT or ROLLBACK.
|
| +*/
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_get_autocommit(sqlite3 *db){
|
| +#ifdef SQLITE_ENABLE_API_ARMOR
|
| + if( !sqlite3SafetyCheckOk(db) ){
|
| + (void)SQLITE_MISUSE_BKPT;
|
| + return 0;
|
| + }
|
| +#endif
|
| + return db->autoCommit;
|
| +}
|
| +
|
| +/*
|
| +** The following routines are substitutes for constants SQLITE_CORRUPT,
|
| +** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
|
| +** constants. They serve two purposes:
|
| +**
|
| +** 1. Serve as a convenient place to set a breakpoint in a debugger
|
| +** to detect when version error conditions occurs.
|
| +**
|
| +** 2. Invoke sqlite3_log() to provide the source code location where
|
| +** a low-level error is first detected.
|
| +*/
|
| +SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
|
| + testcase( sqlite3GlobalConfig.xLog!=0 );
|
| + sqlite3_log(SQLITE_CORRUPT,
|
| + "database corruption at line %d of [%.10s]",
|
| + lineno, 20+sqlite3_sourceid());
|
| + return SQLITE_CORRUPT;
|
| +}
|
| +SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
|
| + testcase( sqlite3GlobalConfig.xLog!=0 );
|
| + sqlite3_log(SQLITE_MISUSE,
|
| + "misuse at line %d of [%.10s]",
|
| + lineno, 20+sqlite3_sourceid());
|
| + return SQLITE_MISUSE;
|
| +}
|
| +SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
|
| + testcase( sqlite3GlobalConfig.xLog!=0 );
|
| + sqlite3_log(SQLITE_CANTOPEN,
|
| + "cannot open file at line %d of [%.10s]",
|
| + lineno, 20+sqlite3_sourceid());
|
| + return SQLITE_CANTOPEN;
|
| +}
|
| +
|
| +
|
| +#ifndef SQLITE_OMIT_DEPRECATED
|
| +/*
|
| +** This is a convenience routine that makes sure that all thread-specific
|
| +** data for this thread has been deallocated.
|
| +**
|
| +** SQLite no longer uses thread-specific data so this routine is now a
|
| +** no-op. It is retained for historical compatibility.
|
| +*/
|
| +SQLITE_API void SQLITE_STDCALL sqlite3_thread_cleanup(void){
|
| +}
|
| +#endif
|
| +
|
| +/*
|
| +** Return meta information about a specific column of a database table.
|
| +** See comment in sqlite3.h (sqlite.h.in) for details.
|
| +*/
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_table_column_metadata(
|
| + sqlite3 *db, /* Connection handle */
|
| + const char *zDbName, /* Database name or NULL */
|
| + const char *zTableName, /* Table name */
|
| + const char *zColumnName, /* Column name */
|
| + char const **pzDataType, /* OUTPUT: Declared data type */
|
| + char const **pzCollSeq, /* OUTPUT: Collation sequence name */
|
| + int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
|
| + int *pPrimaryKey, /* OUTPUT: True if column part of PK */
|
| + int *pAutoinc /* OUTPUT: True if column is auto-increment */
|
| +){
|
| + int rc;
|
| + char *zErrMsg = 0;
|
| + Table *pTab = 0;
|
| + Column *pCol = 0;
|
| + int iCol = 0;
|
| + char const *zDataType = 0;
|
| + char const *zCollSeq = 0;
|
| + int notnull = 0;
|
| + int primarykey = 0;
|
| + int autoinc = 0;
|
| +
|
| +
|
| +#ifdef SQLITE_ENABLE_API_ARMOR
|
| + if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){
|
| + return SQLITE_MISUSE_BKPT;
|
| + }
|
| +#endif
|
| +
|
| + /* Ensure the database schema has been loaded */
|
| + sqlite3_mutex_enter(db->mutex);
|
| + sqlite3BtreeEnterAll(db);
|
| + rc = sqlite3Init(db, &zErrMsg);
|
| + if( SQLITE_OK!=rc ){
|
| + goto error_out;
|
| + }
|
| +
|
| + /* Locate the table in question */
|
| + pTab = sqlite3FindTable(db, zTableName, zDbName);
|
| + if( !pTab || pTab->pSelect ){
|
| + pTab = 0;
|
| + goto error_out;
|
| + }
|
| +
|
| + /* Find the column for which info is requested */
|
| + if( zColumnName==0 ){
|
| + /* Query for existance of table only */
|
| + }else{
|
| + for(iCol=0; iCol<pTab->nCol; iCol++){
|
| + pCol = &pTab->aCol[iCol];
|
| + if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
|
| + break;
|
| + }
|
| + }
|
| + if( iCol==pTab->nCol ){
|
| + if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
|
| + iCol = pTab->iPKey;
|
| + pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
|
| + }else{
|
| + pTab = 0;
|
| + goto error_out;
|
| + }
|
| + }
|
| + }
|
| +
|
| + /* The following block stores the meta information that will be returned
|
| + ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
|
| + ** and autoinc. At this point there are two possibilities:
|
| + **
|
| + ** 1. The specified column name was rowid", "oid" or "_rowid_"
|
| + ** and there is no explicitly declared IPK column.
|
| + **
|
| + ** 2. The table is not a view and the column name identified an
|
| + ** explicitly declared column. Copy meta information from *pCol.
|
| + */
|
| + if( pCol ){
|
| + zDataType = pCol->zType;
|
| + zCollSeq = pCol->zColl;
|
| + notnull = pCol->notNull!=0;
|
| + primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
|
| + autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
|
| + }else{
|
| + zDataType = "INTEGER";
|
| + primarykey = 1;
|
| + }
|
| + if( !zCollSeq ){
|
| + zCollSeq = sqlite3StrBINARY;
|
| + }
|
| +
|
| +error_out:
|
| + sqlite3BtreeLeaveAll(db);
|
| +
|
| + /* Whether the function call succeeded or failed, set the output parameters
|
| + ** to whatever their local counterparts contain. If an error did occur,
|
| + ** this has the effect of zeroing all output parameters.
|
| + */
|
| + if( pzDataType ) *pzDataType = zDataType;
|
| + if( pzCollSeq ) *pzCollSeq = zCollSeq;
|
| + if( pNotNull ) *pNotNull = notnull;
|
| + if( pPrimaryKey ) *pPrimaryKey = primarykey;
|
| + if( pAutoinc ) *pAutoinc = autoinc;
|
| +
|
| + if( SQLITE_OK==rc && !pTab ){
|
| + sqlite3DbFree(db, zErrMsg);
|
| + zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
|
| + zColumnName);
|
| + rc = SQLITE_ERROR;
|
| + }
|
| + sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
|
| + sqlite3DbFree(db, zErrMsg);
|
| + rc = sqlite3ApiExit(db, rc);
|
| + sqlite3_mutex_leave(db->mutex);
|
| + return rc;
|
| +}
|
| +
|
| +/*
|
| +** Sleep for a little while. Return the amount of time slept.
|
| +*/
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_sleep(int ms){
|
| + sqlite3_vfs *pVfs;
|
| + int rc;
|
| + pVfs = sqlite3_vfs_find(0);
|
| + if( pVfs==0 ) return 0;
|
| +
|
| + /* This function works in milliseconds, but the underlying OsSleep()
|
| + ** API uses microseconds. Hence the 1000's.
|
| + */
|
| + rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
|
| + return rc;
|
| +}
|
| +
|
| +/*
|
| +** Enable or disable the extended result codes.
|
| +*/
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_extended_result_codes(sqlite3 *db, int onoff){
|
| +#ifdef SQLITE_ENABLE_API_ARMOR
|
| + if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
|
| +#endif
|
| + sqlite3_mutex_enter(db->mutex);
|
| + db->errMask = onoff ? 0xffffffff : 0xff;
|
| + sqlite3_mutex_leave(db->mutex);
|
| + return SQLITE_OK;
|
| +}
|
| +
|
| +/*
|
| +** Invoke the xFileControl method on a particular database.
|
| +*/
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
|
| + int rc = SQLITE_ERROR;
|
| + Btree *pBtree;
|
| +
|
| +#ifdef SQLITE_ENABLE_API_ARMOR
|
| + if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
|
| +#endif
|
| + sqlite3_mutex_enter(db->mutex);
|
| + pBtree = sqlite3DbNameToBtree(db, zDbName);
|
| + if( pBtree ){
|
| + Pager *pPager;
|
| + sqlite3_file *fd;
|
| + sqlite3BtreeEnter(pBtree);
|
| + pPager = sqlite3BtreePager(pBtree);
|
| + assert( pPager!=0 );
|
| + fd = sqlite3PagerFile(pPager);
|
| + assert( fd!=0 );
|
| + if( op==SQLITE_FCNTL_FILE_POINTER ){
|
| + *(sqlite3_file**)pArg = fd;
|
| + rc = SQLITE_OK;
|
| + }else if( op==SQLITE_FCNTL_VFS_POINTER ){
|
| + *(sqlite3_vfs**)pArg = sqlite3PagerVfs(pPager);
|
| + rc = SQLITE_OK;
|
| + }else if( op==SQLITE_FCNTL_JOURNAL_POINTER ){
|
| + *(sqlite3_file**)pArg = sqlite3PagerJrnlFile(pPager);
|
| + rc = SQLITE_OK;
|
| + }else if( fd->pMethods ){
|
| + rc = sqlite3OsFileControl(fd, op, pArg);
|
| + }else{
|
| + rc = SQLITE_NOTFOUND;
|
| + }
|
| + sqlite3BtreeLeave(pBtree);
|
| + }
|
| + sqlite3_mutex_leave(db->mutex);
|
| + return rc;
|
| +}
|
| +
|
| +/*
|
| +** Interface to the testing logic.
|
| +*/
|
| +SQLITE_API int SQLITE_CDECL sqlite3_test_control(int op, ...){
|
| + int rc = 0;
|
| +#ifdef SQLITE_OMIT_BUILTIN_TEST
|
| + UNUSED_PARAMETER(op);
|
| +#else
|
| + va_list ap;
|
| + va_start(ap, op);
|
| + switch( op ){
|
| +
|
| + /*
|
| + ** Save the current state of the PRNG.
|
| + */
|
| + case SQLITE_TESTCTRL_PRNG_SAVE: {
|
| + sqlite3PrngSaveState();
|
| + break;
|
| + }
|
| +
|
| + /*
|
| + ** Restore the state of the PRNG to the last state saved using
|
| + ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
|
| + ** this verb acts like PRNG_RESET.
|
| + */
|
| + case SQLITE_TESTCTRL_PRNG_RESTORE: {
|
| + sqlite3PrngRestoreState();
|
| + break;
|
| + }
|
| +
|
| + /*
|
| + ** Reset the PRNG back to its uninitialized state. The next call
|
| + ** to sqlite3_randomness() will reseed the PRNG using a single call
|
| + ** to the xRandomness method of the default VFS.
|
| + */
|
| + case SQLITE_TESTCTRL_PRNG_RESET: {
|
| + sqlite3_randomness(0,0);
|
| + break;
|
| + }
|
| +
|
| + /*
|
| + ** sqlite3_test_control(BITVEC_TEST, size, program)
|
| + **
|
| + ** Run a test against a Bitvec object of size. The program argument
|
| + ** is an array of integers that defines the test. Return -1 on a
|
| + ** memory allocation error, 0 on success, or non-zero for an error.
|
| + ** See the sqlite3BitvecBuiltinTest() for additional information.
|
| + */
|
| + case SQLITE_TESTCTRL_BITVEC_TEST: {
|
| + int sz = va_arg(ap, int);
|
| + int *aProg = va_arg(ap, int*);
|
| + rc = sqlite3BitvecBuiltinTest(sz, aProg);
|
| + break;
|
| + }
|
| +
|
| + /*
|
| + ** sqlite3_test_control(FAULT_INSTALL, xCallback)
|
| + **
|
| + ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
|
| + ** if xCallback is not NULL.
|
| + **
|
| + ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
|
| + ** is called immediately after installing the new callback and the return
|
| + ** value from sqlite3FaultSim(0) becomes the return from
|
| + ** sqlite3_test_control().
|
| + */
|
| + case SQLITE_TESTCTRL_FAULT_INSTALL: {
|
| + /* MSVC is picky about pulling func ptrs from va lists.
|
| + ** http://support.microsoft.com/kb/47961
|
| + ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
|
| + */
|
| + typedef int(*TESTCALLBACKFUNC_t)(int);
|
| + sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);
|
| + rc = sqlite3FaultSim(0);
|
| + break;
|
| + }
|
| +
|
| + /*
|
| + ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
|
| + **
|
| + ** Register hooks to call to indicate which malloc() failures
|
| + ** are benign.
|
| + */
|
| + case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
|
| + typedef void (*void_function)(void);
|
| + void_function xBenignBegin;
|
| + void_function xBenignEnd;
|
| + xBenignBegin = va_arg(ap, void_function);
|
| + xBenignEnd = va_arg(ap, void_function);
|
| + sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
|
| + break;
|
| + }
|
| +
|
| + /*
|
| + ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
|
| + **
|
| + ** Set the PENDING byte to the value in the argument, if X>0.
|
| + ** Make no changes if X==0. Return the value of the pending byte
|
| + ** as it existing before this routine was called.
|
| + **
|
| + ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
|
| + ** an incompatible database file format. Changing the PENDING byte
|
| + ** while any database connection is open results in undefined and
|
| + ** deleterious behavior.
|
| + */
|
| + case SQLITE_TESTCTRL_PENDING_BYTE: {
|
| + rc = PENDING_BYTE;
|
| +#ifndef SQLITE_OMIT_WSD
|
| + {
|
| + unsigned int newVal = va_arg(ap, unsigned int);
|
| + if( newVal ) sqlite3PendingByte = newVal;
|
| + }
|
| +#endif
|
| + break;
|
| + }
|
| +
|
| + /*
|
| + ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
|
| + **
|
| + ** This action provides a run-time test to see whether or not
|
| + ** assert() was enabled at compile-time. If X is true and assert()
|
| + ** is enabled, then the return value is true. If X is true and
|
| + ** assert() is disabled, then the return value is zero. If X is
|
| + ** false and assert() is enabled, then the assertion fires and the
|
| + ** process aborts. If X is false and assert() is disabled, then the
|
| + ** return value is zero.
|
| + */
|
| + case SQLITE_TESTCTRL_ASSERT: {
|
| + volatile int x = 0;
|
| + assert( (x = va_arg(ap,int))!=0 );
|
| + rc = x;
|
| + break;
|
| + }
|
| +
|
| +
|
| + /*
|
| + ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
|
| + **
|
| + ** This action provides a run-time test to see how the ALWAYS and
|
| + ** NEVER macros were defined at compile-time.
|
| + **
|
| + ** The return value is ALWAYS(X).
|
| + **
|
| + ** The recommended test is X==2. If the return value is 2, that means
|
| + ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
|
| + ** default setting. If the return value is 1, then ALWAYS() is either
|
| + ** hard-coded to true or else it asserts if its argument is false.
|
| + ** The first behavior (hard-coded to true) is the case if
|
| + ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
|
| + ** behavior (assert if the argument to ALWAYS() is false) is the case if
|
| + ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
|
| + **
|
| + ** The run-time test procedure might look something like this:
|
| + **
|
| + ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
|
| + ** // ALWAYS() and NEVER() are no-op pass-through macros
|
| + ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
|
| + ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
|
| + ** }else{
|
| + ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
|
| + ** }
|
| + */
|
| + case SQLITE_TESTCTRL_ALWAYS: {
|
| + int x = va_arg(ap,int);
|
| + rc = ALWAYS(x);
|
| + break;
|
| + }
|
| +
|
| + /*
|
| + ** sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
|
| + **
|
| + ** The integer returned reveals the byte-order of the computer on which
|
| + ** SQLite is running:
|
| + **
|
| + ** 1 big-endian, determined at run-time
|
| + ** 10 little-endian, determined at run-time
|
| + ** 432101 big-endian, determined at compile-time
|
| + ** 123410 little-endian, determined at compile-time
|
| + */
|
| + case SQLITE_TESTCTRL_BYTEORDER: {
|
| + rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
|
| + break;
|
| + }
|
| +
|
| + /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
|
| + **
|
| + ** Set the nReserve size to N for the main database on the database
|
| + ** connection db.
|
| + */
|
| + case SQLITE_TESTCTRL_RESERVE: {
|
| + sqlite3 *db = va_arg(ap, sqlite3*);
|
| + int x = va_arg(ap,int);
|
| + sqlite3_mutex_enter(db->mutex);
|
| + sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
|
| + sqlite3_mutex_leave(db->mutex);
|
| + break;
|
| + }
|
| +
|
| + /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
|
| + **
|
| + ** Enable or disable various optimizations for testing purposes. The
|
| + ** argument N is a bitmask of optimizations to be disabled. For normal
|
| + ** operation N should be 0. The idea is that a test program (like the
|
| + ** SQL Logic Test or SLT test module) can run the same SQL multiple times
|
| + ** with various optimizations disabled to verify that the same answer
|
| + ** is obtained in every case.
|
| + */
|
| + case SQLITE_TESTCTRL_OPTIMIZATIONS: {
|
| + sqlite3 *db = va_arg(ap, sqlite3*);
|
| + db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
|
| + break;
|
| + }
|
| +
|
| +#ifdef SQLITE_N_KEYWORD
|
| + /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
|
| + **
|
| + ** If zWord is a keyword recognized by the parser, then return the
|
| + ** number of keywords. Or if zWord is not a keyword, return 0.
|
| + **
|
| + ** This test feature is only available in the amalgamation since
|
| + ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
|
| + ** is built using separate source files.
|
| + */
|
| + case SQLITE_TESTCTRL_ISKEYWORD: {
|
| + const char *zWord = va_arg(ap, const char*);
|
| + int n = sqlite3Strlen30(zWord);
|
| + rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
|
| + break;
|
| + }
|
| +#endif
|
| +
|
| + /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
|
| + **
|
| + ** Pass pFree into sqlite3ScratchFree().
|
| + ** If sz>0 then allocate a scratch buffer into pNew.
|
| + */
|
| + case SQLITE_TESTCTRL_SCRATCHMALLOC: {
|
| + void *pFree, **ppNew;
|
| + int sz;
|
| + sz = va_arg(ap, int);
|
| + ppNew = va_arg(ap, void**);
|
| + pFree = va_arg(ap, void*);
|
| + if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
|
| + sqlite3ScratchFree(pFree);
|
| + break;
|
| + }
|
| +
|
| + /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
|
| + **
|
| + ** If parameter onoff is non-zero, configure the wrappers so that all
|
| + ** subsequent calls to localtime() and variants fail. If onoff is zero,
|
| + ** undo this setting.
|
| + */
|
| + case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
|
| + sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
|
| + break;
|
| + }
|
| +
|
| + /* sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
|
| + **
|
| + ** Set or clear a flag that indicates that the database file is always well-
|
| + ** formed and never corrupt. This flag is clear by default, indicating that
|
| + ** database files might have arbitrary corruption. Setting the flag during
|
| + ** testing causes certain assert() statements in the code to be activated
|
| + ** that demonstrat invariants on well-formed database files.
|
| + */
|
| + case SQLITE_TESTCTRL_NEVER_CORRUPT: {
|
| + sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
|
| + break;
|
| + }
|
| +
|
| +
|
| + /* sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
|
| + **
|
| + ** Set the VDBE coverage callback function to xCallback with context
|
| + ** pointer ptr.
|
| + */
|
| + case SQLITE_TESTCTRL_VDBE_COVERAGE: {
|
| +#ifdef SQLITE_VDBE_COVERAGE
|
| + typedef void (*branch_callback)(void*,int,u8,u8);
|
| + sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
|
| + sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
|
| +#endif
|
| + break;
|
| + }
|
| +
|
| + /* sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
|
| + case SQLITE_TESTCTRL_SORTER_MMAP: {
|
| + sqlite3 *db = va_arg(ap, sqlite3*);
|
| + db->nMaxSorterMmap = va_arg(ap, int);
|
| + break;
|
| + }
|
| +
|
| + /* sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
|
| + **
|
| + ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
|
| + ** not.
|
| + */
|
| + case SQLITE_TESTCTRL_ISINIT: {
|
| + if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
|
| + break;
|
| + }
|
| +
|
| + /* sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
|
| + **
|
| + ** This test control is used to create imposter tables. "db" is a pointer
|
| + ** to the database connection. dbName is the database name (ex: "main" or
|
| + ** "temp") which will receive the imposter. "onOff" turns imposter mode on
|
| + ** or off. "tnum" is the root page of the b-tree to which the imposter
|
| + ** table should connect.
|
| + **
|
| + ** Enable imposter mode only when the schema has already been parsed. Then
|
| + ** run a single CREATE TABLE statement to construct the imposter table in
|
| + ** the parsed schema. Then turn imposter mode back off again.
|
| + **
|
| + ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
|
| + ** the schema to be reparsed the next time it is needed. This has the
|
| + ** effect of erasing all imposter tables.
|
| + */
|
| + case SQLITE_TESTCTRL_IMPOSTER: {
|
| + sqlite3 *db = va_arg(ap, sqlite3*);
|
| + sqlite3_mutex_enter(db->mutex);
|
| + db->init.iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
|
| + db->init.busy = db->init.imposterTable = va_arg(ap,int);
|
| + db->init.newTnum = va_arg(ap,int);
|
| + if( db->init.busy==0 && db->init.newTnum>0 ){
|
| + sqlite3ResetAllSchemasOfConnection(db);
|
| + }
|
| + sqlite3_mutex_leave(db->mutex);
|
| + break;
|
| + }
|
| + }
|
| + va_end(ap);
|
| +#endif /* SQLITE_OMIT_BUILTIN_TEST */
|
| + return rc;
|
| +}
|
| +
|
| +/*
|
| +** This is a utility routine, useful to VFS implementations, that checks
|
| +** to see if a database file was a URI that contained a specific query
|
| +** parameter, and if so obtains the value of the query parameter.
|
| +**
|
| +** The zFilename argument is the filename pointer passed into the xOpen()
|
| +** method of a VFS implementation. The zParam argument is the name of the
|
| +** query parameter we seek. This routine returns the value of the zParam
|
| +** parameter if it exists. If the parameter does not exist, this routine
|
| +** returns a NULL pointer.
|
| +*/
|
| +SQLITE_API const char *SQLITE_STDCALL sqlite3_uri_parameter(const char *zFilename, const char *zParam){
|
| + if( zFilename==0 || zParam==0 ) return 0;
|
| + zFilename += sqlite3Strlen30(zFilename) + 1;
|
| + while( zFilename[0] ){
|
| + int x = strcmp(zFilename, zParam);
|
| + zFilename += sqlite3Strlen30(zFilename) + 1;
|
| + if( x==0 ) return zFilename;
|
| + zFilename += sqlite3Strlen30(zFilename) + 1;
|
| + }
|
| + return 0;
|
| +}
|
| +
|
| +/*
|
| +** Return a boolean value for a query parameter.
|
| +*/
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
|
| + const char *z = sqlite3_uri_parameter(zFilename, zParam);
|
| + bDflt = bDflt!=0;
|
| + return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
|
| +}
|
| +
|
| +/*
|
| +** Return a 64-bit integer value for a query parameter.
|
| +*/
|
| +SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_uri_int64(
|
| + const char *zFilename, /* Filename as passed to xOpen */
|
| + const char *zParam, /* URI parameter sought */
|
| + sqlite3_int64 bDflt /* return if parameter is missing */
|
| +){
|
| + const char *z = sqlite3_uri_parameter(zFilename, zParam);
|
| + sqlite3_int64 v;
|
| + if( z && sqlite3DecOrHexToI64(z, &v)==SQLITE_OK ){
|
| + bDflt = v;
|
| + }
|
| + return bDflt;
|
| +}
|
| +
|
| +/*
|
| +** Return the Btree pointer identified by zDbName. Return NULL if not found.
|
| +*/
|
| +SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
|
| + int i;
|
| + for(i=0; i<db->nDb; i++){
|
| + if( db->aDb[i].pBt
|
| + && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
|
| + ){
|
| + return db->aDb[i].pBt;
|
| + }
|
| + }
|
| + return 0;
|
| +}
|
| +
|
| +/*
|
| +** Return the filename of the database associated with a database
|
| +** connection.
|
| +*/
|
| +SQLITE_API const char *SQLITE_STDCALL sqlite3_db_filename(sqlite3 *db, const char *zDbName){
|
| + Btree *pBt;
|
| +#ifdef SQLITE_ENABLE_API_ARMOR
|
| + if( !sqlite3SafetyCheckOk(db) ){
|
| + (void)SQLITE_MISUSE_BKPT;
|
| + return 0;
|
| + }
|
| +#endif
|
| + pBt = sqlite3DbNameToBtree(db, zDbName);
|
| + return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
|
| +}
|
| +
|
| +/*
|
| +** Return 1 if database is read-only or 0 if read/write. Return -1 if
|
| +** no such database exists.
|
| +*/
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
|
| + Btree *pBt;
|
| +#ifdef SQLITE_ENABLE_API_ARMOR
|
| + if( !sqlite3SafetyCheckOk(db) ){
|
| + (void)SQLITE_MISUSE_BKPT;
|
| + return -1;
|
| + }
|
| +#endif
|
| + pBt = sqlite3DbNameToBtree(db, zDbName);
|
| + return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
|
| +}
|
| +
|
| +#ifdef SQLITE_ENABLE_SNAPSHOT
|
| +/*
|
| +** Obtain a snapshot handle for the snapshot of database zDb currently
|
| +** being read by handle db.
|
| +*/
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_snapshot_get(
|
| + sqlite3 *db,
|
| + const char *zDb,
|
| + sqlite3_snapshot **ppSnapshot
|
| +){
|
| + int rc = SQLITE_ERROR;
|
| +#ifndef SQLITE_OMIT_WAL
|
| + int iDb;
|
| +
|
| +#ifdef SQLITE_ENABLE_API_ARMOR
|
| + if( !sqlite3SafetyCheckOk(db) ){
|
| + return SQLITE_MISUSE_BKPT;
|
| + }
|
| +#endif
|
| + sqlite3_mutex_enter(db->mutex);
|
| +
|
| + iDb = sqlite3FindDbName(db, zDb);
|
| + if( iDb==0 || iDb>1 ){
|
| + Btree *pBt = db->aDb[iDb].pBt;
|
| + if( 0==sqlite3BtreeIsInTrans(pBt) ){
|
| + rc = sqlite3BtreeBeginTrans(pBt, 0);
|
| + if( rc==SQLITE_OK ){
|
| + rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot);
|
| + }
|
| + }
|
| + }
|
| +
|
| + sqlite3_mutex_leave(db->mutex);
|
| +#endif /* SQLITE_OMIT_WAL */
|
| + return rc;
|
| +}
|
| +
|
| +/*
|
| +** Open a read-transaction on the snapshot idendified by pSnapshot.
|
| +*/
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_snapshot_open(
|
| + sqlite3 *db,
|
| + const char *zDb,
|
| + sqlite3_snapshot *pSnapshot
|
| +){
|
| + int rc = SQLITE_ERROR;
|
| +#ifndef SQLITE_OMIT_WAL
|
| +
|
| +#ifdef SQLITE_ENABLE_API_ARMOR
|
| + if( !sqlite3SafetyCheckOk(db) ){
|
| + return SQLITE_MISUSE_BKPT;
|
| + }
|
| +#endif
|
| + sqlite3_mutex_enter(db->mutex);
|
| + if( db->autoCommit==0 ){
|
| + int iDb;
|
| + iDb = sqlite3FindDbName(db, zDb);
|
| + if( iDb==0 || iDb>1 ){
|
| + Btree *pBt = db->aDb[iDb].pBt;
|
| + if( 0==sqlite3BtreeIsInReadTrans(pBt) ){
|
| + rc = sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), pSnapshot);
|
| + if( rc==SQLITE_OK ){
|
| + rc = sqlite3BtreeBeginTrans(pBt, 0);
|
| + sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), 0);
|
| + }
|
| + }
|
| + }
|
| + }
|
| +
|
| + sqlite3_mutex_leave(db->mutex);
|
| +#endif /* SQLITE_OMIT_WAL */
|
| + return rc;
|
| +}
|
| +
|
| +/*
|
| +** Free a snapshot handle obtained from sqlite3_snapshot_get().
|
| +*/
|
| +SQLITE_API void SQLITE_STDCALL sqlite3_snapshot_free(sqlite3_snapshot *pSnapshot){
|
| + sqlite3_free(pSnapshot);
|
| +}
|
| +#endif /* SQLITE_ENABLE_SNAPSHOT */
|
| +
|
| +/************** End of main.c ************************************************/
|
| +/************** Begin file notify.c ******************************************/
|
| +/*
|
| +** 2009 March 3
|
| +**
|
| +** The author disclaims copyright to this source code. In place of
|
| +** a legal notice, here is a blessing:
|
| +**
|
| +** May you do good and not evil.
|
| +** May you find forgiveness for yourself and forgive others.
|
| +** May you share freely, never taking more than you give.
|
| +**
|
| +*************************************************************************
|
| +**
|
| +** This file contains the implementation of the sqlite3_unlock_notify()
|
| +** API method and its associated functionality.
|
| +*/
|
| +/* #include "sqliteInt.h" */
|
| +/* #include "btreeInt.h" */
|
| +
|
| +/* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
|
| +#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
|
| +
|
| +/*
|
| +** Public interfaces:
|
| +**
|
| +** sqlite3ConnectionBlocked()
|
| +** sqlite3ConnectionUnlocked()
|
| +** sqlite3ConnectionClosed()
|
| +** sqlite3_unlock_notify()
|
| +*/
|
| +
|
| +#define assertMutexHeld() \
|
| + assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
|
| +
|
| +/*
|
| +** Head of a linked list of all sqlite3 objects created by this process
|
| +** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
|
| +** is not NULL. This variable may only accessed while the STATIC_MASTER
|
| +** mutex is held.
|
| +*/
|
| +static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
|
| +
|
| +#ifndef NDEBUG
|
| +/*
|
| +** This function is a complex assert() that verifies the following
|
| +** properties of the blocked connections list:
|
| +**
|
| +** 1) Each entry in the list has a non-NULL value for either
|
| +** pUnlockConnection or pBlockingConnection, or both.
|
| +**
|
| +** 2) All entries in the list that share a common value for
|
| +** xUnlockNotify are grouped together.
|
| +**
|
| +** 3) If the argument db is not NULL, then none of the entries in the
|
| +** blocked connections list have pUnlockConnection or pBlockingConnection
|
| +** set to db. This is used when closing connection db.
|
| +*/
|
| +static void checkListProperties(sqlite3 *db){
|
| + sqlite3 *p;
|
| + for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
|
| + int seen = 0;
|
| + sqlite3 *p2;
|
| +
|
| + /* Verify property (1) */
|
| + assert( p->pUnlockConnection || p->pBlockingConnection );
|
| +
|
| + /* Verify property (2) */
|
| + for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
|
| + if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
|
| + assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
|
| + assert( db==0 || p->pUnlockConnection!=db );
|
| + assert( db==0 || p->pBlockingConnection!=db );
|
| + }
|
| + }
|
| +}
|
| +#else
|
| +# define checkListProperties(x)
|
| +#endif
|
| +
|
| +/*
|
| +** Remove connection db from the blocked connections list. If connection
|
| +** db is not currently a part of the list, this function is a no-op.
|
| +*/
|
| +static void removeFromBlockedList(sqlite3 *db){
|
| + sqlite3 **pp;
|
| + assertMutexHeld();
|
| + for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
|
| + if( *pp==db ){
|
| + *pp = (*pp)->pNextBlocked;
|
| + break;
|
| + }
|
| + }
|
| +}
|
| +
|
| +/*
|
| +** Add connection db to the blocked connections list. It is assumed
|
| +** that it is not already a part of the list.
|
| +*/
|
| +static void addToBlockedList(sqlite3 *db){
|
| + sqlite3 **pp;
|
| + assertMutexHeld();
|
| + for(
|
| + pp=&sqlite3BlockedList;
|
| + *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
|
| + pp=&(*pp)->pNextBlocked
|
| + );
|
| + db->pNextBlocked = *pp;
|
| + *pp = db;
|
| +}
|
| +
|
| +/*
|
| +** Obtain the STATIC_MASTER mutex.
|
| +*/
|
| +static void enterMutex(void){
|
| + sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
|
| + checkListProperties(0);
|
| +}
|
| +
|
| +/*
|
| +** Release the STATIC_MASTER mutex.
|
| +*/
|
| +static void leaveMutex(void){
|
| + assertMutexHeld();
|
| + checkListProperties(0);
|
| + sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
|
| +}
|
| +
|
| +/*
|
| +** Register an unlock-notify callback.
|
| +**
|
| +** This is called after connection "db" has attempted some operation
|
| +** but has received an SQLITE_LOCKED error because another connection
|
| +** (call it pOther) in the same process was busy using the same shared
|
| +** cache. pOther is found by looking at db->pBlockingConnection.
|
| +**
|
| +** If there is no blocking connection, the callback is invoked immediately,
|
| +** before this routine returns.
|
| +**
|
| +** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
|
| +** a deadlock.
|
| +**
|
| +** Otherwise, make arrangements to invoke xNotify when pOther drops
|
| +** its locks.
|
| +**
|
| +** Each call to this routine overrides any prior callbacks registered
|
| +** on the same "db". If xNotify==0 then any prior callbacks are immediately
|
| +** cancelled.
|
| +*/
|
| +SQLITE_API int SQLITE_STDCALL sqlite3_unlock_notify(
|
| + sqlite3 *db,
|
| + void (*xNotify)(void **, int),
|
| + void *pArg
|
| +){
|
| + int rc = SQLITE_OK;
|
| +
|
| + sqlite3_mutex_enter(db->mutex);
|
| + enterMutex();
|
| +
|
| + if( xNotify==0 ){
|
| + removeFromBlockedList(db);
|
| + db->pBlockingConnection = 0;
|
| + db->pUnlockConnection = 0;
|
| + db->xUnlockNotify = 0;
|
| + db->pUnlockArg = 0;
|
| + }else if( 0==db->pBlockingConnection ){
|
| + /* The blocking transaction has been concluded. Or there never was a
|
| + ** blocking transaction. In either case, invoke the notify callback
|
| + ** immediately.
|
| + */
|
| + xNotify(&pArg, 1);
|
| + }else{
|
| + sqlite3 *p;
|
| +
|
| + for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
|
| + if( p ){
|
| + rc = SQLITE_LOCKED; /* Deadlock detected. */
|
| + }else{
|
| + db->pUnlockConnection = db->pBlockingConnection;
|
| + db->xUnlockNotify = xNotify;
|
| + db->pUnlockArg = pArg;
|
| + removeFromBlockedList(db);
|
| + addToBlockedList(db);
|
| + }
|
| + }
|
| +
|
| + leaveMutex();
|
| + assert( !db->mallocFailed );
|
| + sqlite3ErrorWithMsg(db, rc, (rc?"database is deadlocked":0));
|
| + sqlite3_mutex_leave(db->mutex);
|
| + return rc;
|
| +}
|
| +
|
| +/*
|
| +** This function is called while stepping or preparing a statement
|
| +** associated with connection db. The operation will return SQLITE_LOCKED
|
| +** to the user because it requires a lock that will not be available
|
| +** until connection pBlocker concludes its current transaction.
|
| +*/
|
| +SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
|
| + enterMutex();
|
| + if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
|
| + addToBlockedList(db);
|
| + }
|
| + db->pBlockingConnection = pBlocker;
|
| + leaveMutex();
|
| +}
|
| +
|
| +/*
|
| +** This function is called when
|
| +** the transaction opened by database db has just finished. Locks held
|
| +** by database connection db have been released.
|
| +**
|
| +** This function loops through each entry in the blocked connections
|
| +** list and does the following:
|
| +**
|
| +** 1) If the sqlite3.pBlockingConnection member of a list entry is
|
| +** set to db, then set pBlockingConnection=0.
|
| +**
|
| +** 2) If the sqlite3.pUnlockConnection member of a list entry is
|
| +** set to db, then invoke the configured unlock-notify callback and
|
| +** set pUnlockConnection=0.
|
| +**
|
| +** 3) If the two steps above mean that pBlockingConnection==0 and
|
| +** pUnlockConnection==0, remove the entry from the blocked connections
|
| +** list.
|
| +*/
|
| +SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
|
| + void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
|
| + int nArg = 0; /* Number of entries in aArg[] */
|
| + sqlite3 **pp; /* Iterator variable */
|
| + void **aArg; /* Arguments to the unlock callback */
|
| + void **aDyn = 0; /* Dynamically allocated space for aArg[] */
|
| + void *aStatic[16]; /* Starter space for aArg[]. No malloc required */
|
| +
|
| + aArg = aStatic;
|
| + enterMutex(); /* Enter STATIC_MASTER mutex */
|
| +
|
| + /* This loop runs once for each entry in the blocked-connections list. */
|
| + for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
|
| + sqlite3 *p = *pp;
|
| +
|
| + /* Step 1. */
|
| + if( p->pBlockingConnection==db ){
|
| + p->pBlockingConnection = 0;
|
| + }
|
| +
|
| + /* Step 2. */
|
| + if( p->pUnlockConnection==db ){
|
| + assert( p->xUnlockNotify );
|
| + if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
|
| + xUnlockNotify(aArg, nArg);
|
| + nArg = 0;
|
| + }
|
| +
|
| + sqlite3BeginBenignMalloc();
|
| + assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
|
| + assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
|
| + if( (!aDyn && nArg==(int)ArraySize(aStatic))
|
| + || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
|
| + ){
|
| + /* The aArg[] array needs to grow. */
|
| + void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
|
| + if( pNew ){
|
| + memcpy(pNew, aArg, nArg*sizeof(void *));
|
| + sqlite3_free(aDyn);
|
| + aDyn = aArg = pNew;
|
| + }else{
|
| + /* This occurs when the array of context pointers that need to
|
| + ** be passed to the unlock-notify callback is larger than the
|
| + ** aStatic[] array allocated on the stack and the attempt to
|
| + ** allocate a larger array from the heap has failed.
|
| + **
|
| + ** This is a difficult situation to handle. Returning an error
|
| + ** code to the caller is insufficient, as even if an error code
|
| + ** is returned the transaction on connection db will still be
|
| + ** closed and the unlock-notify callbacks on blocked connections
|
| + ** will go unissued. This might cause the application to wait
|
| + ** indefinitely for an unlock-notify callback that will never
|
| + ** arrive.
|
| + **
|
| + ** Instead, invoke the unlock-notify callback with the context
|
| + ** array already accumulated. We can then clear the array and
|
| + ** begin accumulating any further context pointers without
|
| + ** requiring any dynamic allocation. This is sub-optimal because
|
| + ** it means that instead of one callback with a large array of
|
| + ** context pointers the application will receive two or more
|
| + ** callbacks with smaller arrays of context pointers, which will
|
| + ** reduce the applications ability to prioritize multiple
|
| + ** connections. But it is the best that can be done under the
|
| + ** circumstances.
|
| + */
|
| + xUnlockNotify(aArg, nArg);
|
| + nArg = 0;
|
| + }
|
| + }
|
| + sqlite3EndBenignMalloc();
|
| +
|
| + aArg[nArg++] = p->pUnlockArg;
|
| + xUnlockNotify = p->xUnlockNotify;
|
| + p->pUnlockConnection = 0;
|
| + p->xUnlockNotify = 0;
|
| + p->pUnlockArg = 0;
|
| + }
|
| +
|
| + /* Step 3. */
|
| + if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
|
| + /* Remove connection p from the blocked connections list. */
|
| + *pp = p->pNextBlocked;
|
| + p->pNextBlocked = 0;
|
| + }else{
|
| + pp = &p->pNextBlocked;
|
| + }
|
| + }
|
| +
|
| + if( nArg!=0 ){
|
| + xUnlockNotify(aArg, nArg);
|
| + }
|
| + sqlite3_free(aDyn);
|
| + leaveMutex(); /* Leave STATIC_MASTER mutex */
|
| +}
|
| +
|
| +/*
|
| +** This is called when the database connection passed as an argument is
|
| +** being closed. The connection is removed from the blocked list.
|
| +*/
|
| +SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
|
| + sqlite3ConnectionUnlocked(db);
|
| + enterMutex();
|
| + removeFromBlockedList(db);
|
| + checkListProperties(db);
|
| + leaveMutex();
|
| +}
|
| +#endif
|
| +
|
| +/************** End of notify.c **********************************************/
|
| +/************** Begin file recover.c *****************************************/
|
| +/*
|
| +** 2012 Jan 11
|
| +**
|
| +** The author disclaims copyright to this source code. In place of
|
| +** a legal notice, here is a blessing:
|
| +**
|
| +** May you do good and not evil.
|
| +** May you find forgiveness for yourself and forgive others.
|
| +** May you share freely, never taking more than you give.
|
| +*/
|
| +/* TODO(shess): THIS MODULE IS STILL EXPERIMENTAL. DO NOT USE IT. */
|
| +/* Implements a virtual table "recover" which can be used to recover
|
| + * data from a corrupt table. The table is walked manually, with
|
| + * corrupt items skipped. Additionally, any errors while reading will
|
| + * be skipped.
|
| + *
|
| + * Given a table with this definition:
|
| + *
|
| + * CREATE TABLE Stuff (
|
| + * name TEXT PRIMARY KEY,
|
| + * value TEXT NOT NULL
|
| + * );
|
| + *
|
| + * to recover the data from teh table, you could do something like:
|
| + *
|
| + * -- Attach another database, the original is not trustworthy.
|
| + * ATTACH DATABASE '/tmp/db.db' AS rdb;
|
| + * -- Create a new version of the table.
|
| + * CREATE TABLE rdb.Stuff (
|
| + * name TEXT PRIMARY KEY,
|
| + * value TEXT NOT NULL
|
| + * );
|
| + * -- This will read the original table's data.
|
| + * CREATE VIRTUAL TABLE temp.recover_Stuff using recover(
|
| + * main.Stuff,
|
| + * name TEXT STRICT NOT NULL, -- only real TEXT data allowed
|
| + * value TEXT STRICT NOT NULL
|
| + * );
|
| + * -- Corruption means the UNIQUE constraint may no longer hold for
|
| + * -- Stuff, so either OR REPLACE or OR IGNORE must be used.
|
| + * INSERT OR REPLACE INTO rdb.Stuff (rowid, name, value )
|
| + * SELECT rowid, name, value FROM temp.recover_Stuff;
|
| + * DROP TABLE temp.recover_Stuff;
|
| + * DETACH DATABASE rdb;
|
| + * -- Move db.db to replace original db in filesystem.
|
| + *
|
| + *
|
| + * Usage
|
| + *
|
| + * Given the goal of dealing with corruption, it would not be safe to
|
| + * create a recovery table in the database being recovered. So
|
| + * recovery tables must be created in the temp database. They are not
|
| + * appropriate to persist, in any case. [As a bonus, sqlite_master
|
| + * tables can be recovered. Perhaps more cute than useful, though.]
|
| + *
|
| + * The parameters are a specifier for the table to read, and a column
|
| + * definition for each bit of data stored in that table. The named
|
| + * table must be convertable to a root page number by reading the
|
| + * sqlite_master table. Bare table names are assumed to be in
|
| + * database 0 ("main"), other databases can be specified in db.table
|
| + * fashion.
|
| + *
|
| + * Column definitions are similar to BUT NOT THE SAME AS those
|
| + * provided to CREATE statements:
|
| + * column-def: column-name [type-name [STRICT] [NOT NULL]]
|
| + * type-name: (ANY|ROWID|INTEGER|FLOAT|NUMERIC|TEXT|BLOB)
|
| + *
|
| + * Only those exact type names are accepted, there is no type
|
| + * intuition. The only constraints accepted are STRICT (see below)
|
| + * and NOT NULL. Anything unexpected will cause the create to fail.
|
| + *
|
| + * ANY is a convenience to indicate that manifest typing is desired.
|
| + * It is equivalent to not specifying a type at all. The results for
|
| + * such columns will have the type of the data's storage. The exposed
|
| + * schema will contain no type for that column.
|
| + *
|
| + * ROWID is used for columns representing aliases to the rowid
|
| + * (INTEGER PRIMARY KEY, with or without AUTOINCREMENT), to make the
|
| + * concept explicit. Such columns are actually stored as NULL, so
|
| + * they cannot be simply ignored. The exposed schema will be INTEGER
|
| + * for that column.
|
| + *
|
| + * NOT NULL causes rows with a NULL in that column to be skipped. It
|
| + * also adds NOT NULL to the column in the exposed schema. If the
|
| + * table has ever had columns added using ALTER TABLE, then those
|
| + * columns implicitly contain NULL for rows which have not been
|
| + * updated. [Workaround using COALESCE() in your SELECT statement.]
|
| + *
|
| + * The created table is read-only, with no indices. Any SELECT will
|
| + * be a full-table scan, returning each valid row read from the
|
| + * storage of the backing table. The rowid will be the rowid of the
|
| + * row from the backing table. "Valid" means:
|
| + * - The cell metadata for the row is well-formed. Mainly this means that
|
| + * the cell header info describes a payload of the size indicated by
|
| + * the cell's payload size.
|
| + * - The cell does not run off the page.
|
| + * - The cell does not overlap any other cell on the page.
|
| + * - The cell contains doesn't contain too many columns.
|
| + * - The types of the serialized data match the indicated types (see below).
|
| + *
|
| + *
|
| + * Type affinity versus type storage.
|
| + *
|
| + * http://www.sqlite.org/datatype3.html describes SQLite's type
|
| + * affinity system. The system provides for automated coercion of
|
| + * types in certain cases, transparently enough that many developers
|
| + * do not realize that it is happening. Importantly, it implies that
|
| + * the raw data stored in the database may not have the obvious type.
|
| + *
|
| + * Differences between the stored data types and the expected data
|
| + * types may be a signal of corruption. This module makes some
|
| + * allowances for automatic coercion. It is important to be concious
|
| + * of the difference between the schema exposed by the module, and the
|
| + * data types read from storage. The following table describes how
|
| + * the module interprets things:
|
| + *
|
| + * type schema data STRICT
|
| + * ---- ------ ---- ------
|
| + * ANY <none> any any
|
| + * ROWID INTEGER n/a n/a
|
| + * INTEGER INTEGER integer integer
|
| + * FLOAT FLOAT integer or float float
|
| + * NUMERIC NUMERIC integer, float, or text integer or float
|
| + * TEXT TEXT text or blob text
|
| + * BLOB BLOB blob blob
|
| + *
|
| + * type is the type provided to the recover module, schema is the
|
| + * schema exposed by the module, data is the acceptable types of data
|
| + * decoded from storage, and STRICT is a modification of that.
|
| + *
|
| + * A very loose recovery system might use ANY for all columns, then
|
| + * use the appropriate sqlite3_column_*() calls to coerce to expected
|
| + * types. This doesn't provide much protection if a page from a
|
| + * different table with the same column count is linked into an
|
| + * inappropriate btree.
|
| + *
|
| + * A very tight recovery system might use STRICT to enforce typing on
|
| + * all columns, preferring to skip rows which are valid at the storage
|
| + * level but don't contain the right types. Note that FLOAT STRICT is
|
| + * almost certainly not appropriate, since integral values are
|
| + * transparently stored as integers, when that is more efficient.
|
| + *
|
| + * Another option is to use ANY for all columns and inspect each
|
| + * result manually (using sqlite3_column_*). This should only be
|
| + * necessary in cases where developers have used manifest typing (test
|
| + * to make sure before you decide that you aren't using manifest
|
| + * typing!).
|
| + *
|
| + *
|
| + * Caveats
|
| + *
|
| + * Leaf pages not referenced by interior nodes will not be found.
|
| + *
|
| + * Leaf pages referenced from interior nodes of other tables will not
|
| + * be resolved.
|
| + *
|
| + * Rows referencing invalid overflow pages will be skipped.
|
| + *
|
| + * SQlite rows have a header which describes how to interpret the rest
|
| + * of the payload. The header can be valid in cases where the rest of
|
| + * the record is actually corrupt (in the sense that the data is not
|
| + * the intended data). This can especially happen WRT overflow pages,
|
| + * as lack of atomic updates between pages is the primary form of
|
| + * corruption I have seen in the wild.
|
| + */
|
| +/* The implementation is via a series of cursors. The cursor
|
| + * implementations follow the pattern:
|
| + *
|
| + * // Creates the cursor using various initialization info.
|
| + * int cursorCreate(...);
|
| + *
|
| + * // Returns 1 if there is no more data, 0 otherwise.
|
| + * int cursorEOF(Cursor *pCursor);
|
| + *
|
| + * // Various accessors can be used if not at EOF.
|
| + *
|
| + * // Move to the next item.
|
| + * int cursorNext(Cursor *pCursor);
|
| + *
|
| + * // Destroy the memory associated with the cursor.
|
| + * void cursorDestroy(Cursor *pCursor);
|
| + *
|
| + * References in the following are to sections at
|
| + * http://www.sqlite.org/fileformat2.html .
|
| + *
|
| + * RecoverLeafCursor iterates the records in a leaf table node
|
| + * described in section 1.5 "B-tree Pages". When the node is
|
| + * exhausted, an interior cursor is used to get the next leaf node,
|
| + * and iteration continues there.
|
| + *
|
| + * RecoverInteriorCursor iterates the child pages in an interior table
|
| + * node described in section 1.5 "B-tree Pages". When the node is
|
| + * exhausted, a parent interior cursor is used to get the next
|
| + * interior node at the same level, and iteration continues there.
|
| + *
|
| + * Together these record the path from the leaf level to the root of
|
| + * the tree. Iteration happens from the leaves rather than the root
|
| + * both for efficiency and putting the special case at the front of
|
| + * the list is easier to implement.
|
| + *
|
| + * RecoverCursor uses a RecoverLeafCursor to iterate the rows of a
|
| + * table, returning results via the SQLite virtual table interface.
|
| + */
|
| +/* TODO(shess): It might be useful to allow DEFAULT in types to
|
| + * specify what to do for NULL when an ALTER TABLE case comes up.
|
| + * Unfortunately, simply adding it to the exposed schema and using
|
| + * sqlite3_result_null() does not cause the default to be generate.
|
| + * Handling it ourselves seems hard, unfortunately.
|
| + */
|
| +
|
| +/* #include <assert.h> */
|
| +/* #include <ctype.h> */
|
| +/* #include <stdio.h> */
|
| +/* #include <string.h> */
|
| +
|
| +/* Internal SQLite things that are used:
|
| + * u32, u64, i64 types.
|
| + * Btree, Pager, and DbPage structs.
|
| + * DbPage.pData, .pPager, and .pgno
|
| + * sqlite3 struct.
|
| + * sqlite3BtreePager() and sqlite3BtreeGetPageSize()
|
| + * sqlite3BtreeGetOptimalReserve()
|
| + * sqlite3PagerGet() and sqlite3PagerUnref()
|
| + * getVarint().
|
| + */
|
| +/* #include "sqliteInt.h" */
|
| +
|
| +/* For debugging. */
|
| +#if 0
|
| +#define FNENTRY() fprintf(stderr, "In %s\n", __FUNCTION__)
|
| +#else
|
| +#define FNENTRY()
|
| +#endif
|
| +
|
| +/* Generic constants and helper functions. */
|
| +
|
| +static const unsigned char kTableLeafPage = 0x0D;
|
| +static const unsigned char kTableInteriorPage = 0x05;
|
| +
|
| +/* From section 1.5. */
|
| +static const unsigned kiPageTypeOffset = 0;
|
| +static const unsigned kiPageFreeBlockOffset = 1;
|
| +static const unsigned kiPageCellCountOffset = 3;
|
| +static const unsigned kiPageCellContentOffset = 5;
|
| +static const unsigned kiPageFragmentedBytesOffset = 7;
|
| +static const unsigned knPageLeafHeaderBytes = 8;
|
| +/* Interior pages contain an additional field. */
|
| +static const unsigned kiPageRightChildOffset = 8;
|
| +static const unsigned kiPageInteriorHeaderBytes = 12;
|
| +
|
| +/* Accepted types are specified by a mask. */
|
| +#define MASK_ROWID (1<<0)
|
| +#define MASK_INTEGER (1<<1)
|
| +#define MASK_FLOAT (1<<2)
|
| +#define MASK_TEXT (1<<3)
|
| +#define MASK_BLOB (1<<4)
|
| +#define MASK_NULL (1<<5)
|
| +
|
| +/* Helpers to decode fixed-size fields. */
|
| +static u32 decodeUnsigned16(const unsigned char *pData){
|
| + return (pData[0]<<8) + pData[1];
|
| +}
|
| +static u32 decodeUnsigned32(const unsigned char *pData){
|
| + return (decodeUnsigned16(pData)<<16) + decodeUnsigned16(pData+2);
|
| +}
|
| +static i64 decodeSigned(const unsigned char *pData, unsigned nBytes){
|
| + i64 r = (char)(*pData);
|
| + while( --nBytes ){
|
| + r <<= 8;
|
| + r += *(++pData);
|
| + }
|
| + return r;
|
| +}
|
| +/* Derived from vdbeaux.c, sqlite3VdbeSerialGet(), case 7. */
|
| +/* TODO(shess): Determine if swapMixedEndianFloat() applies. */
|
| +static double decodeFloat64(const unsigned char *pData){
|
| +#if !defined(NDEBUG)
|
| + static const u64 t1 = ((u64)0x3ff00000)<<32;
|
| + static const double r1 = 1.0;
|
| + u64 t2 = t1;
|
| + assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
|
| +#endif
|
| + i64 x = decodeSigned(pData, 8);
|
| + double d;
|
| + memcpy(&d, &x, sizeof(x));
|
| + return d;
|
| +}
|
| +
|
| +/* Return true if a varint can safely be read from pData/nData. */
|
| +/* TODO(shess): DbPage points into the middle of a buffer which
|
| + * contains the page data before DbPage. So code should always be
|
| + * able to read a small number of varints safely. Consider whether to
|
| + * trust that or not.
|
| + */
|
| +static int checkVarint(const unsigned char *pData, unsigned nData){
|
| + unsigned i;
|
| +
|
| + /* In the worst case the decoder takes all 8 bits of the 9th byte. */
|
| + if( nData>=9 ){
|
| + return 1;
|
| + }
|
| +
|
| + /* Look for a high-bit-clear byte in what's left. */
|
| + for( i=0; i<nData; ++i ){
|
| + if( !(pData[i]&0x80) ){
|
| + return 1;
|
| + }
|
| + }
|
| +
|
| + /* Cannot decode in the space given. */
|
| + return 0;
|
| +}
|
| +
|
| +/* Return 1 if n varints can be read from pData/nData. */
|
| +static int checkVarints(const unsigned char *pData, unsigned nData,
|
| + unsigned n){
|
| + unsigned nCur = 0; /* Byte offset within current varint. */
|
| + unsigned nFound = 0; /* Number of varints found. */
|
| + unsigned i;
|
| +
|
| + /* In the worst case the decoder takes all 8 bits of the 9th byte. */
|
| + if( nData>=9*n ){
|
| + return 1;
|
| + }
|
| +
|
| + for( i=0; nFound<n && i<nData; ++i ){
|
| + nCur++;
|
| + if( nCur==9 || !(pData[i]&0x80) ){
|
| + nFound++;
|
| + nCur = 0;
|
| + }
|
| + }
|
| +
|
| + return nFound==n;
|
| +}
|
| +
|
| +/* ctype and str[n]casecmp() can be affected by locale (eg, tr_TR).
|
| + * These versions consider only the ASCII space.
|
| + */
|
| +/* TODO(shess): It may be reasonable to just remove the need for these
|
| + * entirely. The module could require "TEXT STRICT NOT NULL", not
|
| + * "Text Strict Not Null" or whatever the developer felt like typing
|
| + * that day. Handling corrupt data is a PERFECT place to be pedantic.
|
| + */
|
| +static int ascii_isspace(char c){
|
| + /* From fts3_expr.c */
|
| + return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
|
| +}
|
| +static int ascii_isalnum(int x){
|
| + /* From fts3_tokenizer1.c */
|
| + return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
|
| +}
|
| +static int ascii_tolower(int x){
|
| + /* From fts3_tokenizer1.c */
|
| + return (x>='A' && x<='Z') ? x-'A'+'a' : x;
|
| +}
|
| +/* TODO(shess): Consider sqlite3_strnicmp() */
|
| +static int ascii_strncasecmp(const char *s1, const char *s2, size_t n){
|
| + const unsigned char *us1 = (const unsigned char *)s1;
|
| + const unsigned char *us2 = (const unsigned char *)s2;
|
| + while( *us1 && *us2 && n && ascii_tolower(*us1)==ascii_tolower(*us2) ){
|
| + us1++, us2++, n--;
|
| + }
|
| + return n ? ascii_tolower(*us1)-ascii_tolower(*us2) : 0;
|
| +}
|
| +static int ascii_strcasecmp(const char *s1, const char *s2){
|
| + /* If s2 is equal through strlen(s1), will exit while() due to s1's
|
| + * trailing NUL, and return NUL-s2[strlen(s1)].
|
| + */
|
| + return ascii_strncasecmp(s1, s2, strlen(s1)+1);
|
| +}
|
| +
|
| +/* For some reason I kept making mistakes with offset calculations. */
|
| +static const unsigned char *PageData(DbPage *pPage, unsigned iOffset){
|
| + assert( iOffset<=pPage->nPageSize );
|
| + return (unsigned char *)pPage->pData + iOffset;
|
| +}
|
| +
|
| +/* The first page in the file contains a file header in the first 100
|
| + * bytes. The page's header information comes after that. Note that
|
| + * the offsets in the page's header information are relative to the
|
| + * beginning of the page, NOT the end of the page header.
|
| + */
|
| +static const unsigned char *PageHeader(DbPage *pPage){
|
| + if( pPage->pgno==1 ){
|
| + const unsigned nDatabaseHeader = 100;
|
| + return PageData(pPage, nDatabaseHeader);
|
| + }else{
|
| + return PageData(pPage, 0);
|
| + }
|
| +}
|
| +
|
| +/* Helper to fetch the pager and page size for the named database. */
|
| +static int GetPager(sqlite3 *db, const char *zName,
|
| + Pager **pPager, unsigned *pnPageSize){
|
| + Btree *pBt = NULL;
|
| + int i;
|
| + for( i=0; i<db->nDb; ++i ){
|
| + if( ascii_strcasecmp(db->aDb[i].zName, zName)==0 ){
|
| + pBt = db->aDb[i].pBt;
|
| + break;
|
| + }
|
| + }
|
| + if( !pBt ){
|
| + return SQLITE_ERROR;
|
| + }
|
| +
|
| + *pPager = sqlite3BtreePager(pBt);
|
| + *pnPageSize =
|
| + sqlite3BtreeGetPageSize(pBt) - sqlite3BtreeGetOptimalReserve(pBt);
|
| + return SQLITE_OK;
|
| +}
|
| +
|
| +/* iSerialType is a type read from a record header. See "2.1 Record Format".
|
| + */
|
| +
|
| +/* Storage size of iSerialType in bytes. My interpretation of SQLite
|
| + * documentation is that text and blob fields can have 32-bit length.
|
| + * Values past 2^31-12 will need more than 32 bits to encode, which is
|
| + * why iSerialType is u64.
|
| + */
|
| +static u32 SerialTypeLength(u64 iSerialType){
|
| + switch( iSerialType ){
|
| + case 0 : return 0; /* NULL */
|
| + case 1 : return 1; /* Various integers. */
|
| + case 2 : return 2;
|
| + case 3 : return 3;
|
| + case 4 : return 4;
|
| + case 5 : return 6;
|
| + case 6 : return 8;
|
| + case 7 : return 8; /* 64-bit float. */
|
| + case 8 : return 0; /* Constant 0. */
|
| + case 9 : return 0; /* Constant 1. */
|
| + case 10 : case 11 : assert( !"RESERVED TYPE"); return 0;
|
| + }
|
| + return (u32)((iSerialType>>1) - 6);
|
| +}
|
| +
|
| +/* True if iSerialType refers to a blob. */
|
| +static int SerialTypeIsBlob(u64 iSerialType){
|
| + assert( iSerialType>=12 );
|
| + return (iSerialType%2)==0;
|
| +}
|
| +
|
| +/* Returns true if the serialized type represented by iSerialType is
|
| + * compatible with the given type mask.
|
| + */
|
| +static int SerialTypeIsCompatible(u64 iSerialType, unsigned char mask){
|
| + switch( iSerialType ){
|
| + case 0 : return (mask&MASK_NULL)!=0;
|
| + case 1 : return (mask&MASK_INTEGER)!=0;
|
| + case 2 : return (mask&MASK_INTEGER)!=0;
|
| + case 3 : return (mask&MASK_INTEGER)!=0;
|
| + case 4 : return (mask&MASK_INTEGER)!=0;
|
| + case 5 : return (mask&MASK_INTEGER)!=0;
|
| + case 6 : return (mask&MASK_INTEGER)!=0;
|
| + case 7 : return (mask&MASK_FLOAT)!=0;
|
| + case 8 : return (mask&MASK_INTEGER)!=0;
|
| + case 9 : return (mask&MASK_INTEGER)!=0;
|
| + case 10 : assert( !"RESERVED TYPE"); return 0;
|
| + case 11 : assert( !"RESERVED TYPE"); return 0;
|
| + }
|
| + return (mask&(SerialTypeIsBlob(iSerialType) ? MASK_BLOB : MASK_TEXT));
|
| +}
|
| +
|
| +/* Versions of strdup() with return values appropriate for
|
| + * sqlite3_free(). malloc.c has sqlite3DbStrDup()/NDup(), but those
|
| + * need sqlite3DbFree(), which seems intrusive.
|
| + */
|
| +static char *sqlite3_strndup(const char *z, unsigned n){
|
| + char *zNew;
|
| +
|
| + if( z==NULL ){
|
| + return NULL;
|
| + }
|
| +
|
| + zNew = sqlite3_malloc(n+1);
|
| + if( zNew!=NULL ){
|
| + memcpy(zNew, z, n);
|
| + zNew[n] = '\0';
|
| + }
|
| + return zNew;
|
| +}
|
| +static char *sqlite3_strdup(const char *z){
|
| + if( z==NULL ){
|
| + return NULL;
|
| + }
|
| + return sqlite3_strndup(z, strlen(z));
|
| +}
|
| +
|
| +/* Fetch the page number of zTable in zDb from sqlite_master in zDb,
|
| + * and put it in *piRootPage.
|
| + */
|
| +static int getRootPage(sqlite3 *db, const char *zDb, const char *zTable,
|
| + u32 *piRootPage){
|
| + char *zSql; /* SQL selecting root page of named element. */
|
| + sqlite3_stmt *pStmt;
|
| + int rc;
|
| +
|
| + if( strcmp(zTable, "sqlite_master")==0 ){
|
| + *piRootPage = 1;
|
| + return SQLITE_OK;
|
| + }
|
| +
|
| + zSql = sqlite3_mprintf("SELECT rootpage FROM %s.sqlite_master "
|
| + "WHERE type = 'table' AND tbl_name = %Q",
|
| + zDb, zTable);
|
| + if( !zSql ){
|
| + return SQLITE_NOMEM;
|
| + }
|
| +
|
| + rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
|
| + sqlite3_free(zSql);
|
| + if( rc!=SQLITE_OK ){
|
| + return rc;
|
| + }
|
| +
|
| + /* Require a result. */
|
| + rc = sqlite3_step(pStmt);
|
| + if( rc==SQLITE_DONE ){
|
| + rc = SQLITE_CORRUPT;
|
| + }else if( rc==SQLITE_ROW ){
|
| + *piRootPage = sqlite3_column_int(pStmt, 0);
|
| +
|
| + /* Require only one result. */
|
| + rc = sqlite3_step(pStmt);
|
| + if( rc==SQLITE_DONE ){
|
| + rc = SQLITE_OK;
|
| + }else if( rc==SQLITE_ROW ){
|
| + rc = SQLITE_CORRUPT;
|
| + }
|
| + }
|
| + sqlite3_finalize(pStmt);
|
| + return rc;
|
| +}
|
| +
|
| +static int getEncoding(sqlite3 *db, const char *zDb, int* piEncoding){
|
| + sqlite3_stmt *pStmt;
|
| + int rc;
|
| + char *zSql = sqlite3_mprintf("PRAGMA %s.encoding", zDb);
|
| + if( !zSql ){
|
| + return SQLITE_NOMEM;
|
| + }
|
| +
|
| + rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
|
| + sqlite3_free(zSql);
|
| + if( rc!=SQLITE_OK ){
|
| + return rc;
|
| + }
|
| +
|
| + /* Require a result. */
|
| + rc = sqlite3_step(pStmt);
|
| + if( rc==SQLITE_DONE ){
|
| + /* This case should not be possible. */
|
| + rc = SQLITE_CORRUPT;
|
| + }else if( rc==SQLITE_ROW ){
|
| + if( sqlite3_column_type(pStmt, 0)==SQLITE_TEXT ){
|
| + const char* z = (const char *)sqlite3_column_text(pStmt, 0);
|
| + /* These strings match the literals in pragma.c. */
|
| + if( !strcmp(z, "UTF-16le") ){
|
| + *piEncoding = SQLITE_UTF16LE;
|
| + }else if( !strcmp(z, "UTF-16be") ){
|
| + *piEncoding = SQLITE_UTF16BE;
|
| + }else if( !strcmp(z, "UTF-8") ){
|
| + *piEncoding = SQLITE_UTF8;
|
| + }else{
|
| + /* This case should not be possible. */
|
| + *piEncoding = SQLITE_UTF8;
|
| + }
|
| + }else{
|
| + /* This case should not be possible. */
|
| + *piEncoding = SQLITE_UTF8;
|
| + }
|
| +
|
| + /* Require only one result. */
|
| + rc = sqlite3_step(pStmt);
|
| + if( rc==SQLITE_DONE ){
|
| + rc = SQLITE_OK;
|
| + }else if( rc==SQLITE_ROW ){
|
| + /* This case should not be possible. */
|
| + rc = SQLITE_CORRUPT;
|
| + }
|
| + }
|
| + sqlite3_finalize(pStmt);
|
| + return rc;
|
| +}
|
| +
|
| +/* Cursor for iterating interior nodes. Interior page cells contain a
|
| + * child page number and a rowid. The child page contains items left
|
| + * of the rowid (less than). The rightmost page of the subtree is
|
| + * stored in the page header.
|
| + *
|
| + * interiorCursorDestroy - release all resources associated with the
|
| + * cursor and any parent cursors.
|
| + * interiorCursorCreate - create a cursor with the given parent and page.
|
| + * interiorCursorEOF - returns true if neither the cursor nor the
|
| + * parent cursors can return any more data.
|
| + * interiorCursorNextPage - fetch the next child page from the cursor.
|
| + *
|
| + * Logically, interiorCursorNextPage() returns the next child page
|
| + * number from the page the cursor is currently reading, calling the
|
| + * parent cursor as necessary to get new pages to read, until done.
|
| + * SQLITE_ROW if a page is returned, SQLITE_DONE if out of pages,
|
| + * error otherwise. Unfortunately, if the table is corrupted
|
| + * unexpected pages can be returned. If any unexpected page is found,
|
| + * leaf or otherwise, it is returned to the caller for processing,
|
| + * with the interior cursor left empty. The next call to
|
| + * interiorCursorNextPage() will recurse to the parent cursor until an
|
| + * interior page to iterate is returned.
|
| + *
|
| + * Note that while interiorCursorNextPage() will refuse to follow
|
| + * loops, it does not keep track of pages returned for purposes of
|
| + * preventing duplication.
|
| + *
|
| + * Note that interiorCursorEOF() could return false (not at EOF), and
|
| + * interiorCursorNextPage() could still return SQLITE_DONE. This
|
| + * could happen if there are more cells to iterate in an interior
|
| + * page, but those cells refer to invalid pages.
|
| + */
|
| +typedef struct RecoverInteriorCursor RecoverInteriorCursor;
|
| +struct RecoverInteriorCursor {
|
| + RecoverInteriorCursor *pParent; /* Parent node to this node. */
|
| + DbPage *pPage; /* Reference to leaf page. */
|
| + unsigned nPageSize; /* Size of page. */
|
| + unsigned nChildren; /* Number of children on the page. */
|
| + unsigned iChild; /* Index of next child to return. */
|
| +};
|
| +
|
| +static void interiorCursorDestroy(RecoverInteriorCursor *pCursor){
|
| + /* Destroy all the cursors to the root. */
|
| + while( pCursor ){
|
| + RecoverInteriorCursor *p = pCursor;
|
| + pCursor = pCursor->pParent;
|
| +
|
| + if( p->pPage ){
|
| + sqlite3PagerUnref(p->pPage);
|
| + p->pPage = NULL;
|
| + }
|
| +
|
| + memset(p, 0xA5, sizeof(*p));
|
| + sqlite3_free(p);
|
| + }
|
| +}
|
| +
|
| +/* Internal helper. Reset storage in preparation for iterating pPage. */
|
| +static void interiorCursorSetPage(RecoverInteriorCursor *pCursor,
|
| + DbPage *pPage){
|
| + const unsigned knMinCellLength = 2 + 4 + 1;
|
| + unsigned nMaxChildren;
|
| + assert( PageHeader(pPage)[kiPageTypeOffset]==kTableInteriorPage );
|
| +
|
| + if( pCursor->pPage ){
|
| + sqlite3PagerUnref(pCursor->pPage);
|
| + pCursor->pPage = NULL;
|
| + }
|
| + pCursor->pPage = pPage;
|
| + pCursor->iChild = 0;
|
| +
|
| + /* A child for each cell, plus one in the header. */
|
| + pCursor->nChildren = decodeUnsigned16(PageHeader(pPage) +
|
| + kiPageCellCountOffset) + 1;
|
| +
|
| + /* Each child requires a 16-bit offset from an array after the header,
|
| + * and each child contains a 32-bit page number and at least a varint
|
| + * (min size of one byte). The final child page is in the header. So
|
| + * the maximum value for nChildren is:
|
| + * (nPageSize - kiPageInteriorHeaderBytes) /
|
| + * (sizeof(uint16) + sizeof(uint32) + 1) + 1
|
| + */
|
| + /* TODO(shess): This count is very unlikely to be corrupted in
|
| + * isolation, so seeing this could signal to skip the page. OTOH, I
|
| + * can't offhand think of how to get here unless this or the page-type
|
| + * byte is corrupted. Could be an overflow page, but it would require
|
| + * a very large database.
|
| + */
|
| + nMaxChildren =
|
| + (pCursor->nPageSize - kiPageInteriorHeaderBytes) / knMinCellLength + 1;
|
| + if (pCursor->nChildren > nMaxChildren) {
|
| + pCursor->nChildren = nMaxChildren;
|
| + }
|
| +}
|
| +
|
| +static int interiorCursorCreate(RecoverInteriorCursor *pParent,
|
| + DbPage *pPage, int nPageSize,
|
| + RecoverInteriorCursor **ppCursor){
|
| + RecoverInteriorCursor *pCursor =
|
| + sqlite3_malloc(sizeof(RecoverInteriorCursor));
|
| + if( !pCursor ){
|
| + return SQLITE_NOMEM;
|
| + }
|
| +
|
| + memset(pCursor, 0, sizeof(*pCursor));
|
| + pCursor->pParent = pParent;
|
| + pCursor->nPageSize = nPageSize;
|
| + interiorCursorSetPage(pCursor, pPage);
|
| + *ppCursor = pCursor;
|
| + return SQLITE_OK;
|
| +}
|
| +
|
| +/* Internal helper. Return the child page number at iChild. */
|
| +static unsigned interiorCursorChildPage(RecoverInteriorCursor *pCursor){
|
| + const unsigned char *pPageHeader; /* Header of the current page. */
|
| + const unsigned char *pCellOffsets; /* Offset to page's cell offsets. */
|
| + unsigned iCellOffset; /* Offset of target cell. */
|
| +
|
| + assert( pCursor->iChild<pCursor->nChildren );
|
| +
|
| + /* Rightmost child is in the header. */
|
| + pPageHeader = PageHeader(pCursor->pPage);
|
| + if( pCursor->iChild==pCursor->nChildren-1 ){
|
| + return decodeUnsigned32(pPageHeader + kiPageRightChildOffset);
|
| + }
|
| +
|
| + /* Each cell is a 4-byte integer page number and a varint rowid
|
| + * which is greater than the rowid of items in that sub-tree (this
|
| + * module ignores ordering). The offset is from the beginning of the
|
| + * page, not from the page header.
|
| + */
|
| + pCellOffsets = pPageHeader + kiPageInteriorHeaderBytes;
|
| + iCellOffset = decodeUnsigned16(pCellOffsets + pCursor->iChild*2);
|
| + if( iCellOffset<=pCursor->nPageSize-4 ){
|
| + return decodeUnsigned32(PageData(pCursor->pPage, iCellOffset));
|
| + }
|
| +
|
| + /* TODO(shess): Check for cell overlaps? Cells require 4 bytes plus
|
| + * a varint. Check could be identical to leaf check (or even a
|
| + * shared helper testing for "Cells starting in this range"?).
|
| + */
|
| +
|
| + /* If the offset is broken, return an invalid page number. */
|
| + return 0;
|
| +}
|
| +
|
| +static int interiorCursorEOF(RecoverInteriorCursor *pCursor){
|
| + /* Find a parent with remaining children. EOF if none found. */
|
| + while( pCursor && pCursor->iChild>=pCursor->nChildren ){
|
| + pCursor = pCursor->pParent;
|
| + }
|
| + return pCursor==NULL;
|
| +}
|
| +
|
| +/* Internal helper. Used to detect if iPage would cause a loop. */
|
| +static int interiorCursorPageInUse(RecoverInteriorCursor *pCursor,
|
| + unsigned iPage){
|
| + /* Find any parent using the indicated page. */
|
| + while( pCursor && pCursor->pPage->pgno!=iPage ){
|
| + pCursor = pCursor->pParent;
|
| + }
|
| + return pCursor!=NULL;
|
| +}
|
| +
|
| +/* Get the next page from the interior cursor at *ppCursor. Returns
|
| + * SQLITE_ROW with the page in *ppPage, or SQLITE_DONE if out of
|
| + * pages, or the error SQLite returned.
|
| + *
|
| + * If the tree is uneven, then when the cursor attempts to get a new
|
| + * interior page from the parent cursor, it may get a non-interior
|
| + * page. In that case, the new page is returned, and *ppCursor is
|
| + * updated to point to the parent cursor (this cursor is freed).
|
| + */
|
| +/* TODO(shess): I've tried to avoid recursion in most of this code,
|
| + * but this case is more challenging because the recursive call is in
|
| + * the middle of operation. One option for converting it without
|
| + * adding memory management would be to retain the head pointer and
|
| + * use a helper to "back up" as needed. Another option would be to
|
| + * reverse the list during traversal.
|
| + */
|
| +static int interiorCursorNextPage(RecoverInteriorCursor **ppCursor,
|
| + DbPage **ppPage){
|
| + RecoverInteriorCursor *pCursor = *ppCursor;
|
| + while( 1 ){
|
| + int rc;
|
| + const unsigned char *pPageHeader; /* Header of found page. */
|
| +
|
| + /* Find a valid child page which isn't on the stack. */
|
| + while( pCursor->iChild<pCursor->nChildren ){
|
| + const unsigned iPage = interiorCursorChildPage(pCursor);
|
| + pCursor->iChild++;
|
| + if( interiorCursorPageInUse(pCursor, iPage) ){
|
| + fprintf(stderr, "Loop detected at %d\n", iPage);
|
| + }else{
|
| + int rc = sqlite3PagerGet(pCursor->pPage->pPager, iPage, ppPage, 0);
|
| + if( rc==SQLITE_OK ){
|
| + return SQLITE_ROW;
|
| + }
|
| + }
|
| + }
|
| +
|
| + /* This page has no more children. Get next page from parent. */
|
| + if( !pCursor->pParent ){
|
| + return SQLITE_DONE;
|
| + }
|
| + rc = interiorCursorNextPage(&pCursor->pParent, ppPage);
|
| + if( rc!=SQLITE_ROW ){
|
| + return rc;
|
| + }
|
| +
|
| + /* If a non-interior page is received, that either means that the
|
| + * tree is uneven, or that a child was re-used (say as an overflow
|
| + * page). Remove this cursor and let the caller handle the page.
|
| + */
|
| + pPageHeader = PageHeader(*ppPage);
|
| + if( pPageHeader[kiPageTypeOffset]!=kTableInteriorPage ){
|
| + *ppCursor = pCursor->pParent;
|
| + pCursor->pParent = NULL;
|
| + interiorCursorDestroy(pCursor);
|
| + return SQLITE_ROW;
|
| + }
|
| +
|
| + /* Iterate the new page. */
|
| + interiorCursorSetPage(pCursor, *ppPage);
|
| + *ppPage = NULL;
|
| + }
|
| +
|
| + assert(NULL); /* NOTREACHED() */
|
| + return SQLITE_CORRUPT;
|
| +}
|
| +
|
| +/* Large rows are spilled to overflow pages. The row's main page
|
| + * stores the overflow page number after the local payload, with a
|
| + * linked list forward from there as necessary. overflowMaybeCreate()
|
| + * and overflowGetSegment() provide an abstraction for accessing such
|
| + * data while centralizing the code.
|
| + *
|
| + * overflowDestroy - releases all resources associated with the structure.
|
| + * overflowMaybeCreate - create the overflow structure if it is needed
|
| + * to represent the given record. See function comment.
|
| + * overflowGetSegment - fetch a segment from the record, accounting
|
| + * for overflow pages. Segments which are not
|
| + * entirely contained with a page are constructed
|
| + * into a buffer which is returned. See function comment.
|
| + */
|
| +typedef struct RecoverOverflow RecoverOverflow;
|
| +struct RecoverOverflow {
|
| + RecoverOverflow *pNextOverflow;
|
| + DbPage *pPage;
|
| + unsigned nPageSize;
|
| +};
|
| +
|
| +static void overflowDestroy(RecoverOverflow *pOverflow){
|
| + while( pOverflow ){
|
| + RecoverOverflow *p = pOverflow;
|
| + pOverflow = p->pNextOverflow;
|
| +
|
| + if( p->pPage ){
|
| + sqlite3PagerUnref(p->pPage);
|
| + p->pPage = NULL;
|
| + }
|
| +
|
| + memset(p, 0xA5, sizeof(*p));
|
| + sqlite3_free(p);
|
| + }
|
| +}
|
| +
|
| +/* Internal helper. Used to detect if iPage would cause a loop. */
|
| +static int overflowPageInUse(RecoverOverflow *pOverflow, unsigned iPage){
|
| + while( pOverflow && pOverflow->pPage->pgno!=iPage ){
|
| + pOverflow = pOverflow->pNextOverflow;
|
| + }
|
| + return pOverflow!=NULL;
|
| +}
|
| +
|
| +/* Setup to access an nRecordBytes record beginning at iRecordOffset
|
| + * in pPage. If nRecordBytes can be satisfied entirely from pPage,
|
| + * then no overflow pages are needed an *pnLocalRecordBytes is set to
|
| + * nRecordBytes. Otherwise, *ppOverflow is set to the head of a list
|
| + * of overflow pages, and *pnLocalRecordBytes is set to the number of
|
| + * bytes local to pPage.
|
| + *
|
| + * overflowGetSegment() will do the right thing regardless of whether
|
| + * those values are set to be in-page or not.
|
| + */
|
| +static int overflowMaybeCreate(DbPage *pPage, unsigned nPageSize,
|
| + unsigned iRecordOffset, unsigned nRecordBytes,
|
| + unsigned *pnLocalRecordBytes,
|
| + RecoverOverflow **ppOverflow){
|
| + unsigned nLocalRecordBytes; /* Record bytes in the leaf page. */
|
| + unsigned iNextPage; /* Next page number for record data. */
|
| + unsigned nBytes; /* Maximum record bytes as of current page. */
|
| + int rc;
|
| + RecoverOverflow *pFirstOverflow; /* First in linked list of pages. */
|
| + RecoverOverflow *pLastOverflow; /* End of linked list. */
|
| +
|
| + /* Calculations from the "Table B-Tree Leaf Cell" part of section
|
| + * 1.5 of http://www.sqlite.org/fileformat2.html . maxLocal and
|
| + * minLocal to match naming in btree.c.
|
| + */
|
| + const unsigned maxLocal = nPageSize - 35;
|
| + const unsigned minLocal = ((nPageSize-12)*32/255)-23; /* m */
|
| +
|
| + /* Always fit anything smaller than maxLocal. */
|
| + if( nRecordBytes<=maxLocal ){
|
| + *pnLocalRecordBytes = nRecordBytes;
|
| + *ppOverflow = NULL;
|
| + return SQLITE_OK;
|
| + }
|
| +
|
| + /* Calculate the remainder after accounting for minLocal on the leaf
|
| + * page and what packs evenly into overflow pages. If the remainder
|
| + * does not fit into maxLocal, then a partially-full overflow page
|
| + * will be required in any case, so store as little as possible locally.
|
| + */
|
| + nLocalRecordBytes = minLocal+((nRecordBytes-minLocal)%(nPageSize-4));
|
| + if( maxLocal<nLocalRecordBytes ){
|
| + nLocalRecordBytes = minLocal;
|
| + }
|
| +
|
| + /* Don't read off the end of the page. */
|
| + if( iRecordOffset+nLocalRecordBytes+4>nPageSize ){
|
| + return SQLITE_CORRUPT;
|
| + }
|
| +
|
| + /* First overflow page number is after the local bytes. */
|
| + iNextPage =
|
| + decodeUnsigned32(PageData(pPage, iRecordOffset + nLocalRecordBytes));
|
| + nBytes = nLocalRecordBytes;
|
| +
|
| + /* While there are more pages to read, and more bytes are needed,
|
| + * get another page.
|
| + */
|
| + pFirstOverflow = pLastOverflow = NULL;
|
| + rc = SQLITE_OK;
|
| + while( iNextPage && nBytes<nRecordBytes ){
|
| + RecoverOverflow *pOverflow; /* New overflow page for the list. */
|
| +
|
| + rc = sqlite3PagerGet(pPage->pPager, iNextPage, &pPage, 0);
|
| + if( rc!=SQLITE_OK ){
|
| + break;
|
| + }
|
| +
|
| + pOverflow = sqlite3_malloc(sizeof(RecoverOverflow));
|
| + if( !pOverflow ){
|
| + sqlite3PagerUnref(pPage);
|
| + rc = SQLITE_NOMEM;
|
| + break;
|
| + }
|
| + memset(pOverflow, 0, sizeof(*pOverflow));
|
| + pOverflow->pPage = pPage;
|
| + pOverflow->nPageSize = nPageSize;
|
| +
|
| + if( !pFirstOverflow ){
|
| + pFirstOverflow = pOverflow;
|
| + }else{
|
| + pLastOverflow->pNextOverflow = pOverflow;
|
| + }
|
| + pLastOverflow = pOverflow;
|
| +
|
| + iNextPage = decodeUnsigned32(pPage->pData);
|
| + nBytes += nPageSize-4;
|
| +
|
| + /* Avoid loops. */
|
| + if( overflowPageInUse(pFirstOverflow, iNextPage) ){
|
| + fprintf(stderr, "Overflow loop detected at %d\n", iNextPage);
|
| + rc = SQLITE_CORRUPT;
|
| + break;
|
| + }
|
| + }
|
| +
|
| + /* If there were not enough pages, or too many, things are corrupt.
|
| + * Not having enough pages is an obvious problem, all the data
|
| + * cannot be read. Too many pages means that the contents of the
|
| + * row between the main page and the overflow page(s) is
|
| + * inconsistent (most likely one or more of the overflow pages does
|
| + * not really belong to this row).
|
| + */
|
| + if( rc==SQLITE_OK && (nBytes<nRecordBytes || iNextPage) ){
|
| + rc = SQLITE_CORRUPT;
|
| + }
|
| +
|
| + if( rc==SQLITE_OK ){
|
| + *ppOverflow = pFirstOverflow;
|
| + *pnLocalRecordBytes = nLocalRecordBytes;
|
| + }else if( pFirstOverflow ){
|
| + overflowDestroy(pFirstOverflow);
|
| + }
|
| + return rc;
|
| +}
|
| +
|
| +/* Use in concert with overflowMaybeCreate() to efficiently read parts
|
| + * of a potentially-overflowing record. pPage and iRecordOffset are
|
| + * the values passed into overflowMaybeCreate(), nLocalRecordBytes and
|
| + * pOverflow are the values returned by that call.
|
| + *
|
| + * On SQLITE_OK, *ppBase points to nRequestBytes of data at
|
| + * iRequestOffset within the record. If the data exists contiguously
|
| + * in a page, a direct pointer is returned, otherwise a buffer from
|
| + * sqlite3_malloc() is returned with the data. *pbFree is set true if
|
| + * sqlite3_free() should be called on *ppBase.
|
| + */
|
| +/* Operation of this function is subtle. At any time, pPage is the
|
| + * current page, with iRecordOffset and nLocalRecordBytes being record
|
| + * data within pPage, and pOverflow being the overflow page after
|
| + * pPage. This allows the code to handle both the initial leaf page
|
| + * and overflow pages consistently by adjusting the values
|
| + * appropriately.
|
| + */
|
| +static int overflowGetSegment(DbPage *pPage, unsigned iRecordOffset,
|
| + unsigned nLocalRecordBytes,
|
| + RecoverOverflow *pOverflow,
|
| + unsigned iRequestOffset, unsigned nRequestBytes,
|
| + unsigned char **ppBase, int *pbFree){
|
| + unsigned nBase; /* Amount of data currently collected. */
|
| + unsigned char *pBase; /* Buffer to collect record data into. */
|
| +
|
| + /* Skip to the page containing the start of the data. */
|
| + while( iRequestOffset>=nLocalRecordBytes && pOverflow ){
|
| + /* Factor out current page's contribution. */
|
| + iRequestOffset -= nLocalRecordBytes;
|
| +
|
| + /* Move forward to the next page in the list. */
|
| + pPage = pOverflow->pPage;
|
| + iRecordOffset = 4;
|
| + nLocalRecordBytes = pOverflow->nPageSize - iRecordOffset;
|
| + pOverflow = pOverflow->pNextOverflow;
|
| + }
|
| +
|
| + /* If the requested data is entirely within this page, return a
|
| + * pointer into the page.
|
| + */
|
| + if( iRequestOffset+nRequestBytes<=nLocalRecordBytes ){
|
| + /* TODO(shess): "assignment discards qualifiers from pointer target type"
|
| + * Having ppBase be const makes sense, but sqlite3_free() takes non-const.
|
| + */
|
| + *ppBase = (unsigned char *)PageData(pPage, iRecordOffset + iRequestOffset);
|
| + *pbFree = 0;
|
| + return SQLITE_OK;
|
| + }
|
| +
|
| + /* The data range would require additional pages. */
|
| + if( !pOverflow ){
|
| + /* Should never happen, the range is outside the nRecordBytes
|
| + * passed to overflowMaybeCreate().
|
| + */
|
| + assert(NULL); /* NOTREACHED */
|
| + return SQLITE_ERROR;
|
| + }
|
| +
|
| + /* Get a buffer to construct into. */
|
| + nBase = 0;
|
| + pBase = sqlite3_malloc(nRequestBytes);
|
| + if( !pBase ){
|
| + return SQLITE_NOMEM;
|
| + }
|
| + while( nBase<nRequestBytes ){
|
| + /* Copy over data present on this page. */
|
| + unsigned nCopyBytes = nRequestBytes - nBase;
|
| + if( nLocalRecordBytes-iRequestOffset<nCopyBytes ){
|
| + nCopyBytes = nLocalRecordBytes - iRequestOffset;
|
| + }
|
| + memcpy(pBase + nBase, PageData(pPage, iRecordOffset + iRequestOffset),
|
| + nCopyBytes);
|
| + nBase += nCopyBytes;
|
| +
|
| + if( pOverflow ){
|
| + /* Copy from start of record data in future pages. */
|
| + iRequestOffset = 0;
|
| +
|
| + /* Move forward to the next page in the list. Should match
|
| + * first while() loop.
|
| + */
|
| + pPage = pOverflow->pPage;
|
| + iRecordOffset = 4;
|
| + nLocalRecordBytes = pOverflow->nPageSize - iRecordOffset;
|
| + pOverflow = pOverflow->pNextOverflow;
|
| + }else if( nBase<nRequestBytes ){
|
| + /* Ran out of overflow pages with data left to deliver. Not
|
| + * possible if the requested range fits within nRecordBytes
|
| + * passed to overflowMaybeCreate() when creating pOverflow.
|
| + */
|
| + assert(NULL); /* NOTREACHED */
|
| + sqlite3_free(pBase);
|
| + return SQLITE_ERROR;
|
| + }
|
| + }
|
| + assert( nBase==nRequestBytes );
|
| + *ppBase = pBase;
|
| + *pbFree = 1;
|
| + return SQLITE_OK;
|
| +}
|
| +
|
| +/* Primary structure for iterating the contents of a table.
|
| + *
|
| + * leafCursorDestroy - release all resources associated with the cursor.
|
| + * leafCursorCreate - create a cursor to iterate items from tree at
|
| + * the provided root page.
|
| + * leafCursorNextValidCell - get the cursor ready to access data from
|
| + * the next valid cell in the table.
|
| + * leafCursorCellRowid - get the current cell's rowid.
|
| + * leafCursorCellColumns - get current cell's column count.
|
| + * leafCursorCellColInfo - get type and data for a column in current cell.
|
| + *
|
| + * leafCursorNextValidCell skips cells which fail simple integrity
|
| + * checks, such as overlapping other cells, or being located at
|
| + * impossible offsets, or where header data doesn't correctly describe
|
| + * payload data. Returns SQLITE_ROW if a valid cell is found,
|
| + * SQLITE_DONE if all pages in the tree were exhausted.
|
| + *
|
| + * leafCursorCellColInfo() accounts for overflow pages in the style of
|
| + * overflowGetSegment().
|
| + */
|
| +typedef struct RecoverLeafCursor RecoverLeafCursor;
|
| +struct RecoverLeafCursor {
|
| + RecoverInteriorCursor *pParent; /* Parent node to this node. */
|
| + DbPage *pPage; /* Reference to leaf page. */
|
| + unsigned nPageSize; /* Size of pPage. */
|
| + unsigned nCells; /* Number of cells in pPage. */
|
| + unsigned iCell; /* Current cell. */
|
| +
|
| + /* Info parsed from data in iCell. */
|
| + i64 iRowid; /* rowid parsed. */
|
| + unsigned nRecordCols; /* how many items in the record. */
|
| + u64 iRecordOffset; /* offset to record data. */
|
| + /* TODO(shess): nRecordBytes and nRecordHeaderBytes are used in
|
| + * leafCursorCellColInfo() to prevent buffer overruns.
|
| + * leafCursorCellDecode() already verified that the cell is valid, so
|
| + * those checks should be redundant.
|
| + */
|
| + u64 nRecordBytes; /* Size of record data. */
|
| + unsigned nLocalRecordBytes; /* Amount of record data in-page. */
|
| + unsigned nRecordHeaderBytes; /* Size of record header data. */
|
| + unsigned char *pRecordHeader; /* Pointer to record header data. */
|
| + int bFreeRecordHeader; /* True if record header requires free. */
|
| + RecoverOverflow *pOverflow; /* Cell overflow info, if needed. */
|
| +};
|
| +
|
| +/* Internal helper shared between next-page and create-cursor. If
|
| + * pPage is a leaf page, it will be stored in the cursor and state
|
| + * initialized for reading cells.
|
| + *
|
| + * If pPage is an interior page, a new parent cursor is created and
|
| + * injected on the stack. This is necessary to handle trees with
|
| + * uneven depth, but also is used during initial setup.
|
| + *
|
| + * If pPage is not a table page at all, it is discarded.
|
| + *
|
| + * If SQLITE_OK is returned, the caller no longer owns pPage,
|
| + * otherwise the caller is responsible for discarding it.
|
| + */
|
| +static int leafCursorLoadPage(RecoverLeafCursor *pCursor, DbPage *pPage){
|
| + const unsigned char *pPageHeader; /* Header of *pPage */
|
| +
|
| + /* Release the current page. */
|
| + if( pCursor->pPage ){
|
| + sqlite3PagerUnref(pCursor->pPage);
|
| + pCursor->pPage = NULL;
|
| + pCursor->iCell = pCursor->nCells = 0;
|
| + }
|
| +
|
| + /* If the page is an unexpected interior node, inject a new stack
|
| + * layer and try again from there.
|
| + */
|
| + pPageHeader = PageHeader(pPage);
|
| + if( pPageHeader[kiPageTypeOffset]==kTableInteriorPage ){
|
| + RecoverInteriorCursor *pParent;
|
| + int rc = interiorCursorCreate(pCursor->pParent, pPage, pCursor->nPageSize,
|
| + &pParent);
|
| + if( rc!=SQLITE_OK ){
|
| + return rc;
|
| + }
|
| + pCursor->pParent = pParent;
|
| + return SQLITE_OK;
|
| + }
|
| +
|
| + /* Not a leaf page, skip it. */
|
| + if( pPageHeader[kiPageTypeOffset]!=kTableLeafPage ){
|
| + sqlite3PagerUnref(pPage);
|
| + return SQLITE_OK;
|
| + }
|
| +
|
| + /* Take ownership of the page and start decoding. */
|
| + pCursor->pPage = pPage;
|
| + pCursor->iCell = 0;
|
| + pCursor->nCells = decodeUnsigned16(pPageHeader + kiPageCellCountOffset);
|
| + return SQLITE_OK;
|
| +}
|
| +
|
| +/* Get the next leaf-level page in the tree. Returns SQLITE_ROW when
|
| + * a leaf page is found, SQLITE_DONE when no more leaves exist, or any
|
| + * error which occurred.
|
| + */
|
| +static int leafCursorNextPage(RecoverLeafCursor *pCursor){
|
| + if( !pCursor->pParent ){
|
| + return SQLITE_DONE;
|
| + }
|
| +
|
| + /* Repeatedly load the parent's next child page until a leaf is found. */
|
| + do {
|
| + DbPage *pNextPage;
|
| + int rc = interiorCursorNextPage(&pCursor->pParent, &pNextPage);
|
| + if( rc!=SQLITE_ROW ){
|
| + assert( rc==SQLITE_DONE );
|
| + return rc;
|
| + }
|
| +
|
| + rc = leafCursorLoadPage(pCursor, pNextPage);
|
| + if( rc!=SQLITE_OK ){
|
| + sqlite3PagerUnref(pNextPage);
|
| + return rc;
|
| + }
|
| + } while( !pCursor->pPage );
|
| +
|
| + return SQLITE_ROW;
|
| +}
|
| +
|
| +static void leafCursorDestroyCellData(RecoverLeafCursor *pCursor){
|
| + if( pCursor->bFreeRecordHeader ){
|
| + sqlite3_free(pCursor->pRecordHeader);
|
| + }
|
| + pCursor->bFreeRecordHeader = 0;
|
| + pCursor->pRecordHeader = NULL;
|
| +
|
| + if( pCursor->pOverflow ){
|
| + overflowDestroy(pCursor->pOverflow);
|
| + pCursor->pOverflow = NULL;
|
| + }
|
| +}
|
| +
|
| +static void leafCursorDestroy(RecoverLeafCursor *pCursor){
|
| + leafCursorDestroyCellData(pCursor);
|
| +
|
| + if( pCursor->pParent ){
|
| + interiorCursorDestroy(pCursor->pParent);
|
| + pCursor->pParent = NULL;
|
| + }
|
| +
|
| + if( pCursor->pPage ){
|
| + sqlite3PagerUnref(pCursor->pPage);
|
| + pCursor->pPage = NULL;
|
| + }
|
| +
|
| + memset(pCursor, 0xA5, sizeof(*pCursor));
|
| + sqlite3_free(pCursor);
|
| +}
|
| +
|
| +/* Create a cursor to iterate the rows from the leaf pages of a table
|
| + * rooted at iRootPage.
|
| + */
|
| +/* TODO(shess): recoverOpen() calls this to setup the cursor, and I
|
| + * think that recoverFilter() may make a hard assumption that the
|
| + * cursor returned will turn up at least one valid cell.
|
| + *
|
| + * The cases I can think of which break this assumption are:
|
| + * - pPage is a valid leaf page with no valid cells.
|
| + * - pPage is a valid interior page with no valid leaves.
|
| + * - pPage is a valid interior page who's leaves contain no valid cells.
|
| + * - pPage is not a valid leaf or interior page.
|
| + */
|
| +static int leafCursorCreate(Pager *pPager, unsigned nPageSize,
|
| + u32 iRootPage, RecoverLeafCursor **ppCursor){
|
| + DbPage *pPage; /* Reference to page at iRootPage. */
|
| + RecoverLeafCursor *pCursor; /* Leaf cursor being constructed. */
|
| + int rc;
|
| +
|
| + /* Start out with the root page. */
|
| + rc = sqlite3PagerGet(pPager, iRootPage, &pPage, 0);
|
| + if( rc!=SQLITE_OK ){
|
| + return rc;
|
| + }
|
| +
|
| + pCursor = sqlite3_malloc(sizeof(RecoverLeafCursor));
|
| + if( !pCursor ){
|
| + sqlite3PagerUnref(pPage);
|
| + return SQLITE_NOMEM;
|
| + }
|
| + memset(pCursor, 0, sizeof(*pCursor));
|
| +
|
| + pCursor->nPageSize = nPageSize;
|
| +
|
| + rc = leafCursorLoadPage(pCursor, pPage);
|
| + if( rc!=SQLITE_OK ){
|
| + sqlite3PagerUnref(pPage);
|
| + leafCursorDestroy(pCursor);
|
| + return rc;
|
| + }
|
| +
|
| + /* pPage wasn't a leaf page, find the next leaf page. */
|
| + if( !pCursor->pPage ){
|
| + rc = leafCursorNextPage(pCursor);
|
| + if( rc!=SQLITE_DONE && rc!=SQLITE_ROW ){
|
| + leafCursorDestroy(pCursor);
|
| + return rc;
|
| + }
|
| + }
|
| +
|
| + *ppCursor = pCursor;
|
| + return SQLITE_OK;
|
| +}
|
| +
|
| +/* Useful for setting breakpoints. */
|
| +static int ValidateError(){
|
| + return SQLITE_ERROR;
|
| +}
|
| +
|
| +/* Setup the cursor for reading the information from cell iCell. */
|
| +static int leafCursorCellDecode(RecoverLeafCursor *pCursor){
|
| + const unsigned char *pPageHeader; /* Header of current page. */
|
| + const unsigned char *pPageEnd; /* Byte after end of current page. */
|
| + const unsigned char *pCellOffsets; /* Pointer to page's cell offsets. */
|
| + unsigned iCellOffset; /* Offset of current cell (iCell). */
|
| + const unsigned char *pCell; /* Pointer to data at iCellOffset. */
|
| + unsigned nCellMaxBytes; /* Maximum local size of iCell. */
|
| + unsigned iEndOffset; /* End of iCell's in-page data. */
|
| + u64 nRecordBytes; /* Expected size of cell, w/overflow. */
|
| + u64 iRowid; /* iCell's rowid (in table). */
|
| + unsigned nRead; /* Amount of cell read. */
|
| + unsigned nRecordHeaderRead; /* Header data read. */
|
| + u64 nRecordHeaderBytes; /* Header size expected. */
|
| + unsigned nRecordCols; /* Columns read from header. */
|
| + u64 nRecordColBytes; /* Bytes in payload for those columns. */
|
| + unsigned i;
|
| + int rc;
|
| +
|
| + assert( pCursor->iCell<pCursor->nCells );
|
| +
|
| + leafCursorDestroyCellData(pCursor);
|
| +
|
| + /* Find the offset to the row. */
|
| + pPageHeader = PageHeader(pCursor->pPage);
|
| + pCellOffsets = pPageHeader + knPageLeafHeaderBytes;
|
| + pPageEnd = PageData(pCursor->pPage, pCursor->nPageSize);
|
| + if( pCellOffsets + pCursor->iCell*2 + 2 > pPageEnd ){
|
| + return ValidateError();
|
| + }
|
| + iCellOffset = decodeUnsigned16(pCellOffsets + pCursor->iCell*2);
|
| + if( iCellOffset>=pCursor->nPageSize ){
|
| + return ValidateError();
|
| + }
|
| +
|
| + pCell = PageData(pCursor->pPage, iCellOffset);
|
| + nCellMaxBytes = pCursor->nPageSize - iCellOffset;
|
| +
|
| + /* B-tree leaf cells lead with varint record size, varint rowid and
|
| + * varint header size.
|
| + */
|
| + /* TODO(shess): The smallest page size is 512 bytes, which has an m
|
| + * of 39. Three varints need at most 27 bytes to encode. I think.
|
| + */
|
| + if( !checkVarints(pCell, nCellMaxBytes, 3) ){
|
| + return ValidateError();
|
| + }
|
| +
|
| + nRead = getVarint(pCell, &nRecordBytes);
|
| + assert( iCellOffset+nRead<=pCursor->nPageSize );
|
| + pCursor->nRecordBytes = nRecordBytes;
|
| +
|
| + nRead += getVarint(pCell + nRead, &iRowid);
|
| + assert( iCellOffset+nRead<=pCursor->nPageSize );
|
| + pCursor->iRowid = (i64)iRowid;
|
| +
|
| + pCursor->iRecordOffset = iCellOffset + nRead;
|
| +
|
| + /* Start overflow setup here because nLocalRecordBytes is needed to
|
| + * check cell overlap.
|
| + */
|
| + rc = overflowMaybeCreate(pCursor->pPage, pCursor->nPageSize,
|
| + pCursor->iRecordOffset, pCursor->nRecordBytes,
|
| + &pCursor->nLocalRecordBytes,
|
| + &pCursor->pOverflow);
|
| + if( rc!=SQLITE_OK ){
|
| + return ValidateError();
|
| + }
|
| +
|
| + /* Check that no other cell starts within this cell. */
|
| + iEndOffset = pCursor->iRecordOffset + pCursor->nLocalRecordBytes;
|
| + for( i=0; i<pCursor->nCells && pCellOffsets + i*2 + 2 <= pPageEnd; ++i ){
|
| + const unsigned iOtherOffset = decodeUnsigned16(pCellOffsets + i*2);
|
| + if( iOtherOffset>iCellOffset && iOtherOffset<iEndOffset ){
|
| + return ValidateError();
|
| + }
|
| + }
|
| +
|
| + nRecordHeaderRead = getVarint(pCell + nRead, &nRecordHeaderBytes);
|
| + assert( nRecordHeaderBytes<=nRecordBytes );
|
| + pCursor->nRecordHeaderBytes = nRecordHeaderBytes;
|
| +
|
| + /* Large headers could overflow if pages are small. */
|
| + rc = overflowGetSegment(pCursor->pPage,
|
| + pCursor->iRecordOffset, pCursor->nLocalRecordBytes,
|
| + pCursor->pOverflow, 0, nRecordHeaderBytes,
|
| + &pCursor->pRecordHeader, &pCursor->bFreeRecordHeader);
|
| + if( rc!=SQLITE_OK ){
|
| + return ValidateError();
|
| + }
|
| +
|
| + /* Tally up the column count and size of data. */
|
| + nRecordCols = 0;
|
| + nRecordColBytes = 0;
|
| + while( nRecordHeaderRead<nRecordHeaderBytes ){
|
| + u64 iSerialType; /* Type descriptor for current column. */
|
| + if( !checkVarint(pCursor->pRecordHeader + nRecordHeaderRead,
|
| + nRecordHeaderBytes - nRecordHeaderRead) ){
|
| + return ValidateError();
|
| + }
|
| + nRecordHeaderRead += getVarint(pCursor->pRecordHeader + nRecordHeaderRead,
|
| + &iSerialType);
|
| + if( iSerialType==10 || iSerialType==11 ){
|
| + return ValidateError();
|
| + }
|
| + nRecordColBytes += SerialTypeLength(iSerialType);
|
| + nRecordCols++;
|
| + }
|
| + pCursor->nRecordCols = nRecordCols;
|
| +
|
| + /* Parsing the header used as many bytes as expected. */
|
| + if( nRecordHeaderRead!=nRecordHeaderBytes ){
|
| + return ValidateError();
|
| + }
|
| +
|
| + /* Calculated record is size of expected record. */
|
| + if( nRecordHeaderBytes+nRecordColBytes!=nRecordBytes ){
|
| + return ValidateError();
|
| + }
|
| +
|
| + return SQLITE_OK;
|
| +}
|
| +
|
| +static i64 leafCursorCellRowid(RecoverLeafCursor *pCursor){
|
| + return pCursor->iRowid;
|
| +}
|
| +
|
| +static unsigned leafCursorCellColumns(RecoverLeafCursor *pCursor){
|
| + return pCursor->nRecordCols;
|
| +}
|
| +
|
| +/* Get the column info for the cell. Pass NULL for ppBase to prevent
|
| + * retrieving the data segment. If *pbFree is true, *ppBase must be
|
| + * freed by the caller using sqlite3_free().
|
| + */
|
| +static int leafCursorCellColInfo(RecoverLeafCursor *pCursor,
|
| + unsigned iCol, u64 *piColType,
|
| + unsigned char **ppBase, int *pbFree){
|
| + const unsigned char *pRecordHeader; /* Current cell's header. */
|
| + u64 nRecordHeaderBytes; /* Bytes in pRecordHeader. */
|
| + unsigned nRead; /* Bytes read from header. */
|
| + u64 iColEndOffset; /* Offset to end of column in cell. */
|
| + unsigned nColsSkipped; /* Count columns as procesed. */
|
| + u64 iSerialType; /* Type descriptor for current column. */
|
| +
|
| + /* Implicit NULL for columns past the end. This case happens when
|
| + * rows have not been updated since an ALTER TABLE added columns.
|
| + * It is more convenient to address here than in callers.
|
| + */
|
| + if( iCol>=pCursor->nRecordCols ){
|
| + *piColType = 0;
|
| + if( ppBase ){
|
| + *ppBase = 0;
|
| + *pbFree = 0;
|
| + }
|
| + return SQLITE_OK;
|
| + }
|
| +
|
| + /* Must be able to decode header size. */
|
| + pRecordHeader = pCursor->pRecordHeader;
|
| + if( !checkVarint(pRecordHeader, pCursor->nRecordHeaderBytes) ){
|
| + return SQLITE_CORRUPT;
|
| + }
|
| +
|
| + /* Rather than caching the header size and how many bytes it took,
|
| + * decode it every time.
|
| + */
|
| + nRead = getVarint(pRecordHeader, &nRecordHeaderBytes);
|
| + assert( nRecordHeaderBytes==pCursor->nRecordHeaderBytes );
|
| +
|
| + /* Scan forward to the indicated column. Scans to _after_ column
|
| + * for later range checking.
|
| + */
|
| + /* TODO(shess): This could get expensive for very wide tables. An
|
| + * array of iSerialType could be built in leafCursorCellDecode(), but
|
| + * the number of columns is dynamic per row, so it would add memory
|
| + * management complexity. Enough info to efficiently forward
|
| + * iterate could be kept, if all clients forward iterate
|
| + * (recoverColumn() may not).
|
| + */
|
| + iColEndOffset = 0;
|
| + nColsSkipped = 0;
|
| + while( nColsSkipped<=iCol && nRead<nRecordHeaderBytes ){
|
| + if( !checkVarint(pRecordHeader + nRead, nRecordHeaderBytes - nRead) ){
|
| + return SQLITE_CORRUPT;
|
| + }
|
| + nRead += getVarint(pRecordHeader + nRead, &iSerialType);
|
| + iColEndOffset += SerialTypeLength(iSerialType);
|
| + nColsSkipped++;
|
| + }
|
| +
|
| + /* Column's data extends past record's end. */
|
| + if( nRecordHeaderBytes+iColEndOffset>pCursor->nRecordBytes ){
|
| + return SQLITE_CORRUPT;
|
| + }
|
| +
|
| + *piColType = iSerialType;
|
| + if( ppBase ){
|
| + const u32 nColBytes = SerialTypeLength(iSerialType);
|
| +
|
| + /* Offset from start of record to beginning of column. */
|
| + const unsigned iColOffset = nRecordHeaderBytes+iColEndOffset-nColBytes;
|
| +
|
| + return overflowGetSegment(pCursor->pPage, pCursor->iRecordOffset,
|
| + pCursor->nLocalRecordBytes, pCursor->pOverflow,
|
| + iColOffset, nColBytes, ppBase, pbFree);
|
| + }
|
| + return SQLITE_OK;
|
| +}
|
| +
|
| +static int leafCursorNextValidCell(RecoverLeafCursor *pCursor){
|
| + while( 1 ){
|
| + int rc;
|
| +
|
| + /* Move to the next cell. */
|
| + pCursor->iCell++;
|
| +
|
| + /* No more cells, get the next leaf. */
|
| + if( pCursor->iCell>=pCursor->nCells ){
|
| + rc = leafCursorNextPage(pCursor);
|
| + if( rc!=SQLITE_ROW ){
|
| + return rc;
|
| + }
|
| + assert( pCursor->iCell==0 );
|
| + }
|
| +
|
| + /* If the cell is valid, indicate that a row is available. */
|
| + rc = leafCursorCellDecode(pCursor);
|
| + if( rc==SQLITE_OK ){
|
| + return SQLITE_ROW;
|
| + }
|
| +
|
| + /* Iterate until done or a valid row is found. */
|
| + /* TODO(shess): Remove debugging output. */
|
| + fprintf(stderr, "Skipping invalid cell\n");
|
| + }
|
| + return SQLITE_ERROR;
|
| +}
|
| +
|
| +typedef struct Recover Recover;
|
| +struct Recover {
|
| + sqlite3_vtab base;
|
| + sqlite3 *db; /* Host database connection */
|
| + char *zDb; /* Database containing target table */
|
| + char *zTable; /* Target table */
|
| + unsigned nCols; /* Number of columns in target table */
|
| + unsigned char *pTypes; /* Types of columns in target table */
|
| +};
|
| +
|
| +/* Internal helper for deleting the module. */
|
| +static void recoverRelease(Recover *pRecover){
|
| + sqlite3_free(pRecover->zDb);
|
| + sqlite3_free(pRecover->zTable);
|
| + sqlite3_free(pRecover->pTypes);
|
| + memset(pRecover, 0xA5, sizeof(*pRecover));
|
| + sqlite3_free(pRecover);
|
| +}
|
| +
|
| +/* Helper function for initializing the module. Forward-declared so
|
| + * recoverCreate() and recoverConnect() can see it.
|
| + */
|
| +static int recoverInit(
|
| + sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **
|
| +);
|
| +
|
| +static int recoverCreate(
|
| + sqlite3 *db,
|
| + void *pAux,
|
| + int argc, const char *const*argv,
|
| + sqlite3_vtab **ppVtab,
|
| + char **pzErr
|
| +){
|
| + FNENTRY();
|
| + return recoverInit(db, pAux, argc, argv, ppVtab, pzErr);
|
| +}
|
| +
|
| +/* This should never be called. */
|
| +static int recoverConnect(
|
| + sqlite3 *db,
|
| + void *pAux,
|
| + int argc, const char *const*argv,
|
| + sqlite3_vtab **ppVtab,
|
| + char **pzErr
|
| +){
|
| + FNENTRY();
|
| + return recoverInit(db, pAux, argc, argv, ppVtab, pzErr);
|
| +}
|
| +
|
| +/* No indices supported. */
|
| +static int recoverBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
|
| + FNENTRY();
|
| + return SQLITE_OK;
|
| +}
|
| +
|
| +/* Logically, this should never be called. */
|
| +static int recoverDisconnect(sqlite3_vtab *pVtab){
|
| + FNENTRY();
|
| + recoverRelease((Recover*)pVtab);
|
| + return SQLITE_OK;
|
| +}
|
| +
|
| +static int recoverDestroy(sqlite3_vtab *pVtab){
|
| + FNENTRY();
|
| + recoverRelease((Recover*)pVtab);
|
| + return SQLITE_OK;
|
| +}
|
| +
|
| +typedef struct RecoverCursor RecoverCursor;
|
| +struct RecoverCursor {
|
| + sqlite3_vtab_cursor base;
|
| + RecoverLeafCursor *pLeafCursor;
|
| + int iEncoding;
|
| + int bEOF;
|
| +};
|
| +
|
| +static int recoverOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
|
| + Recover *pRecover = (Recover*)pVTab;
|
| + u32 iRootPage; /* Root page of the backing table. */
|
| + int iEncoding; /* UTF encoding for backing database. */
|
| + unsigned nPageSize; /* Size of pages in backing database. */
|
| + Pager *pPager; /* Backing database pager. */
|
| + RecoverLeafCursor *pLeafCursor; /* Cursor to read table's leaf pages. */
|
| + RecoverCursor *pCursor; /* Cursor to read rows from leaves. */
|
| + int rc;
|
| +
|
| + FNENTRY();
|
| +
|
| + iRootPage = 0;
|
| + rc = getRootPage(pRecover->db, pRecover->zDb, pRecover->zTable,
|
| + &iRootPage);
|
| + if( rc!=SQLITE_OK ){
|
| + return rc;
|
| + }
|
| +
|
| + iEncoding = 0;
|
| + rc = getEncoding(pRecover->db, pRecover->zDb, &iEncoding);
|
| + if( rc!=SQLITE_OK ){
|
| + return rc;
|
| + }
|
| +
|
| + rc = GetPager(pRecover->db, pRecover->zDb, &pPager, &nPageSize);
|
| + if( rc!=SQLITE_OK ){
|
| + return rc;
|
| + }
|
| +
|
| + rc = leafCursorCreate(pPager, nPageSize, iRootPage, &pLeafCursor);
|
| + if( rc!=SQLITE_OK ){
|
| + return rc;
|
| + }
|
| +
|
| + pCursor = sqlite3_malloc(sizeof(RecoverCursor));
|
| + if( !pCursor ){
|
| + leafCursorDestroy(pLeafCursor);
|
| + return SQLITE_NOMEM;
|
| + }
|
| + memset(pCursor, 0, sizeof(*pCursor));
|
| + pCursor->base.pVtab = pVTab;
|
| + pCursor->pLeafCursor = pLeafCursor;
|
| + pCursor->iEncoding = iEncoding;
|
| +
|
| + /* If no leaf pages were found, empty result set. */
|
| + /* TODO(shess): leafCursorNextValidCell() would return SQLITE_ROW or
|
| + * SQLITE_DONE to indicate whether there is further data to consider.
|
| + */
|
| + pCursor->bEOF = (pLeafCursor->pPage==NULL);
|
| +
|
| + *ppCursor = (sqlite3_vtab_cursor*)pCursor;
|
| + return SQLITE_OK;
|
| +}
|
| +
|
| +static int recoverClose(sqlite3_vtab_cursor *cur){
|
| + RecoverCursor *pCursor = (RecoverCursor*)cur;
|
| + FNENTRY();
|
| + if( pCursor->pLeafCursor ){
|
| + leafCursorDestroy(pCursor->pLeafCursor);
|
| + pCursor->pLeafCursor = NULL;
|
| + }
|
| + memset(pCursor, 0xA5, sizeof(*pCursor));
|
| + sqlite3_free(cur);
|
| + return SQLITE_OK;
|
| +}
|
| +
|
| +/* Helpful place to set a breakpoint. */
|
| +static int RecoverInvalidCell(){
|
| + return SQLITE_ERROR;
|
| +}
|
| +
|
| +/* Returns SQLITE_OK if the cell has an appropriate number of columns
|
| + * with the appropriate types of data.
|
| + */
|
| +static int recoverValidateLeafCell(Recover *pRecover, RecoverCursor *pCursor){
|
| + unsigned i;
|
| +
|
| + /* If the row's storage has too many columns, skip it. */
|
| + if( leafCursorCellColumns(pCursor->pLeafCursor)>pRecover->nCols ){
|
| + return RecoverInvalidCell();
|
| + }
|
| +
|
| + /* Skip rows with unexpected types. */
|
| + for( i=0; i<pRecover->nCols; ++i ){
|
| + u64 iType; /* Storage type of column i. */
|
| + int rc;
|
| +
|
| + /* ROWID alias. */
|
| + if( (pRecover->pTypes[i]&MASK_ROWID) ){
|
| + continue;
|
| + }
|
| +
|
| + rc = leafCursorCellColInfo(pCursor->pLeafCursor, i, &iType, NULL, NULL);
|
| + assert( rc==SQLITE_OK );
|
| + if( rc!=SQLITE_OK || !SerialTypeIsCompatible(iType, pRecover->pTypes[i]) ){
|
| + return RecoverInvalidCell();
|
| + }
|
| + }
|
| +
|
| + return SQLITE_OK;
|
| +}
|
| +
|
| +static int recoverNext(sqlite3_vtab_cursor *pVtabCursor){
|
| + RecoverCursor *pCursor = (RecoverCursor*)pVtabCursor;
|
| + Recover *pRecover = (Recover*)pCursor->base.pVtab;
|
| + int rc;
|
| +
|
| + FNENTRY();
|
| +
|
| + /* Scan forward to the next cell with valid storage, then check that
|
| + * the stored data matches the schema.
|
| + */
|
| + while( (rc = leafCursorNextValidCell(pCursor->pLeafCursor))==SQLITE_ROW ){
|
| + if( recoverValidateLeafCell(pRecover, pCursor)==SQLITE_OK ){
|
| + return SQLITE_OK;
|
| + }
|
| + }
|
| +
|
| + if( rc==SQLITE_DONE ){
|
| + pCursor->bEOF = 1;
|
| + return SQLITE_OK;
|
| + }
|
| +
|
| + assert( rc!=SQLITE_OK );
|
| + return rc;
|
| +}
|
| +
|
| +static int recoverFilter(
|
| + sqlite3_vtab_cursor *pVtabCursor,
|
| + int idxNum, const char *idxStr,
|
| + int argc, sqlite3_value **argv
|
| +){
|
| + RecoverCursor *pCursor = (RecoverCursor*)pVtabCursor;
|
| + Recover *pRecover = (Recover*)pCursor->base.pVtab;
|
| + int rc;
|
| +
|
| + FNENTRY();
|
| +
|
| + /* There were no valid leaf pages in the table. */
|
| + if( pCursor->bEOF ){
|
| + return SQLITE_OK;
|
| + }
|
| +
|
| + /* Load the first cell, and iterate forward if it's not valid. If no cells at
|
| + * all are valid, recoverNext() sets bEOF and returns appropriately.
|
| + */
|
| + rc = leafCursorCellDecode(pCursor->pLeafCursor);
|
| + if( rc!=SQLITE_OK || recoverValidateLeafCell(pRecover, pCursor)!=SQLITE_OK ){
|
| + return recoverNext(pVtabCursor);
|
| + }
|
| +
|
| + return SQLITE_OK;
|
| +}
|
| +
|
| +static int recoverEof(sqlite3_vtab_cursor *pVtabCursor){
|
| + RecoverCursor *pCursor = (RecoverCursor*)pVtabCursor;
|
| + FNENTRY();
|
| + return pCursor->bEOF;
|
| +}
|
| +
|
| +static int recoverColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
|
| + RecoverCursor *pCursor = (RecoverCursor*)cur;
|
| + Recover *pRecover = (Recover*)pCursor->base.pVtab;
|
| + u64 iColType; /* Storage type of column i. */
|
| + unsigned char *pColData; /* Column i's data. */
|
| + int shouldFree; /* Non-zero if pColData should be freed. */
|
| + int rc;
|
| +
|
| + FNENTRY();
|
| +
|
| + if( (unsigned)i>=pRecover->nCols ){
|
| + return SQLITE_ERROR;
|
| + }
|
| +
|
| + /* ROWID alias. */
|
| + if( (pRecover->pTypes[i]&MASK_ROWID) ){
|
| + sqlite3_result_int64(ctx, leafCursorCellRowid(pCursor->pLeafCursor));
|
| + return SQLITE_OK;
|
| + }
|
| +
|
| + pColData = NULL;
|
| + shouldFree = 0;
|
| + rc = leafCursorCellColInfo(pCursor->pLeafCursor, i, &iColType,
|
| + &pColData, &shouldFree);
|
| + if( rc!=SQLITE_OK ){
|
| + return rc;
|
| + }
|
| + /* recoverValidateLeafCell() should guarantee that this will never
|
| + * occur.
|
| + */
|
| + if( !SerialTypeIsCompatible(iColType, pRecover->pTypes[i]) ){
|
| + if( shouldFree ){
|
| + sqlite3_free(pColData);
|
| + }
|
| + return SQLITE_ERROR;
|
| + }
|
| +
|
| + switch( iColType ){
|
| + case 0 : sqlite3_result_null(ctx); break;
|
| + case 1 : sqlite3_result_int64(ctx, decodeSigned(pColData, 1)); break;
|
| + case 2 : sqlite3_result_int64(ctx, decodeSigned(pColData, 2)); break;
|
| + case 3 : sqlite3_result_int64(ctx, decodeSigned(pColData, 3)); break;
|
| + case 4 : sqlite3_result_int64(ctx, decodeSigned(pColData, 4)); break;
|
| + case 5 : sqlite3_result_int64(ctx, decodeSigned(pColData, 6)); break;
|
| + case 6 : sqlite3_result_int64(ctx, decodeSigned(pColData, 8)); break;
|
| + case 7 : sqlite3_result_double(ctx, decodeFloat64(pColData)); break;
|
| + case 8 : sqlite3_result_int(ctx, 0); break;
|
| + case 9 : sqlite3_result_int(ctx, 1); break;
|
| + case 10 : assert( iColType!=10 ); break;
|
| + case 11 : assert( iColType!=11 ); break;
|
| +
|
| + default : {
|
| + u32 l = SerialTypeLength(iColType);
|
| +
|
| + /* If pColData was already allocated, arrange to pass ownership. */
|
| + sqlite3_destructor_type pFn = SQLITE_TRANSIENT;
|
| + if( shouldFree ){
|
| + pFn = sqlite3_free;
|
| + shouldFree = 0;
|
| + }
|
| +
|
| + if( SerialTypeIsBlob(iColType) ){
|
| + sqlite3_result_blob(ctx, pColData, l, pFn);
|
| + }else{
|
| + if( pCursor->iEncoding==SQLITE_UTF16LE ){
|
| + sqlite3_result_text16le(ctx, (const void*)pColData, l, pFn);
|
| + }else if( pCursor->iEncoding==SQLITE_UTF16BE ){
|
| + sqlite3_result_text16be(ctx, (const void*)pColData, l, pFn);
|
| + }else{
|
| + sqlite3_result_text(ctx, (const char*)pColData, l, pFn);
|
| + }
|
| + }
|
| + } break;
|
| + }
|
| + if( shouldFree ){
|
| + sqlite3_free(pColData);
|
| + }
|
| + return SQLITE_OK;
|
| +}
|
| +
|
| +static int recoverRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
|
| + RecoverCursor *pCursor = (RecoverCursor*)pVtabCursor;
|
| + FNENTRY();
|
| + *pRowid = leafCursorCellRowid(pCursor->pLeafCursor);
|
| + return SQLITE_OK;
|
| +}
|
| +
|
| +static sqlite3_module recoverModule = {
|
| + 0, /* iVersion */
|
| + recoverCreate, /* xCreate - create a table */
|
| + recoverConnect, /* xConnect - connect to an existing table */
|
| + recoverBestIndex, /* xBestIndex - Determine search strategy */
|
| + recoverDisconnect, /* xDisconnect - Disconnect from a table */
|
| + recoverDestroy, /* xDestroy - Drop a table */
|
| + recoverOpen, /* xOpen - open a cursor */
|
| + recoverClose, /* xClose - close a cursor */
|
| + recoverFilter, /* xFilter - configure scan constraints */
|
| + recoverNext, /* xNext - advance a cursor */
|
| + recoverEof, /* xEof */
|
| + recoverColumn, /* xColumn - read data */
|
| + recoverRowid, /* xRowid - read data */
|
| + 0, /* xUpdate - write data */
|
| + 0, /* xBegin - begin transaction */
|
| + 0, /* xSync - sync transaction */
|
| + 0, /* xCommit - commit transaction */
|
| + 0, /* xRollback - rollback transaction */
|
| + 0, /* xFindFunction - function overloading */
|
| + 0, /* xRename - rename the table */
|
| +};
|
| +
|
| +CHROMIUM_SQLITE_API
|
| +int recoverVtableInit(sqlite3 *db){
|
| + return sqlite3_create_module_v2(db, "recover", &recoverModule, NULL, 0);
|
| +}
|
| +
|
| +/* This section of code is for parsing the create input and
|
| + * initializing the module.
|
| + */
|
| +
|
| +/* Find the next word in zText and place the endpoints in pzWord*.
|
| + * Returns true if the word is non-empty. "Word" is defined as
|
| + * ASCII alphanumeric plus '_' at this time.
|
| + */
|
| +static int findWord(const char *zText,
|
| + const char **pzWordStart, const char **pzWordEnd){
|
| + int r;
|
| + while( ascii_isspace(*zText) ){
|
| + zText++;
|
| + }
|
| + *pzWordStart = zText;
|
| + while( ascii_isalnum(*zText) || *zText=='_' ){
|
| + zText++;
|
| + }
|
| + r = zText>*pzWordStart; /* In case pzWordStart==pzWordEnd */
|
| + *pzWordEnd = zText;
|
| + return r;
|
| +}
|
| +
|
| +/* Return true if the next word in zText is zWord, also setting
|
| + * *pzContinue to the character after the word.
|
| + */
|
| +static int expectWord(const char *zText, const char *zWord,
|
| + const char **pzContinue){
|
| + const char *zWordStart, *zWordEnd;
|
| + if( findWord(zText, &zWordStart, &zWordEnd) &&
|
| + ascii_strncasecmp(zWord, zWordStart, zWordEnd - zWordStart)==0 ){
|
| + *pzContinue = zWordEnd;
|
| + return 1;
|
| + }
|
| + return 0;
|
| +}
|
| +
|
| +/* Parse the name and type information out of parameter. In case of
|
| + * success, *pzNameStart/End contain the name of the column,
|
| + * *pzTypeStart/End contain the top-level type, and *pTypeMask has the
|
| + * type mask to use for the column.
|
| + */
|
| +static int findNameAndType(const char *parameter,
|
| + const char **pzNameStart, const char **pzNameEnd,
|
| + const char **pzTypeStart, const char **pzTypeEnd,
|
| + unsigned char *pTypeMask){
|
| + unsigned nNameLen; /* Length of found name. */
|
| + const char *zEnd; /* Current end of parsed column information. */
|
| + int bNotNull; /* Non-zero if NULL is not allowed for name. */
|
| + int bStrict; /* Non-zero if column requires exact type match. */
|
| + const char *zDummy; /* Dummy parameter, result unused. */
|
| + unsigned i;
|
| +
|
| + /* strictMask is used for STRICT, strictMask|otherMask if STRICT is
|
| + * not supplied. zReplace provides an alternate type to expose to
|
| + * the caller.
|
| + */
|
| + static struct {
|
| + const char *zName;
|
| + unsigned char strictMask;
|
| + unsigned char otherMask;
|
| + const char *zReplace;
|
| + } kTypeInfo[] = {
|
| + { "ANY",
|
| + MASK_INTEGER | MASK_FLOAT | MASK_BLOB | MASK_TEXT | MASK_NULL,
|
| + 0, "",
|
| + },
|
| + { "ROWID", MASK_INTEGER | MASK_ROWID, 0, "INTEGER", },
|
| + { "INTEGER", MASK_INTEGER | MASK_NULL, 0, NULL, },
|
| + { "FLOAT", MASK_FLOAT | MASK_NULL, MASK_INTEGER, NULL, },
|
| + { "NUMERIC", MASK_INTEGER | MASK_FLOAT | MASK_NULL, MASK_TEXT, NULL, },
|
| + { "TEXT", MASK_TEXT | MASK_NULL, MASK_BLOB, NULL, },
|
| + { "BLOB", MASK_BLOB | MASK_NULL, 0, NULL, },
|
| + };
|
| +
|
| + if( !findWord(parameter, pzNameStart, pzNameEnd) ){
|
| + return SQLITE_MISUSE;
|
| + }
|
| +
|
| + /* Manifest typing, accept any storage type. */
|
| + if( !findWord(*pzNameEnd, pzTypeStart, pzTypeEnd) ){
|
| + *pzTypeEnd = *pzTypeStart = "";
|
| + *pTypeMask = MASK_INTEGER | MASK_FLOAT | MASK_BLOB | MASK_TEXT | MASK_NULL;
|
| + return SQLITE_OK;
|
| + }
|
| +
|
| + nNameLen = *pzTypeEnd - *pzTypeStart;
|
| + for( i=0; i<ArraySize(kTypeInfo); ++i ){
|
| + if( ascii_strncasecmp(kTypeInfo[i].zName, *pzTypeStart, nNameLen)==0 ){
|
| + break;
|
| + }
|
| + }
|
| + if( i==ArraySize(kTypeInfo) ){
|
| + return SQLITE_MISUSE;
|
| + }
|
| +
|
| + zEnd = *pzTypeEnd;
|
| + bStrict = 0;
|
| + if( expectWord(zEnd, "STRICT", &zEnd) ){
|
| + /* TODO(shess): Ick. But I don't want another single-purpose
|
| + * flag, either.
|
| + */
|
| + if( kTypeInfo[i].zReplace && !kTypeInfo[i].zReplace[0] ){
|
| + return SQLITE_MISUSE;
|
| + }
|
| + bStrict = 1;
|
| + }
|
| +
|
| + bNotNull = 0;
|
| + if( expectWord(zEnd, "NOT", &zEnd) ){
|
| + if( expectWord(zEnd, "NULL", &zEnd) ){
|
| + bNotNull = 1;
|
| + }else{
|
| + /* Anything other than NULL after NOT is an error. */
|
| + return SQLITE_MISUSE;
|
| + }
|
| + }
|
| +
|
| + /* Anything else is an error. */
|
| + if( findWord(zEnd, &zDummy, &zDummy) ){
|
| + return SQLITE_MISUSE;
|
| + }
|
| +
|
| + *pTypeMask = kTypeInfo[i].strictMask;
|
| + if( !bStrict ){
|
| + *pTypeMask |= kTypeInfo[i].otherMask;
|
| + }
|
| + if( bNotNull ){
|
| + *pTypeMask &= ~MASK_NULL;
|
| + }
|
| + if( kTypeInfo[i].zReplace ){
|
| + *pzTypeStart = kTypeInfo[i].zReplace;
|
| + *pzTypeEnd = *pzTypeStart + strlen(*pzTypeStart);
|
| + }
|
| + return SQLITE_OK;
|
| +}
|
| +
|
| +/* Parse the arguments, placing type masks in *pTypes and the exposed
|
| + * schema in *pzCreateSql (for sqlite3_declare_vtab).
|
| + */
|
| +static int ParseColumnsAndGenerateCreate(unsigned nCols,
|
| + const char *const *pCols,
|
| + char **pzCreateSql,
|
| + unsigned char *pTypes,
|
| + char **pzErr){
|
| + unsigned i;
|
| + char *zCreateSql = sqlite3_mprintf("CREATE TABLE x(");
|
| + if( !zCreateSql ){
|
| + return SQLITE_NOMEM;
|
| + }
|
| +
|
| + for( i=0; i<nCols; i++ ){
|
| + const char *zSep = (i < nCols - 1 ? ", " : ")");
|
| + const char *zNotNull = "";
|
| + const char *zNameStart, *zNameEnd;
|
| + const char *zTypeStart, *zTypeEnd;
|
| + int rc = findNameAndType(pCols[i],
|
| + &zNameStart, &zNameEnd,
|
| + &zTypeStart, &zTypeEnd,
|
| + &pTypes[i]);
|
| + if( rc!=SQLITE_OK ){
|
| + *pzErr = sqlite3_mprintf("unable to parse column %d", i);
|
| + sqlite3_free(zCreateSql);
|
| + return rc;
|
| + }
|
| +
|
| + if( !(pTypes[i]&MASK_NULL) ){
|
| + zNotNull = " NOT NULL";
|
| + }
|
| +
|
| + /* Add name and type to the create statement. */
|
| + zCreateSql = sqlite3_mprintf("%z%.*s %.*s%s%s",
|
| + zCreateSql,
|
| + zNameEnd - zNameStart, zNameStart,
|
| + zTypeEnd - zTypeStart, zTypeStart,
|
| + zNotNull, zSep);
|
| + if( !zCreateSql ){
|
| + return SQLITE_NOMEM;
|
| + }
|
| + }
|
| +
|
| + *pzCreateSql = zCreateSql;
|
| + return SQLITE_OK;
|
| +}
|
| +
|
| +/* Helper function for initializing the module. */
|
| +/* argv[0] module name
|
| + * argv[1] db name for virtual table
|
| + * argv[2] virtual table name
|
| + * argv[3] backing table name
|
| + * argv[4] columns
|
| + */
|
| +/* TODO(shess): Since connect isn't supported, could inline into
|
| + * recoverCreate().
|
| + */
|
| +/* TODO(shess): Explore cases where it would make sense to set *pzErr. */
|
| +static int recoverInit(
|
| + sqlite3 *db, /* Database connection */
|
| + void *pAux, /* unused */
|
| + int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
|
| + sqlite3_vtab **ppVtab, /* OUT: New virtual table */
|
| + char **pzErr /* OUT: Error message, if any */
|
| +){
|
| + const int kTypeCol = 4; /* First argument with column type info. */
|
| + Recover *pRecover; /* Virtual table structure being created. */
|
| + char *zDot; /* Any dot found in "db.table" backing. */
|
| + u32 iRootPage; /* Root page of backing table. */
|
| + char *zCreateSql; /* Schema of created virtual table. */
|
| + int rc;
|
| +
|
| + /* Require to be in the temp database. */
|
| + if( ascii_strcasecmp(argv[1], "temp")!=0 ){
|
| + *pzErr = sqlite3_mprintf("recover table must be in temp database");
|
| + return SQLITE_MISUSE;
|
| + }
|
| +
|
| + /* Need the backing table and at least one column. */
|
| + if( argc<=kTypeCol ){
|
| + *pzErr = sqlite3_mprintf("no columns specified");
|
| + return SQLITE_MISUSE;
|
| + }
|
| +
|
| + pRecover = sqlite3_malloc(sizeof(Recover));
|
| + if( !pRecover ){
|
| + return SQLITE_NOMEM;
|
| + }
|
| + memset(pRecover, 0, sizeof(*pRecover));
|
| + pRecover->base.pModule = &recoverModule;
|
| + pRecover->db = db;
|
| +
|
| + /* Parse out db.table, assuming main if no dot. */
|
| + zDot = strchr(argv[3], '.');
|
| + if( !zDot ){
|
| + pRecover->zDb = sqlite3_strdup(db->aDb[0].zName);
|
| + pRecover->zTable = sqlite3_strdup(argv[3]);
|
| + }else if( zDot>argv[3] && zDot[1]!='\0' ){
|
| + pRecover->zDb = sqlite3_strndup(argv[3], zDot - argv[3]);
|
| + pRecover->zTable = sqlite3_strdup(zDot + 1);
|
| + }else{
|
| + /* ".table" or "db." not allowed. */
|
| + *pzErr = sqlite3_mprintf("ill-formed table specifier");
|
| + recoverRelease(pRecover);
|
| + return SQLITE_ERROR;
|
| + }
|
| +
|
| + pRecover->nCols = argc - kTypeCol;
|
| + pRecover->pTypes = sqlite3_malloc(pRecover->nCols);
|
| + if( !pRecover->zDb || !pRecover->zTable || !pRecover->pTypes ){
|
| + recoverRelease(pRecover);
|
| + return SQLITE_NOMEM;
|
| + }
|
| +
|
| + /* Require the backing table to exist. */
|
| + /* TODO(shess): Be more pedantic about the form of the descriptor
|
| + * string. This already fails for poorly-formed strings, simply
|
| + * because there won't be a root page, but it would make more sense
|
| + * to be explicit.
|
| + */
|
| + rc = getRootPage(pRecover->db, pRecover->zDb, pRecover->zTable, &iRootPage);
|
| + if( rc!=SQLITE_OK ){
|
| + *pzErr = sqlite3_mprintf("unable to find backing table");
|
| + recoverRelease(pRecover);
|
| + return rc;
|
| + }
|
| +
|
| + /* Parse the column definitions. */
|
| + rc = ParseColumnsAndGenerateCreate(pRecover->nCols, argv + kTypeCol,
|
| + &zCreateSql, pRecover->pTypes, pzErr);
|
| + if( rc!=SQLITE_OK ){
|
| + recoverRelease(pRecover);
|
| + return rc;
|
| + }
|
| +
|
| + rc = sqlite3_declare_vtab(db, zCreateSql);
|
| + sqlite3_free(zCreateSql);
|
| + if( rc!=SQLITE_OK ){
|
| + recoverRelease(pRecover);
|
| + return rc;
|
| + }
|
| +
|
| + *ppVtab = (sqlite3_vtab *)pRecover;
|
| + return SQLITE_OK;
|
| +}
|
| +
|
| +/************** End of recover.c *********************************************/
|
| +
|
| +/* Chain include. */
|
| +#include "sqlite3.06.c"
|
|
|