/ Changes On Branch branch-3.7.11
Login

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Changes In Branch branch-3.7.11 Excluding Merge-Ins

This is equivalent to a diff from 00bb9c9ce4 to f0f492245e

2017-07-21
07:45
Add new interfaces sqlite3_result_pointer(), and sqlite3_value_pointer() and use them to transfer the eponymous FTS3 column pointer to the snippet() and offsets() routines. This changes is a cherry-pick of [f0f49224] with version-specific edits. That check-in was inspired by check-in [72de49f2]. (check-in: 69906880ce user: drh tags: branch-3.9.2)
03:23
Add new interfaces sqlite3_result_pointer(), and sqlite3_value_pointer() and use them to transfer the eponymous FTS3 column pointer to the snippet() and offsets() routines. This is a cherry-pick of [f0f492245e95], which is in turn inspired by check-in [72de49f2]. (Leaf check-in: a66a5b397b user: drh tags: branch-3.8.6)
03:09
Add new interfaces sqlite3_result_pointer(), and sqlite3_value_pointer() and use them to transfer the eponymous FTS3 column pointer to the snippet() and offsets() routines. This changes is inspired by check-in [72de49f2] but is new implementation, not a cherry-pick. (Leaf check-in: f0f492245e user: drh tags: branch-3.7.11)
2015-05-21
02:24
Silently ignore any attempt to add a prefix index for prefixes zero bytes in size to an fts3/4 table. Or any prefix index size so large that it overflows a 32-bit signed integer. Cherrypick [ad4b19d2ac0889a] (check-in: 000197cc4e user: drh tags: branch-3.7.11)
00:50
Add the ".open" command to the command-line shell. Cherrypick from [21eccb919441]. (check-in: a71e2a72c5 user: drh tags: branch-3.7.11)
2012-03-20
15:10
Remove the _SafeInit() entry points from the TCL interface. They have long been no-ops. Removing them completely avoids confusion as to why they don't work. (check-in: 0fb26c7bfa user: drh tags: trunk)
11:35
Version 3.7.11 (check-in: 00bb9c9ce4 user: drh tags: trunk, release, version-3.7.11)
03:10
Fix out-of-bounds array references in the "echo" virtual table module used for testing. No changes to the SQLite core. (check-in: 7b449b301e user: drh tags: trunk)

Changes to ext/fts3/fts3.c.

   916    916       for(p=zParam; *p; p++){
   917    917         if( *p==',' ) nIndex++;
   918    918       }
   919    919     }
   920    920   
   921    921     aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
   922    922     *apIndex = aIndex;
   923         -  *pnIndex = nIndex;
   924    923     if( !aIndex ){
   925    924       return SQLITE_NOMEM;
   926    925     }
   927    926   
   928    927     memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
   929    928     if( zParam ){
   930    929       const char *p = zParam;
   931    930       int i;
   932    931       for(i=1; i<nIndex; i++){
   933    932         int nPrefix;
   934    933         if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
   935         -      aIndex[i].nPrefix = nPrefix;
          934  +      if( nPrefix<=0 ){
          935  +        nIndex--;
          936  +        i--;
          937  +      }else{
          938  +        aIndex[i].nPrefix = nPrefix;
          939  +      }
   936    940         p++;
   937    941       }
   938    942     }
   939    943   
          944  +  *pnIndex = nIndex;
   940    945     return SQLITE_OK;
   941    946   }
   942    947   
   943    948   /*
   944    949   ** This function is called when initializing an FTS4 table that uses the
   945    950   ** content=xxx option. It determines the number of and names of the columns
   946    951   ** of the new FTS4 table.
................................................................................
   967    972   */
   968    973   static int fts3ContentColumns(
   969    974     sqlite3 *db,                    /* Database handle */
   970    975     const char *zDb,                /* Name of db (i.e. "main", "temp" etc.) */
   971    976     const char *zTbl,               /* Name of content table */
   972    977     const char ***pazCol,           /* OUT: Malloc'd array of column names */
   973    978     int *pnCol,                     /* OUT: Size of array *pazCol */
   974         -  int *pnStr                      /* OUT: Bytes of string content */
          979  +  int *pnStr,                     /* OUT: Bytes of string content */
          980  +  char **pzErr                    /* OUT: error message */
   975    981   ){
   976    982     int rc = SQLITE_OK;             /* Return code */
   977    983     char *zSql;                     /* "SELECT *" statement on zTbl */  
   978    984     sqlite3_stmt *pStmt = 0;        /* Compiled version of zSql */
   979    985   
   980    986     zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
   981    987     if( !zSql ){
   982    988       rc = SQLITE_NOMEM;
   983    989     }else{
   984    990       rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
          991  +    if( rc!=SQLITE_OK ){
          992  +      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
          993  +    }
   985    994     }
   986    995     sqlite3_free(zSql);
   987    996   
   988    997     if( rc==SQLITE_OK ){
   989    998       const char **azCol;           /* Output array */
   990    999       int nStr = 0;                 /* Size of all column names (incl. 0x00) */
   991   1000       int nCol;                     /* Number of table columns */
................................................................................
  1211   1220       sqlite3_free(zCompress); 
  1212   1221       sqlite3_free(zUncompress); 
  1213   1222       zCompress = 0;
  1214   1223       zUncompress = 0;
  1215   1224       if( nCol==0 ){
  1216   1225         sqlite3_free((void*)aCol); 
  1217   1226         aCol = 0;
  1218         -      rc = fts3ContentColumns(db, argv[1], zContent, &aCol, &nCol, &nString);
         1227  +      rc = fts3ContentColumns(db, argv[1], zContent,&aCol,&nCol,&nString,pzErr);
  1219   1228   
  1220   1229         /* If a languageid= option was specified, remove the language id
  1221   1230         ** column from the aCol[] array. */ 
  1222   1231         if( rc==SQLITE_OK && zLanguageid ){
  1223   1232           int j;
  1224   1233           for(j=0; j<nCol; j++){
  1225   1234             if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
................................................................................
  3054   3063       /* This call is a request for the "docid" column. Since "docid" is an 
  3055   3064       ** alias for "rowid", use the xRowid() method to obtain the value.
  3056   3065       */
  3057   3066       sqlite3_result_int64(pCtx, pCsr->iPrevId);
  3058   3067     }else if( iCol==p->nColumn ){
  3059   3068       /* The extra column whose name is the same as the table.
  3060   3069       ** Return a blob which is a pointer to the cursor.  */
  3061         -    sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
         3070  +    sqlite3_result_pointer(pCtx, pCsr);
  3062   3071     }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
  3063   3072       sqlite3_result_int64(pCtx, pCsr->iLangid);
  3064   3073     }else{
  3065   3074       /* The requested column is either a user column (one that contains 
  3066   3075       ** indexed data), or the language-id column.  */
  3067   3076       rc = fts3CursorSeek(0, pCsr);
  3068   3077   
................................................................................
  3181   3190   */
  3182   3191   static int fts3FunctionArg(
  3183   3192     sqlite3_context *pContext,      /* SQL function call context */
  3184   3193     const char *zFunc,              /* Function name */
  3185   3194     sqlite3_value *pVal,            /* argv[0] passed to function */
  3186   3195     Fts3Cursor **ppCsr              /* OUT: Store cursor handle here */
  3187   3196   ){
  3188         -  Fts3Cursor *pRet;
  3189         -  if( sqlite3_value_type(pVal)!=SQLITE_BLOB 
  3190         -   || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
  3191         -  ){
         3197  +  Fts3Cursor *pRet = (Fts3Cursor*)sqlite3_value_pointer(pVal);
         3198  +  if( pRet==0 ){
  3192   3199       char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
  3193   3200       sqlite3_result_error(pContext, zErr, -1);
  3194   3201       sqlite3_free(zErr);
  3195   3202       return SQLITE_ERROR;
  3196   3203     }
  3197         -  memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
  3198   3204     *ppCsr = pRet;
  3199   3205     return SQLITE_OK;
  3200   3206   }
  3201   3207   
  3202   3208   /*
  3203   3209   ** Implementation of the snippet() function for FTS3
  3204   3210   */

Changes to src/fkey.c.

  1014   1014   
  1015   1015         /* Create the expression "OLD.zToCol = zFromCol". It is important
  1016   1016         ** that the "OLD.zToCol" term is on the LHS of the = operator, so
  1017   1017         ** that the affinity and collation sequence associated with the
  1018   1018         ** parent table are used for the comparison. */
  1019   1019         pEq = sqlite3PExpr(pParse, TK_EQ,
  1020   1020             sqlite3PExpr(pParse, TK_DOT, 
  1021         -            sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
  1022         -            sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
         1021  +            sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
         1022  +            sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)
  1023   1023             , 0),
  1024         -          sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
         1024  +          sqlite3ExprAlloc(db, TK_ID, &tFromCol, 0)
  1025   1025         , 0);
  1026   1026         pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  1027   1027   
  1028   1028         /* For ON UPDATE, construct the next term of the WHEN clause.
  1029   1029         ** The final WHEN clause will be like this:
  1030   1030         **
  1031   1031         **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
  1032   1032         */
  1033   1033         if( pChanges ){
  1034   1034           pEq = sqlite3PExpr(pParse, TK_IS,
  1035   1035               sqlite3PExpr(pParse, TK_DOT, 
  1036         -              sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
  1037         -              sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
         1036  +              sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
         1037  +              sqlite3ExprAlloc(db, TK_ID, &tToCol, 0),
  1038   1038                 0),
  1039   1039               sqlite3PExpr(pParse, TK_DOT, 
  1040         -              sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
  1041         -              sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
         1040  +              sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
         1041  +              sqlite3ExprAlloc(db, TK_ID, &tToCol, 0),
  1042   1042                 0),
  1043   1043               0);
  1044   1044           pWhen = sqlite3ExprAnd(db, pWhen, pEq);
  1045   1045         }
  1046   1046     
  1047   1047         if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
  1048   1048           Expr *pNew;
  1049   1049           if( action==OE_Cascade ){
  1050   1050             pNew = sqlite3PExpr(pParse, TK_DOT, 
  1051         -            sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
  1052         -            sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
         1051  +            sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
         1052  +            sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)
  1053   1053             , 0);
  1054   1054           }else if( action==OE_SetDflt ){
  1055   1055             Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
  1056   1056             if( pDflt ){
  1057   1057               pNew = sqlite3ExprDup(db, pDflt, 0);
  1058   1058             }else{
  1059   1059               pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
................................................................................
  1092   1092       /* Disable lookaside memory allocation */
  1093   1093       enableLookaside = db->lookaside.bEnabled;
  1094   1094       db->lookaside.bEnabled = 0;
  1095   1095   
  1096   1096       pTrigger = (Trigger *)sqlite3DbMallocZero(db, 
  1097   1097           sizeof(Trigger) +         /* struct Trigger */
  1098   1098           sizeof(TriggerStep) +     /* Single step in trigger program */
  1099         -        nFrom + 1                 /* Space for pStep->target.z */
         1099  +        nFrom + 1                 /* Space for pStep->zTarget */
  1100   1100       );
  1101   1101       if( pTrigger ){
  1102   1102         pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
  1103         -      pStep->target.z = (char *)&pStep[1];
  1104         -      pStep->target.n = nFrom;
  1105         -      memcpy((char *)pStep->target.z, zFrom, nFrom);
         1103  +      pStep->zTarget = (char *)&pStep[1];
         1104  +      memcpy((char *)pStep->zTarget, zFrom, nFrom);
  1106   1105     
  1107   1106         pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  1108   1107         pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
  1109   1108         pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  1110   1109         if( pWhen ){
  1111   1110           pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
  1112   1111           pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);

Changes to src/prepare.c.

    63     63       return 1;
    64     64     }
    65     65   
    66     66     assert( iDb>=0 && iDb<db->nDb );
    67     67     if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
    68     68     if( argv[1]==0 ){
    69     69       corruptSchema(pData, argv[0], 0);
    70         -  }else if( argv[2] && argv[2][0] ){
           70  +  }else if( argv[2] && sqlite3_strnicmp(argv[2],"create ",7)==0 ){
    71     71       /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
    72     72       ** But because db->init.busy is set to 1, no VDBE code is generated
    73     73       ** or executed.  All the parser does is build the internal data
    74     74       ** structures that describe the table, index, or view.
    75     75       */
    76     76       int rc;
    77     77       sqlite3_stmt *pStmt;
................................................................................
    94     94             db->mallocFailed = 1;
    95     95           }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
    96     96             corruptSchema(pData, argv[0], sqlite3_errmsg(db));
    97     97           }
    98     98         }
    99     99       }
   100    100       sqlite3_finalize(pStmt);
   101         -  }else if( argv[0]==0 ){
   102         -    corruptSchema(pData, 0, 0);
          101  +  }else if( argv[0]==0 || (argv[2]!=0 && argv[2][0]!=0) ){
          102  +    corruptSchema(pData, argv[0], 0);
   103    103     }else{
   104    104       /* If the SQL column is blank it means this is an index that
   105    105       ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
   106    106       ** constraint for a CREATE TABLE.  The index should have already
   107    107       ** been created when we processed the CREATE TABLE.  All we have
   108    108       ** to do here is record the root page number for that index.
   109    109       */

Changes to src/shell.c.

   430    430     char nullvalue[20];    /* The text to print when a NULL comes back from
   431    431                            ** the database */
   432    432     struct previous_mode_data explainPrev;
   433    433                            /* Holds the mode information just before
   434    434                            ** .explain ON */
   435    435     char outfile[FILENAME_MAX]; /* Filename for *out */
   436    436     const char *zDbFilename;    /* name of the database file */
          437  +  char *zFreeOnClose;         /* Filename to free when closing */
   437    438     const char *zVfs;           /* Name of VFS to use */
   438    439     sqlite3_stmt *pStmt;   /* Current statement if any. */
   439    440     FILE *pLog;            /* Write log output here */
   440    441   };
   441    442   
   442    443   /*
   443    444   ** These are the allowed modes.
................................................................................
  1412   1413     "                         html     HTML <table> code\n"
  1413   1414     "                         insert   SQL insert statements for TABLE\n"
  1414   1415     "                         line     One value per line\n"
  1415   1416     "                         list     Values delimited by .separator string\n"
  1416   1417     "                         tabs     Tab-separated values\n"
  1417   1418     "                         tcl      TCL list elements\n"
  1418   1419     ".nullvalue STRING      Print STRING in place of NULL values\n"
         1420  +  ".open ?FILENAME?       Close existing database and reopen FILENAME\n"
  1419   1421     ".output FILENAME       Send output to FILENAME\n"
  1420   1422     ".output stdout         Send output to the screen\n"
  1421   1423     ".prompt MAIN CONTINUE  Replace the standard prompts\n"
  1422   1424     ".quit                  Exit this program\n"
  1423   1425     ".read FILENAME         Execute SQL in FILENAME\n"
  1424   1426     ".restore ?DB? FILE     Restore content of DB (default \"main\") from FILE\n"
  1425   1427     ".schema ?TABLE?        Show the CREATE statements\n"
................................................................................
  1443   1445   /* Forward reference */
  1444   1446   static int process_input(struct callback_data *p, FILE *in);
  1445   1447   
  1446   1448   /*
  1447   1449   ** Make sure the database is open.  If it is not, then open it.  If
  1448   1450   ** the database fails to open, print an error message and exit.
  1449   1451   */
  1450         -static void open_db(struct callback_data *p){
         1452  +static void open_db(struct callback_data *p, int keepAlive){
  1451   1453     if( p->db==0 ){
  1452   1454       sqlite3_open(p->zDbFilename, &p->db);
  1453   1455       db = p->db;
  1454   1456       if( db && sqlite3_errcode(db)==SQLITE_OK ){
  1455   1457         sqlite3_create_function(db, "shellstatic", 0, SQLITE_UTF8, 0,
  1456   1458             shellstaticFunc, 0, 0);
  1457   1459       }
  1458   1460       if( db==0 || SQLITE_OK!=sqlite3_errcode(db) ){
  1459   1461         fprintf(stderr,"Error: unable to open database \"%s\": %s\n", 
  1460   1462             p->zDbFilename, sqlite3_errmsg(db));
         1463  +      if( keepAlive ) return;
  1461   1464         exit(1);
  1462   1465       }
  1463   1466   #ifndef SQLITE_OMIT_LOAD_EXTENSION
  1464   1467       sqlite3_enable_load_extension(p->db, 1);
  1465   1468   #endif
  1466   1469     }
  1467   1470   }
................................................................................
  1574   1577       }
  1575   1578       rc = sqlite3_open(zDestFile, &pDest);
  1576   1579       if( rc!=SQLITE_OK ){
  1577   1580         fprintf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
  1578   1581         sqlite3_close(pDest);
  1579   1582         return 1;
  1580   1583       }
  1581         -    open_db(p);
         1584  +    open_db(p, 0);
  1582   1585       pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
  1583   1586       if( pBackup==0 ){
  1584   1587         fprintf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
  1585   1588         sqlite3_close(pDest);
  1586   1589         return 1;
  1587   1590       }
  1588   1591       while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
................................................................................
  1599   1602     if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 && nArg>1 && nArg<3 ){
  1600   1603       bail_on_error = booleanValue(azArg[1]);
  1601   1604     }else
  1602   1605   
  1603   1606     if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 && nArg==1 ){
  1604   1607       struct callback_data data;
  1605   1608       char *zErrMsg = 0;
  1606         -    open_db(p);
         1609  +    open_db(p, 0);
  1607   1610       memcpy(&data, p, sizeof(data));
  1608   1611       data.showHeader = 1;
  1609   1612       data.mode = MODE_Column;
  1610   1613       data.colWidth[0] = 3;
  1611   1614       data.colWidth[1] = 15;
  1612   1615       data.colWidth[2] = 58;
  1613   1616       data.cnt = 0;
................................................................................
  1616   1619         fprintf(stderr,"Error: %s\n", zErrMsg);
  1617   1620         sqlite3_free(zErrMsg);
  1618   1621         rc = 1;
  1619   1622       }
  1620   1623     }else
  1621   1624   
  1622   1625     if( c=='d' && strncmp(azArg[0], "dump", n)==0 && nArg<3 ){
  1623         -    open_db(p);
         1626  +    open_db(p, 0);
  1624   1627       /* When playing back a "dump", the content might appear in an order
  1625   1628       ** which causes immediate foreign key constraints to be violated.
  1626   1629       ** So disable foreign-key constraint enforcement to prevent problems. */
  1627   1630       fprintf(p->out, "PRAGMA foreign_keys=OFF;\n");
  1628   1631       fprintf(p->out, "BEGIN TRANSACTION;\n");
  1629   1632       p->writableSchema = 0;
  1630   1633       sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
................................................................................
  1734   1737       char *zSql;                 /* An SQL statement */
  1735   1738       char *zLine;                /* A single line of input from the file */
  1736   1739       char **azCol;               /* zLine[] broken up into columns */
  1737   1740       char *zCommit;              /* How to commit changes */   
  1738   1741       FILE *in;                   /* The input file */
  1739   1742       int lineno = 0;             /* Line number of input file */
  1740   1743   
  1741         -    open_db(p);
         1744  +    open_db(p, 0);
  1742   1745       nSep = strlen30(p->separator);
  1743   1746       if( nSep==0 ){
  1744   1747         fprintf(stderr, "Error: non-null separator required for import\n");
  1745   1748         return 1;
  1746   1749       }
  1747   1750       zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
  1748   1751       if( zSql==0 ){
................................................................................
  1849   1852       sqlite3_finalize(pStmt);
  1850   1853       sqlite3_exec(p->db, zCommit, 0, 0, 0);
  1851   1854     }else
  1852   1855   
  1853   1856     if( c=='i' && strncmp(azArg[0], "indices", n)==0 && nArg<3 ){
  1854   1857       struct callback_data data;
  1855   1858       char *zErrMsg = 0;
  1856         -    open_db(p);
         1859  +    open_db(p, 0);
  1857   1860       memcpy(&data, p, sizeof(data));
  1858   1861       data.showHeader = 0;
  1859   1862       data.mode = MODE_List;
  1860   1863       if( nArg==1 ){
  1861   1864         rc = sqlite3_exec(p->db,
  1862   1865           "SELECT name FROM sqlite_master "
  1863   1866           "WHERE type='index' AND name NOT LIKE 'sqlite_%' "
................................................................................
  1915   1918   
  1916   1919   #ifndef SQLITE_OMIT_LOAD_EXTENSION
  1917   1920     if( c=='l' && strncmp(azArg[0], "load", n)==0 && nArg>=2 ){
  1918   1921       const char *zFile, *zProc;
  1919   1922       char *zErrMsg = 0;
  1920   1923       zFile = azArg[1];
  1921   1924       zProc = nArg>=3 ? azArg[2] : 0;
  1922         -    open_db(p);
         1925  +    open_db(p, 0);
  1923   1926       rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
  1924   1927       if( rc!=SQLITE_OK ){
  1925   1928         fprintf(stderr, "Error: %s\n", zErrMsg);
  1926   1929         sqlite3_free(zErrMsg);
  1927   1930         rc = 1;
  1928   1931       }
  1929   1932     }else
................................................................................
  1993   1996       }
  1994   1997     }else
  1995   1998   
  1996   1999     if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 && nArg==2 ) {
  1997   2000       sqlite3_snprintf(sizeof(p->nullvalue), p->nullvalue,
  1998   2001                        "%.*s", (int)ArraySize(p->nullvalue)-1, azArg[1]);
  1999   2002     }else
         2003  +
         2004  +  if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
         2005  +    sqlite3 *savedDb = p->db;
         2006  +    const char *zSavedFilename = p->zDbFilename;
         2007  +    char *zNewFilename = 0;
         2008  +    p->db = 0;
         2009  +    if( nArg>=2 ){
         2010  +      p->zDbFilename = zNewFilename = sqlite3_mprintf("%s", azArg[1]);
         2011  +    }
         2012  +    open_db(p, 1);
         2013  +    if( p->db!=0 ){
         2014  +      sqlite3_close(savedDb);
         2015  +      sqlite3_free(p->zFreeOnClose);
         2016  +      p->zFreeOnClose = zNewFilename;
         2017  +    }else{
         2018  +      sqlite3_free(zNewFilename);
         2019  +      p->db = savedDb;
         2020  +      p->zDbFilename = zSavedFilename;
         2021  +    }
         2022  +  }else
  2000   2023   
  2001   2024     if( c=='o' && strncmp(azArg[0], "output", n)==0 && nArg==2 ){
  2002   2025       if( p->out!=stdout ){
  2003   2026         fclose(p->out);
  2004   2027       }
  2005   2028       if( strcmp(azArg[1],"stdout")==0 ){
  2006   2029         p->out = stdout;
................................................................................
  2057   2080       }
  2058   2081       rc = sqlite3_open(zSrcFile, &pSrc);
  2059   2082       if( rc!=SQLITE_OK ){
  2060   2083         fprintf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
  2061   2084         sqlite3_close(pSrc);
  2062   2085         return 1;
  2063   2086       }
  2064         -    open_db(p);
         2087  +    open_db(p, 0);
  2065   2088       pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
  2066   2089       if( pBackup==0 ){
  2067   2090         fprintf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  2068   2091         sqlite3_close(pSrc);
  2069   2092         return 1;
  2070   2093       }
  2071   2094       while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
................................................................................
  2087   2110       }
  2088   2111       sqlite3_close(pSrc);
  2089   2112     }else
  2090   2113   
  2091   2114     if( c=='s' && strncmp(azArg[0], "schema", n)==0 && nArg<3 ){
  2092   2115       struct callback_data data;
  2093   2116       char *zErrMsg = 0;
  2094         -    open_db(p);
         2117  +    open_db(p, 0);
  2095   2118       memcpy(&data, p, sizeof(data));
  2096   2119       data.showHeader = 0;
  2097   2120       data.mode = MODE_Semi;
  2098   2121       if( nArg>1 ){
  2099   2122         int i;
  2100   2123         for(i=0; azArg[1][i]; i++) azArg[1][i] = ToLower(azArg[1][i]);
  2101   2124         if( strcmp(azArg[1],"sqlite_master")==0 ){
................................................................................
  2193   2216       p->statsOn = booleanValue(azArg[1]);
  2194   2217     }else
  2195   2218   
  2196   2219     if( c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0 && nArg<3 ){
  2197   2220       char **azResult;
  2198   2221       int nRow;
  2199   2222       char *zErrMsg;
  2200         -    open_db(p);
         2223  +    open_db(p, 0);
  2201   2224       if( nArg==1 ){
  2202   2225         rc = sqlite3_get_table(p->db,
  2203   2226           "SELECT name FROM sqlite_master "
  2204   2227           "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%' "
  2205   2228           "UNION ALL "
  2206   2229           "SELECT name FROM sqlite_temp_master "
  2207   2230           "WHERE type IN ('table','view') "
................................................................................
  2269   2292         { "optimizations",         SQLITE_TESTCTRL_OPTIMIZATIONS          },
  2270   2293         { "iskeyword",             SQLITE_TESTCTRL_ISKEYWORD              },
  2271   2294         { "scratchmalloc",         SQLITE_TESTCTRL_SCRATCHMALLOC          },
  2272   2295       };
  2273   2296       int testctrl = -1;
  2274   2297       int rc = 0;
  2275   2298       int i, n;
  2276         -    open_db(p);
         2299  +    open_db(p, 0);
  2277   2300   
  2278   2301       /* convert testctrl text option to value. allow any unique prefix
  2279   2302       ** of the option name, or a numerical value. */
  2280   2303       n = strlen30(azArg[1]);
  2281   2304       for(i=0; i<(int)(sizeof(aCtrl)/sizeof(aCtrl[0])); i++){
  2282   2305         if( strncmp(azArg[1], aCtrl[i].zCtrlName, n)==0 ){
  2283   2306           if( testctrl<0 ){
................................................................................
  2368   2391                     azArg[1]);
  2369   2392             break;
  2370   2393         }
  2371   2394       }
  2372   2395     }else
  2373   2396   
  2374   2397     if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 && nArg==2 ){
  2375         -    open_db(p);
         2398  +    open_db(p, 0);
  2376   2399       sqlite3_busy_timeout(p->db, atoi(azArg[1]));
  2377   2400     }else
  2378   2401       
  2379   2402     if( HAS_TIMER && c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0
  2380   2403      && nArg==2
  2381   2404     ){
  2382   2405       enableTimer = booleanValue(azArg[1]);
  2383   2406     }else
  2384         -  
         2407  +
  2385   2408     if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
  2386   2409       printf("SQLite %s %s\n" /*extra-version-info*/,
  2387   2410           sqlite3_libversion(), sqlite3_sourceid());
  2388   2411     }else
  2389   2412   
  2390   2413     if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
  2391   2414       const char *zDbName = nArg==2 ? azArg[1] : "main";
................................................................................
  2551   2574         zSql[nSql++] = '\n';
  2552   2575         memcpy(&zSql[nSql], zLine, len+1);
  2553   2576         nSql += len;
  2554   2577       }
  2555   2578       if( zSql && _contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
  2556   2579                   && sqlite3_complete(zSql) ){
  2557   2580         p->cnt = 0;
  2558         -      open_db(p);
         2581  +      open_db(p, 0);
  2559   2582         BEGIN_TIMER;
  2560   2583         rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg);
  2561   2584         END_TIMER;
  2562   2585         if( rc || zErrMsg ){
  2563   2586           char zPrefix[100];
  2564   2587           if( in!=0 || !stdin_is_interactive ){
  2565   2588             sqlite3_snprintf(sizeof(zPrefix), zPrefix, 
................................................................................
  2879   2902   
  2880   2903     /* Go ahead and open the database file if it already exists.  If the
  2881   2904     ** file does not exist, delay opening it.  This prevents empty database
  2882   2905     ** files from being created if a user mistypes the database name argument
  2883   2906     ** to the sqlite command-line tool.
  2884   2907     */
  2885   2908     if( access(data.zDbFilename, 0)==0 ){
  2886         -    open_db(&data);
         2909  +    open_db(&data, 0);
  2887   2910     }
  2888   2911   
  2889   2912     /* Process the initialization file if there is one.  If no -init option
  2890   2913     ** is given on the command line, look for a file named ~/.sqliterc and
  2891   2914     ** try to process it.
  2892   2915     */
  2893   2916     rc = process_sqliterc(&data,zInitFile);
................................................................................
  2971   2994         if( i==argc-1 ) break;
  2972   2995         i++;
  2973   2996         z = argv[i];
  2974   2997         if( z[0]=='.' ){
  2975   2998           rc = do_meta_command(z, &data);
  2976   2999           if( rc && bail_on_error ) return rc;
  2977   3000         }else{
  2978         -        open_db(&data);
         3001  +        open_db(&data, 0);
  2979   3002           rc = shell_exec(data.db, z, shell_callback, &data, &zErrMsg);
  2980   3003           if( zErrMsg!=0 ){
  2981   3004             fprintf(stderr,"Error: %s\n", zErrMsg);
  2982   3005             if( bail_on_error ) return rc!=0 ? rc : 1;
  2983   3006           }else if( rc!=0 ){
  2984   3007             fprintf(stderr,"Error: unable to process SQL \"%s\"\n", z);
  2985   3008             if( bail_on_error ) return rc;
................................................................................
  2994   3017   
  2995   3018     if( zFirstCmd ){
  2996   3019       /* Run just the command that follows the database name
  2997   3020       */
  2998   3021       if( zFirstCmd[0]=='.' ){
  2999   3022         rc = do_meta_command(zFirstCmd, &data);
  3000   3023       }else{
  3001         -      open_db(&data);
         3024  +      open_db(&data, 0);
  3002   3025         rc = shell_exec(data.db, zFirstCmd, shell_callback, &data, &zErrMsg);
  3003   3026         if( zErrMsg!=0 ){
  3004   3027           fprintf(stderr,"Error: %s\n", zErrMsg);
  3005   3028           return rc!=0 ? rc : 1;
  3006   3029         }else if( rc!=0 ){
  3007   3030           fprintf(stderr,"Error: unable to process SQL \"%s\"\n", zFirstCmd);
  3008   3031           return rc;
................................................................................
  3042   3065         rc = process_input(&data, stdin);
  3043   3066       }
  3044   3067     }
  3045   3068     set_table_name(&data, 0);
  3046   3069     if( data.db ){
  3047   3070       sqlite3_close(data.db);
  3048   3071     }
         3072  +  sqlite3_free(data.zFreeOnClose); 
  3049   3073     return rc;
  3050   3074   }

Changes to src/sqlite.h.in.

  3941   3941   */
  3942   3942   const void *sqlite3_value_blob(sqlite3_value*);
  3943   3943   int sqlite3_value_bytes(sqlite3_value*);
  3944   3944   int sqlite3_value_bytes16(sqlite3_value*);
  3945   3945   double sqlite3_value_double(sqlite3_value*);
  3946   3946   int sqlite3_value_int(sqlite3_value*);
  3947   3947   sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
         3948  +void *sqlite3_value_pointer(sqlite3_value*);
  3948   3949   const unsigned char *sqlite3_value_text(sqlite3_value*);
  3949   3950   const void *sqlite3_value_text16(sqlite3_value*);
  3950   3951   const void *sqlite3_value_text16le(sqlite3_value*);
  3951   3952   const void *sqlite3_value_text16be(sqlite3_value*);
  3952   3953   int sqlite3_value_type(sqlite3_value*);
  3953   3954   int sqlite3_value_numeric_type(sqlite3_value*);
  3954   3955   
................................................................................
  4198   4199   void sqlite3_result_error16(sqlite3_context*, const void*, int);
  4199   4200   void sqlite3_result_error_toobig(sqlite3_context*);
  4200   4201   void sqlite3_result_error_nomem(sqlite3_context*);
  4201   4202   void sqlite3_result_error_code(sqlite3_context*, int);
  4202   4203   void sqlite3_result_int(sqlite3_context*, int);
  4203   4204   void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
  4204   4205   void sqlite3_result_null(sqlite3_context*);
         4206  +void sqlite3_result_pointer(sqlite3_context*, void*);
  4205   4207   void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
  4206   4208   void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
  4207   4209   void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
  4208   4210   void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
  4209   4211   void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
  4210   4212   void sqlite3_result_zeroblob(sqlite3_context*, int n);
  4211   4213   

Changes to src/sqliteInt.h.

  2337   2337    * "SELECT" statement. The meanings of the other members is determined by the 
  2338   2338    * value of "op" as follows:
  2339   2339    *
  2340   2340    * (op == TK_INSERT)
  2341   2341    * orconf    -> stores the ON CONFLICT algorithm
  2342   2342    * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
  2343   2343    *              this stores a pointer to the SELECT statement. Otherwise NULL.
  2344         - * target    -> A token holding the quoted name of the table to insert into.
         2344  + * zTarget   -> Dequoted name of the table to insert into.
  2345   2345    * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
  2346   2346    *              this stores values to be inserted. Otherwise NULL.
  2347   2347    * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ... 
  2348   2348    *              statement, then this stores the column-names to be
  2349   2349    *              inserted into.
  2350   2350    *
  2351   2351    * (op == TK_DELETE)
  2352         - * target    -> A token holding the quoted name of the table to delete from.
         2352  + * zTarget   -> Dequoted name of the table to delete from.
  2353   2353    * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
  2354   2354    *              Otherwise NULL.
  2355   2355    * 
  2356   2356    * (op == TK_UPDATE)
  2357         - * target    -> A token holding the quoted name of the table to update rows of.
         2357  + * zTarget   -> Dequoted name of the table to update.
  2358   2358    * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
  2359   2359    *              Otherwise NULL.
  2360   2360    * pExprList -> A list of the columns to update and the expressions to update
  2361   2361    *              them to. See sqlite3Update() documentation of "pChanges"
  2362   2362    *              argument.
  2363   2363    * 
  2364   2364    */
  2365   2365   struct TriggerStep {
  2366   2366     u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
  2367   2367     u8 orconf;           /* OE_Rollback etc. */
  2368   2368     Trigger *pTrig;      /* The trigger that this step is a part of */
  2369         -  Select *pSelect;     /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
  2370         -  Token target;        /* Target table for DELETE, UPDATE, INSERT */
         2369  +  Select *pSelect;     /* SELECT statement or RHS of INSERT INTO SELECT ... */
         2370  +  char *zTarget;       /* Target table for DELETE, UPDATE, INSERT */
  2371   2371     Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
  2372   2372     ExprList *pExprList; /* SET clause for UPDATE.  VALUES clause for INSERT */
  2373   2373     IdList *pIdList;     /* Column names for INSERT */
  2374   2374     TriggerStep *pNext;  /* Next in the link-list */
  2375   2375     TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
  2376   2376   };
  2377   2377   

Changes to src/trigger.c.

   369    369   static TriggerStep *triggerStepAllocate(
   370    370     sqlite3 *db,                /* Database connection */
   371    371     u8 op,                      /* Trigger opcode */
   372    372     Token *pName                /* The target name */
   373    373   ){
   374    374     TriggerStep *pTriggerStep;
   375    375   
   376         -  pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
          376  +  pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n + 1);
   377    377     if( pTriggerStep ){
   378    378       char *z = (char*)&pTriggerStep[1];
   379    379       memcpy(z, pName->z, pName->n);
   380         -    pTriggerStep->target.z = z;
   381         -    pTriggerStep->target.n = pName->n;
          380  +    sqlite3Dequote(z);
          381  +    pTriggerStep->zTarget = z;
   382    382       pTriggerStep->op = op;
   383    383     }
   384    384     return pTriggerStep;
   385    385   }
   386    386   
   387    387   /*
   388    388   ** Build a trigger step out of an INSERT statement.  Return a pointer
................................................................................
   663    663     if( pMask ){
   664    664       *pMask = mask;
   665    665     }
   666    666     return (mask ? pList : 0);
   667    667   }
   668    668   
   669    669   /*
   670         -** Convert the pStep->target token into a SrcList and return a pointer
          670  +** Convert the pStep->zTarget string into a SrcList and return a pointer
   671    671   ** to that SrcList.
   672    672   **
   673    673   ** This routine adds a specific database name, if needed, to the target when
   674    674   ** forming the SrcList.  This prevents a trigger in one database from
   675    675   ** referring to a target in another database.  An exception is when the
   676    676   ** trigger is in TEMP in which case it can refer to any other database it
   677    677   ** wants.
   678    678   */
   679    679   static SrcList *targetSrcList(
   680    680     Parse *pParse,       /* The parsing context */
   681    681     TriggerStep *pStep   /* The trigger containing the target token */
   682    682   ){
          683  +  sqlite3 *db = pParse->db;
   683    684     int iDb;             /* Index of the database to use */
   684    685     SrcList *pSrc;       /* SrcList to be returned */
   685    686   
   686         -  pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
          687  +  pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
   687    688     if( pSrc ){
   688    689       assert( pSrc->nSrc>0 );
   689         -    assert( pSrc->a!=0 );
   690         -    iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
          690  +    pSrc->a[pSrc->nSrc-1].zName = sqlite3DbStrDup(db, pStep->zTarget);
          691  +    iDb = sqlite3SchemaToIndex(db, pStep->pTrig->pSchema);
   691    692       if( iDb==0 || iDb>=2 ){
   692         -      sqlite3 *db = pParse->db;
   693         -      assert( iDb<pParse->db->nDb );
          693  +      assert( iDb<db->nDb );
   694    694         pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
   695    695       }
   696    696     }
   697    697     return pSrc;
   698    698   }
   699    699   
   700    700   /*

Changes to src/vdbeInt.h.

   147    147   struct Mem {
   148    148     sqlite3 *db;        /* The associated database connection */
   149    149     char *z;            /* String or BLOB value */
   150    150     double r;           /* Real value */
   151    151     union {
   152    152       i64 i;              /* Integer value used when MEM_Int is set in flags */
   153    153       int nZero;          /* Used when bit MEM_Zero is set in flags */
          154  +    void *pPtr;         /* Pointer when flags==MEM_Ptr|MEM_Null */
   154    155       FuncDef *pDef;      /* Used only when flags==MEM_Agg */
   155    156       RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
   156    157       VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
   157    158     } u;
   158    159     int n;              /* Number of characters in string value, excluding '\0' */
   159    160     u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
   160    161     u8  type;           /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
................................................................................
   190    191   #define MEM_TypeMask  0x00ff   /* Mask of type bits */
   191    192   
   192    193   /* Whenever Mem contains a valid string or blob representation, one of
   193    194   ** the following flags must be set to determine the memory management
   194    195   ** policy for Mem.z.  The MEM_Term flag tells us whether or not the
   195    196   ** string is \000 or \u0000 terminated
   196    197   */
          198  +#define MEM_Ptr       0x8000   /* u.pPtr is valid if type==SQLITE_NULL */
   197    199   #define MEM_Term      0x0200   /* String rep is nul terminated */
   198    200   #define MEM_Dyn       0x0400   /* Need to call sqliteFree() on Mem.z */
   199    201   #define MEM_Static    0x0800   /* Mem.z points to a static string */
   200    202   #define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
   201    203   #define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
   202    204   #define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
   203    205   #ifdef SQLITE_OMIT_INCRBLOB
................................................................................
   205    207     #define MEM_Zero 0x0000
   206    208   #endif
   207    209   
   208    210   /*
   209    211   ** Clear any existing type flags from a Mem and replace them with f
   210    212   */
   211    213   #define MemSetTypeFlag(p, f) \
   212         -   ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
          214  +   ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero|MEM_Ptr))|f)
   213    215   
   214    216   /*
   215    217   ** Return true if a memory cell is not marked as invalid.  This macro
   216    218   ** is for use inside assert() statements only.
   217    219   */
   218    220   #ifdef SQLITE_DEBUG
   219    221   #define memIsValid(M)  ((M)->flags & MEM_Invalid)==0

Changes to src/vdbeapi.c.

   158    158     return sqlite3VdbeRealValue((Mem*)pVal);
   159    159   }
   160    160   int sqlite3_value_int(sqlite3_value *pVal){
   161    161     return (int)sqlite3VdbeIntValue((Mem*)pVal);
   162    162   }
   163    163   sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
   164    164     return sqlite3VdbeIntValue((Mem*)pVal);
          165  +}
          166  +void *sqlite3_value_pointer(sqlite3_value *pVal){
          167  +  Mem *p = (Mem*)pVal;
          168  +  if( (p->flags&(MEM_TypeMask|MEM_Ptr))==(MEM_Null|MEM_Ptr) ) return p->u.pPtr;
          169  +  return 0;
   165    170   }
   166    171   const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
   167    172     return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
   168    173   }
   169    174   #ifndef SQLITE_OMIT_UTF16
   170    175   const void *sqlite3_value_text16(sqlite3_value* pVal){
   171    176     return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
................................................................................
   229    234   void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
   230    235     assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   231    236     sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
   232    237   }
   233    238   void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
   234    239     assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   235    240     sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
          241  +}
          242  +void sqlite3_result_pointer(sqlite3_context *pCtx, void *pPtr){
          243  +  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
          244  +  sqlite3VdbeMemSetNull(&pCtx->s);
          245  +  assert( (pCtx->s.flags & (MEM_TypeMask|MEM_Ptr))==MEM_Null );
          246  +  pCtx->s.flags |= MEM_Ptr;
          247  +  pCtx->s.u.pPtr = pPtr;
   236    248   }
   237    249   void sqlite3_result_null(sqlite3_context *pCtx){
   238    250     assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   239    251     sqlite3VdbeMemSetNull(&pCtx->s);
   240    252   }
   241    253   void sqlite3_result_text(
   242    254     sqlite3_context *pCtx, 

Changes to src/vtab.c.

    20     20   ** this struct allocated on the stack. It is used by the implementation of 
    21     21   ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
    22     22   ** are invoked only from within xCreate and xConnect methods.
    23     23   */
    24     24   struct VtabCtx {
    25     25     Table *pTab;
    26     26     VTable *pVTable;
           27  +  VtabCtx *pPrior;    /* Parent context (if any) */
           28  +  int bDeclared;      /* True after sqlite3_declare_vtab() is called */
    27     29   };
    28     30   
    29     31   /*
    30     32   ** The actual function that does the work of creating a new module.
    31     33   ** This function implements the sqlite3_create_module() and
    32     34   ** sqlite3_create_module_v2() interfaces.
    33     35   */
................................................................................
   449    451   ){
   450    452     VtabCtx sCtx;
   451    453     VTable *pVTable;
   452    454     int rc;
   453    455     const char *const*azArg = (const char *const*)pTab->azModuleArg;
   454    456     int nArg = pTab->nModuleArg;
   455    457     char *zErr = 0;
   456         -  char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
          458  +  char *zModuleName;
          459  +  VtabCtx *pCtx;
   457    460   
          461  +  /* Check that the virtual-table is not already being initialized */
          462  +  for(pCtx=db->pVtabCtx; pCtx; pCtx=pCtx->pPrior){
          463  +    if( pCtx->pTab==pTab ){
          464  +      *pzErr = sqlite3MPrintf(db, 
          465  +          "vtable constructor called recursively: %s", pTab->zName
          466  +      );
          467  +      return SQLITE_LOCKED;
          468  +    }
          469  +  }
          470  +
          471  +  zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
   458    472     if( !zModuleName ){
   459    473       return SQLITE_NOMEM;
   460    474     }
   461    475   
   462    476     pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
   463    477     if( !pVTable ){
   464    478       sqlite3DbFree(db, zModuleName);
................................................................................
   468    482     pVTable->pMod = pMod;
   469    483   
   470    484     /* Invoke the virtual table constructor */
   471    485     assert( &db->pVtabCtx );
   472    486     assert( xConstruct );
   473    487     sCtx.pTab = pTab;
   474    488     sCtx.pVTable = pVTable;
          489  +  sCtx.pPrior = db->pVtabCtx;
          490  +  sCtx.bDeclared = 0;
   475    491     db->pVtabCtx = &sCtx;
   476    492     rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
   477         -  db->pVtabCtx = 0;
          493  +  db->pVtabCtx = sCtx.pPrior;
   478    494     if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
          495  +  assert( sCtx.pTab==pTab );
   479    496   
   480    497     if( SQLITE_OK!=rc ){
   481    498       if( zErr==0 ){
   482    499         *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
   483    500       }else {
   484    501         *pzErr = sqlite3MPrintf(db, "%s", zErr);
   485    502         sqlite3_free(zErr);
................................................................................
   486    503       }
   487    504       sqlite3DbFree(db, pVTable);
   488    505     }else if( ALWAYS(pVTable->pVtab) ){
   489    506       /* Justification of ALWAYS():  A correct vtab constructor must allocate
   490    507       ** the sqlite3_vtab object if successful.  */
   491    508       pVTable->pVtab->pModule = pMod->pModule;
   492    509       pVTable->nRef = 1;
   493         -    if( sCtx.pTab ){
          510  +    if( sCtx.bDeclared==0 ){
   494    511         const char *zFormat = "vtable constructor did not declare schema: %s";
   495    512         *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
   496    513         sqlite3VtabUnlock(pVTable);
   497    514         rc = SQLITE_ERROR;
   498    515       }else{
   499    516         int iCol;
   500    517         /* If everything went according to plan, link the new VTable structure
................................................................................
   656    673   
   657    674   /*
   658    675   ** This function is used to set the schema of a virtual table.  It is only
   659    676   ** valid to call this function from within the xCreate() or xConnect() of a
   660    677   ** virtual table module.
   661    678   */
   662    679   int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
          680  +  VtabCtx *pCtx = db->pVtabCtx;
   663    681     Parse *pParse;
   664         -
   665    682     int rc = SQLITE_OK;
   666    683     Table *pTab;
   667    684     char *zErr = 0;
   668    685   
   669    686     sqlite3_mutex_enter(db->mutex);
   670         -  if( !db->pVtabCtx || !(pTab = db->pVtabCtx->pTab) ){
          687  +  if( !pCtx || pCtx->bDeclared ){
   671    688       sqlite3Error(db, SQLITE_MISUSE, 0);
   672    689       sqlite3_mutex_leave(db->mutex);
   673    690       return SQLITE_MISUSE_BKPT;
   674    691     }
          692  +  pTab = pCtx->pTab;
   675    693     assert( (pTab->tabFlags & TF_Virtual)!=0 );
   676    694   
   677    695     pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
   678    696     if( pParse==0 ){
   679    697       rc = SQLITE_NOMEM;
   680    698     }else{
   681    699       pParse->declareVtab = 1;
................................................................................
   690    708       ){
   691    709         if( !pTab->aCol ){
   692    710           pTab->aCol = pParse->pNewTable->aCol;
   693    711           pTab->nCol = pParse->pNewTable->nCol;
   694    712           pParse->pNewTable->nCol = 0;
   695    713           pParse->pNewTable->aCol = 0;
   696    714         }
   697         -      db->pVtabCtx->pTab = 0;
          715  +      pCtx->bDeclared = 1;
   698    716       }else{
   699    717         sqlite3Error(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
   700    718         sqlite3DbFree(db, zErr);
   701    719         rc = SQLITE_ERROR;
   702    720       }
   703    721       pParse->declareVtab = 0;
   704    722     

Changes to test/analyze.test.

   354    354       UPDATE sqlite_master SET sql='nonsense' WHERE name='sqlite_stat1';
   355    355     }
   356    356     db close
   357    357     catch { sqlite3 db test.db }
   358    358     catchsql {
   359    359       ANALYZE
   360    360     }
   361         -} {1 {malformed database schema (sqlite_stat1) - near "nonsense": syntax error}}
          361  +} {1 {malformed database schema (sqlite_stat1)}}
   362    362   
   363    363   
   364    364   finish_test

Changes to test/e_reindex.test.

    44     44   #    Test this by corrupting some database indexes, running REINDEX, and
    45     45   #    observing that the corruption is gone.
    46     46   #
    47     47   do_execsql_test e_reindex-1.1 {
    48     48     INSERT INTO t1 VALUES(1, 2);
    49     49     INSERT INTO t1 VALUES(3, 4);
    50     50     INSERT INTO t1 VALUES(5, 6);
           51  +  CREATE TABLE saved(a,b,c,d,e);
           52  +  INSERT INTO saved SELECT * FROM sqlite_master WHERE type = 'index';
    51     53     PRAGMA writable_schema = 1;
    52         -  UPDATE sqlite_master SET sql = '-- ' || sql WHERE type = 'index';
           54  +  DELETE FROM sqlite_master WHERE type = 'index';
    53     55   } {}
    54     56   
    55     57   db close
    56     58   sqlite3 db test.db
    57     59   do_execsql_test e_reindex-1.2 {
    58     60     DELETE FROM t1 WHERE a = 3;
    59     61     INSERT INTO t1 VALUES(7, 8);
    60     62     INSERT INTO t1 VALUES(9, 10);
    61     63     PRAGMA writable_schema = 1;
    62         -  UPDATE sqlite_master SET sql = substr(sql, 4) WHERE type = 'index';
           64  +  INSERT INTO sqlite_master SELECT * FROM saved;
           65  +  DROP TABLE saved;
    63     66   } {}
    64     67   
    65     68   db close
    66     69   sqlite3 db test.db
    67     70   do_execsql_test e_reindex-1.3 {
    68     71     PRAGMA integrity_check;
    69     72   } [list \

Changes to test/fkey1.test.

   113    113       );
   114    114       PRAGMA foreign_key_list(t9);
   115    115     }
   116    116   } [concat                        \
   117    117     {0 0 t5 d {} {SET DEFAULT} CASCADE NONE} \
   118    118     {0 1 t5 e {} {SET DEFAULT} CASCADE NONE} \
   119    119   ]
          120  +
          121  +# Stress the dequoting logic.  The first test is not so bad.
          122  +do_execsql_test fkey1-4.0 {
          123  +  PRAGMA foreign_keys=ON;
          124  +  CREATE TABLE "xx1"("xx2" TEXT PRIMARY KEY, "xx3" TEXT);
          125  +  INSERT INTO "xx1"("xx2","xx3") VALUES('abc','def');
          126  +  CREATE TABLE "xx4"("xx5" TEXT REFERENCES "xx1" ON DELETE CASCADE);
          127  +  INSERT INTO "xx4"("xx5") VALUES('abc');
          128  +  INSERT INTO "xx1"("xx2","xx3") VALUES('uvw','xyz');
          129  +  SELECT 1, "xx5" FROM "xx4";
          130  +  DELETE FROM "xx1";
          131  +  SELECT 2, "xx5" FROM "xx4";
          132  +} {1 abc}
          133  +
          134  +# This case is identical to the previous except the "xx" in each name
          135  +# is changed to a single escaped double-quote character.
          136  +do_execsql_test fkey1-4.1 {
          137  +  PRAGMA foreign_keys=ON;
          138  +  CREATE TABLE """1"("""2" TEXT PRIMARY KEY, """3" TEXT);
          139  +  INSERT INTO """1"("""2","""3") VALUES('abc','def');
          140  +  CREATE TABLE """4"("""5" TEXT REFERENCES """1" ON DELETE CASCADE);
          141  +  INSERT INTO """4"("""5") VALUES('abc');
          142  +  INSERT INTO """1"("""2","""3") VALUES('uvw','xyz');
          143  +  SELECT 1, """5" FROM """4";
          144  +  DELETE FROM """1";
          145  +  SELECT 2, """5" FROM """4";
          146  +} {1 abc}
          147  +do_execsql_test fkey1-4.2 {
          148  +  PRAGMA table_info="""1";
          149  +} {0 {"2} TEXT 0 {} 1 1 {"3} TEXT 0 {} 0}
   120    150   
   121    151   finish_test

Changes to test/fts3prefix.test.

   205    205   #
   206    206   do_catchsql_test 5.1 {
   207    207     CREATE VIRTUAL TABLE t4 USING fts4(prefix="abc");
   208    208   } {1 {error parsing prefix parameter: abc}}
   209    209   do_catchsql_test 5.2 {
   210    210     CREATE VIRTUAL TABLE t4 USING fts4(prefix="");
   211    211   } {0 {}}
          212  +do_catchsql_test 5.3 {
          213  +  CREATE VIRTUAL TABLE t5 USING fts4(prefix="-1");
          214  +} {1 {error parsing prefix parameter: -1}}
          215  +
          216  +#-------------------------------------------------------------------------
          217  +# Prefix indexes of size 0 are ignored. Demonstrate this by showing that
          218  +# adding prefix=0 does not change the contents of the %_segdir table.
          219  +#
          220  +reset_db
          221  +do_execsql_test 6.1.1 {
          222  +  CREATE VIRTUAL TABLE t1 USING fts4(prefix=0);
          223  +  CREATE VIRTUAL TABLE t2 USING fts4;
          224  +  INSERT INTO t1 VALUES('Twas Mulga Bill, from Eaglehawk, ');
          225  +  INSERT INTO t2 VALUES('Twas Mulga Bill, from Eaglehawk, ');
          226  +} {}
          227  +do_execsql_test 6.1.2 {
          228  +  SELECT md5sum(quote(root)) FROM t1_segdir;
          229  +} [db eval {SELECT md5sum(quote(root)) FROM t2_segdir}]
          230  +
          231  +reset_db
          232  +do_execsql_test 6.2.1 {
          233  +  CREATE VIRTUAL TABLE t1 USING fts4(prefix="1,0,2");
          234  +  CREATE VIRTUAL TABLE t2 USING fts4(prefix="1,2");
          235  +  INSERT INTO t1 VALUES('that caught the cycling craze;');
          236  +  INSERT INTO t2 VALUES('that caught the cycling craze;');
          237  +} {}
          238  +do_execsql_test 6.2.2 {
          239  +  SELECT md5sum(quote(root)) FROM t1_segdir;
          240  +} [db eval {SELECT md5sum(quote(root)) FROM t2_segdir}]
          241  +
          242  +reset_db
          243  +do_execsql_test 6.3.1 {
          244  +  CREATE VIRTUAL TABLE t1 USING fts4(prefix="1,3,2");
          245  +  CREATE VIRTUAL TABLE t2 USING fts4(prefix="1,2");
          246  +  INSERT INTO t1 VALUES('He turned away the good old horse');
          247  +  INSERT INTO t2 VALUES('He turned away the good old horse');
          248  +} {}
          249  +do_test 6.3.2 {
          250  +  set one [db eval {SELECT md5sum(quote(root)) FROM t1_segdir}]
          251  +  set two [db eval {SELECT md5sum(quote(root)) FROM t2_segdir}]
          252  +  expr {$one == $two}
          253  +} 0
          254  +
          255  +reset_db
          256  +do_execsql_test 6.4.1 {
          257  +  CREATE VIRTUAL TABLE t1 USING fts4(prefix="1,600,2");
          258  +  CREATE VIRTUAL TABLE t2 USING fts4(prefix="1,2");
          259  +  INSERT INTO t1 VALUES('that served him many days;');
          260  +  INSERT INTO t2 VALUES('that served him many days;');
          261  +} {}
          262  +do_execsql_test 6.4.2 {
          263  +  SELECT md5sum(quote(root)) FROM t1_segdir;
          264  +} [db eval {SELECT md5sum(quote(root)) FROM t2_segdir}]
          265  +
          266  +reset_db
          267  +do_execsql_test 6.5.1 {
          268  +  CREATE VIRTUAL TABLE t1 USING fts4(prefix="2147483647,2147483648,2147483649");
          269  +  CREATE VIRTUAL TABLE t2 USING fts4(prefix="");
          270  +  INSERT INTO t1 VALUES('He dressed himself in cycling clothes');
          271  +  INSERT INTO t2 VALUES('He dressed himself in cycling clothes');
          272  +} {}
          273  +do_execsql_test 6.5.2 {
          274  +  SELECT md5sum(quote(root)) FROM t1_segdir;
          275  +} [db eval {SELECT md5sum(quote(root)) FROM t2_segdir}]
   212    276   
   213    277   finish_test

Changes to test/fts4content.test.

    42     42   #   7.* - Test that if content=xxx is specified and table xxx does not
    43     43   #         exist, the FTS table can still be used for INSERT and some
    44     44   #         SELECT statements.
    45     45   #
    46     46   #   8.* - Test that if the content=xxx and prefix options are used together,
    47     47   #         the 'rebuild' command still works.
    48     48   #
           49  +#   11.* - Test that circular references (e.g. "t1(content=t1)") are
           50  +#          detected.
           51  +#
    49     52   
    50     53   do_execsql_test 1.1.1 {
    51     54     CREATE TABLE t1(a, b, c);
    52     55     INSERT INTO t1 VALUES('w x', 'x y', 'y z');
    53     56     CREATE VIRTUAL TABLE ft1 USING fts4(content=t1);
    54     57   }
    55     58   
................................................................................
   400    403   }
   401    404   
   402    405   #-------------------------------------------------------------------------
   403    406   # Test cases 6.* test 
   404    407   # 
   405    408   do_catchsql_test 6.1.1 {
   406    409     CREATE VIRTUAL TABLE ft7 USING fts4(content=t7);
   407         -} {1 {vtable constructor failed: ft7}}
          410  +} {1 {no such table: main.t7}}
   408    411   
   409    412   do_execsql_test 6.2.1 {
   410    413     CREATE TABLE t7(one, two);
   411    414     CREATE VIRTUAL TABLE ft7 USING fts4(content=t7);
   412    415     INSERT INTO t7 VALUES('A B', 'B A');
   413    416     INSERT INTO t7 VALUES('C D', 'A A');
   414    417     SELECT * FROM ft7;
................................................................................
   427    430     SELECT name FROM sqlite_master WHERE name LIKE '%t7%'
   428    431   } {
   429    432     ft7 ft7_segments ft7_segdir sqlite_autoindex_ft7_segdir_1 
   430    433     ft7_docsize ft7_stat
   431    434   }
   432    435   do_catchsql_test 6.2.4 {
   433    436     SELECT * FROM ft7;
   434         -} {1 {vtable constructor failed: ft7}}
          437  +} {1 {no such table: main.t7}}
   435    438   do_execsql_test 6.2.5 {
   436    439     CREATE TABLE t7(x, y);
   437    440     INSERT INTO t7 VALUES('A B', 'B A');
   438    441     INSERT INTO t7 VALUES('C D', 'A A');
   439    442     SELECT * FROM ft7;
   440    443   } {
   441    444     {A B} {B A} {C D} {A A}
................................................................................
   517    520   }
   518    521   
   519    522   do_execsql_test 8.2 { SELECT * FROM ft10 WHERE a MATCH 'ab*';          }
   520    523   do_execsql_test 8.3 { INSERT INTO ft10(ft10) VALUES('rebuild');        }
   521    524   do_execsql_test 8.4 { SELECT rowid FROM ft10 WHERE a MATCH 'ab*';      } {1 2 3}
   522    525   do_execsql_test 8.5 { SELECT rowid FROM ft10 WHERE b MATCH 'abav*';    } {3}
   523    526   do_execsql_test 8.6 { SELECT rowid FROM ft10 WHERE ft10 MATCH 'abas*'; } {1}
          527  +
          528  +#-------------------------------------------------------------------------
          529  +# Test cases 9.*
          530  +# 
          531  +reset_db
          532  +register_echo_module [sqlite3_connection_pointer db]
          533  +
          534  +do_execsql_test 9.1 {
          535  +  CREATE TABLE tbl1(a, b);
          536  +  INSERT INTO tbl1 VALUES('a b', 'c d');
          537  +  INSERT INTO tbl1 VALUES('e f', 'a b');
          538  +  CREATE VIRTUAL TABLE e1 USING echo(tbl1);
          539  +  CREATE VIRTUAL TABLE ft1 USING fts4(content=e1);
          540  +  INSERT INTO ft1(ft1) VALUES('rebuild');
          541  +}
          542  +
          543  +do_execsql_test 9.2 {
          544  +  SELECT rowid, * FROM ft1 WHERE ft1 MATCH 'e'
          545  +} {2 {e f} {a b}}
          546  +
          547  +do_execsql_test 9.3 {
          548  +  SELECT rowid, * FROM ft1 WHERE ft1 MATCH 'a'
          549  +} {1 {a b} {c d} 2 {e f} {a b}}
          550  +
          551  +do_execsql_test 9.4 { 
          552  +  DELETE FROM ft1 WHERE docid=1;
          553  +}
          554  +
          555  +do_execsql_test 9.5 {
          556  +  SELECT rowid, * FROM ft1 WHERE ft1 MATCH 'a'
          557  +} {2 {e f} {a b}}
          558  +
          559  +do_execsql_test 9.6 {
          560  +  INSERT INTO ft1(ft1) VALUES('rebuild');
          561  +  SELECT rowid, * FROM ft1 WHERE ft1 MATCH 'a'
          562  +} {1 {a b} {c d} 2 {e f} {a b}}
          563  +
          564  +#-------------------------------------------------------------------------
          565  +# Test cases 11.*
          566  +# 
          567  +reset_db
          568  +
          569  +do_catchsql_test 11.1 {
          570  +  CREATE VIRTUAL TABLE x1 USING fts4(content=x1);
          571  +} {1 {vtable constructor called recursively: x1}}
   524    572   
   525    573   finish_test

Changes to test/index3.test.

    47     47     execsql {
    48     48       PRAGMA writable_schema=on;
    49     49       UPDATE sqlite_master SET sql='nonsense';
    50     50     }
    51     51     db close
    52     52     catch { sqlite3 db test.db }
    53     53     catchsql { DROP INDEX i1 }
    54         -} {1 {malformed database schema (t1) - near "nonsense": syntax error}}
           54  +} {1 {malformed database schema (t1)}}
    55     55   
    56     56   finish_test

Changes to test/trigger7.test.

   110    110     execsql {
   111    111       PRAGMA writable_schema=on;
   112    112       UPDATE sqlite_master SET sql='nonsense';
   113    113     }
   114    114     db close
   115    115     catch { sqlite3 db test.db }
   116    116     catchsql { DROP TRIGGER t2r5 }
   117         -} {1 {malformed database schema (t2r12) - near "nonsense": syntax error}}
          117  +} {1 {malformed database schema (t2r12)}}
   118    118   
   119    119   finish_test

Changes to test/triggerC.test.

     8      8   #    May you share freely, never taking more than you give.
     9      9   #
    10     10   #***********************************************************************
    11     11   #
    12     12   
    13     13   set testdir [file dirname $argv0]
    14     14   source $testdir/tester.tcl
           15  +set testprefix triggerC
    15     16   ifcapable {!trigger} {
    16     17     finish_test
    17     18     return
    18     19   }
    19     20   
    20     21   #-------------------------------------------------------------------------
    21     22   # Test organization:
................................................................................
   946    947     END;
   947    948   } {}
   948    949   do_catchsql_test triggerC-13.2 {
   949    950     UPDATE t12 SET a=a+1, b=b+1;
   950    951   } {1 {too many levels of trigger recursion}}
   951    952   
   952    953   
          954  +
          955  +#-------------------------------------------------------------------------
          956  +# Check that table names used by trigger programs are dequoted exactly
          957  +# once.
          958  +#
          959  +do_execsql_test 15.1.1 {
          960  +  PRAGMA recursive_triggers = 1;
          961  +  CREATE TABLE node(
          962  +      id int not null primary key, 
          963  +      pid int not null default 0 references node,
          964  +      key varchar not null, 
          965  +      path varchar default '',
          966  +      unique(pid, key)
          967  +      );
          968  +  CREATE TRIGGER node_delete_referencing AFTER DELETE ON "node"
          969  +    BEGIN
          970  +    DELETE FROM "node" WHERE pid = old."id";
          971  +  END;
          972  +}
          973  +do_execsql_test 15.1.2 {
          974  +  INSERT INTO node(id, pid, key) VALUES(9, 0, 'test');
          975  +  INSERT INTO node(id, pid, key) VALUES(90, 9, 'test1');
          976  +  INSERT INTO node(id, pid, key) VALUES(900, 90, 'test2');
          977  +  DELETE FROM node WHERE id=9;
          978  +  SELECT * FROM node;
          979  +}
          980  +
          981  +do_execsql_test 15.2.1 {
          982  +  CREATE TABLE   x1  (x);
          983  +
          984  +  CREATE TABLE   x2  (a, b);
          985  +  CREATE TABLE '"x2"'(a, b);
          986  +
          987  +  INSERT INTO x2 VALUES(1, 2);
          988  +  INSERT INTO x2 VALUES(3, 4);
          989  +  INSERT INTO '"x2"' SELECT * FROM x2;
          990  +
          991  +  CREATE TRIGGER x1ai AFTER INSERT ON x1 BEGIN
          992  +    INSERT INTO """x2""" VALUES('x', 'y');
          993  +    DELETE FROM """x2""" WHERE a=1;
          994  +    UPDATE """x2""" SET b = 11 WHERE a = 3;
          995  +  END;
          996  +
          997  +  INSERT INTO x1 VALUES('go!');
          998  +}
          999  +
         1000  +do_execsql_test 15.2.2 { SELECT * FROM x2;       } {1 2 3 4}
         1001  +do_execsql_test 15.2.3 { SELECT * FROM """x2"""; } {3 11 x y}
   953   1002   
   954   1003   finish_test