/ Check-in [00759af0]
Login

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

Overview
Comment:Merge recent enhancements from trunk.
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | apple-osx
Files: files | file ages | folders
SHA1: 00759af053e0ea9bd73dba2cf6cad83598ea393b
User & Date: drh 2016-09-07 18:20:09
Context
2016-09-16
17:50
Merge recent changes from trunk. check-in: e3d9efa2 user: drh tags: apple-osx
2016-09-07
18:20
Merge recent enhancements from trunk. check-in: 00759af0 user: drh tags: apple-osx
18:11
Add the ext/misc/memvfs.c extension that implements a VFS for read-only database files contained in memory. check-in: 12b7782a user: drh tags: trunk
2016-08-08
14:21
Merge all changes from the 3.14 release. check-in: c3cd543f user: drh tags: apple-osx
Changes
Hide Diffs Side-by-Side Diffs Show Whitespace Changes Patch

Changes to Makefile.msc.

    19     19   # <</mark>>
    20     20   
    21     21   # Set this non-0 to enable full warnings (-W4, etc) when compiling.
    22     22   #
    23     23   !IFNDEF USE_FULLWARN
    24     24   USE_FULLWARN = 0
    25     25   !ENDIF
           26  +
           27  +# Set this non-0 to enable full runtime error checks (-RTC1, etc).  This
           28  +# has no effect if (any) optimizations are enabled.
           29  +#
           30  +!IFNDEF USE_RUNTIME_CHECKS
           31  +USE_RUNTIME_CHECKS = 0
           32  +!ENDIF
    26     33   
    27     34   # Set this non-0 to use "stdcall" calling convention for the core library
    28     35   # and shell executable.
    29     36   #
    30     37   !IFNDEF USE_STDCALL
    31     38   USE_STDCALL = 0
    32     39   !ENDIF
................................................................................
   831    838   
   832    839   # If optimizations are enabled or disabled (either implicitly or
   833    840   # explicitly), add the necessary flags.
   834    841   #
   835    842   !IF $(DEBUG)>1 || $(OPTIMIZATIONS)==0
   836    843   TCC = $(TCC) -Od
   837    844   BCC = $(BCC) -Od
          845  +!IF $(USE_RUNTIME_CHECKS)!=0
          846  +TCC = $(TCC) -RTC1
          847  +BCC = $(BCC) -RTC1
          848  +!ENDIF
   838    849   !ELSEIF $(OPTIMIZATIONS)>=3
   839    850   TCC = $(TCC) -Ox
   840    851   BCC = $(BCC) -Ox
   841    852   !ELSEIF $(OPTIMIZATIONS)==2
   842    853   TCC = $(TCC) -O2
   843    854   BCC = $(BCC) -O2
   844    855   !ELSEIF $(OPTIMIZATIONS)==1

Changes to VERSION.

     1         -3.14.0
            1  +3.15.0

Changes to autoconf/Makefile.msc.

   452    452   # also be noted here that building any target with these "stdcall" options
   453    453   # will most likely fail if the Tcl library is also required.  This is due
   454    454   # to how the Tcl library functions are declared and exported (i.e. without
   455    455   # an explicit calling convention, which results in "cdecl").
   456    456   #
   457    457   !IF $(USE_STDCALL)!=0 || $(FOR_WIN10)!=0
   458    458   !IF "$(PLATFORM)"=="x86"
   459         -CORE_CCONV_OPTS = -Gz -DSQLITE_CDECL=__cdecl -DSQLITE_APICALL=__stdcall -DSQLITE_CALLBACK=__stdcall -DSQLITE_SYSAPI=__stdcall
   460         -SHELL_CCONV_OPTS = -Gz -DSQLITE_CDECL=__cdecl -DSQLITE_APICALL=__stdcall -DSQLITE_CALLBACK=__stdcall -DSQLITE_SYSAPI=__stdcall
          459  +CORE_CCONV_OPTS = -Gz -DSQLITE_CDECL=__cdecl -DSQLITE_STDCALL=__stdcall
          460  +SHELL_CCONV_OPTS = -Gz -DSQLITE_CDECL=__cdecl -DSQLITE_STDCALL=__stdcall
   461    461   !ELSE
   462    462   !IFNDEF PLATFORM
   463         -CORE_CCONV_OPTS = -Gz -DSQLITE_CDECL=__cdecl -DSQLITE_APICALL=__stdcall -DSQLITE_CALLBACK=__stdcall -DSQLITE_SYSAPI=__stdcall
   464         -SHELL_CCONV_OPTS = -Gz -DSQLITE_CDECL=__cdecl -DSQLITE_APICALL=__stdcall -DSQLITE_CALLBACK=__stdcall -DSQLITE_SYSAPI=__stdcall
          463  +CORE_CCONV_OPTS = -Gz -DSQLITE_CDECL=__cdecl -DSQLITE_STDCALL=__stdcall
          464  +SHELL_CCONV_OPTS = -Gz -DSQLITE_CDECL=__cdecl -DSQLITE_STDCALL=__stdcall
   465    465   !ELSE
   466    466   CORE_CCONV_OPTS =
   467    467   SHELL_CCONV_OPTS =
   468    468   !ENDIF
   469    469   !ENDIF
   470    470   !ELSE
   471    471   CORE_CCONV_OPTS =

Changes to configure.

     1      1   #! /bin/sh
     2      2   # Guess values for system-dependent variables and create Makefiles.
     3         -# Generated by GNU Autoconf 2.69 for sqlite 3.14.0.
            3  +# Generated by GNU Autoconf 2.69 for sqlite 3.15.0.
     4      4   #
     5      5   #
     6      6   # Copyright (C) 1992-1996, 1998-2012 Free Software Foundation, Inc.
     7      7   #
     8      8   #
     9      9   # This configure script is free software; the Free Software Foundation
    10     10   # gives unlimited permission to copy, distribute and modify it.
................................................................................
   722    722   subdirs=
   723    723   MFLAGS=
   724    724   MAKEFLAGS=
   725    725   
   726    726   # Identity of this package.
   727    727   PACKAGE_NAME='sqlite'
   728    728   PACKAGE_TARNAME='sqlite'
   729         -PACKAGE_VERSION='3.14.0'
   730         -PACKAGE_STRING='sqlite 3.14.0'
          729  +PACKAGE_VERSION='3.15.0'
          730  +PACKAGE_STRING='sqlite 3.15.0'
   731    731   PACKAGE_BUGREPORT=''
   732    732   PACKAGE_URL=''
   733    733   
   734    734   # Factoring default headers for most tests.
   735    735   ac_includes_default="\
   736    736   #include <stdio.h>
   737    737   #ifdef HAVE_SYS_TYPES_H
................................................................................
  1459   1459   #
  1460   1460   # Report the --help message.
  1461   1461   #
  1462   1462   if test "$ac_init_help" = "long"; then
  1463   1463     # Omit some internal or obsolete options to make the list less imposing.
  1464   1464     # This message is too long to be a string in the A/UX 3.1 sh.
  1465   1465     cat <<_ACEOF
  1466         -\`configure' configures sqlite 3.14.0 to adapt to many kinds of systems.
         1466  +\`configure' configures sqlite 3.15.0 to adapt to many kinds of systems.
  1467   1467   
  1468   1468   Usage: $0 [OPTION]... [VAR=VALUE]...
  1469   1469   
  1470   1470   To assign environment variables (e.g., CC, CFLAGS...), specify them as
  1471   1471   VAR=VALUE.  See below for descriptions of some of the useful variables.
  1472   1472   
  1473   1473   Defaults for the options are specified in brackets.
................................................................................
  1524   1524     --build=BUILD     configure for building on BUILD [guessed]
  1525   1525     --host=HOST       cross-compile to build programs to run on HOST [BUILD]
  1526   1526   _ACEOF
  1527   1527   fi
  1528   1528   
  1529   1529   if test -n "$ac_init_help"; then
  1530   1530     case $ac_init_help in
  1531         -     short | recursive ) echo "Configuration of sqlite 3.14.0:";;
         1531  +     short | recursive ) echo "Configuration of sqlite 3.15.0:";;
  1532   1532      esac
  1533   1533     cat <<\_ACEOF
  1534   1534   
  1535   1535   Optional Features:
  1536   1536     --disable-option-checking  ignore unrecognized --enable/--with options
  1537   1537     --disable-FEATURE       do not include FEATURE (same as --enable-FEATURE=no)
  1538   1538     --enable-FEATURE[=ARG]  include FEATURE [ARG=yes]
................................................................................
  1648   1648       cd "$ac_pwd" || { ac_status=$?; break; }
  1649   1649     done
  1650   1650   fi
  1651   1651   
  1652   1652   test -n "$ac_init_help" && exit $ac_status
  1653   1653   if $ac_init_version; then
  1654   1654     cat <<\_ACEOF
  1655         -sqlite configure 3.14.0
         1655  +sqlite configure 3.15.0
  1656   1656   generated by GNU Autoconf 2.69
  1657   1657   
  1658   1658   Copyright (C) 2012 Free Software Foundation, Inc.
  1659   1659   This configure script is free software; the Free Software Foundation
  1660   1660   gives unlimited permission to copy, distribute and modify it.
  1661   1661   _ACEOF
  1662   1662     exit
................................................................................
  2067   2067     eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
  2068   2068   
  2069   2069   } # ac_fn_c_check_header_mongrel
  2070   2070   cat >config.log <<_ACEOF
  2071   2071   This file contains any messages produced by compilers while
  2072   2072   running configure, to aid debugging if configure makes a mistake.
  2073   2073   
  2074         -It was created by sqlite $as_me 3.14.0, which was
         2074  +It was created by sqlite $as_me 3.15.0, which was
  2075   2075   generated by GNU Autoconf 2.69.  Invocation command line was
  2076   2076   
  2077   2077     $ $0 $@
  2078   2078   
  2079   2079   _ACEOF
  2080   2080   exec 5>>config.log
  2081   2081   {
................................................................................
 12147  12147   test $as_write_fail = 0 && chmod +x $CONFIG_STATUS || ac_write_fail=1
 12148  12148   
 12149  12149   cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
 12150  12150   # Save the log message, to keep $0 and so on meaningful, and to
 12151  12151   # report actual input values of CONFIG_FILES etc. instead of their
 12152  12152   # values after options handling.
 12153  12153   ac_log="
 12154         -This file was extended by sqlite $as_me 3.14.0, which was
        12154  +This file was extended by sqlite $as_me 3.15.0, which was
 12155  12155   generated by GNU Autoconf 2.69.  Invocation command line was
 12156  12156   
 12157  12157     CONFIG_FILES    = $CONFIG_FILES
 12158  12158     CONFIG_HEADERS  = $CONFIG_HEADERS
 12159  12159     CONFIG_LINKS    = $CONFIG_LINKS
 12160  12160     CONFIG_COMMANDS = $CONFIG_COMMANDS
 12161  12161     $ $0 $@
................................................................................
 12213  12213   
 12214  12214   Report bugs to the package provider."
 12215  12215   
 12216  12216   _ACEOF
 12217  12217   cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
 12218  12218   ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`"
 12219  12219   ac_cs_version="\\
 12220         -sqlite config.status 3.14.0
        12220  +sqlite config.status 3.15.0
 12221  12221   configured by $0, generated by GNU Autoconf 2.69,
 12222  12222     with options \\"\$ac_cs_config\\"
 12223  12223   
 12224  12224   Copyright (C) 2012 Free Software Foundation, Inc.
 12225  12225   This config.status script is free software; the Free Software Foundation
 12226  12226   gives unlimited permission to copy, distribute and modify it."
 12227  12227   

Changes to ext/fts5/fts5Int.h.

   733    733   
   734    734   void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase*);
   735    735   void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset*);
   736    736   void sqlite3Fts5ParseNodeFree(Fts5ExprNode*);
   737    737   
   738    738   void sqlite3Fts5ParseSetDistance(Fts5Parse*, Fts5ExprNearset*, Fts5Token*);
   739    739   void sqlite3Fts5ParseSetColset(Fts5Parse*, Fts5ExprNearset*, Fts5Colset*);
          740  +Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse*, Fts5Colset*);
   740    741   void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p);
   741    742   void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token*);
   742    743   
   743    744   /*
   744    745   ** End of interface to code in fts5_expr.c.
   745    746   **************************************************************************/
   746    747   

Changes to ext/fts5/fts5_aux.c.

   185    185         rc = fts5CInstIterNext(&p->iter);
   186    186       }
   187    187     }
   188    188   
   189    189     if( p->iRangeEnd>0 && iPos==p->iRangeEnd ){
   190    190       fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
   191    191       p->iOff = iEndOff;
   192         -    if( iPos<p->iter.iEnd ){
          192  +    if( iPos>=p->iter.iStart && iPos<p->iter.iEnd ){
   193    193         fts5HighlightAppend(&rc, p, p->zClose, -1);
   194    194       }
   195    195     }
   196    196   
   197    197     return rc;
   198    198   }
   199    199   
................................................................................
   241    241     if( rc!=SQLITE_OK ){
   242    242       sqlite3_result_error_code(pCtx, rc);
   243    243     }
   244    244   }
   245    245   /*
   246    246   ** End of highlight() implementation.
   247    247   **************************************************************************/
          248  +
          249  +/*
          250  +** Context object passed to the fts5SentenceFinderCb() function.
          251  +*/
          252  +typedef struct Fts5SFinder Fts5SFinder;
          253  +struct Fts5SFinder {
          254  +  int iPos;                       /* Current token position */
          255  +  int nFirstAlloc;                /* Allocated size of aFirst[] */
          256  +  int nFirst;                     /* Number of entries in aFirst[] */
          257  +  int *aFirst;                    /* Array of first token in each sentence */
          258  +  const char *zDoc;               /* Document being tokenized */
          259  +};
          260  +
          261  +/*
          262  +** Add an entry to the Fts5SFinder.aFirst[] array. Grow the array if
          263  +** necessary. Return SQLITE_OK if successful, or SQLITE_NOMEM if an
          264  +** error occurs.
          265  +*/
          266  +static int fts5SentenceFinderAdd(Fts5SFinder *p, int iAdd){
          267  +  if( p->nFirstAlloc==p->nFirst ){
          268  +    int nNew = p->nFirstAlloc ? p->nFirstAlloc*2 : 64;
          269  +    int *aNew;
          270  +
          271  +    aNew = (int*)sqlite3_realloc(p->aFirst, nNew*sizeof(int));
          272  +    if( aNew==0 ) return SQLITE_NOMEM;
          273  +    p->aFirst = aNew;
          274  +    p->nFirstAlloc = nNew;
          275  +  }
          276  +  p->aFirst[p->nFirst++] = iAdd;
          277  +  return SQLITE_OK;
          278  +}
          279  +
          280  +/*
          281  +** This function is an xTokenize() callback used by the auxiliary snippet()
          282  +** function. Its job is to identify tokens that are the first in a sentence.
          283  +** For each such token, an entry is added to the SFinder.aFirst[] array.
          284  +*/
          285  +static int fts5SentenceFinderCb(
          286  +  void *pContext,                 /* Pointer to HighlightContext object */
          287  +  int tflags,                     /* Mask of FTS5_TOKEN_* flags */
          288  +  const char *pToken,             /* Buffer containing token */
          289  +  int nToken,                     /* Size of token in bytes */
          290  +  int iStartOff,                  /* Start offset of token */
          291  +  int iEndOff                     /* End offset of token */
          292  +){
          293  +  int rc = SQLITE_OK;
          294  +
          295  +  if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
          296  +    Fts5SFinder *p = (Fts5SFinder*)pContext;
          297  +    if( p->iPos>0 ){
          298  +      int i;
          299  +      char c = 0;
          300  +      for(i=iStartOff-1; i>=0; i--){
          301  +        c = p->zDoc[i];
          302  +        if( c!=' ' && c!='\t' && c!='\n' && c!='\r' ) break;
          303  +      }
          304  +      if( i!=iStartOff-1 && (c=='.' || c==':') ){
          305  +        rc = fts5SentenceFinderAdd(p, p->iPos);
          306  +      }
          307  +    }else{
          308  +      rc = fts5SentenceFinderAdd(p, 0);
          309  +    }
          310  +    p->iPos++;
          311  +  }
          312  +  return rc;
          313  +}
          314  +
          315  +static int fts5SnippetScore(
          316  +  const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
          317  +  Fts5Context *pFts,              /* First arg to pass to pApi functions */
          318  +  int nDocsize,                   /* Size of column in tokens */
          319  +  unsigned char *aSeen,           /* Array with one element per query phrase */
          320  +  int iCol,                       /* Column to score */
          321  +  int iPos,                       /* Starting offset to score */
          322  +  int nToken,                     /* Max tokens per snippet */
          323  +  int *pnScore,                   /* OUT: Score */
          324  +  int *piPos                      /* OUT: Adjusted offset */
          325  +){
          326  +  int rc;
          327  +  int i;
          328  +  int ip = 0;
          329  +  int ic = 0;
          330  +  int iOff = 0;
          331  +  int iFirst = -1;
          332  +  int nInst;
          333  +  int nScore = 0;
          334  +  int iLast = 0;
          335  +
          336  +  rc = pApi->xInstCount(pFts, &nInst);
          337  +  for(i=0; i<nInst && rc==SQLITE_OK; i++){
          338  +    rc = pApi->xInst(pFts, i, &ip, &ic, &iOff);
          339  +    if( rc==SQLITE_OK && ic==iCol && iOff>=iPos && iOff<(iPos+nToken) ){
          340  +      nScore += (aSeen[ip] ? 1 : 1000);
          341  +      aSeen[ip] = 1;
          342  +      if( iFirst<0 ) iFirst = iOff;
          343  +      iLast = iOff + pApi->xPhraseSize(pFts, ip);
          344  +    }
          345  +  }
          346  +
          347  +  *pnScore = nScore;
          348  +  if( piPos ){
          349  +    int iAdj = iFirst - (nToken - (iLast-iFirst)) / 2;
          350  +    if( (iAdj+nToken)>nDocsize ) iAdj = nDocsize - nToken;
          351  +    if( iAdj<0 ) iAdj = 0;
          352  +    *piPos = iAdj;
          353  +  }
          354  +
          355  +  return rc;
          356  +}
   248    357   
   249    358   /*
   250    359   ** Implementation of snippet() function.
   251    360   */
   252    361   static void fts5SnippetFunction(
   253    362     const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
   254    363     Fts5Context *pFts,              /* First arg to pass to pApi functions */
................................................................................
   263    372     int nToken;                     /* 5th argument to snippet() */
   264    373     int nInst = 0;                  /* Number of instance matches this row */
   265    374     int i;                          /* Used to iterate through instances */
   266    375     int nPhrase;                    /* Number of phrases in query */
   267    376     unsigned char *aSeen;           /* Array of "seen instance" flags */
   268    377     int iBestCol;                   /* Column containing best snippet */
   269    378     int iBestStart = 0;             /* First token of best snippet */
   270         -  int iBestLast;                  /* Last token of best snippet */
   271    379     int nBestScore = 0;             /* Score of best snippet */
   272    380     int nColSize = 0;               /* Total size of iBestCol in tokens */
          381  +  Fts5SFinder sFinder;            /* Used to find the beginnings of sentences */
          382  +  int nCol;
   273    383   
   274    384     if( nVal!=5 ){
   275    385       const char *zErr = "wrong number of arguments to function snippet()";
   276    386       sqlite3_result_error(pCtx, zErr, -1);
   277    387       return;
   278    388     }
   279    389   
          390  +  nCol = pApi->xColumnCount(pFts);
   280    391     memset(&ctx, 0, sizeof(HighlightContext));
   281    392     iCol = sqlite3_value_int(apVal[0]);
   282    393     ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
   283    394     ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
   284    395     zEllips = (const char*)sqlite3_value_text(apVal[3]);
   285    396     nToken = sqlite3_value_int(apVal[4]);
   286         -  iBestLast = nToken-1;
   287    397   
   288    398     iBestCol = (iCol>=0 ? iCol : 0);
   289    399     nPhrase = pApi->xPhraseCount(pFts);
   290    400     aSeen = sqlite3_malloc(nPhrase);
   291    401     if( aSeen==0 ){
   292    402       rc = SQLITE_NOMEM;
   293    403     }
   294         -
   295    404     if( rc==SQLITE_OK ){
   296    405       rc = pApi->xInstCount(pFts, &nInst);
   297    406     }
   298         -  for(i=0; rc==SQLITE_OK && i<nInst; i++){
   299         -    int ip, iSnippetCol, iStart;
          407  +
          408  +  memset(&sFinder, 0, sizeof(Fts5SFinder));
          409  +  for(i=0; i<nCol; i++){
          410  +    if( iCol<0 || iCol==i ){
          411  +      int nDoc;
          412  +      int nDocsize;
          413  +      int ii;
          414  +      sFinder.iPos = 0;
          415  +      sFinder.nFirst = 0;
          416  +      rc = pApi->xColumnText(pFts, i, &sFinder.zDoc, &nDoc);
          417  +      if( rc!=SQLITE_OK ) break;
          418  +      rc = pApi->xTokenize(pFts, 
          419  +          sFinder.zDoc, nDoc, (void*)&sFinder,fts5SentenceFinderCb
          420  +      );
          421  +      if( rc!=SQLITE_OK ) break;
          422  +      rc = pApi->xColumnSize(pFts, i, &nDocsize);
          423  +      if( rc!=SQLITE_OK ) break;
          424  +
          425  +      for(ii=0; rc==SQLITE_OK && ii<nInst; ii++){
          426  +        int ip, ic, io;
          427  +        int iAdj;
          428  +        int nScore;
          429  +        int jj;
          430  +
          431  +        rc = pApi->xInst(pFts, ii, &ip, &ic, &io);
          432  +        if( ic!=i || rc!=SQLITE_OK ) continue;
          433  +        memset(aSeen, 0, nPhrase);
          434  +        rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i,
          435  +            io, nToken, &nScore, &iAdj
          436  +        );
          437  +        if( rc==SQLITE_OK && nScore>nBestScore ){
          438  +          nBestScore = nScore;
          439  +          iBestCol = i;
          440  +          iBestStart = iAdj;
          441  +          nColSize = nDocsize;
          442  +        }
          443  +
          444  +        if( rc==SQLITE_OK && sFinder.nFirst && nDocsize>nToken ){
          445  +          for(jj=0; jj<(sFinder.nFirst-1); jj++){
          446  +            if( sFinder.aFirst[jj+1]>io ) break;
          447  +          }
          448  +
          449  +          if( sFinder.aFirst[jj]<io ){
          450  +            int nScore;
   300    451       memset(aSeen, 0, nPhrase);
   301         -    rc = pApi->xInst(pFts, i, &ip, &iSnippetCol, &iStart);
   302         -    if( rc==SQLITE_OK && (iCol<0 || iSnippetCol==iCol) ){
   303         -      int nScore = 1000;
   304         -      int iLast = iStart - 1 + pApi->xPhraseSize(pFts, ip);
   305         -      int j;
   306         -      aSeen[ip] = 1;
          452  +            rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i, 
          453  +              sFinder.aFirst[jj], nToken, &nScore, 0
          454  +            );
   307    455   
   308         -      for(j=i+1; rc==SQLITE_OK && j<nInst; j++){
   309         -        int ic; int io; int iFinal;
   310         -        rc = pApi->xInst(pFts, j, &ip, &ic, &io);
   311         -        iFinal = io + pApi->xPhraseSize(pFts, ip) - 1;
   312         -        if( rc==SQLITE_OK && ic==iSnippetCol && iLast<iStart+nToken ){
   313         -          nScore += aSeen[ip] ? 1000 : 1;
   314         -          aSeen[ip] = 1;
   315         -          if( iFinal>iLast ) iLast = iFinal;
   316         -        }
   317         -      }
   318         -
          456  +            nScore += (sFinder.aFirst[jj]==0 ? 120 : 100);
   319    457         if( rc==SQLITE_OK && nScore>nBestScore ){
   320         -        iBestCol = iSnippetCol;
   321         -        iBestStart = iStart;
   322         -        iBestLast = iLast;
   323    458           nBestScore = nScore;
          459  +              iBestCol = i;
          460  +              iBestStart = sFinder.aFirst[jj];
          461  +              nColSize = nDocsize;
          462  +            }
          463  +          }
          464  +        }
   324    465         }
   325    466       }
   326    467     }
   327    468   
   328         -  if( rc==SQLITE_OK ){
   329         -    rc = pApi->xColumnSize(pFts, iBestCol, &nColSize);
   330         -  }
   331    469     if( rc==SQLITE_OK ){
   332    470       rc = pApi->xColumnText(pFts, iBestCol, &ctx.zIn, &ctx.nIn);
   333    471     }
          472  +  if( rc==SQLITE_OK && nColSize==0 ){
          473  +    rc = pApi->xColumnSize(pFts, iBestCol, &nColSize);
          474  +  }
   334    475     if( ctx.zIn ){
   335    476       if( rc==SQLITE_OK ){
   336    477         rc = fts5CInstIterInit(pApi, pFts, iBestCol, &ctx.iter);
   337    478       }
   338    479   
   339         -    if( (iBestStart+nToken-1)>iBestLast ){
   340         -      iBestStart -= (iBestStart+nToken-1-iBestLast) / 2;
   341         -    }
   342         -    if( iBestStart+nToken>nColSize ){
   343         -      iBestStart = nColSize - nToken;
   344         -    }
   345         -    if( iBestStart<0 ) iBestStart = 0;
   346         -
   347    480       ctx.iRangeStart = iBestStart;
   348    481       ctx.iRangeEnd = iBestStart + nToken - 1;
   349    482   
   350    483       if( iBestStart>0 ){
   351    484         fts5HighlightAppend(&rc, &ctx, zEllips, -1);
   352    485       }
          486  +
          487  +    /* Advance iterator ctx.iter so that it points to the first coalesced
          488  +    ** phrase instance at or following position iBestStart. */
          489  +    while( ctx.iter.iStart>=0 && ctx.iter.iStart<iBestStart && rc==SQLITE_OK ){
          490  +      rc = fts5CInstIterNext(&ctx.iter);
          491  +    }
          492  +
   353    493       if( rc==SQLITE_OK ){
   354    494         rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
   355    495       }
   356    496       if( ctx.iRangeEnd>=(nColSize-1) ){
   357    497         fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
   358    498       }else{
   359    499         fts5HighlightAppend(&rc, &ctx, zEllips, -1);
   360    500       }
   361         -
          501  +  }
   362    502       if( rc==SQLITE_OK ){
   363    503         sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
   364    504       }else{
   365    505         sqlite3_result_error_code(pCtx, rc);
   366    506       }
   367    507       sqlite3_free(ctx.zOut);
   368         -  }
   369    508     sqlite3_free(aSeen);
          509  +  sqlite3_free(sFinder.aFirst);
   370    510   }
   371    511   
   372    512   /************************************************************************/
   373    513   
   374    514   /*
   375    515   ** The first time the bm25() function is called for a query, an instance
   376    516   ** of the following structure is allocated and populated.

Changes to ext/fts5/fts5_expr.c.

   163    163       case ')':  tok = FTS5_RP;    break;
   164    164       case '{':  tok = FTS5_LCP;   break;
   165    165       case '}':  tok = FTS5_RCP;   break;
   166    166       case ':':  tok = FTS5_COLON; break;
   167    167       case ',':  tok = FTS5_COMMA; break;
   168    168       case '+':  tok = FTS5_PLUS;  break;
   169    169       case '*':  tok = FTS5_STAR;  break;
          170  +    case '-':  tok = FTS5_MINUS; break;
   170    171       case '\0': tok = FTS5_EOF;   break;
   171    172   
   172    173       case '"': {
   173    174         const char *z2;
   174    175         tok = FTS5_STRING;
   175    176   
   176    177         for(z2=&z[1]; 1; z2++){
................................................................................
  1654   1655     if( rc==SQLITE_OK ){
  1655   1656       pNew->pRoot->pNear = (Fts5ExprNearset*)sqlite3Fts5MallocZero(&rc, 
  1656   1657           sizeof(Fts5ExprNearset) + sizeof(Fts5ExprPhrase*));
  1657   1658     }
  1658   1659     if( rc==SQLITE_OK ){
  1659   1660       Fts5Colset *pColsetOrig = pOrig->pNode->pNear->pColset;
  1660   1661       if( pColsetOrig ){
  1661         -      int nByte = sizeof(Fts5Colset) + pColsetOrig->nCol * sizeof(int);
         1662  +      int nByte = sizeof(Fts5Colset) + (pColsetOrig->nCol-1) * sizeof(int);
  1662   1663         Fts5Colset *pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&rc, nByte);
  1663   1664         if( pColset ){ 
  1664   1665           memcpy(pColset, pColsetOrig, nByte);
  1665   1666         }
  1666   1667         pNew->pRoot->pNear->pColset = pColset;
  1667   1668       }
  1668   1669     }
................................................................................
  1788   1789       /* Check that the array is in order and contains no duplicate entries. */
  1789   1790       for(i=1; i<pNew->nCol; i++) assert( pNew->aiCol[i]>pNew->aiCol[i-1] );
  1790   1791   #endif
  1791   1792     }
  1792   1793   
  1793   1794     return pNew;
  1794   1795   }
         1796  +
         1797  +/*
         1798  +** Allocate and return an Fts5Colset object specifying the inverse of
         1799  +** the colset passed as the second argument. Free the colset passed
         1800  +** as the second argument before returning.
         1801  +*/
         1802  +Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse *pParse, Fts5Colset *p){
         1803  +  Fts5Colset *pRet;
         1804  +  int nCol = pParse->pConfig->nCol;
         1805  +
         1806  +  pRet = (Fts5Colset*)sqlite3Fts5MallocZero(&pParse->rc, 
         1807  +      sizeof(Fts5Colset) + sizeof(int)*nCol
         1808  +  );
         1809  +  if( pRet ){
         1810  +    int i;
         1811  +    int iOld = 0;
         1812  +    for(i=0; i<nCol; i++){
         1813  +      if( iOld>=p->nCol || p->aiCol[iOld]!=i ){
         1814  +        pRet->aiCol[pRet->nCol++] = i;
         1815  +      }else{
         1816  +        iOld++;
         1817  +      }
         1818  +    }
         1819  +  }
         1820  +
         1821  +  sqlite3_free(p);
         1822  +  return pRet;
         1823  +}
  1795   1824   
  1796   1825   Fts5Colset *sqlite3Fts5ParseColset(
  1797   1826     Fts5Parse *pParse,              /* Store SQLITE_NOMEM here if required */
  1798   1827     Fts5Colset *pColset,            /* Existing colset object */
  1799   1828     Fts5Token *p
  1800   1829   ){
  1801   1830     Fts5Colset *pRet = 0;

Changes to ext/fts5/fts5_index.c.

   698    698       p->nRead++;
   699    699     }
   700    700   
   701    701     assert( (pRet==0)==(p->rc!=SQLITE_OK) );
   702    702     return pRet;
   703    703   }
   704    704   
   705         -
   706    705   /*
   707    706   ** Release a reference to data record returned by an earlier call to
   708    707   ** fts5DataRead().
   709    708   */
   710    709   static void fts5DataRelease(Fts5Data *pData){
   711    710     sqlite3_free(pData);
   712    711   }
          712  +
          713  +static Fts5Data *fts5LeafRead(Fts5Index *p, i64 iRowid){
          714  +  Fts5Data *pRet = fts5DataRead(p, iRowid);
          715  +  if( pRet ){
          716  +    if( pRet->szLeaf>pRet->nn ){
          717  +      p->rc = FTS5_CORRUPT;
          718  +      fts5DataRelease(pRet);
          719  +      pRet = 0;
          720  +    }
          721  +  }
          722  +  return pRet;
          723  +}
   713    724   
   714    725   static int fts5IndexPrepareStmt(
   715    726     Fts5Index *p,
   716    727     sqlite3_stmt **ppStmt,
   717    728     char *zSql
   718    729   ){
   719    730     if( p->rc==SQLITE_OK ){
................................................................................
  1515   1526     Fts5StructureSegment *pSeg = pIter->pSeg;
  1516   1527     fts5DataRelease(pIter->pLeaf);
  1517   1528     pIter->iLeafPgno++;
  1518   1529     if( pIter->pNextLeaf ){
  1519   1530       pIter->pLeaf = pIter->pNextLeaf;
  1520   1531       pIter->pNextLeaf = 0;
  1521   1532     }else if( pIter->iLeafPgno<=pSeg->pgnoLast ){
  1522         -    pIter->pLeaf = fts5DataRead(p, 
         1533  +    pIter->pLeaf = fts5LeafRead(p, 
  1523   1534           FTS5_SEGMENT_ROWID(pSeg->iSegid, pIter->iLeafPgno)
  1524   1535       );
  1525   1536     }else{
  1526   1537       pIter->pLeaf = 0;
  1527   1538     }
  1528   1539     pLeaf = pIter->pLeaf;
  1529   1540   
................................................................................
  2020   2031           pIter->iLeafOffset = iOff;
  2021   2032   
  2022   2033           if( pLeaf->nn>pLeaf->szLeaf ){
  2023   2034             pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
  2024   2035                 &pLeaf->p[pLeaf->szLeaf], pIter->iEndofDoclist
  2025   2036                 );
  2026   2037           }
  2027         -
  2028   2038         }
  2029   2039         else if( pLeaf->nn>pLeaf->szLeaf ){
  2030   2040           pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
  2031   2041               &pLeaf->p[pLeaf->szLeaf], iOff
  2032   2042               );
  2033   2043           pIter->iLeafOffset = iOff;
  2034   2044           pIter->iEndofDoclist = iOff;
................................................................................
  2264   2274         bEndOfPage = 1;
  2265   2275         break;
  2266   2276       }
  2267   2277   
  2268   2278       iPgidx += fts5GetVarint32(&a[iPgidx], nKeep);
  2269   2279       iTermOff += nKeep;
  2270   2280       iOff = iTermOff;
         2281  +
         2282  +    if( iOff>=n ){
         2283  +      p->rc = FTS5_CORRUPT;
         2284  +      return;
         2285  +    }
  2271   2286   
  2272   2287       /* Read the nKeep field of the next term. */
  2273   2288       fts5FastGetVarint32(a, iOff, nKeep);
  2274   2289     }
  2275   2290   
  2276   2291    search_failed:
  2277   2292     if( bGe==0 ){
................................................................................
  3190   3205       ** Fts5Iter.poslist buffer and then set the output pointer to point
  3191   3206       ** to this buffer.  */
  3192   3207       fts5BufferZero(&pIter->poslist);
  3193   3208       fts5SegiterPoslist(pIter->pIndex, pSeg, 0, &pIter->poslist);
  3194   3209       pIter->base.pData = pIter->poslist.p;
  3195   3210     }
  3196   3211   }
         3212  +
         3213  +/*
         3214  +** xSetOutputs callback used when the Fts5Colset object has nCol==0 (match
         3215  +** against no columns at all).
         3216  +*/
         3217  +static void fts5IterSetOutputs_ZeroColset(Fts5Iter *pIter, Fts5SegIter *pSeg){
         3218  +  UNUSED_PARAM(pSeg);
         3219  +  pIter->base.nData = 0;
         3220  +}
  3197   3221   
  3198   3222   /*
  3199   3223   ** xSetOutputs callback used by detail=col when there is a column filter
  3200   3224   ** and there are 100 or more columns. Also called as a fallback from
  3201   3225   ** fts5IterSetOutputs_Col100 if the column-list spans more than one page.
  3202   3226   */
  3203   3227   static void fts5IterSetOutputs_Col(Fts5Iter *pIter, Fts5SegIter *pSeg){
................................................................................
  3295   3319       if( pConfig->eDetail==FTS5_DETAIL_NONE ){
  3296   3320         pIter->xSetOutputs = fts5IterSetOutputs_None;
  3297   3321       }
  3298   3322   
  3299   3323       else if( pIter->pColset==0 ){
  3300   3324         pIter->xSetOutputs = fts5IterSetOutputs_Nocolset;
  3301   3325       }
         3326  +
         3327  +    else if( pIter->pColset->nCol==0 ){
         3328  +      pIter->xSetOutputs = fts5IterSetOutputs_ZeroColset;
         3329  +    }
  3302   3330   
  3303   3331       else if( pConfig->eDetail==FTS5_DETAIL_FULL ){
  3304   3332         pIter->xSetOutputs = fts5IterSetOutputs_Full;
  3305   3333       }
  3306   3334   
  3307   3335       else{
  3308   3336         assert( pConfig->eDetail==FTS5_DETAIL_COLUMNS );

Changes to ext/fts5/fts5parse.y.

   116    116   }
   117    117   
   118    118   %type colset {Fts5Colset*}
   119    119   %destructor colset { sqlite3_free($$); }
   120    120   %type colsetlist {Fts5Colset*}
   121    121   %destructor colsetlist { sqlite3_free($$); }
   122    122   
          123  +colset(A) ::= MINUS LCP colsetlist(X) RCP. { 
          124  +    A = sqlite3Fts5ParseColsetInvert(pParse, X);
          125  +}
   123    126   colset(A) ::= LCP colsetlist(X) RCP. { A = X; }
   124    127   colset(A) ::= STRING(X). {
   125    128     A = sqlite3Fts5ParseColset(pParse, 0, &X);
   126    129   }
          130  +colset(A) ::= MINUS STRING(X). {
          131  +  A = sqlite3Fts5ParseColset(pParse, 0, &X);
          132  +  A = sqlite3Fts5ParseColsetInvert(pParse, A);
          133  +}
   127    134   
   128    135   colsetlist(A) ::= colsetlist(Y) STRING(X). { 
   129    136     A = sqlite3Fts5ParseColset(pParse, Y, &X); }
   130    137   colsetlist(A) ::= STRING(X). { 
   131    138     A = sqlite3Fts5ParseColset(pParse, 0, &X); 
   132    139   }
   133         -
   134    140   
   135    141   %type nearset     {Fts5ExprNearset*}
   136    142   %type nearphrases {Fts5ExprNearset*}
   137    143   %destructor nearset { sqlite3Fts5ParseNearsetFree($$); }
   138    144   %destructor nearphrases { sqlite3Fts5ParseNearsetFree($$); }
   139    145   
   140    146   nearset(A) ::= phrase(X). { A = sqlite3Fts5ParseNearset(pParse, 0, X); }

Changes to ext/fts5/test/fts5af.test.

    68     68     1.6 {o o o o o X o} {o o o o o [X] o}
    69     69     1.7 {o o o o o o X} {o o o o o o [X]}
    70     70   
    71     71     2.1 {X o o o o o o o} {[X] o o o o o o...}
    72     72     2.2 {o X o o o o o o} {o [X] o o o o o...}
    73     73     2.3 {o o X o o o o o} {o o [X] o o o o...}
    74     74     2.4 {o o o X o o o o} {o o o [X] o o o...}
    75         -  2.5 {o o o o X o o o} {...o o o [X] o o o}
    76         -  2.6 {o o o o o X o o} {...o o o o [X] o o}
    77         -  2.7 {o o o o o o X o} {...o o o o o [X] o}
           75  +  2.5 {o o o o X o o o} {o o o o [X] o o...}
           76  +  2.6 {o o o o o X o o} {o o o o o [X] o...}
           77  +  2.7 {o o o o o o X o} {o o o o o o [X]...}
    78     78     2.8 {o o o o o o o X} {...o o o o o o [X]}
           79  +
           80  +  2.9  {o o o o o o o X o}       {...o o o o o [X] o}
           81  +  2.10 {o o o o o o o X o o}     {...o o o o [X] o o}
           82  +  2.11 {o o o o o o o X o o o}   {...o o o [X] o o o}
           83  +  2.12 {o o o o o o o X o o o o} {...o o o [X] o o o...}
           84  +
    79     85   
    80     86     3.1 {X o o o o o o o o} {[X] o o o o o o...}
    81     87     3.2 {o X o o o o o o o} {o [X] o o o o o...}
    82     88     3.3 {o o X o o o o o o} {o o [X] o o o o...}
    83     89     3.4 {o o o X o o o o o} {o o o [X] o o o...}
    84         -  3.5 {o o o o X o o o o} {...o o o [X] o o o...}
    85         -  3.6 {o o o o o X o o o} {...o o o [X] o o o}
    86         -  3.7 {o o o o o o X o o} {...o o o o [X] o o}
    87         -  3.8 {o o o o o o o X o} {...o o o o o [X] o}
    88         -  3.9 {o o o o o o o o X} {...o o o o o o [X]}
           90  +
           91  +  3.5 {o o o o o o o X o o o o} {...o o o [X] o o o...}
           92  +  3.6 {o o o o o o o o X o o o} {...o o o [X] o o o}
           93  +  3.7 {o o o o o o o o o X o o} {...o o o o [X] o o}
           94  +  3.8 {o o o o o o o o o o X o} {...o o o o o [X] o}
           95  +  3.9 {o o o o o o o o o o o X} {...o o o o o o [X]}
    89     96   
    90     97     4.1 {X o o o o o X o o} {[X] o o o o o [X]...}
    91         -  4.2 {o X o o o o o X o} {...[X] o o o o o [X]...}
    92         -  4.3 {o o X o o o o o X} {...[X] o o o o o [X]}
           98  +  4.2 {o o o o o o o X o o o o o X o} {...[X] o o o o o [X]...}
           99  +  4.3 {o o o o o o o o X o o o o o X} {...[X] o o o o o [X]}
    93    100   
    94    101     5.1 {X o o o o X o o o} {[X] o o o o [X] o...}
    95         -  5.2 {o X o o o o X o o} {...[X] o o o o [X] o...}
    96         -  5.3 {o o X o o o o X o} {...[X] o o o o [X] o}
    97         -  5.4 {o o o X o o o o X} {...o [X] o o o o [X]}
          102  +  5.2 {o o o o o o o X o o o o X o o} {...[X] o o o o [X] o...}
          103  +  5.3 {o o o o o o o o X o o o o X o} {...[X] o o o o [X] o}
          104  +  5.4 {o o o o o o o o o X o o o o X} {...o [X] o o o o [X]}
    98    105   
    99    106     6.1 {X o o o X o o o} {[X] o o o [X] o o...}
   100    107     6.2 {o X o o o X o o o} {o [X] o o o [X] o...}
   101         -  6.3 {o o X o o o X o o} {...o [X] o o o [X] o...}
   102         -  6.4 {o o o X o o o X o} {...o [X] o o o [X] o}
   103         -  6.5 {o o o o X o o o X} {...o o [X] o o o [X]}
          108  +  6.3 {o o o o o o o X o o o X o o} {...o [X] o o o [X] o...}
          109  +  6.4 {o o o o o o o o X o o o X o} {...o [X] o o o [X] o}
          110  +  6.5 {o o o o o o o o o X o o o X} {...o o [X] o o o [X]}
   104    111   
   105    112     7.1 {X o o X o o o o o} {[X] o o [X] o o o...}
   106    113     7.2 {o X o o X o o o o} {o [X] o o [X] o o...}
   107         -  7.3 {o o X o o X o o o} {...o [X] o o [X] o o...}
   108         -  7.4 {o o o X o o X o o} {...o [X] o o [X] o o}
   109         -  7.5 {o o o o X o o X o} {...o o [X] o o [X] o}
   110         -  7.6 {o o o o o X o o X} {...o o o [X] o o [X]}
          114  +  7.3 {o o o o o o o X o o X o o o} {...o [X] o o [X] o o...}
          115  +  7.4 {o o o o o o o o X o o X o o} {...o [X] o o [X] o o}
          116  +  7.5 {o o o o o o o o o X o o X o} {...o o [X] o o [X] o}
          117  +  7.6 {o o o o o o o o o o X o o X} {...o o o [X] o o [X]}
          118  +
          119  +  8.1 {o o o o o o o o o X o o o o o o o o o o o o o o o o X X X o o o}
          120  +      {...o o [X] [X] [X] o o...}
          121  +  8.2 {o o o o o o o. o o X o o o o o o o o o o o o o o o o X X X o o o} 
          122  +      {...o o [X] o o o o...}
          123  +  8.3 {o o o o X o o o o o o o o o o o o o o o o o o o o o X X X o o o} 
          124  +      {o o o o [X] o o...}
   111    125   } {
   112    126     do_snippet_test 1.$tn $doc X $res
   113    127   }
   114    128   
   115    129   if {[detail_is_full]} {
   116    130     foreach {tn doc res} {
   117    131       1.1 {X Y o o o o o} {[X Y] o o o o o}
................................................................................
   120    134       1.4 {o o o X Y o o} {o o o [X Y] o o}
   121    135       1.5 {o o o o X Y o} {o o o o [X Y] o}
   122    136       1.6 {o o o o o X Y} {o o o o o [X Y]}
   123    137   
   124    138       2.1 {X Y o o o o o o} {[X Y] o o o o o...}
   125    139       2.2 {o X Y o o o o o} {o [X Y] o o o o...}
   126    140       2.3 {o o X Y o o o o} {o o [X Y] o o o...}
   127         -    2.4 {o o o X Y o o o} {...o o [X Y] o o o}
   128         -    2.5 {o o o o X Y o o} {...o o o [X Y] o o}
   129         -    2.6 {o o o o o X Y o} {...o o o o [X Y] o}
   130         -    2.7 {o o o o o o X Y} {...o o o o o [X Y]}
          141  +    2.4 {o o o o o o o X Y o o o} {...o o [X Y] o o o}
          142  +    2.5 {o o o o o o o o X Y o o} {...o o o [X Y] o o}
          143  +    2.6 {o o o o o o o o o X Y o} {...o o o o [X Y] o}
          144  +    2.7 {o o o o o o o o o o X Y} {...o o o o o [X Y]}
   131    145   
   132    146       3.1 {X Y o o o o o o o} {[X Y] o o o o o...}
   133    147       3.2 {o X Y o o o o o o} {o [X Y] o o o o...}
   134    148       3.3 {o o X Y o o o o o} {o o [X Y] o o o...}
   135         -    3.4 {o o o X Y o o o o} {...o o [X Y] o o o...}
   136         -    3.5 {o o o o X Y o o o} {...o o [X Y] o o o}
   137         -    3.6 {o o o o o X Y o o} {...o o o [X Y] o o}
   138         -    3.7 {o o o o o o X Y o} {...o o o o [X Y] o}
   139         -    3.8 {o o o o o o o X Y} {...o o o o o [X Y]}
          149  +    3.4 {o o o o o o o X Y o o o o} {...o o [X Y] o o o...}
          150  +    3.5 {o o o o o o o o X Y o o o} {...o o [X Y] o o o}
          151  +    3.6 {o o o o o o o o o X Y o o} {...o o o [X Y] o o}
          152  +    3.7 {o o o o o o o o o o X Y o} {...o o o o [X Y] o}
          153  +    3.8 {o o o o o o o o o o o X Y} {...o o o o o [X Y]}
   140    154     } {
   141    155       do_snippet_test 2.$tn $doc "X + Y" $res
   142    156     }
   143    157   }
   144    158   
          159  +do_execsql_test 4.0 {
          160  +  CREATE VIRTUAL TABLE x1 USING fts5(a, b);
          161  +  INSERT INTO x1 VALUES('xyz', '1 2 3 4 5 6 7 8 9 10 11 12 13');
          162  +  SELECT snippet(x1, 1, '[', ']', '...', 5) FROM x1('xyz');
          163  +} {
          164  +  {1 2 3 4 5...}
          165  +}
          166  +
          167  +do_execsql_test 5.0 {
          168  +  CREATE VIRTUAL TABLE p1 USING fts5(a, b);
          169  +  INSERT INTO p1 VALUES(
          170  +    'x a a a a a a a a a a',
          171  +    'a a a a a a a a a a a a a a a a a a a x'
          172  +  );
          173  +}
          174  +do_execsql_test 5.1 {
          175  +  SELECT snippet(p1, 0, '[', ']', '...', 6) FROM p1('x');
          176  +} {{[x] a a a a a...}}
          177  +
   145    178   } ;# foreach_detail_mode 
   146    179   
   147    180   finish_test
   148    181   

Added ext/fts5/test/fts5colset.test.

            1  +# 2016 August 10
            2  +#
            3  +# The author disclaims copyright to this source code.  In place of
            4  +# a legal notice, here is a blessing:
            5  +#
            6  +#    May you do good and not evil.
            7  +#    May you find forgiveness for yourself and forgive others.
            8  +#    May you share freely, never taking more than you give.
            9  +#
           10  +#*************************************************************************
           11  +# This file implements regression tests for SQLite library.  The
           12  +# focus of this script is testing the FTS5 module.
           13  +#
           14  +
           15  +source [file join [file dirname [info script]] fts5_common.tcl]
           16  +set testprefix fts5colset
           17  +
           18  +# If SQLITE_ENABLE_FTS5 is not defined, omit this file.
           19  +ifcapable !fts5 {
           20  +  finish_test
           21  +  return
           22  +}
           23  +
           24  +foreach_detail_mode $::testprefix {
           25  +  if {[detail_is_none]} continue
           26  +
           27  +  do_execsql_test 1.0 {
           28  +    CREATE VIRTUAL TABLE t1 USING fts5(a, b, c, d, detail=%DETAIL%);
           29  +    INSERT INTO t1 VALUES('a', 'b', 'c', 'd');  -- 1
           30  +    INSERT INTO t1 VALUES('d', 'a', 'b', 'c');  -- 2
           31  +    INSERT INTO t1 VALUES('c', 'd', 'a', 'b');  -- 3
           32  +    INSERT INTO t1 VALUES('b', 'c', 'd', 'a');  -- 4
           33  +  }
           34  +
           35  +  foreach {tn q res} {
           36  +    1 "a"          {1 2 3 4}
           37  +    2 "{a}   : a"  {1}
           38  +    3 "-{a}   : a" {2 3 4}
           39  +    4 "- {a c} : a" {2 4}
           40  +    5 " - {d d c} : a" {1 2}
           41  +    6 "- {d c b a} : a" {}
           42  +    7 "-{\"a\"} : b" {1 2 3}
           43  +    8 "- c : a" {1 2 4}
           44  +    9 "-c : a"  {1 2 4}
           45  +    10 "-\"c\" : a"  {1 2 4}
           46  +  } {
           47  +  breakpoint
           48  +    do_execsql_test 1.$tn {
           49  +      SELECT rowid FROM t1($q)
           50  +    } $res
           51  +  }
           52  +
           53  +
           54  +}
           55  +
           56  +
           57  +finish_test
           58  +
           59  +

Changes to ext/fts5/test/fts5corrupt2.test.

    33     33     CREATE VIRTUAL TABLE t1 USING fts5(x);
    34     34     INSERT INTO t1(t1, rank) VALUES('pgsz', 32);
    35     35     WITH ii(i) AS (SELECT 1 UNION SELECT i+1 FROM ii WHERE i<100)
    36     36     INSERT INTO t1 SELECT rnddoc(10) FROM ii;
    37     37   }
    38     38   set mask [expr 31 << 31]
    39     39   
    40         -if 1 {
           40  +if 0 {
    41     41   
    42     42   # Test 1:
    43     43   #
    44     44   #   For each page in the t1_data table, open a transaction and DELETE
    45     45   #   the t1_data entry. Then run:
    46     46   #
    47     47   #     * an integrity-check, and
................................................................................
    78     78       }
    79     79     
    80     80       do_execsql_test 1.$tno.$tn.3.$rowid {
    81     81         ROLLBACK;
    82     82         INSERT INTO t1(t1) VALUES('integrity-check');
    83     83       } {}
    84     84     }
           85  +}
           86  +
    85     87   }
    86     88   
    87     89   # Using the same database as the 1.* tests.
    88     90   #
    89     91   # Run N-1 tests, where N is the number of bytes in the rightmost leaf page
    90     92   # of the fts index. For test $i, truncate the rightmost leafpage to $i
    91     93   # bytes. Then test both the integrity-check detects the corruption.
................................................................................
   206    208         set {} 1
   207    209       } {1}
   208    210   
   209    211       execsql ROLLBACK
   210    212     }
   211    213   
   212    214     # do_test 4.$tn.x { expr $nCorrupt>0 } 1
   213         -}
   214         -
   215    215   }
   216    216   
   217    217   set doc [string repeat "A B C " 1000]
   218    218   do_execsql_test 5.0 {
   219    219     CREATE VIRTUAL TABLE x5 USING fts5(tt);
   220    220     INSERT INTO x5(x5, rank) VALUES('pgsz', 32);
   221    221     WITH ii(i) AS (SELECT 1 UNION ALL SELECT i+1 FROM ii WHERE i<10) 

Changes to ext/fts5/test/fts5unicode2.test.

   156    156        the maximum x value.
   157    157     }
   158    158     3 "ROW" {
   159    159        ...returns the value of y on the same [row] that contains 
   160    160        the maximum x value.
   161    161     }
   162    162     4 "rollback" {
   163         -     ...[ROLLBACK]. Instead, the pending statement
   164         -     will return SQLITE_ABORT upon next access after the [ROLLBACK].
          163  +     Pending statements no longer block [ROLLBACK]. Instead, the pending
          164  +     statement will return SQLITE_ABORT upon...
   165    165     }
   166    166     5 "rOllback" {
   167         -     ...[ROLLBACK]. Instead, the pending statement
   168         -     will return SQLITE_ABORT upon next access after the [ROLLBACK].
          167  +     Pending statements no longer block [ROLLBACK]. Instead, the pending
          168  +     statement will return SQLITE_ABORT upon...
   169    169     }
   170    170     6 "lang*" {
   171    171        Added support for the FTS4 [languageid] option.
   172    172     }
   173    173   } {
   174    174     do_test 2.$tn {
   175    175       set q [mapdoc $query]

Added ext/misc/memvfs.c.

            1  +/*
            2  +** 2016-09-07
            3  +**
            4  +** The author disclaims copyright to this source code.  In place of
            5  +** a legal notice, here is a blessing:
            6  +**
            7  +**    May you do good and not evil.
            8  +**    May you find forgiveness for yourself and forgive others.
            9  +**    May you share freely, never taking more than you give.
           10  +**
           11  +******************************************************************************
           12  +**
           13  +** This is an in-memory read-only VFS implementation.  The application
           14  +** supplies a block of memory which is the database file, and this VFS
           15  +** uses that block of memory.
           16  +**
           17  +** Because there is no place to store journals and no good way to lock
           18  +** the "file", this VFS is read-only.
           19  +**
           20  +** USAGE:
           21  +**
           22  +**    sqlite3_open_v2("file:/whatever?ptr=0xf05538&sz=14336", &db,
           23  +**                    SQLITE_OPEN_READONLY | SQLITE_OPEN_URI,
           24  +**                    "memvfs");
           25  +**
           26  +** The ptr= and sz= query parameters are required or the open will fail.
           27  +** The ptr= parameter gives the memory address of the buffer holding the
           28  +** read-only database and sz= gives the size of the database.  The parameter
           29  +** values may be in hexadecimal or decimal.  The filename is ignored.
           30  +*/
           31  +#include <sqlite3ext.h>
           32  +SQLITE_EXTENSION_INIT1
           33  +#include <string.h>
           34  +#include <assert.h>
           35  +
           36  +
           37  +/*
           38  +** Forward declaration of objects used by this utility
           39  +*/
           40  +typedef struct sqlite3_vfs MemVfs;
           41  +typedef struct MemFile MemFile;
           42  +
           43  +/* Access to a lower-level VFS that (might) implement dynamic loading,
           44  +** access to randomness, etc.
           45  +*/
           46  +#define ORIGVFS(p) ((sqlite3_vfs*)((p)->pAppData))
           47  +
           48  +/* An open file */
           49  +struct MemFile {
           50  +  sqlite3_file base;              /* IO methods */
           51  +  sqlite3_int64 sz;               /* Size of the file */
           52  +  unsigned char *aData;           /* content of the file */
           53  +};
           54  +
           55  +/*
           56  +** Methods for MemFile
           57  +*/
           58  +static int memClose(sqlite3_file*);
           59  +static int memRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
           60  +static int memWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst);
           61  +static int memTruncate(sqlite3_file*, sqlite3_int64 size);
           62  +static int memSync(sqlite3_file*, int flags);
           63  +static int memFileSize(sqlite3_file*, sqlite3_int64 *pSize);
           64  +static int memLock(sqlite3_file*, int);
           65  +static int memUnlock(sqlite3_file*, int);
           66  +static int memCheckReservedLock(sqlite3_file*, int *pResOut);
           67  +static int memFileControl(sqlite3_file*, int op, void *pArg);
           68  +static int memSectorSize(sqlite3_file*);
           69  +static int memDeviceCharacteristics(sqlite3_file*);
           70  +static int memShmMap(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
           71  +static int memShmLock(sqlite3_file*, int offset, int n, int flags);
           72  +static void memShmBarrier(sqlite3_file*);
           73  +static int memShmUnmap(sqlite3_file*, int deleteFlag);
           74  +static int memFetch(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
           75  +static int memUnfetch(sqlite3_file*, sqlite3_int64 iOfst, void *p);
           76  +
           77  +/*
           78  +** Methods for MemVfs
           79  +*/
           80  +static int memOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);
           81  +static int memDelete(sqlite3_vfs*, const char *zName, int syncDir);
           82  +static int memAccess(sqlite3_vfs*, const char *zName, int flags, int *);
           83  +static int memFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut);
           84  +static void *memDlOpen(sqlite3_vfs*, const char *zFilename);
           85  +static void memDlError(sqlite3_vfs*, int nByte, char *zErrMsg);
           86  +static void (*memDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void);
           87  +static void memDlClose(sqlite3_vfs*, void*);
           88  +static int memRandomness(sqlite3_vfs*, int nByte, char *zOut);
           89  +static int memSleep(sqlite3_vfs*, int microseconds);
           90  +static int memCurrentTime(sqlite3_vfs*, double*);
           91  +static int memGetLastError(sqlite3_vfs*, int, char *);
           92  +static int memCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*);
           93  +
           94  +static sqlite3_vfs mem_vfs = {
           95  +  2,                           /* iVersion */
           96  +  0,                           /* szOsFile (set when registered) */
           97  +  1024,                        /* mxPathname */
           98  +  0,                           /* pNext */
           99  +  "memvfs",                    /* zName */
          100  +  0,                           /* pAppData (set when registered) */ 
          101  +  memOpen,                     /* xOpen */
          102  +  memDelete,                   /* xDelete */
          103  +  memAccess,                   /* xAccess */
          104  +  memFullPathname,             /* xFullPathname */
          105  +  memDlOpen,                   /* xDlOpen */
          106  +  memDlError,                  /* xDlError */
          107  +  memDlSym,                    /* xDlSym */
          108  +  memDlClose,                  /* xDlClose */
          109  +  memRandomness,               /* xRandomness */
          110  +  memSleep,                    /* xSleep */
          111  +  memCurrentTime,              /* xCurrentTime */
          112  +  memGetLastError,             /* xGetLastError */
          113  +  memCurrentTimeInt64          /* xCurrentTimeInt64 */
          114  +};
          115  +
          116  +static const sqlite3_io_methods mem_io_methods = {
          117  +  3,                              /* iVersion */
          118  +  memClose,                      /* xClose */
          119  +  memRead,                       /* xRead */
          120  +  memWrite,                      /* xWrite */
          121  +  memTruncate,                   /* xTruncate */
          122  +  memSync,                       /* xSync */
          123  +  memFileSize,                   /* xFileSize */
          124  +  memLock,                       /* xLock */
          125  +  memUnlock,                     /* xUnlock */
          126  +  memCheckReservedLock,          /* xCheckReservedLock */
          127  +  memFileControl,                /* xFileControl */
          128  +  memSectorSize,                 /* xSectorSize */
          129  +  memDeviceCharacteristics,      /* xDeviceCharacteristics */
          130  +  memShmMap,                     /* xShmMap */
          131  +  memShmLock,                    /* xShmLock */
          132  +  memShmBarrier,                 /* xShmBarrier */
          133  +  memShmUnmap,                   /* xShmUnmap */
          134  +  memFetch,                      /* xFetch */
          135  +  memUnfetch                     /* xUnfetch */
          136  +};
          137  +
          138  +
          139  +
          140  +/*
          141  +** Close an mem-file.
          142  +**
          143  +** The pData pointer is owned by the application, so there is nothing
          144  +** to free.
          145  +*/
          146  +static int memClose(sqlite3_file *pFile){
          147  +  return SQLITE_OK;
          148  +}
          149  +
          150  +/*
          151  +** Read data from an mem-file.
          152  +*/
          153  +static int memRead(
          154  +  sqlite3_file *pFile, 
          155  +  void *zBuf, 
          156  +  int iAmt, 
          157  +  sqlite_int64 iOfst
          158  +){
          159  +  MemFile *p = (MemFile *)pFile;
          160  +  memcpy(zBuf, p->aData+iOfst, iAmt);
          161  +  return SQLITE_OK;
          162  +}
          163  +
          164  +/*
          165  +** Write data to an mem-file.
          166  +*/
          167  +static int memWrite(
          168  +  sqlite3_file *pFile,
          169  +  const void *z,
          170  +  int iAmt,
          171  +  sqlite_int64 iOfst
          172  +){
          173  +  return SQLITE_READONLY;
          174  +}
          175  +
          176  +/*
          177  +** Truncate an mem-file.
          178  +*/
          179  +static int memTruncate(sqlite3_file *pFile, sqlite_int64 size){
          180  +  return SQLITE_READONLY;
          181  +}
          182  +
          183  +/*
          184  +** Sync an mem-file.
          185  +*/
          186  +static int memSync(sqlite3_file *pFile, int flags){
          187  +  return SQLITE_READONLY;
          188  +}
          189  +
          190  +/*
          191  +** Return the current file-size of an mem-file.
          192  +*/
          193  +static int memFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
          194  +  MemFile *p = (MemFile *)pFile;
          195  +  *pSize = p->sz;
          196  +  return SQLITE_OK;
          197  +}
          198  +
          199  +/*
          200  +** Lock an mem-file.
          201  +*/
          202  +static int memLock(sqlite3_file *pFile, int eLock){
          203  +  return SQLITE_READONLY;
          204  +}
          205  +
          206  +/*
          207  +** Unlock an mem-file.
          208  +*/
          209  +static int memUnlock(sqlite3_file *pFile, int eLock){
          210  +  return SQLITE_OK;
          211  +}
          212  +
          213  +/*
          214  +** Check if another file-handle holds a RESERVED lock on an mem-file.
          215  +*/
          216  +static int memCheckReservedLock(sqlite3_file *pFile, int *pResOut){
          217  +  *pResOut = 0;
          218  +  return SQLITE_OK;
          219  +}
          220  +
          221  +/*
          222  +** File control method. For custom operations on an mem-file.
          223  +*/
          224  +static int memFileControl(sqlite3_file *pFile, int op, void *pArg){
          225  +  MemFile *p = (MemFile *)pFile;
          226  +  int rc = SQLITE_NOTFOUND;
          227  +  if( op==SQLITE_FCNTL_VFSNAME ){
          228  +    *(char**)pArg = sqlite3_mprintf("mem(%p,%lld)", p->aData, p->sz);
          229  +    rc = SQLITE_OK;
          230  +  }
          231  +  return rc;
          232  +}
          233  +
          234  +/*
          235  +** Return the sector-size in bytes for an mem-file.
          236  +*/
          237  +static int memSectorSize(sqlite3_file *pFile){
          238  +  return 1024;
          239  +}
          240  +
          241  +/*
          242  +** Return the device characteristic flags supported by an mem-file.
          243  +*/
          244  +static int memDeviceCharacteristics(sqlite3_file *pFile){
          245  +  return SQLITE_IOCAP_IMMUTABLE;
          246  +}
          247  +
          248  +/* Create a shared memory file mapping */
          249  +static int memShmMap(
          250  +  sqlite3_file *pFile,
          251  +  int iPg,
          252  +  int pgsz,
          253  +  int bExtend,
          254  +  void volatile **pp
          255  +){
          256  +  return SQLITE_READONLY;
          257  +}
          258  +
          259  +/* Perform locking on a shared-memory segment */
          260  +static int memShmLock(sqlite3_file *pFile, int offset, int n, int flags){
          261  +  return SQLITE_READONLY;
          262  +}
          263  +
          264  +/* Memory barrier operation on shared memory */
          265  +static void memShmBarrier(sqlite3_file *pFile){
          266  +  return;
          267  +}
          268  +
          269  +/* Unmap a shared memory segment */
          270  +static int memShmUnmap(sqlite3_file *pFile, int deleteFlag){
          271  +  return SQLITE_OK;
          272  +}
          273  +
          274  +/* Fetch a page of a memory-mapped file */
          275  +static int memFetch(
          276  +  sqlite3_file *pFile,
          277  +  sqlite3_int64 iOfst,
          278  +  int iAmt,
          279  +  void **pp
          280  +){
          281  +  MemFile *p = (MemFile *)pFile;
          282  +  *pp = (void*)(p->aData + iOfst);
          283  +  return SQLITE_OK;
          284  +}
          285  +
          286  +/* Release a memory-mapped page */
          287  +static int memUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *pPage){
          288  +  return SQLITE_OK;
          289  +}
          290  +
          291  +/*
          292  +** Open an mem file handle.
          293  +*/
          294  +static int memOpen(
          295  +  sqlite3_vfs *pVfs,
          296  +  const char *zName,
          297  +  sqlite3_file *pFile,
          298  +  int flags,
          299  +  int *pOutFlags
          300  +){
          301  +  MemFile *p = (MemFile*)pFile;
          302  +  memset(p, 0, sizeof(*p));
          303  +  if( (flags & SQLITE_OPEN_MAIN_DB)==0 ) return SQLITE_CANTOPEN;
          304  +  p->aData = (unsigned char*)sqlite3_uri_int64(zName,"ptr",0);
          305  +  if( p->aData==0 ) return SQLITE_CANTOPEN;
          306  +  p->sz = sqlite3_uri_int64(zName,"sz",0);
          307  +  if( p->sz<0 ) return SQLITE_CANTOPEN;
          308  +  pFile->pMethods = &mem_io_methods;
          309  +  return SQLITE_OK;
          310  +}
          311  +
          312  +/*
          313  +** Delete the file located at zPath. If the dirSync argument is true,
          314  +** ensure the file-system modifications are synced to disk before
          315  +** returning.
          316  +*/
          317  +static int memDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
          318  +  return SQLITE_READONLY;
          319  +}
          320  +
          321  +/*
          322  +** Test for access permissions. Return true if the requested permission
          323  +** is available, or false otherwise.
          324  +*/
          325  +static int memAccess(
          326  +  sqlite3_vfs *pVfs, 
          327  +  const char *zPath, 
          328  +  int flags, 
          329  +  int *pResOut
          330  +){
          331  +  /* The spec says there are three possible values for flags.  But only
          332  +  ** two of them are actually used */
          333  +  assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
          334  +  if( flags==SQLITE_ACCESS_READWRITE ){
          335  +    *pResOut = 0;
          336  +  }else{
          337  +    *pResOut = 1;
          338  +  }
          339  +  return SQLITE_OK;
          340  +}
          341  +
          342  +/*
          343  +** Populate buffer zOut with the full canonical pathname corresponding
          344  +** to the pathname in zPath. zOut is guaranteed to point to a buffer
          345  +** of at least (INST_MAX_PATHNAME+1) bytes.
          346  +*/
          347  +static int memFullPathname(
          348  +  sqlite3_vfs *pVfs, 
          349  +  const char *zPath, 
          350  +  int nOut, 
          351  +  char *zOut
          352  +){
          353  +  sqlite3_snprintf(nOut, zOut, "%s", zPath);
          354  +  return SQLITE_OK;
          355  +}
          356  +
          357  +/*
          358  +** Open the dynamic library located at zPath and return a handle.
          359  +*/
          360  +static void *memDlOpen(sqlite3_vfs *pVfs, const char *zPath){
          361  +  return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath);
          362  +}
          363  +
          364  +/*
          365  +** Populate the buffer zErrMsg (size nByte bytes) with a human readable
          366  +** utf-8 string describing the most recent error encountered associated 
          367  +** with dynamic libraries.
          368  +*/
          369  +static void memDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
          370  +  ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg);
          371  +}
          372  +
          373  +/*
          374  +** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
          375  +*/
          376  +static void (*memDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){
          377  +  return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym);
          378  +}
          379  +
          380  +/*
          381  +** Close the dynamic library handle pHandle.
          382  +*/
          383  +static void memDlClose(sqlite3_vfs *pVfs, void *pHandle){
          384  +  ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle);
          385  +}
          386  +
          387  +/*
          388  +** Populate the buffer pointed to by zBufOut with nByte bytes of 
          389  +** random data.
          390  +*/
          391  +static int memRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
          392  +  return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut);
          393  +}
          394  +
          395  +/*
          396  +** Sleep for nMicro microseconds. Return the number of microseconds 
          397  +** actually slept.
          398  +*/
          399  +static int memSleep(sqlite3_vfs *pVfs, int nMicro){
          400  +  return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro);
          401  +}
          402  +
          403  +/*
          404  +** Return the current time as a Julian Day number in *pTimeOut.
          405  +*/
          406  +static int memCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
          407  +  return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut);
          408  +}
          409  +
          410  +static int memGetLastError(sqlite3_vfs *pVfs, int a, char *b){
          411  +  return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b);
          412  +}
          413  +static int memCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p){
          414  +  return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p);
          415  +}
          416  +
          417  +#ifdef MEMVFS_TEST
          418  +/*
          419  +**       memload(FILENAME)
          420  +**
          421  +** This an SQL function used to help in testing the memvfs VFS.  The
          422  +** function reads the content of a file into memory and then returns
          423  +** a string that gives the locate and size of the in-memory buffer.
          424  +*/
          425  +#include <stdio.h>
          426  +static void memvfsMemloadFunc(
          427  +  sqlite3_context *context,
          428  +  int argc,
          429  +  sqlite3_value **argv
          430  +){
          431  +  unsigned char *p;
          432  +  sqlite3_int64 sz;
          433  +  FILE *in;
          434  +  const char *zFilename = (const char*)sqlite3_value_text(argv[0]);
          435  +  char zReturn[100];
          436  +
          437  +  if( zFilename==0 ) return;
          438  +  in = fopen(zFilename, "rb");
          439  +  if( in==0 ) return;
          440  +  fseek(in, 0, SEEK_END);
          441  +  sz = ftell(in);
          442  +  rewind(in);
          443  +  p = sqlite3_malloc( sz );
          444  +  if( p==0 ){
          445  +    fclose(in);
          446  +    sqlite3_result_error_nomem(context);
          447  +    return;
          448  +  }
          449  +  fread(p, sz, 1, in);
          450  +  fclose(in);
          451  +  sqlite3_snprintf(sizeof(zReturn),zReturn,"ptr=%lld&sz=%lld",
          452  +                   (sqlite3_int64)p, sz);
          453  +  sqlite3_result_text(context, zReturn, -1, SQLITE_TRANSIENT);
          454  +}
          455  +/* Called for each new database connection */
          456  +static int memvfsRegister(
          457  +  sqlite3 *db,
          458  +  const char **pzErrMsg,
          459  +  const struct sqlite3_api_routines *pThunk
          460  +){
          461  +  return sqlite3_create_function(db, "memload", 1, SQLITE_UTF8, 0,
          462  +                                 memvfsMemloadFunc, 0, 0);
          463  +}
          464  +#endif /* MEMVFS_TEST */
          465  +
          466  +  
          467  +#ifdef _WIN32
          468  +__declspec(dllexport)
          469  +#endif
          470  +/* 
          471  +** This routine is called when the extension is loaded.
          472  +** Register the new VFS.
          473  +*/
          474  +int sqlite3_memvfs_init(
          475  +  sqlite3 *db, 
          476  +  char **pzErrMsg, 
          477  +  const sqlite3_api_routines *pApi
          478  +){
          479  +  int rc = SQLITE_OK;
          480  +  SQLITE_EXTENSION_INIT2(pApi);
          481  +  mem_vfs.pAppData = sqlite3_vfs_find(0);
          482  +  mem_vfs.szOsFile = sizeof(MemFile);
          483  +  rc = sqlite3_vfs_register(&mem_vfs, 1);
          484  +#ifdef MEMVFS_TEST
          485  +  if( rc==SQLITE_OK ){
          486  +    rc = sqlite3_auto_extension((void(*)(void))memvfsRegister);
          487  +  }
          488  +#endif
          489  +  if( rc==SQLITE_OK ) rc = SQLITE_OK_LOAD_PERMANENTLY;
          490  +  return rc;
          491  +}

Changes to ext/rbu/rbudiff.test.

   136    136       );
   137    137       DELETE FROM t2;
   138    138       INSERT INTO t2 VALUES(1,
   139    139           X'0000000000000000111111111111111122222222222222223333333FFF333333'
   140    140       );
   141    141     }
   142    142   
          143  +  4 {
          144  +    CREATE TABLE x1(a, b, c, PRIMARY KEY(a, b, c));
          145  +    INSERT INTO x1 VALUES('u', 'v', NULL);
          146  +    INSERT INTO x1 VALUES('x', 'y', 'z');
          147  +    INSERT INTO x1 VALUES('a', NULL, 'b');
          148  +  } {
          149  +    INSERT INTO x1 VALUES('a', 'b', 'c');
          150  +  }
          151  +
   143    152   } {
   144    153     catch { db close }
   145    154   
   146    155     forcedelete test.db test.db2
   147    156     sqlite3 db test.db
   148    157     db eval "$init"
   149    158     sqlite3 db test.db2
................................................................................
   275    284         db2 eval { INSERT INTO t1(t1) VALUES('integrity-check') }
   276    285       } {}
   277    286   
   278    287       db close
   279    288       db2 close
   280    289     }
   281    290   }
          291  +
   282    292   
   283    293   finish_test
   284    294   

Changes to ext/rbu/rbuprogress.test.

   356    356         CREATE TABLE t1(a, b, c);
   357    357         CREATE INDEX t1c ON t1(c);
   358    358       }
   359    359       vtab { 
   360    360         CREATE VIRTUAL TABLE t1 USING fts5(a, b, c);
   361    361       }
   362    362     } {
          363  +
          364  +    if {$tn=="vtab"} { ifcapable !fts5 break }
   363    365   
   364    366       foreach {tn2 rbusql r1 r2} {
   365    367         1 {
   366    368           CREATE TABLE data0_t1(a, b, c, rbu_rowid, rbu_control);
   367    369           INSERT INTO data0_t1 VALUES(15, 15, 15, 4, 0);
   368    370           INSERT INTO data0_t1 VALUES(20, 20, 20, 5, 0);
   369    371           CREATE TABLE rbu_count(tbl, cnt);

Changes to ext/rbu/rbuvacuum2.test.

   152    152         SELECT * FROM sqlite_master;
   153    153       } {
   154    154       table t1 t1 2 {CREATE TABLE t1(a, b, c)}
   155    155       view v1 v1 0 {CREATE VIEW v1 AS SELECT * FROM t1}
   156    156       trigger tr1 t1 0 {CREATE TRIGGER tr1 AFTER INSERT ON t1 BEGIN SELECT 1; END}
   157    157       }
   158    158     }
          159  +}
          160  +  
          161  +#-------------------------------------------------------------------------
          162  +# Test that passing a NULL value as the second argument to 
          163  +# sqlite3rbu_vacuum() causes it to:
          164  +#
          165  +#   * Use <database>-vacuum as the state db, and
          166  +#   * Set the state db permissions to the same as those on the db file.
          167  +#
          168  +db close
          169  +if {$::tcl_platform(platform)=="unix"} {
          170  +  forcedelete test.db
          171  +
          172  +  sqlite3 db test.db
          173  +  do_execsql_test 5.0 {
          174  +    CREATE TABLE t1(a, b);
          175  +    INSERT INTO t1 VALUES(1, 2);
          176  +    INSERT INTO t1 VALUES(3, 4);
          177  +    INSERT INTO t1 VALUES(5, 6);
          178  +    INSERT INTO t1 VALUES(7, 8);
          179  +  }
          180  +  db close
          181  +
          182  +  foreach {tn perm} {
          183  +    1 00755
          184  +    2 00666
          185  +    3 00644
          186  +    4 00444
          187  +  } {
          188  +    forcedelete test.db-vacuum
          189  +
          190  +    do_test 5.$tn.1 {
          191  +      file attributes test.db -permissions $perm
          192  +      sqlite3rbu_vacuum rbu test.db
          193  +      rbu step
          194  +    } {SQLITE_OK}
   159    195   
          196  +    do_test 5.$tn.2 { file exists test.db-vacuum } 1
          197  +    do_test 5.$tn.3 { file attributes test.db-vacuum -permissions} $perm
          198  +    rbu close
          199  +  }
   160    200   }
          201  +
   161    202   
   162    203   finish_test
          204  +

Changes to ext/rbu/sqlite3rbu.c.

  2330   2330   
  2331   2331   
  2332   2332   /*
  2333   2333   ** Open the database handle and attach the RBU database as "rbu". If an
  2334   2334   ** error occurs, leave an error code and message in the RBU handle.
  2335   2335   */
  2336   2336   static void rbuOpenDatabase(sqlite3rbu *p){
  2337         -  assert( p->rc==SQLITE_OK );
  2338         -  assert( p->dbMain==0 && p->dbRbu==0 );
  2339         -  assert( rbuIsVacuum(p) || p->zTarget!=0 );
         2337  +  assert( p->rc || (p->dbMain==0 && p->dbRbu==0) );
         2338  +  assert( p->rc || rbuIsVacuum(p) || p->zTarget!=0 );
  2340   2339   
  2341   2340     /* Open the RBU database */
  2342   2341     p->dbRbu = rbuOpenDbhandle(p, p->zRbu, 1);
  2343   2342   
  2344   2343     if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
  2345   2344       sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
         2345  +    if( p->zState==0 ){
         2346  +      const char *zFile = sqlite3_db_filename(p->dbRbu, "main");
         2347  +      p->zState = rbuMPrintf(p, "file://%s-vacuum?modeof=%s", zFile, zFile);
         2348  +    }
  2346   2349     }
  2347   2350   
  2348   2351     /* If using separate RBU and state databases, attach the state database to
  2349   2352     ** the RBU db handle now.  */
  2350   2353     if( p->zState ){
  2351   2354       rbuMPrintfExec(p, p->dbRbu, "ATTACH %Q AS stat", p->zState);
  2352   2355       memcpy(p->zStateDb, "stat", 4);
................................................................................
  3473   3476     const char *zTarget, 
  3474   3477     const char *zRbu,
  3475   3478     const char *zState
  3476   3479   ){
  3477   3480     sqlite3rbu *p;
  3478   3481     size_t nTarget = zTarget ? strlen(zTarget) : 0;
  3479   3482     size_t nRbu = strlen(zRbu);
  3480         -  size_t nState = zState ? strlen(zState) : 0;
  3481         -  size_t nByte = sizeof(sqlite3rbu) + nTarget+1 + nRbu+1+ nState+1;
         3483  +  size_t nByte = sizeof(sqlite3rbu) + nTarget+1 + nRbu+1;
  3482   3484   
  3483   3485     p = (sqlite3rbu*)sqlite3_malloc64(nByte);
  3484   3486     if( p ){
  3485   3487       RbuState *pState = 0;
  3486   3488   
  3487   3489       /* Create the custom VFS. */
  3488   3490       memset(p, 0, sizeof(sqlite3rbu));
................................................................................
  3496   3498           memcpy(p->zTarget, zTarget, nTarget+1);
  3497   3499           pCsr += nTarget+1;
  3498   3500         }
  3499   3501         p->zRbu = pCsr;
  3500   3502         memcpy(p->zRbu, zRbu, nRbu+1);
  3501   3503         pCsr += nRbu+1;
  3502   3504         if( zState ){
  3503         -        p->zState = pCsr;
  3504         -        memcpy(p->zState, zState, nState+1);
         3505  +        p->zState = rbuMPrintf(p, "%s", zState);
  3505   3506         }
  3506   3507         rbuOpenDatabase(p);
  3507   3508       }
  3508   3509   
  3509   3510       if( p->rc==SQLITE_OK ){
  3510   3511         pState = rbuLoadState(p);
  3511   3512         assert( pState || p->rc!=SQLITE_OK );
................................................................................
  3606   3607       }
  3607   3608   
  3608   3609       rbuFreeState(pState);
  3609   3610     }
  3610   3611   
  3611   3612     return p;
  3612   3613   }
         3614  +
         3615  +/*
         3616  +** Allocate and return an RBU handle with all fields zeroed except for the
         3617  +** error code, which is set to SQLITE_MISUSE.
         3618  +*/
         3619  +static sqlite3rbu *rbuMisuseError(void){
         3620  +  sqlite3rbu *pRet;
         3621  +  pRet = sqlite3_malloc64(sizeof(sqlite3rbu));
         3622  +  if( pRet ){
         3623  +    memset(pRet, 0, sizeof(sqlite3rbu));
         3624  +    pRet->rc = SQLITE_MISUSE;
         3625  +  }
         3626  +  return pRet;
         3627  +}
  3613   3628   
  3614   3629   /*
  3615   3630   ** Open and return a new RBU handle. 
  3616   3631   */
  3617   3632   sqlite3rbu *sqlite3rbu_open(
  3618   3633     const char *zTarget, 
  3619   3634     const char *zRbu,
  3620   3635     const char *zState
  3621   3636   ){
         3637  +  if( zTarget==0 || zRbu==0 ){ return rbuMisuseError(); }
  3622   3638     /* TODO: Check that zTarget and zRbu are non-NULL */
  3623   3639     return openRbuHandle(zTarget, zRbu, zState);
  3624   3640   }
  3625   3641   
  3626   3642   /*
  3627   3643   ** Open a handle to begin or resume an RBU VACUUM operation.
  3628   3644   */
  3629   3645   sqlite3rbu *sqlite3rbu_vacuum(
  3630   3646     const char *zTarget, 
  3631   3647     const char *zState
  3632   3648   ){
         3649  +  if( zTarget==0 ){ return rbuMisuseError(); }
  3633   3650     /* TODO: Check that both arguments are non-NULL */
  3634   3651     return openRbuHandle(0, zTarget, zState);
  3635   3652   }
  3636   3653   
  3637   3654   /*
  3638   3655   ** Return the database handle used by pRbu.
  3639   3656   */
................................................................................
  3703   3720       rbuDeleteVfs(p);
  3704   3721       sqlite3_free(p->aBuf);
  3705   3722       sqlite3_free(p->aFrame);
  3706   3723   
  3707   3724       rbuEditErrmsg(p);
  3708   3725       rc = p->rc;
  3709   3726       *pzErrmsg = p->zErrmsg;
         3727  +    sqlite3_free(p->zState);
  3710   3728       sqlite3_free(p);
  3711   3729     }else{
  3712   3730       rc = SQLITE_NOMEM;
  3713   3731       *pzErrmsg = 0;
  3714   3732     }
  3715   3733     return rc;
  3716   3734   }

Changes to ext/rbu/sqlite3rbu.h.

   100    100   ** Instead of a regular table, the RBU database may also contain virtual
   101    101   ** tables or view named using the data_<target> naming scheme. 
   102    102   **
   103    103   ** Instead of the plain data_<target> naming scheme, RBU database tables 
   104    104   ** may also be named data<integer>_<target>, where <integer> is any sequence
   105    105   ** of zero or more numeric characters (0-9). This can be significant because
   106    106   ** tables within the RBU database are always processed in order sorted by 
   107         -** name. By judicious selection of the the <integer> portion of the names
          107  +** name. By judicious selection of the <integer> portion of the names
   108    108   ** of the RBU tables the user can therefore control the order in which they
   109    109   ** are processed. This can be useful, for example, to ensure that "external
   110    110   ** content" FTS4 tables are updated before their underlying content tables.
   111    111   **
   112    112   ** If the target database table is a virtual table or a table that has no
   113    113   ** PRIMARY KEY declaration, the data_% table must also contain a column 
   114    114   ** named "rbu_rowid". This column is mapped to the tables implicit primary 
................................................................................
   315    315   );
   316    316   
   317    317   /*
   318    318   ** Open an RBU handle to perform an RBU vacuum on database file zTarget.
   319    319   ** An RBU vacuum is similar to SQLite's built-in VACUUM command, except
   320    320   ** that it can be suspended and resumed like an RBU update.
   321    321   **
   322         -** The second argument to this function, which may not be NULL, identifies 
   323         -** a database in which to store the state of the RBU vacuum operation if
   324         -** it is suspended. The first time sqlite3rbu_vacuum() is called, to start
   325         -** an RBU vacuum operation, the state database should either not exist or
   326         -** be empty (contain no tables). If an RBU vacuum is suspended by calling
          322  +** The second argument to this function identifies a database in which 
          323  +** to store the state of the RBU vacuum operation if it is suspended. The 
          324  +** first time sqlite3rbu_vacuum() is called, to start an RBU vacuum
          325  +** operation, the state database should either not exist or be empty
          326  +** (contain no tables). If an RBU vacuum is suspended by calling 
   327    327   ** sqlite3rbu_close() on the RBU handle before sqlite3rbu_step() has
   328    328   ** returned SQLITE_DONE, the vacuum state is stored in the state database. 
   329    329   ** The vacuum can be resumed by calling this function to open a new RBU
   330    330   ** handle specifying the same target and state databases.
          331  +**
          332  +** If the second argument passed to this function is NULL, then the
          333  +** name of the state database is "<database>-vacuum", where <database>
          334  +** is the name of the target database file. In this case, on UNIX, if the
          335  +** state database is not already present in the file-system, it is created
          336  +** with the same permissions as the target db is made.
   331    337   **
   332    338   ** This function does not delete the state database after an RBU vacuum
   333    339   ** is completed, even if it created it. However, if the call to
   334    340   ** sqlite3rbu_close() returns any value other than SQLITE_OK, the contents
   335    341   ** of the state tables within the state database are zeroed. This way,
   336    342   ** the next call to sqlite3rbu_vacuum() opens a handle that starts a 
   337    343   ** new RBU vacuum operation.

Changes to ext/rbu/test_rbu.c.

   236    236     Tcl_Obj *CONST objv[]
   237    237   ){
   238    238     sqlite3rbu *pRbu = 0;
   239    239     const char *zCmd;
   240    240     const char *zTarget;
   241    241     const char *zStateDb = 0;
   242    242   
   243         -  if( objc!=4 ){
   244         -    Tcl_WrongNumArgs(interp, 1, objv, "NAME TARGET-DB STATE-DB");
          243  +  if( objc!=3 && objc!=4 ){
          244  +    Tcl_WrongNumArgs(interp, 1, objv, "NAME TARGET-DB ?STATE-DB?");
   245    245       return TCL_ERROR;
   246    246     }
   247    247     zCmd = Tcl_GetString(objv[1]);
   248    248     zTarget = Tcl_GetString(objv[2]);
   249         -  zStateDb = Tcl_GetString(objv[3]);
          249  +  if( objc==4 ) zStateDb = Tcl_GetString(objv[3]);
   250    250   
   251    251     pRbu = sqlite3rbu_vacuum(zTarget, zStateDb);
   252    252     Tcl_CreateObjCommand(interp, zCmd, test_sqlite3rbu_cmd, (ClientData)pRbu, 0);
   253    253     Tcl_SetObjResult(interp, objv[1]);
   254    254     return TCL_OK;
   255    255   }
   256    256   

Changes to ext/rtree/rtree.c.

  1539   1539     memset(pCsr, 0, sizeof(RtreeCursor));
  1540   1540     pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
  1541   1541   
  1542   1542     pCsr->iStrategy = idxNum;
  1543   1543     if( idxNum==1 ){
  1544   1544       /* Special case - lookup by rowid. */
  1545   1545       RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
  1546         -    RtreeSearchPoint *p;     /* Search point for the the leaf */
         1546  +    RtreeSearchPoint *p;     /* Search point for the leaf */
  1547   1547       i64 iRowid = sqlite3_value_int64(argv[0]);
  1548   1548       i64 iNode = 0;
  1549   1549       rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
  1550   1550       if( rc==SQLITE_OK && pLeaf!=0 ){
  1551   1551         p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
  1552   1552         assert( p!=0 );  /* Always returns pCsr->sPoint */
  1553   1553         pCsr->aNode[0] = pLeaf;

Changes to ext/session/session_common.tcl.

    71     71   
    72     72   proc do_common_sql {sql} {
    73     73     execsql $sql db
    74     74     execsql $sql db2
    75     75   }
    76     76   
    77     77   proc changeset_from_sql {sql {dbname main}} {
           78  +  if {$dbname == "main"} {
           79  +    return [sql_exec_changeset db $sql]
           80  +  }
    78     81     set rc [catch {
    79     82       sqlite3session S db $dbname
    80     83       db eval "SELECT name FROM $dbname.sqlite_master WHERE type = 'table'" {
    81     84         S attach $name
    82     85       }
    83     86       db eval $sql
    84     87       S changeset

Changes to ext/session/sqlite3session.h.

   723    723     void *pB,                       /* Pointer to buffer containing changeset B */
   724    724     int *pnOut,                     /* OUT: Number of bytes in output changeset */
   725    725     void **ppOut                    /* OUT: Buffer containing output changeset */
   726    726   );
   727    727   
   728    728   
   729    729   /*
   730         -** Changegroup handle.
          730  +** CAPI3REF: Changegroup Handle
   731    731   */
   732    732   typedef struct sqlite3_changegroup sqlite3_changegroup;
   733    733   
   734    734   /*
   735         -** CAPI3REF: Combine two or more changesets into a single changeset.
          735  +** CAPI3REF: Create A New Changegroup Object
   736    736   **
   737    737   ** An sqlite3_changegroup object is used to combine two or more changesets
   738    738   ** (or patchsets) into a single changeset (or patchset). A single changegroup
   739    739   ** object may combine changesets or patchsets, but not both. The output is
   740    740   ** always in the same format as the input.
   741    741   **
   742    742   ** If successful, this function returns SQLITE_OK and populates (*pp) with
................................................................................
   765    765   ** As well as the regular sqlite3changegroup_add() and 
   766    766   ** sqlite3changegroup_output() functions, also available are the streaming
   767    767   ** versions sqlite3changegroup_add_strm() and sqlite3changegroup_output_strm().
   768    768   */
   769    769   int sqlite3changegroup_new(sqlite3_changegroup **pp);
   770    770   
   771    771   /*
          772  +** CAPI3REF: Add A Changeset To A Changegroup
          773  +**
   772    774   ** Add all changes within the changeset (or patchset) in buffer pData (size
   773    775   ** nData bytes) to the changegroup. 
   774    776   **
   775    777   ** If the buffer contains a patchset, then all prior calls to this function
   776    778   ** on the same changegroup object must also have specified patchsets. Or, if
   777    779   ** the buffer contains a changeset, so must have the earlier calls to this
   778    780   ** function. Otherwise, SQLITE_ERROR is returned and no changes are added
................................................................................
   840    842   ** final contents of the changegroup is undefined.
   841    843   **
   842    844   ** If no error occurs, SQLITE_OK is returned.
   843    845   */
   844    846   int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData);
   845    847   
   846    848   /*
          849  +** CAPI3REF: Obtain A Composite Changeset From A Changegroup
          850  +**
   847    851   ** Obtain a buffer containing a changeset (or patchset) representing the
   848    852   ** current contents of the changegroup. If the inputs to the changegroup
   849    853   ** were themselves changesets, the output is a changeset. Or, if the
   850    854   ** inputs were patchsets, the output is also a patchset.
   851    855   **
   852    856   ** As with the output of the sqlite3session_changeset() and
   853    857   ** sqlite3session_patchset() functions, all changes related to a single
................................................................................
   868    872   int sqlite3changegroup_output(
   869    873     sqlite3_changegroup*,
   870    874     int *pnData,                    /* OUT: Size of output buffer in bytes */
   871    875     void **ppData                   /* OUT: Pointer to output buffer */
   872    876   );
   873    877   
   874    878   /*
   875         -** Delete a changegroup object.
          879  +** CAPI3REF: Delete A Changegroup Object
   876    880   */
   877    881   void sqlite3changegroup_delete(sqlite3_changegroup*);
   878    882   
   879    883   /*
   880    884   ** CAPI3REF: Apply A Changeset To A Database
   881    885   **
   882    886   ** Apply a changeset to a database. This function attempts to update the

Changes to ext/session/test_session.c.

    24     24   typedef struct TestStreamInput TestStreamInput;
    25     25   struct TestStreamInput {
    26     26     int nStream;                    /* Maximum chunk size */
    27     27     unsigned char *aData;           /* Pointer to buffer containing data */
    28     28     int nData;                      /* Size of buffer aData in bytes */
    29     29     int iData;                      /* Bytes of data already read by sessions */
    30     30   };
           31  +
           32  +/*
           33  +** Extract an sqlite3* db handle from the object passed as the second
           34  +** argument. If successful, set *pDb to point to the db handle and return
           35  +** TCL_OK. Otherwise, return TCL_ERROR.
           36  +*/
           37  +static int dbHandleFromObj(Tcl_Interp *interp, Tcl_Obj *pObj, sqlite3 **pDb){
           38  +  Tcl_CmdInfo info;
           39  +  if( 0==Tcl_GetCommandInfo(interp, Tcl_GetString(pObj), &info) ){
           40  +    Tcl_AppendResult(interp, "no such handle: ", Tcl_GetString(pObj), 0);
           41  +    return TCL_ERROR;
           42  +  }
           43  +
           44  +  *pDb = *(sqlite3 **)info.objClientData;
           45  +  return TCL_OK;
           46  +}
           47  +
           48  +/*************************************************************************
           49  +** The following code is copied byte-for-byte from the sessions module
           50  +** documentation.  It is used by some of the sessions modules tests to
           51  +** ensure that the example in the documentation does actually work.
           52  +*/ 
           53  +/*
           54  +** Argument zSql points to a buffer containing an SQL script to execute 
           55  +** against the database handle passed as the first argument. As well as
           56  +** executing the SQL script, this function collects a changeset recording
           57  +** all changes made to the "main" database file. Assuming no error occurs,
           58  +** output variables (*ppChangeset) and (*pnChangeset) are set to point
           59  +** to a buffer containing the changeset and the size of the changeset in
           60  +** bytes before returning SQLITE_OK. In this case it is the responsibility
           61  +** of the caller to eventually free the changeset blob by passing it to
           62  +** the sqlite3_free function.
           63  +**
           64  +** Or, if an error does occur, return an SQLite error code. The final
           65  +** value of (*pChangeset) and (*pnChangeset) are undefined in this case.
           66  +*/
           67  +int sql_exec_changeset(
           68  +  sqlite3 *db,                  /* Database handle */
           69  +  const char *zSql,             /* SQL script to execute */
           70  +  int *pnChangeset,             /* OUT: Size of changeset blob in bytes */
           71  +  void **ppChangeset            /* OUT: Pointer to changeset blob */
           72  +){
           73  +  sqlite3_session *pSession = 0;
           74  +  int rc;
           75  +
           76  +  /* Create a new session object */
           77  +  rc = sqlite3session_create(db, "main", &pSession);
           78  +
           79  +  /* Configure the session object to record changes to all tables */
           80  +  if( rc==SQLITE_OK ) rc = sqlite3session_attach(pSession, NULL);
           81  +
           82  +  /* Execute the SQL script */
           83  +  if( rc==SQLITE_OK ) rc = sqlite3_exec(db, zSql, 0, 0, 0);
           84  +
           85  +  /* Collect the changeset */
           86  +  if( rc==SQLITE_OK ){
           87  +    rc = sqlite3session_changeset(pSession, pnChangeset, ppChangeset);
           88  +  }
           89  +
           90  +  /* Delete the session object */
           91  +  sqlite3session_delete(pSession);
           92  +
           93  +  return rc;
           94  +}
           95  +/************************************************************************/
           96  +
           97  +/*
           98  +** Tclcmd: sql_exec_changeset DB SQL
           99  +*/
          100  +static int SQLITE_TCLAPI test_sql_exec_changeset(
          101  +  void * clientData,
          102  +  Tcl_Interp *interp,
          103  +  int objc,
          104  +  Tcl_Obj *CONST objv[]
          105  +){
          106  +  const char *zSql;
          107  +  sqlite3 *db;
          108  +  void *pChangeset;
          109  +  int nChangeset;
          110  +  int rc;
          111  +
          112  +  if( objc!=3 ){
          113  +    Tcl_WrongNumArgs(interp, 1, objv, "DB SQL");
          114  +    return TCL_ERROR;
          115  +  }
          116  +  if( dbHandleFromObj(interp, objv[1], &db) ) return TCL_ERROR;
          117  +  zSql = (const char*)Tcl_GetString(objv[2]);
          118  +
          119  +  rc = sql_exec_changeset(db, zSql, &nChangeset, &pChangeset);
          120  +  if( rc!=SQLITE_OK ){
          121  +    Tcl_ResetResult(interp);
          122  +    Tcl_AppendResult(interp, "error in sql_exec_changeset()", 0);
          123  +    return TCL_ERROR;
          124  +  }
          125  +
          126  +  Tcl_SetObjResult(interp, Tcl_NewByteArrayObj(pChangeset, nChangeset));
          127  +  sqlite3_free(pChangeset);
          128  +  return TCL_OK;
          129  +}
          130  +
          131  +
    31    132   
    32    133   #define SESSION_STREAM_TCL_VAR "sqlite3session_streams"
    33    134   
    34    135   /*
    35    136   ** Attempt to find the global variable zVar within interpreter interp
    36    137   ** and extract an integer value from it. Return this value.
    37    138   **
................................................................................
   915   1016       return test_session_error(interp, rc, 0);
   916   1017     }
   917   1018   
   918   1019     return TCL_OK;
   919   1020   }
   920   1021   
   921   1022   int TestSession_Init(Tcl_Interp *interp){
   922         -  Tcl_CreateObjCommand(interp, "sqlite3session", test_sqlite3session, 0, 0);
   923         -  Tcl_CreateObjCommand(
   924         -      interp, "sqlite3session_foreach", test_sqlite3session_foreach, 0, 0
   925         -  );
   926         -  Tcl_CreateObjCommand(
   927         -      interp, "sqlite3changeset_invert", test_sqlite3changeset_invert, 0, 0
   928         -  );
   929         -  Tcl_CreateObjCommand(
   930         -      interp, "sqlite3changeset_concat", test_sqlite3changeset_concat, 0, 0
   931         -  );
   932         -  Tcl_CreateObjCommand(
   933         -      interp, "sqlite3changeset_apply", test_sqlite3changeset_apply, 0, 0
   934         -  );
   935         -  Tcl_CreateObjCommand(
   936         -      interp, "sqlite3changeset_apply_replace_all", 
   937         -      test_sqlite3changeset_apply_replace_all, 0, 0
   938         -  );
         1023  +  struct Cmd {
         1024  +    const char *zCmd;
         1025  +    Tcl_ObjCmdProc *xProc;
         1026  +  } aCmd[] = {
         1027  +    { "sqlite3session", test_sqlite3session },
         1028  +    { "sqlite3session_foreach", test_sqlite3session_foreach },
         1029  +    { "sqlite3changeset_invert", test_sqlite3changeset_invert },
         1030  +    { "sqlite3changeset_concat", test_sqlite3changeset_concat },
         1031  +    { "sqlite3changeset_apply", test_sqlite3changeset_apply },
         1032  +    { "sqlite3changeset_apply_replace_all", 
         1033  +      test_sqlite3changeset_apply_replace_all },
         1034  +    { "sql_exec_changeset", test_sql_exec_changeset },
         1035  +  };
         1036  +  int i;
         1037  +
         1038  +  for(i=0; i<sizeof(aCmd)/sizeof(struct Cmd); i++){
         1039  +    struct Cmd *p = &aCmd[i];
         1040  +    Tcl_CreateObjCommand(interp, p->zCmd, p->xProc, 0, 0);
         1041  +  }
         1042  +
   939   1043     return TCL_OK;
   940   1044   }
   941   1045   
   942   1046   #endif /* SQLITE_TEST && SQLITE_SESSION && SQLITE_PREUPDATE_HOOK */

Changes to src/alter.c.

   409    409     if( NEVER(db->mallocFailed) ) goto exit_rename_table;
   410    410     assert( pSrc->nSrc==1 );
   411    411     assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
   412    412   
   413    413     pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
   414    414     if( !pTab ) goto exit_rename_table;
   415    415     iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   416         -  zDb = db->aDb[iDb].zName;
          416  +  zDb = db->aDb[iDb].zDbSName;
   417    417     db->flags |= SQLITE_PreferBuiltin;
   418    418   
   419    419     /* Get a NULL terminated version of the new table name. */
   420    420     zName = sqlite3NameFromToken(db, pName);
   421    421     if( !zName ) goto exit_rename_table;
   422    422   
   423    423     /* Check that a table or index named 'zName' does not already exist
................................................................................
   607    607     if( pParse->nErr || db->mallocFailed ) return;
   608    608     assert( v!=0 );
   609    609     pNew = pParse->pNewTable;
   610    610     assert( pNew );
   611    611   
   612    612     assert( sqlite3BtreeHoldsAllMutexes(db) );
   613    613     iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
   614         -  zDb = db->aDb[iDb].zName;
          614  +  zDb = db->aDb[iDb].zDbSName;
   615    615     zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
   616    616     pCol = &pNew->aCol[pNew->nCol-1];
   617    617     pDflt = pCol->pDflt;
   618    618     pTab = sqlite3FindTable(db, zTab, zDb);
   619    619     assert( pTab );
   620    620   
   621    621   #ifndef SQLITE_OMIT_AUTHORIZATION

Changes to src/analyze.c.

   206    206   
   207    207     /* Create new statistic tables if they do not exist, or clear them
   208    208     ** if they do already exist.
   209    209     */
   210    210     for(i=0; i<ArraySize(aTable); i++){
   211    211       const char *zTab = aTable[i].zName;
   212    212       Table *pStat;
   213         -    if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
          213  +    if( (pStat = sqlite3FindTable(db, zTab, pDb->zDbSName))==0 ){
   214    214         if( aTable[i].zCols ){
   215    215           /* The sqlite_statN table does not exist. Create it. Note that a 
   216    216           ** side-effect of the CREATE TABLE statement is to leave the rootpage 
   217    217           ** of the new table in register pParse->regRoot. This is important 
   218    218           ** because the OpenWrite opcode below will be needing it. */
   219    219           sqlite3NestedParse(pParse,
   220         -            "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
          220  +            "CREATE TABLE %Q.%s(%s)", pDb->zDbSName, zTab, aTable[i].zCols
   221    221           );
   222    222           aRoot[i] = pParse->regRoot;
   223    223           aCreateTbl[i] = OPFLAG_P2ISREG;
   224    224         }
   225    225       }else{
   226    226         /* The table already exists. If zWhere is not NULL, delete all entries 
   227    227         ** associated with the table zWhere. If zWhere is NULL, delete the
................................................................................
   228    228         ** entire contents of the table. */
   229    229         aRoot[i] = pStat->tnum;
   230    230         aCreateTbl[i] = 0;
   231    231         sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
   232    232         if( zWhere ){
   233    233           sqlite3NestedParse(pParse,
   234    234              "DELETE FROM %Q.%s WHERE %s=%Q",
   235         -           pDb->zName, zTab, zWhereType, zWhere
          235  +           pDb->zDbSName, zTab, zWhereType, zWhere
   236    236           );
   237    237         }else{
   238    238           /* The sqlite_stat[134] table already exists.  Delete all rows. */
   239    239           sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
   240    240         }
   241    241       }
   242    242     }
................................................................................
   990    990     }
   991    991     assert( sqlite3BtreeHoldsAllMutexes(db) );
   992    992     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   993    993     assert( iDb>=0 );
   994    994     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   995    995   #ifndef SQLITE_OMIT_AUTHORIZATION
   996    996     if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
   997         -      db->aDb[iDb].zName ) ){
          997  +      db->aDb[iDb].zDbSName ) ){
   998    998       return;
   999    999     }
  1000   1000   #endif
  1001   1001   
  1002   1002     /* Establish a read-lock on the table at the shared-cache level. 
  1003   1003     ** Open a read-only cursor on the table. Also allocate a cursor number
  1004   1004     ** to use for scanning indexes (iIdxCur). No index cursor is opened at
................................................................................
  1380   1380           sqlite3DbFree(db, z);
  1381   1381         }
  1382   1382       }
  1383   1383     }else{
  1384   1384       /* Form 3: Analyze the fully qualified table name */
  1385   1385       iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
  1386   1386       if( iDb>=0 ){
  1387         -      zDb = db->aDb[iDb].zName;
         1387  +      zDb = db->aDb[iDb].zDbSName;
  1388   1388         z = sqlite3NameFromToken(db, pTableName);
  1389   1389         if( z ){
  1390   1390           if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
  1391   1391             analyzeTable(pParse, pIdx->pTable, pIdx);
  1392   1392           }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
  1393   1393             analyzeTable(pParse, pTab, 0);
  1394   1394           }
................................................................................
  1840   1840       sqlite3DeleteIndexSamples(db, pIdx);
  1841   1841       pIdx->aSample = 0;
  1842   1842   #endif
  1843   1843     }
  1844   1844   
  1845   1845     /* Load new statistics out of the sqlite_stat1 table */
  1846   1846     sInfo.db = db;
  1847         -  sInfo.zDatabase = db->aDb[iDb].zName;
         1847  +  sInfo.zDatabase = db->aDb[iDb].zDbSName;
  1848   1848     if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)!=0 ){
  1849   1849       zSql = sqlite3MPrintf(db, 
  1850   1850           "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
  1851   1851       if( zSql==0 ){
  1852   1852         rc = SQLITE_NOMEM_BKPT;
  1853   1853       }else{
  1854   1854         rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);

Changes to src/attach.c.

    93     93       goto attach_error;
    94     94     }
    95     95     if( !db->autoCommit ){
    96     96       zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
    97     97       goto attach_error;
    98     98     }
    99     99     for(i=0; i<db->nDb; i++){
   100         -    char *z = db->aDb[i].zName;
          100  +    char *z = db->aDb[i].zDbSName;
   101    101       assert( z && zName );
   102    102       if( sqlite3StrICmp(z, zName)==0 ){
   103    103         zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
   104    104         goto attach_error;
   105    105       }
   106    106     }
   107    107   
................................................................................
   158    158   #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   159    159       sqlite3BtreeSetPagerFlags(aNew->pBt,
   160    160                         PAGER_SYNCHRONOUS_FULL | (db->flags & PAGER_FLAGS_MASK));
   161    161   #endif
   162    162       sqlite3BtreeLeave(aNew->pBt);
   163    163     }
   164    164     aNew->safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
   165         -  aNew->zName = sqlite3DbStrDup(db, zName);
   166         -  if( rc==SQLITE_OK && aNew->zName==0 ){
          165  +  aNew->zDbSName = sqlite3DbStrDup(db, zName);
          166  +  if( rc==SQLITE_OK && aNew->zDbSName==0 ){
   167    167       rc = SQLITE_NOMEM_BKPT;
   168    168     }
   169    169   
   170    170   
   171    171   #ifdef SQLITE_HAS_CODEC
   172    172     if( rc==SQLITE_OK ){
   173    173       extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
................................................................................
   271    271   
   272    272     UNUSED_PARAMETER(NotUsed);
   273    273   
   274    274     if( zName==0 ) zName = "";
   275    275     for(i=0; i<db->nDb; i++){
   276    276       pDb = &db->aDb[i];
   277    277       if( pDb->pBt==0 ) continue;
   278         -    if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
          278  +    if( sqlite3StrICmp(pDb->zDbSName, zName)==0 ) break;
   279    279     }
   280    280   
   281    281     if( i>=db->nDb ){
   282    282       sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
   283    283       goto detach_error;
   284    284     }
   285    285     if( i<2 ){
................................................................................
   429    429     const Token *pName  /* Name of the view, trigger, or index */
   430    430   ){
   431    431     sqlite3 *db;
   432    432   
   433    433     db = pParse->db;
   434    434     assert( db->nDb>iDb );
   435    435     pFix->pParse = pParse;
   436         -  pFix->zDb = db->aDb[iDb].zName;
          436  +  pFix->zDb = db->aDb[iDb].zDbSName;
   437    437     pFix->pSchema = db->aDb[iDb].pSchema;
   438    438     pFix->zType = zType;
   439    439     pFix->pName = pName;
   440    440     pFix->bVarOnly = (iDb==1);
   441    441   }
   442    442   
   443    443   /*

Changes to src/auth.c.

   104    104   int sqlite3AuthReadCol(
   105    105     Parse *pParse,                  /* The parser context */
   106    106     const char *zTab,               /* Table name */
   107    107     const char *zCol,               /* Column name */
   108    108     int iDb                         /* Index of containing database. */
   109    109   ){
   110    110     sqlite3 *db = pParse->db;       /* Database handle */
   111         -  char *zDb = db->aDb[iDb].zName; /* Name of attached database */
          111  +  char *zDb = db->aDb[iDb].zDbSName; /* Schema name of attached database */
   112    112     int rc;                         /* Auth callback return code */
   113    113   
   114    114     if( db->init.busy ) return SQLITE_OK;
   115    115     rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext
   116    116   #ifdef SQLITE_USER_AUTHENTICATION
   117    117                    ,db->auth.zAuthUser
   118    118   #endif

Changes to src/backup.c.

   192    192       p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
   193    193       p->pDestDb = pDestDb;
   194    194       p->pSrcDb = pSrcDb;
   195    195       p->iNext = 1;
   196    196       p->isAttached = 0;
   197    197   
   198    198       if( 0==p->pSrc || 0==p->pDest 
   199         -     || setDestPgsz(p)==SQLITE_NOMEM 
   200    199        || checkReadTransaction(pDestDb, p->pDest)!=SQLITE_OK 
   201    200        ){
   202    201         /* One (or both) of the named databases did not exist or an OOM
   203    202         ** error was hit. Or there is a transaction open on the destination
   204    203         ** database. The error has already been written into the pDestDb 
   205    204         ** handle. All that is left to do here is free the sqlite3_backup 
   206    205         ** structure.  */
................................................................................
   380    379       */
   381    380       if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
   382    381         rc = SQLITE_BUSY;
   383    382       }else{
   384    383         rc = SQLITE_OK;
   385    384       }
   386    385   
   387         -    /* Lock the destination database, if it is not locked already. */
   388         -    if( SQLITE_OK==rc && p->bDestLocked==0
   389         -     && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2)) 
   390         -    ){
   391         -      p->bDestLocked = 1;
   392         -      sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
   393         -    }
   394         -
   395    386       /* If there is no open read-transaction on the source database, open
   396    387       ** one now. If a transaction is opened here, then it will be closed
   397    388       ** before this function exits.
   398    389       */
   399    390       if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
   400    391         rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
   401    392         bCloseTrans = 1;
   402    393       }
          394  +
          395  +    /* If the destination database has not yet been locked (i.e. if this
          396  +    ** is the first call to backup_step() for the current backup operation),
          397  +    ** try to set its page size to the same as the source database. This
          398  +    ** is especially important on ZipVFS systems, as in that case it is
          399  +    ** not possible to create a database file that uses one page size by
          400  +    ** writing to it with another.  */
          401  +    if( p->bDestLocked==0 && rc==SQLITE_OK && setDestPgsz(p)==SQLITE_NOMEM ){
          402  +      rc = SQLITE_NOMEM;
          403  +    }
          404  +
          405  +    /* Lock the destination database, if it is not locked already. */
          406  +    if( SQLITE_OK==rc && p->bDestLocked==0
          407  +     && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2)) 
          408  +    ){
          409  +      p->bDestLocked = 1;
          410  +      sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
          411  +    }
   403    412   
   404    413       /* Do not allow backup if the destination database is in WAL mode
   405    414       ** and the page sizes are different between source and destination */
   406    415       pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
   407    416       pgszDest = sqlite3BtreeGetPageSize(p->pDest);
   408    417       destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
   409    418       if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){

Changes to src/build.c.

   149    149       while( sqlite3VdbeDeletePriorOpcode(v, OP_Close) ){}
   150    150       sqlite3VdbeAddOp0(v, OP_Halt);
   151    151   
   152    152   #if SQLITE_USER_AUTHENTICATION
   153    153       if( pParse->nTableLock>0 && db->init.busy==0 ){
   154    154         sqlite3UserAuthInit(db);
   155    155         if( db->auth.authLevel<UAUTH_User ){
   156         -        pParse->rc = SQLITE_AUTH_USER;
   157    156           sqlite3ErrorMsg(pParse, "user not authenticated");
          157  +        pParse->rc = SQLITE_AUTH_USER;
   158    158           return;
   159    159         }
   160    160       }
   161    161   #endif
   162    162   
   163    163       /* The cookie mask contains one bit for each database file open.
   164    164       ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
................................................................................
   314    314     ** exists */
   315    315     if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
   316    316       return 0;
   317    317     }
   318    318   #endif
   319    319     for(i=OMIT_TEMPDB; i<db->nDb; i++){
   320    320       int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
   321         -    if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
          321  +    if( zDatabase==0 || sqlite3StrICmp(zDatabase, db->aDb[j].zDbSName)==0 ){
   322    322       assert( sqlite3SchemaMutexHeld(db, j, 0) );
   323    323       p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
   324    324       if( p ) break;
   325    325     }
          326  +  }
   326    327     return p;
   327    328   }
   328    329   
   329    330   /*
   330    331   ** Locate the in-memory structure that describes a particular database
   331    332   ** table given the name of that table and (optionally) the name of the
   332    333   ** database containing the table.  Return NULL if not found.  Also leave an
................................................................................
   391    392     u32 flags,
   392    393     struct SrcList_item *p
   393    394   ){
   394    395     const char *zDb;
   395    396     assert( p->pSchema==0 || p->zDatabase==0 );
   396    397     if( p->pSchema ){
   397    398       int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
   398         -    zDb = pParse->db->aDb[iDb].zName;
          399  +    zDb = pParse->db->aDb[iDb].zDbSName;
   399    400     }else{
   400    401       zDb = p->zDatabase;
   401    402     }
   402    403     return sqlite3LocateTable(pParse, flags, p->zName, zDb);
   403    404   }
   404    405   
   405    406   /*
................................................................................
   419    420     int i;
   420    421     /* All mutexes are required for schema access.  Make sure we hold them. */
   421    422     assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
   422    423     for(i=OMIT_TEMPDB; i<db->nDb; i++){
   423    424       int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
   424    425       Schema *pSchema = db->aDb[j].pSchema;
   425    426       assert( pSchema );
   426         -    if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
          427  +    if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zDbSName) ) continue;
   427    428       assert( sqlite3SchemaMutexHeld(db, j, 0) );
   428    429       p = sqlite3HashFind(&pSchema->idxHash, zName);
   429    430       if( p ) break;
   430    431     }
   431    432     return p;
   432    433   }
   433    434   
................................................................................
   488    489   ** are never candidates for being collapsed.
   489    490   */
   490    491   void sqlite3CollapseDatabaseArray(sqlite3 *db){
   491    492     int i, j;
   492    493     for(i=j=2; i<db->nDb; i++){
   493    494       struct Db *pDb = &db->aDb[i];
   494    495       if( pDb->pBt==0 ){
   495         -      sqlite3DbFree(db, pDb->zName);
   496         -      pDb->zName = 0;
          496  +      sqlite3DbFree(db, pDb->zDbSName);
          497  +      pDb->zDbSName = 0;
   497    498         continue;
   498    499       }
   499    500       if( j<i ){
   500    501         db->aDb[j] = db->aDb[i];
   501    502       }
   502    503       j++;
   503    504     }
................................................................................
   709    710   ** -1 if the named db cannot be found.
   710    711   */
   711    712   int sqlite3FindDbName(sqlite3 *db, const char *zName){
   712    713     int i = -1;         /* Database number */
   713    714     if( zName ){
   714    715       Db *pDb;
   715    716       for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
   716         -      if( 0==sqlite3StrICmp(pDb->zName, zName) ) break;
          717  +      if( 0==sqlite3StrICmp(pDb->zDbSName, zName) ) break;
   717    718       }
   718    719     }
   719    720     return i;
   720    721   }
   721    722   
   722    723   /*
   723    724   ** The token *pName contains the name of a database (either "main" or
................................................................................
   768    769       *pUnqual = pName2;
   769    770       iDb = sqlite3FindDb(db, pName1);
   770    771       if( iDb<0 ){
   771    772         sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
   772    773         return -1;
   773    774       }
   774    775     }else{
   775         -    assert( db->init.iDb==0 || db->init.busy );
          776  +    assert( db->init.iDb==0 || db->init.busy || (db->flags & SQLITE_Vacuum)!=0);
   776    777       iDb = db->init.iDb;
   777    778       *pUnqual = pName1;
   778    779     }
   779    780     return iDb;
   780    781   }
   781    782   
   782    783   /*
................................................................................
   879    880     {
   880    881       static const u8 aCode[] = {
   881    882          SQLITE_CREATE_TABLE,
   882    883          SQLITE_CREATE_TEMP_TABLE,
   883    884          SQLITE_CREATE_VIEW,
   884    885          SQLITE_CREATE_TEMP_VIEW
   885    886       };
   886         -    char *zDb = db->aDb[iDb].zName;
          887  +    char *zDb = db->aDb[iDb].zDbSName;
   887    888       if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
   888    889         goto begin_table_error;
   889    890       }
   890    891       if( !isVirtual && sqlite3AuthCheck(pParse, (int)aCode[isTemp+2*isView],
   891    892                                          zName, 0, zDb) ){
   892    893         goto begin_table_error;
   893    894       }
................................................................................
   898    899     ** index or table name in the same database.  Issue an error message if
   899    900     ** it does. The exception is if the statement being parsed was passed
   900    901     ** to an sqlite3_declare_vtab() call. In that case only the column names
   901    902     ** and types will be used, so there is no need to test for namespace
   902    903     ** collisions.
   903    904     */
   904    905     if( !IN_DECLARE_VTAB ){
   905         -    char *zDb = db->aDb[iDb].zName;
          906  +    char *zDb = db->aDb[iDb].zDbSName;
   906    907       if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   907    908         goto begin_table_error;
   908    909       }
   909    910       pTable = sqlite3FindTable(db, zName, zDb);
   910    911       if( pTable ){
   911    912         if( !noErr ){
   912    913           sqlite3ErrorMsg(pParse, "table %T already exists", pName);
................................................................................
  1991   1992       ** SQLITE_MASTER table.  We just need to update that slot with all
  1992   1993       ** the information we've collected.
  1993   1994       */
  1994   1995       sqlite3NestedParse(pParse,
  1995   1996         "UPDATE %Q.%s "
  1996   1997            "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
  1997   1998          "WHERE rowid=#%d",
  1998         -      db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
         1999  +      db->aDb[iDb].zDbSName, SCHEMA_TABLE(iDb),
  1999   2000         zType,
  2000   2001         p->zName,
  2001   2002         p->zName,
  2002   2003         pParse->regRoot,
  2003   2004         zStmt,
  2004   2005         pParse->regRowid
  2005   2006       );
................................................................................
  2006   2007       sqlite3DbFree(db, zStmt);
  2007   2008       sqlite3ChangeCookie(pParse, iDb);
  2008   2009   
  2009   2010   #ifndef SQLITE_OMIT_AUTOINCREMENT
  2010   2011       /* Check to see if we need to create an sqlite_sequence table for
  2011   2012       ** keeping track of autoincrement keys.
  2012   2013       */
  2013         -    if( p->tabFlags & TF_Autoincrement ){
         2014  +    if( (p->tabFlags & TF_Autoincrement)!=0 ){
  2014   2015         Db *pDb = &db->aDb[iDb];
  2015   2016         assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  2016   2017         if( pDb->pSchema->pSeqTab==0 ){
  2017   2018           sqlite3NestedParse(pParse,
  2018   2019             "CREATE TABLE %Q.sqlite_sequence(name,seq)",
  2019         -          pDb->zName
         2020  +          pDb->zDbSName
  2020   2021           );
  2021   2022         }
  2022   2023       }
  2023   2024   #endif
  2024   2025   
  2025   2026       /* Reparse everything to update our internal data structures */
  2026   2027       sqlite3VdbeAddParseSchemaOp(v, iDb,
................................................................................
  2326   2327     **
  2327   2328     ** The "#NNN" in the SQL is a special constant that means whatever value
  2328   2329     ** is in register NNN.  See grammar rules associated with the TK_REGISTER
  2329   2330     ** token for additional information.
  2330   2331     */
  2331   2332     sqlite3NestedParse(pParse, 
  2332   2333        "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
  2333         -     pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
         2334  +     pParse->db->aDb[iDb].zDbSName, SCHEMA_TABLE(iDb), iTable, r1, r1);
  2334   2335   #endif
  2335   2336     sqlite3ReleaseTempReg(pParse, r1);
  2336   2337   }
  2337   2338   
  2338   2339   /*
  2339   2340   ** Write VDBE code to erase table pTab and all associated indices on disk.
  2340   2341   ** Code to update the sqlite_master tables and internal schema definitions
................................................................................
  2402   2403   static void sqlite3ClearStatTables(
  2403   2404     Parse *pParse,         /* The parsing context */
  2404   2405     int iDb,               /* The database number */
  2405   2406     const char *zType,     /* "idx" or "tbl" */
  2406   2407     const char *zName      /* Name of index or table */
  2407   2408   ){
  2408   2409     int i;
  2409         -  const char *zDbName = pParse->db->aDb[iDb].zName;
         2410  +  const char *zDbName = pParse->db->aDb[iDb].zDbSName;
  2410   2411     for(i=1; i<=4; i++){
  2411   2412       char zTab[24];
  2412   2413       sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
  2413   2414       if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
  2414   2415         sqlite3NestedParse(pParse,
  2415   2416           "DELETE FROM %Q.%s WHERE %s=%Q",
  2416   2417           zDbName, zTab, zType, zName
................................................................................
  2455   2456     ** the table being dropped. This is done before the table is dropped
  2456   2457     ** at the btree level, in case the sqlite_sequence table needs to
  2457   2458     ** move as a result of the drop (can happen in auto-vacuum mode).
  2458   2459     */
  2459   2460     if( pTab->tabFlags & TF_Autoincrement ){
  2460   2461       sqlite3NestedParse(pParse,
  2461   2462         "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
  2462         -      pDb->zName, pTab->zName
         2463  +      pDb->zDbSName, pTab->zName
  2463   2464       );
  2464   2465     }
  2465   2466   #endif
  2466   2467   
  2467   2468     /* Drop all SQLITE_MASTER table and index entries that refer to the
  2468   2469     ** table. The program name loops through the master table and deletes
  2469   2470     ** every row that refers to a table of the same name as the one being
  2470   2471     ** dropped. Triggers are handled separately because a trigger can be
  2471   2472     ** created in the temp database that refers to a table in another
  2472   2473     ** database.
  2473   2474     */
  2474   2475     sqlite3NestedParse(pParse, 
  2475   2476         "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
  2476         -      pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
         2477  +      pDb->zDbSName, SCHEMA_TABLE(iDb), pTab->zName);
  2477   2478     if( !isView && !IsVirtual(pTab) ){
  2478   2479       destroyTable(pParse, pTab);
  2479   2480     }
  2480   2481   
  2481   2482     /* Remove the table entry from SQLite's internal schema and modify
  2482   2483     ** the schema cookie.
  2483   2484     */
................................................................................
  2523   2524     if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
  2524   2525       goto exit_drop_table;
  2525   2526     }
  2526   2527   #ifndef SQLITE_OMIT_AUTHORIZATION
  2527   2528     {
  2528   2529       int code;
  2529   2530       const char *zTab = SCHEMA_TABLE(iDb);
  2530         -    const char *zDb = db->aDb[iDb].zName;
         2531  +    const char *zDb = db->aDb[iDb].zDbSName;
  2531   2532       const char *zArg2 = 0;
  2532   2533       if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
  2533   2534         goto exit_drop_table;
  2534   2535       }
  2535   2536       if( isView ){
  2536   2537         if( !OMIT_TEMPDB && iDb==1 ){
  2537   2538           code = SQLITE_DROP_TEMP_VIEW;
................................................................................
  2764   2765     KeyInfo *pKey;                 /* KeyInfo for index */
  2765   2766     int regRecord;                 /* Register holding assembled index record */
  2766   2767     sqlite3 *db = pParse->db;      /* The database connection */
  2767   2768     int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  2768   2769   
  2769   2770   #ifndef SQLITE_OMIT_AUTHORIZATION
  2770   2771     if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
  2771         -      db->aDb[iDb].zName ) ){
         2772  +      db->aDb[iDb].zDbSName ) ){
  2772   2773       return;
  2773   2774     }
  2774   2775   #endif
  2775   2776   
  2776   2777     /* Require a write-lock on the table to perform this operation */
  2777   2778     sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  2778   2779   
................................................................................
  3016   3017       }
  3017   3018       if( !db->init.busy ){
  3018   3019         if( sqlite3FindTable(db, zName, 0)!=0 ){
  3019   3020           sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
  3020   3021           goto exit_create_index;
  3021   3022         }
  3022   3023       }
  3023         -    if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
         3024  +    if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){
  3024   3025         if( !ifNotExist ){
  3025   3026           sqlite3ErrorMsg(pParse, "index %s already exists", zName);
  3026   3027         }else{
  3027   3028           assert( !db->init.busy );
  3028   3029           sqlite3CodeVerifySchema(pParse, iDb);
  3029   3030         }
  3030   3031         goto exit_create_index;
................................................................................
  3046   3047       if( IN_DECLARE_VTAB ) zName[7]++;
  3047   3048     }
  3048   3049   
  3049   3050     /* Check for authorization to create an index.
  3050   3051     */
  3051   3052   #ifndef SQLITE_OMIT_AUTHORIZATION
  3052   3053     {
  3053         -    const char *zDb = pDb->zName;
         3054  +    const char *zDb = pDb->zDbSName;
  3054   3055       if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
  3055   3056         goto exit_create_index;
  3056   3057       }
  3057   3058       i = SQLITE_CREATE_INDEX;
  3058   3059       if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
  3059   3060       if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
  3060   3061         goto exit_create_index;
................................................................................
  3361   3362         zStmt = 0;
  3362   3363       }
  3363   3364   
  3364   3365       /* Add an entry in sqlite_master for this index
  3365   3366       */
  3366   3367       sqlite3NestedParse(pParse, 
  3367   3368           "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
  3368         -        db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
         3369  +        db->aDb[iDb].zDbSName, SCHEMA_TABLE(iDb),
  3369   3370           pIndex->zName,
  3370   3371           pTab->zName,
  3371   3372           iMem,
  3372   3373           zStmt
  3373   3374       );
  3374   3375       sqlite3DbFree(db, zStmt);
  3375   3376   
................................................................................
  3495   3496       goto exit_drop_index;
  3496   3497     }
  3497   3498     iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  3498   3499   #ifndef SQLITE_OMIT_AUTHORIZATION
  3499   3500     {
  3500   3501       int code = SQLITE_DROP_INDEX;
  3501   3502       Table *pTab = pIndex->pTable;
  3502         -    const char *zDb = db->aDb[iDb].zName;
         3503  +    const char *zDb = db->aDb[iDb].zDbSName;
  3503   3504       const char *zTab = SCHEMA_TABLE(iDb);
  3504   3505       if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  3505   3506         goto exit_drop_index;
  3506   3507       }
  3507   3508       if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
  3508   3509       if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
  3509   3510         goto exit_drop_index;
................................................................................
  3513   3514   
  3514   3515     /* Generate code to remove the index and from the master table */
  3515   3516     v = sqlite3GetVdbe(pParse);
  3516   3517     if( v ){
  3517   3518       sqlite3BeginWriteOperation(pParse, 1, iDb);
  3518   3519       sqlite3NestedParse(pParse,
  3519   3520          "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
  3520         -       db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
         3521  +       db->aDb[iDb].zDbSName, SCHEMA_TABLE(iDb), pIndex->zName
  3521   3522       );
  3522   3523       sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
  3523   3524       sqlite3ChangeCookie(pParse, iDb);
  3524   3525       destroyRootPage(pParse, pIndex->tnum, iDb);
  3525   3526       sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
  3526   3527     }
  3527   3528   
................................................................................
  4058   4059   ** attached database. Otherwise, invoke it for the database named zDb only.
  4059   4060   */
  4060   4061   void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
  4061   4062     sqlite3 *db = pParse->db;
  4062   4063     int i;
  4063   4064     for(i=0; i<db->nDb; i++){
  4064   4065       Db *pDb = &db->aDb[i];
  4065         -    if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
         4066  +    if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zDbSName)) ){
  4066   4067         sqlite3CodeVerifySchema(pParse, i);
  4067   4068       }
  4068   4069     }
  4069   4070   }
  4070   4071   
  4071   4072   /*
  4072   4073   ** Generate VDBE code that prepares for doing an operation that
................................................................................
  4305   4306       }
  4306   4307       sqlite3DbFree(db, zColl);
  4307   4308     }
  4308   4309     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
  4309   4310     if( iDb<0 ) return;
  4310   4311     z = sqlite3NameFromToken(db, pObjName);
  4311   4312     if( z==0 ) return;
  4312         -  zDb = db->aDb[iDb].zName;
         4313  +  zDb = db->aDb[iDb].zDbSName;
  4313   4314     pTab = sqlite3FindTable(db, z, zDb);
  4314   4315     if( pTab ){
  4315   4316       reindexTable(pParse, pTab, 0);
  4316   4317       sqlite3DbFree(db, z);
  4317   4318       return;
  4318   4319     }
  4319   4320     pIndex = sqlite3FindIndex(db, z, zDb);

Changes to src/dbstat.c.

   598    598     pCsr->pStmt = 0;
   599    599     zMaster = pCsr->iDb==1 ? "sqlite_temp_master" : "sqlite_master";
   600    600     zSql = sqlite3_mprintf(
   601    601         "SELECT 'sqlite_master' AS name, 1 AS rootpage, 'table' AS type"
   602    602         "  UNION ALL  "
   603    603         "SELECT name, rootpage, type"
   604    604         "  FROM \"%w\".%s WHERE rootpage!=0"
   605         -      "  ORDER BY name", pTab->db->aDb[pCsr->iDb].zName, zMaster);
          605  +      "  ORDER BY name", pTab->db->aDb[pCsr->iDb].zDbSName, zMaster);
   606    606     if( zSql==0 ){
   607    607       return SQLITE_NOMEM_BKPT;
   608    608     }else{
   609    609       rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
   610    610       sqlite3_free(zSql);
   611    611     }
   612    612   
................................................................................
   652    652         break;
   653    653       case 9:            /* pgsize */
   654    654         sqlite3_result_int(ctx, pCsr->szPage);
   655    655         break;
   656    656       default: {          /* schema */
   657    657         sqlite3 *db = sqlite3_context_db_handle(ctx);
   658    658         int iDb = pCsr->iDb;
   659         -      sqlite3_result_text(ctx, db->aDb[iDb].zName, -1, SQLITE_STATIC);
          659  +      sqlite3_result_text(ctx, db->aDb[iDb].zDbSName, -1, SQLITE_STATIC);
   660    660         break;
   661    661       }
   662    662     }
   663    663     return SQLITE_OK;
   664    664   }
   665    665   
   666    666   static int statRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){

Changes to src/delete.c.

    98     98     sqlite3 *db = pParse->db;
    99     99     int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
   100    100     pWhere = sqlite3ExprDup(db, pWhere, 0);
   101    101     pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
   102    102     if( pFrom ){
   103    103       assert( pFrom->nSrc==1 );
   104    104       pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
   105         -    pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
          105  +    pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zDbSName);
   106    106       assert( pFrom->a[0].pOn==0 );
   107    107       assert( pFrom->a[0].pUsing==0 );
   108    108     }
   109    109     pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 
   110    110                             SF_IncludeHidden, 0, 0);
   111    111     sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
   112    112     sqlite3Select(pParse, pSel, &dest);
................................................................................
   285    285     }
   286    286   
   287    287     if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
   288    288       goto delete_from_cleanup;
   289    289     }
   290    290     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   291    291     assert( iDb<db->nDb );
   292         -  zDb = db->aDb[iDb].zName;
          292  +  zDb = db->aDb[iDb].zDbSName;
   293    293     rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
   294    294     assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
   295    295     if( rcauth==SQLITE_DENY ){
   296    296       goto delete_from_cleanup;
   297    297     }
   298    298     assert(!isView || pTrigger);
   299    299   

Changes to src/fkey.c.

   867    867     /* Exactly one of regOld and regNew should be non-zero. */
   868    868     assert( (regOld==0)!=(regNew==0) );
   869    869   
   870    870     /* If foreign-keys are disabled, this function is a no-op. */
   871    871     if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
   872    872   
   873    873     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   874         -  zDb = db->aDb[iDb].zName;
          874  +  zDb = db->aDb[iDb].zDbSName;
   875    875   
   876    876     /* Loop through all the foreign key constraints for which pTab is the
   877    877     ** child table (the table that the foreign key definition is part of).  */
   878    878     for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
   879    879       Table *pTo;                   /* Parent table of foreign key pFKey */
   880    880       Index *pIdx = 0;              /* Index on key columns in pTo */
   881    881       int *aiFree = 0;

Changes to src/insert.c.

   196    196     return 0;
   197    197   }
   198    198   
   199    199   #ifndef SQLITE_OMIT_AUTOINCREMENT
   200    200   /*
   201    201   ** Locate or create an AutoincInfo structure associated with table pTab
   202    202   ** which is in database iDb.  Return the register number for the register
   203         -** that holds the maximum rowid.
          203  +** that holds the maximum rowid.  Return zero if pTab is not an AUTOINCREMENT
          204  +** table.  (Also return zero when doing a VACUUM since we do not want to
          205  +** update the AUTOINCREMENT counters during a VACUUM.)
   204    206   **
   205    207   ** There is at most one AutoincInfo structure per table even if the
   206    208   ** same table is autoincremented multiple times due to inserts within
   207    209   ** triggers.  A new AutoincInfo structure is created if this is the
   208    210   ** first use of table pTab.  On 2nd and subsequent uses, the original
   209    211   ** AutoincInfo structure is used.
   210    212   **
................................................................................
   219    221   */
   220    222   static int autoIncBegin(
   221    223     Parse *pParse,      /* Parsing context */
   222    224     int iDb,            /* Index of the database holding pTab */
   223    225     Table *pTab         /* The table we are writing to */
   224    226   ){
   225    227     int memId = 0;      /* Register holding maximum rowid */
   226         -  if( pTab->tabFlags & TF_Autoincrement ){
          228  +  if( (pTab->tabFlags & TF_Autoincrement)!=0
          229  +   && (pParse->db->flags & SQLITE_Vacuum)==0
          230  +  ){
   227    231       Parse *pToplevel = sqlite3ParseToplevel(pParse);
   228    232       AutoincInfo *pInfo;
   229    233   
   230    234       pInfo = pToplevel->pAinc;
   231    235       while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
   232    236       if( pInfo==0 ){
   233    237         pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
................................................................................
   543    547     pTab = sqlite3SrcListLookup(pParse, pTabList);
   544    548     if( pTab==0 ){
   545    549       goto insert_cleanup;
   546    550     }
   547    551     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   548    552     assert( iDb<db->nDb );
   549    553     pDb = &db->aDb[iDb];
   550         -  zDb = pDb->zName;
          554  +  zDb = pDb->zDbSName;
   551    555     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
   552    556       goto insert_cleanup;
   553    557     }
   554    558     withoutRowid = !HasRowid(pTab);
   555    559   
   556    560     /* Figure out if we have any triggers and if the table being
   557    561     ** inserted into is a view
................................................................................
  1773   1777     }else{
  1774   1778       sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
  1775   1779     }
  1776   1780     if( piIdxCur ) *piIdxCur = iBase;
  1777   1781     for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  1778   1782       int iIdxCur = iBase++;
  1779   1783       assert( pIdx->pSchema==pTab->pSchema );
         1784  +    if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
         1785  +      if( piDataCur ) *piDataCur = iIdxCur;
         1786  +      p5 = 0;
         1787  +    }
  1780   1788       if( aToOpen==0 || aToOpen[i+1] ){
  1781   1789         sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
  1782   1790         sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  1783         -      VdbeComment((v, "%s", pIdx->zName));
  1784         -    }
  1785         -    if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
  1786         -      if( piDataCur ) *piDataCur = iIdxCur;
  1787         -    }else{
  1788   1791         sqlite3VdbeChangeP5(v, p5);
         1792  +      VdbeComment((v, "%s", pIdx->zName));
  1789   1793       }
  1790   1794     }
  1791   1795     if( iBase>pParse->nTab ) pParse->nTab = iBase;
  1792   1796     return i;
  1793   1797   }
  1794   1798   
  1795   1799   

Changes to src/main.c.

   788    788   ** Configuration settings for an individual database connection
   789    789   */
   790    790   int sqlite3_db_config(sqlite3 *db, int op, ...){
   791    791     va_list ap;
   792    792     int rc;
   793    793     va_start(ap, op);
   794    794     switch( op ){
          795  +    case SQLITE_DBCONFIG_MAINDBNAME: {
          796  +      db->aDb[0].zDbSName = va_arg(ap,char*);
          797  +      rc = SQLITE_OK;
          798  +      break;
          799  +    }
   795    800       case SQLITE_DBCONFIG_LOOKASIDE: {
   796    801         void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
   797    802         int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
   798    803         int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
   799    804         rc = setupLookaside(db, pBuf, sz, cnt);
   800    805         break;
   801    806       }
................................................................................
  1841   1846   ){
  1842   1847   #ifdef SQLITE_ENABLE_API_ARMOR
  1843   1848     if( !sqlite3SafetyCheckOk(db) ){
  1844   1849       return SQLITE_MISUSE_BKPT;
  1845   1850     }
  1846   1851   #endif
  1847   1852     sqlite3_mutex_enter(db->mutex);
         1853  +  if( mTrace==0 ) xTrace = 0;
         1854  +  if( xTrace==0 ) mTrace = 0;
  1848   1855     db->mTrace = mTrace;
  1849   1856     db->xTrace = xTrace;
  1850   1857     db->pTraceArg = pArg;
  1851   1858     sqlite3_mutex_leave(db->mutex);
  1852   1859     return SQLITE_OK;
  1853   1860   }
  1854   1861   
................................................................................
  3024   3031     if( !db->mallocFailed ) ENC(db) = SCHEMA_ENC(db);
  3025   3032     sqlite3BtreeLeave(db->aDb[0].pBt);
  3026   3033     db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
  3027   3034   
  3028   3035     /* The default safety_level for the main database is FULL; for the temp
  3029   3036     ** database it is OFF. This matches the pager layer defaults.  
  3030   3037     */
  3031         -  db->aDb[0].zName = "main";
         3038  +  db->aDb[0].zDbSName = "main";
  3032   3039     db->aDb[0].safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
  3033         -  db->aDb[1].zName = "temp";
         3040  +  db->aDb[1].zDbSName = "temp";
  3034   3041     db->aDb[1].safety_level = PAGER_SYNCHRONOUS_OFF;
  3035   3042   
  3036   3043     db->magic = SQLITE_MAGIC_OPEN;
  3037   3044     if( db->mallocFailed ){
  3038   3045       goto opendb_out;
  3039   3046     }
  3040   3047   
  3041   3048     /* Register all built-in functions, but do not attempt to read the
  3042   3049     ** database schema yet. This is delayed until the first time the database
  3043   3050     ** is accessed.
  3044   3051     */
  3045   3052     sqlite3Error(db, SQLITE_OK);
  3046   3053     sqlite3RegisterPerConnectionBuiltinFunctions(db);
         3054  +  rc = sqlite3_errcode(db);
         3055  +
         3056  +#ifdef SQLITE_ENABLE_FTS5
         3057  +  /* Register any built-in FTS5 module before loading the automatic
         3058  +  ** extensions. This allows automatic extensions to register FTS5 
         3059  +  ** tokenizers and auxiliary functions.  */
         3060  +  if( !db->mallocFailed && rc==SQLITE_OK ){
         3061  +    rc = sqlite3Fts5Init(db);
         3062  +  }
         3063  +#endif
  3047   3064   
  3048   3065     /* Load automatic extensions - extensions that have been registered
  3049   3066     ** using the sqlite3_automatic_extension() API.
  3050   3067     */
  3051         -  rc = sqlite3_errcode(db);
  3052   3068     if( rc==SQLITE_OK ){
  3053   3069       sqlite3AutoLoadExtensions(db);
  3054   3070       rc = sqlite3_errcode(db);
  3055   3071       if( rc!=SQLITE_OK ){
  3056   3072         goto opendb_out;
  3057   3073       }
  3058   3074     }
................................................................................
  3071   3087     }
  3072   3088   #endif
  3073   3089   
  3074   3090   #ifdef SQLITE_ENABLE_FTS3 /* automatically defined by SQLITE_ENABLE_FTS4 */
  3075   3091     if( !db->mallocFailed && rc==SQLITE_OK ){
  3076   3092       rc = sqlite3Fts3Init(db);
  3077   3093     }
  3078         -#endif
  3079         -
  3080         -#ifdef SQLITE_ENABLE_FTS5
  3081         -  if( !db->mallocFailed && rc==SQLITE_OK ){
  3082         -    rc = sqlite3Fts5Init(db);
  3083         -  }
  3084   3094   #endif
  3085   3095   
  3086   3096   #ifdef SQLITE_ENABLE_ICU
  3087   3097     if( !db->mallocFailed && rc==SQLITE_OK ){
  3088   3098       rc = sqlite3IcuInit(db);
  3089   3099     }
  3090   3100   #endif
................................................................................
  4019   4029   /*
  4020   4030   ** Return the Btree pointer identified by zDbName.  Return NULL if not found.
  4021   4031   */
  4022   4032   Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
  4023   4033     int i;
  4024   4034     for(i=0; i<db->nDb; i++){
  4025   4035       if( db->aDb[i].pBt
  4026         -     && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
         4036  +     && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zDbSName)==0)
  4027   4037       ){
  4028   4038         return db->aDb[i].pBt;
  4029   4039       }
  4030   4040     }
  4031   4041     return 0;
  4032   4042   }
  4033   4043   

Changes to src/os_unix.c.

  6702   6702         }
  6703   6703       }
  6704   6704       unixLeaveMutex();
  6705   6705     }
  6706   6706   #endif    /* if !OS_VXWORKS */
  6707   6707     return pUnused;
  6708   6708   }
         6709  +
         6710  +/*
         6711  +** Find the mode, uid and gid of file zFile. 
         6712  +*/
         6713  +static int getFileMode(
         6714  +  const char *zFile,              /* File name */
         6715  +  mode_t *pMode,                  /* OUT: Permissions of zFile */
         6716  +  uid_t *pUid,                    /* OUT: uid of zFile. */
         6717  +  gid_t *pGid                     /* OUT: gid of zFile. */
         6718  +){
         6719  +  struct stat sStat;              /* Output of stat() on database file */
         6720  +  int rc = SQLITE_OK;
         6721  +  if( 0==osStat(zFile, &sStat) ){
         6722  +    *pMode = sStat.st_mode & 0777;
         6723  +    *pUid = sStat.st_uid;
         6724  +    *pGid = sStat.st_gid;
         6725  +  }else{
         6726  +    rc = SQLITE_IOERR_FSTAT;
         6727  +  }
         6728  +  return rc;
         6729  +}
  6709   6730   
  6710   6731   /*
  6711   6732   ** This function is called by unixOpen() to determine the unix permissions
  6712   6733   ** to create new files with. If no error occurs, then SQLITE_OK is returned
  6713   6734   ** and a value suitable for passing as the third argument to open(2) is
  6714   6735   ** written to *pMode. If an IO error occurs, an SQLite error code is 
  6715   6736   ** returned and the value of *pMode is not modified.
................................................................................
  6738   6759     int rc = SQLITE_OK;             /* Return Code */
  6739   6760     *pMode = 0;
  6740   6761     *pUid = 0;
  6741   6762     *pGid = 0;
  6742   6763     if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
  6743   6764       char zDb[MAX_PATHNAME+1];     /* Database file path */
  6744   6765       int nDb;                      /* Number of valid bytes in zDb */
  6745         -    struct stat sStat;            /* Output of stat() on database file */
  6746   6766   
  6747   6767       /* zPath is a path to a WAL or journal file. The following block derives
  6748   6768       ** the path to the associated database file from zPath. This block handles
  6749   6769       ** the following naming conventions:
  6750   6770       **
  6751   6771       **   "<path to db>-journal"
  6752   6772       **   "<path to db>-wal"
................................................................................
  6769   6789         if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
  6770   6790   #endif
  6771   6791         nDb--;
  6772   6792       }
  6773   6793       memcpy(zDb, zPath, nDb);
  6774   6794       zDb[nDb] = '\0';
  6775   6795   
  6776         -    if( 0==osStat(zDb, &sStat) ){
  6777         -      *pMode = sStat.st_mode & 0777;
  6778         -      *pUid = sStat.st_uid;
  6779         -      *pGid = sStat.st_gid;
  6780         -    }else{
  6781         -      rc = SQLITE_IOERR_FSTAT;
  6782         -    }
         6796  +    rc = getFileMode(zDb, pMode, pUid, pGid);
  6783   6797     }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
  6784   6798       *pMode = 0600;
         6799  +  }else if( flags & SQLITE_OPEN_URI ){
         6800  +    /* If this is a main database file and the file was opened using a URI
         6801  +    ** filename, check for the "modeof" parameter. If present, interpret
         6802  +    ** its value as a filename and try to copy the mode, uid and gid from
         6803  +    ** that file.  */
         6804  +    const char *z = sqlite3_uri_parameter(zPath, "modeof");
         6805  +    if( z ){
         6806  +      rc = getFileMode(z, pMode, pUid, pGid);
         6807  +    }
  6785   6808     }
  6786   6809     return rc;
  6787   6810   }
  6788   6811   
  6789   6812   /*
  6790   6813   ** Open the file zPath.
  6791   6814   ** 

Changes to src/pager.c.

  6678   6678   ** then savepoint iSavepoint is also destroyed.
  6679   6679   **
  6680   6680   ** This function may return SQLITE_NOMEM if a memory allocation fails,
  6681   6681   ** or an IO error code if an IO error occurs while rolling back a 
  6682   6682   ** savepoint. If no errors occur, SQLITE_OK is returned.
  6683   6683   */ 
  6684   6684   int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
  6685         -  int rc = pPager->errCode;       /* Return code */
         6685  +  int rc = pPager->errCode;
         6686  +  
         6687  +#ifdef SQLITE_ENABLE_ZIPVFS
         6688  +  if( op==SAVEPOINT_RELEASE ) rc = SQLITE_OK;
         6689  +#endif
  6686   6690   
  6687   6691     assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  6688   6692     assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
  6689   6693   
  6690   6694     if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
  6691   6695       int ii;            /* Iterator variable */
  6692   6696       int nNew;          /* Number of remaining savepoints after this op. */
................................................................................
  6719   6723       ** the database file, so the playback operation can be skipped.
  6720   6724       */
  6721   6725       else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
  6722   6726         PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
  6723   6727         rc = pagerPlaybackSavepoint(pPager, pSavepoint);
  6724   6728         assert(rc!=SQLITE_DONE);
  6725   6729       }
         6730  +    
         6731  +#ifdef SQLITE_ENABLE_ZIPVFS
         6732  +    /* If the cache has been modified but the savepoint cannot be rolled 
         6733  +    ** back journal_mode=off, put the pager in the error state. This way,
         6734  +    ** if the VFS used by this pager includes ZipVFS, the entire transaction
         6735  +    ** can be rolled back at the ZipVFS level.  */
         6736  +    else if( 
         6737  +        pPager->journalMode==PAGER_JOURNALMODE_OFF 
         6738  +     && pPager->eState>=PAGER_WRITER_CACHEMOD
         6739  +    ){
         6740  +      pPager->errCode = SQLITE_ABORT;
         6741  +      pPager->eState = PAGER_ERROR;
         6742  +    }
         6743  +#endif
  6726   6744     }
  6727   6745   
  6728   6746     return rc;
  6729   6747   }
  6730   6748   
  6731   6749   /*
  6732   6750   ** Return the full pathname of the database file.

Changes to src/parse.y.

  1281   1281   //
  1282   1282   cmd ::= DROP INDEX ifexists(E) fullname(X).   {sqlite3DropIndex(pParse, X, E);}
  1283   1283   
  1284   1284   ///////////////////////////// The VACUUM command /////////////////////////////
  1285   1285   //
  1286   1286   %ifndef SQLITE_OMIT_VACUUM
  1287   1287   %ifndef SQLITE_OMIT_ATTACH
  1288         -cmd ::= VACUUM.                {sqlite3Vacuum(pParse);}
  1289         -cmd ::= VACUUM nm.             {sqlite3Vacuum(pParse);}
         1288  +cmd ::= VACUUM.                {sqlite3Vacuum(pParse,0);}
         1289  +cmd ::= VACUUM nm(X).          {sqlite3Vacuum(pParse,&X);}
  1290   1290   %endif  SQLITE_OMIT_ATTACH
  1291   1291   %endif  SQLITE_OMIT_VACUUM
  1292   1292   
  1293   1293   ///////////////////////////// The PRAGMA command /////////////////////////////
  1294   1294   //
  1295   1295   %ifndef SQLITE_OMIT_PRAGMA
  1296   1296   cmd ::= PRAGMA nm(X) dbnm(Z).                {sqlite3Pragma(pParse,&X,&Z,0,0);}

Changes to src/pcache1.c.

   627    627   **
   628    628   ** The PCache mutex must be held when this function is called.
   629    629   */
   630    630   static void pcache1TruncateUnsafe(
   631    631     PCache1 *pCache,             /* The cache to truncate */
   632    632     unsigned int iLimit          /* Drop pages with this pgno or larger */
   633    633   ){
   634         -  TESTONLY( unsigned int nPage = 0; )  /* To assert pCache->nPage is correct */
   635         -  unsigned int h;
          634  +  TESTONLY( int nPage = 0; )  /* To assert pCache->nPage is correct */
          635  +  unsigned int h, iStop;
   636    636     assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
   637         -  for(h=0; h<pCache->nHash; h++){
   638         -    PgHdr1 **pp = &pCache->apHash[h]; 
          637  +  assert( pCache->iMaxKey >= iLimit );
          638  +  assert( pCache->nHash > 0 );
          639  +  if( pCache->iMaxKey - iLimit < pCache->nHash ){
          640  +    /* If we are just shaving the last few pages off the end of the
          641  +    ** cache, then there is no point in scanning the entire hash table.
          642  +    ** Only scan those hash slots that might contain pages that need to
          643  +    ** be removed. */
          644  +    h = iLimit % pCache->nHash;
          645  +    iStop = pCache->iMaxKey % pCache->nHash;
          646  +    TESTONLY( nPage = -10; )  /* Disable the pCache->nPage validity check */
          647  +  }else{
          648  +    /* This is the general case where many pages are being removed.
          649  +    ** It is necessary to scan the entire hash table */
          650  +    h = pCache->nHash/2;
          651  +    iStop = h - 1;
          652  +  }
          653  +  for(;;){
          654  +    PgHdr1 **pp;
   639    655       PgHdr1 *pPage;
          656  +    assert( h<pCache->nHash );
          657  +    pp = &pCache->apHash[h]; 
   640    658       while( (pPage = *pp)!=0 ){
   641    659         if( pPage->iKey>=iLimit ){
   642    660           pCache->nPage--;
   643    661           *pp = pPage->pNext;
   644    662           if( !pPage->isPinned ) pcache1PinPage(pPage);
   645    663           pcache1FreePage(pPage);
   646    664         }else{
   647    665           pp = &pPage->pNext;
   648         -        TESTONLY( nPage++; )
          666  +        TESTONLY( if( nPage>=0 ) nPage++; )
   649    667         }
   650    668       }
          669  +    if( h==iStop ) break;
          670  +    h = (h+1) % pCache->nHash;
   651    671     }
   652         -  assert( pCache->nPage==nPage );
          672  +  assert( nPage<0 || pCache->nPage==(unsigned)nPage );
   653    673   }
   654    674   
   655    675   /******************************************************************************/
   656    676   /******** sqlite3_pcache Methods **********************************************/
   657    677   
   658    678   /*
   659    679   ** Implementation of the sqlite3_pcache.xInit method.
................................................................................
  1122   1142   ** Destroy a cache allocated using pcache1Create().
  1123   1143   */
  1124   1144   static void pcache1Destroy(sqlite3_pcache *p){
  1125   1145     PCache1 *pCache = (PCache1 *)p;
  1126   1146     PGroup *pGroup = pCache->pGroup;
  1127   1147     assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
  1128   1148     pcache1EnterMutex(pGroup);
  1129         -  pcache1TruncateUnsafe(pCache, 0);
         1149  +  if( pCache->nPage ) pcache1TruncateUnsafe(pCache, 0);
  1130   1150     assert( pGroup->nMaxPage >= pCache->nMax );
  1131   1151     pGroup->nMaxPage -= pCache->nMax;
  1132   1152     assert( pGroup->nMinPage >= pCache->nMin );
  1133   1153     pGroup->nMinPage -= pCache->nMin;
  1134   1154     pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  1135   1155     pcache1EnforceMaxPage(pCache);
  1136   1156     pcache1LeaveMutex(pGroup);

Changes to src/pragma.c.

   334    334     if( minusFlag ){
   335    335       zRight = sqlite3MPrintf(db, "-%T", pValue);
   336    336     }else{
   337    337       zRight = sqlite3NameFromToken(db, pValue);
   338    338     }
   339    339   
   340    340     assert( pId2 );
   341         -  zDb = pId2->n>0 ? pDb->zName : 0;
          341  +  zDb = pId2->n>0 ? pDb->zDbSName : 0;
   342    342     if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
   343    343       goto pragma_out;
   344    344     }
   345    345   
   346    346     /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
   347    347     ** connection.  If it returns SQLITE_OK, then assume that the VFS
   348    348     ** handled the pragma and generate a no-op prepared statement.
................................................................................
  1187   1187     case PragTyp_DATABASE_LIST: {
  1188   1188       static const char *azCol[] = { "seq", "name", "file" };
  1189   1189       int i;
  1190   1190       pParse->nMem = 3;
  1191   1191       setAllColumnNames(v, 3, azCol); assert( 3==ArraySize(azCol) );
  1192   1192       for(i=0; i<db->nDb; i++){
  1193   1193         if( db->aDb[i].pBt==0 ) continue;
  1194         -      assert( db->aDb[i].zName!=0 );
         1194  +      assert( db->aDb[i].zDbSName!=0 );
  1195   1195         sqlite3VdbeMultiLoad(v, 1, "iss",
  1196   1196            i,
  1197         -         db->aDb[i].zName,
         1197  +         db->aDb[i].zDbSName,
  1198   1198            sqlite3BtreeGetFilename(db->aDb[i].pBt));
  1199   1199         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  1200   1200       }
  1201   1201     }
  1202   1202     break;
  1203   1203   
  1204   1204     case PragTyp_COLLATION_LIST: {
................................................................................
  1479   1479         pParse->nMem = MAX( pParse->nMem, 8+mxIdx );
  1480   1480   
  1481   1481         /* Do the b-tree integrity checks */
  1482   1482         sqlite3VdbeAddOp4(v, OP_IntegrityCk, 2, cnt, 1, (char*)aRoot,P4_INTARRAY);
  1483   1483         sqlite3VdbeChangeP5(v, (u8)i);
  1484   1484         addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
  1485   1485         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  1486         -         sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
         1486  +         sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zDbSName),
  1487   1487            P4_DYNAMIC);
  1488   1488         sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
  1489   1489         sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
  1490   1490         sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
  1491   1491         sqlite3VdbeJumpHere(v, addr);
  1492   1492   
  1493   1493         /* Make sure all the indices are constructed correctly.
................................................................................
  1918   1918       int i;
  1919   1919       setAllColumnNames(v, 2, azCol); assert( 2==ArraySize(azCol) );
  1920   1920       pParse->nMem = 2;
  1921   1921       for(i=0; i<db->nDb; i++){
  1922   1922         Btree *pBt;
  1923   1923         const char *zState = "unknown";
  1924   1924         int j;
  1925         -      if( db->aDb[i].zName==0 ) continue;
         1925  +      if( db->aDb[i].zDbSName==0 ) continue;
  1926   1926         pBt = db->aDb[i].pBt;
  1927   1927         if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
  1928   1928           zState = "closed";
  1929         -      }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0, 
         1929  +      }else if( sqlite3_file_control(db, i ? db->aDb[i].zDbSName : 0, 
  1930   1930                                        SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
  1931   1931            zState = azLockName[j];
  1932   1932         }
  1933         -      sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zName, zState);
         1933  +      sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zDbSName, zState);
  1934   1934         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
  1935   1935       }
  1936   1936       break;
  1937   1937     }
  1938   1938   #endif
  1939   1939   
  1940   1940   #ifdef SQLITE_HAS_CODEC

Changes to src/prepare.c.

    72     72     }else if( sqlite3_strnicmp(argv[2],"create ",7)==0 ){
    73     73       /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
    74     74       ** But because db->init.busy is set to 1, no VDBE code is generated
    75     75       ** or executed.  All the parser does is build the internal data
    76     76       ** structures that describe the table, index, or view.
    77     77       */
    78     78       int rc;
           79  +    u8 saved_iDb = db->init.iDb;
    79     80       sqlite3_stmt *pStmt;
    80     81       TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */
    81     82   
    82     83       assert( db->init.busy );
    83     84       db->init.iDb = iDb;
    84     85       db->init.newTnum = sqlite3Atoi(argv[1]);
    85     86       db->init.orphanTrigger = 0;
    86     87       TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
    87     88       rc = db->errCode;
    88     89       assert( (rc&0xFF)==(rcp&0xFF) );
    89         -    db->init.iDb = 0;
           90  +    db->init.iDb = saved_iDb;
           91  +    assert( saved_iDb==0 || (db->flags & SQLITE_Vacuum)!=0 );
    90     92       if( SQLITE_OK!=rc ){
    91     93         if( db->init.orphanTrigger ){
    92     94           assert( iDb==1 );
    93     95         }else{
    94     96           pData->rc = rc;
    95     97           if( rc==SQLITE_NOMEM ){
    96     98             sqlite3OomFault(db);
................................................................................
   106    108       /* If the SQL column is blank it means this is an index that
   107    109       ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
   108    110       ** constraint for a CREATE TABLE.  The index should have already
   109    111       ** been created when we processed the CREATE TABLE.  All we have
   110    112       ** to do here is record the root page number for that index.
   111    113       */
   112    114       Index *pIndex;
   113         -    pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
          115  +    pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zDbSName);
   114    116       if( pIndex==0 ){
   115    117         /* This can occur if there exists an index on a TEMP table which
   116    118         ** has the same name as another index on a permanent index.  Since
   117    119         ** the permanent table is hidden by the TEMP table, we can also
   118    120         ** safely ignore the index on the permanent table.
   119    121         */
   120    122         /* Do Nothing */;
................................................................................
   285    287     /* Read the schema information out of the schema tables
   286    288     */
   287    289     assert( db->init.busy );
   288    290     {
   289    291       char *zSql;
   290    292       zSql = sqlite3MPrintf(db, 
   291    293           "SELECT name, rootpage, sql FROM \"%w\".%s ORDER BY rowid",
   292         -        db->aDb[iDb].zName, zMasterName);
          294  +        db->aDb[iDb].zDbSName, zMasterName);
   293    295   #ifndef SQLITE_OMIT_AUTHORIZATION
   294    296       {
   295    297         sqlite3_xauth xAuth;
   296    298         xAuth = db->xAuth;
   297    299         db->xAuth = 0;
   298    300   #endif
   299    301         rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
................................................................................
   560    562     */
   561    563     for(i=0; i<db->nDb; i++) {
   562    564       Btree *pBt = db->aDb[i].pBt;
   563    565       if( pBt ){
   564    566         assert( sqlite3BtreeHoldsMutex(pBt) );
   565    567         rc = sqlite3BtreeSchemaLocked(pBt);
   566    568         if( rc ){
   567         -        const char *zDb = db->aDb[i].zName;
          569  +        const char *zDb = db->aDb[i].zDbSName;
   568    570           sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb);
   569    571           testcase( db->flags & SQLITE_ReadUncommitted );
   570    572           goto end_prepare;
   571    573         }
   572    574       }
   573    575     }
   574    576   

Changes to src/resolve.c.

   217    217         /* Silently ignore database qualifiers inside CHECK constraints and
   218    218         ** partial indices.  Do not raise errors because that might break
   219    219         ** legacy and because it does not hurt anything to just ignore the
   220    220         ** database name. */
   221    221         zDb = 0;
   222    222       }else{
   223    223         for(i=0; i<db->nDb; i++){
   224         -        assert( db->aDb[i].zName );
   225         -        if( sqlite3StrICmp(db->aDb[i].zName,zDb)==0 ){
          224  +        assert( db->aDb[i].zDbSName );
          225  +        if( sqlite3StrICmp(db->aDb[i].zDbSName,zDb)==0 ){
   226    226             pSchema = db->aDb[i].pSchema;
   227    227             break;
   228    228           }
   229    229         }
   230    230       }
   231    231     }
   232    232   

Changes to src/select.c.

  1454   1454             zOrigCol = pTab->aCol[iCol].zName;
  1455   1455             zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
  1456   1456             estWidth = pTab->aCol[iCol].szEst;
  1457   1457           }
  1458   1458           zOrigTab = pTab->zName;
  1459   1459           if( pNC->pParse ){
  1460   1460             int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
  1461         -          zOrigDb = pNC->pParse->db->aDb[iDb].zName;
         1461  +          zOrigDb = pNC->pParse->db->aDb[iDb].zDbSName;
  1462   1462           }
  1463   1463   #else
  1464   1464           if( iCol<0 ){
  1465   1465             zType = "INTEGER";
  1466   1466           }else{
  1467   1467             zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
  1468   1468             estWidth = pTab->aCol[iCol].szEst;
................................................................................
  4410   4410             if( db->mallocFailed ) break;
  4411   4411             if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
  4412   4412               pSub = 0;
  4413   4413               if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
  4414   4414                 continue;
  4415   4415               }
  4416   4416               iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  4417         -            zSchemaName = iDb>=0 ? db->aDb[iDb].zName : "*";
         4417  +            zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : "*";
  4418   4418             }
  4419   4419             for(j=0; j<pTab->nCol; j++){
  4420   4420               char *zName = pTab->aCol[j].zName;
  4421   4421               char *zColname;  /* The computed column name */
  4422   4422               char *zToFree;   /* Malloced string that needs to be freed */
  4423   4423               Token sColname;  /* Computed column name as a token */
  4424   4424   

Changes to src/shell.c.

   520    520         zLine[n] = 0;
   521    521         break;
   522    522       }
   523    523     }
   524    524   #if defined(_WIN32) || defined(WIN32)
   525    525     /* For interactive input on Windows systems, translate the
   526    526     ** multi-byte characterset characters into UTF-8. */
   527         -  if( stdin_is_interactive ){
          527  +  if( stdin_is_interactive && in==stdin ){
   528    528       char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
   529    529       if( zTrans ){
   530    530         int nTrans = strlen30(zTrans)+1;
   531    531         if( nTrans>nLine ){
   532    532           zLine = realloc(zLine, nTrans);
   533    533           if( zLine==0 ){
   534    534             sqlite3_free(zTrans);
................................................................................
  4901   4901     int startline = 0;        /* Line number for start of current input */
  4902   4902   
  4903   4903     while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
  4904   4904       fflush(p->out);
  4905   4905       zLine = one_input_line(in, zLine, nSql>0);
  4906   4906       if( zLine==0 ){
  4907   4907         /* End of input */
  4908         -      if( stdin_is_interactive ) printf("\n");
         4908  +      if( in==0 && stdin_is_interactive ) printf("\n");
  4909   4909         break;
  4910   4910       }
  4911   4911       if( seenInterrupt ){
  4912   4912         if( in!=0 ) break;
  4913   4913         seenInterrupt = 0;
  4914   4914       }
  4915   4915       lineno++;

Changes to src/sqlite.h.in.

  1966   1966   ** C-API or the SQL function.
  1967   1967   ** The second parameter is a pointer to an integer into which
  1968   1968   ** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface
  1969   1969   ** is disabled or enabled following this call.  The second parameter may
  1970   1970   ** be a NULL pointer, in which case the new setting is not reported back.
  1971   1971   ** </dd>
  1972   1972   **
         1973  +** <dt>SQLITE_DBCONFIG_MAINDBNAME</dt>
         1974  +** <dd> ^This option is used to change the name of the "main" database
         1975  +** schema.  ^The sole argument is a pointer to a constant UTF8 string
         1976  +** which will become the new schema name in place of "main".  ^SQLite
         1977  +** does not make a copy of the new main schema name string, so the application
         1978  +** must ensure that the argument passed into this DBCONFIG option is unchanged
         1979  +** until after the database connection closes.
         1980  +** </dd>
         1981  +**
  1973   1982   ** </dl>
  1974   1983   */
         1984  +#define SQLITE_DBCONFIG_MAINDBNAME            1000 /* const char* */
  1975   1985   #define SQLITE_DBCONFIG_LOOKASIDE             1001 /* void* int int */
  1976   1986   #define SQLITE_DBCONFIG_ENABLE_FKEY           1002 /* int int* */
  1977   1987   #define SQLITE_DBCONFIG_ENABLE_TRIGGER        1003 /* int int* */
  1978   1988   #define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */
  1979   1989   #define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */
  1980   1990   
  1981   1991   

Changes to src/sqliteInt.h.

  1093   1093   ** Each database file to be accessed by the system is an instance
  1094   1094   ** of the following structure.  There are normally two of these structures
  1095   1095   ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
  1096   1096   ** aDb[1] is the database file used to hold temporary tables.  Additional
  1097   1097   ** databases may be attached.
  1098   1098   */
  1099   1099   struct Db {
  1100         -  char *zName;         /* Name of this database */
         1100  +  char *zDbSName;      /* Name of this database. (schema name, not filename) */
  1101   1101     Btree *pBt;          /* The B*Tree structure for this database file */
  1102   1102     u8 safety_level;     /* How aggressive at syncing data to disk */
  1103   1103     u8 bSyncSet;         /* True if "PRAGMA synchronous=N" has been run */
  1104   1104     Schema *pSchema;     /* Pointer to database schema (possibly shared) */
  1105   1105   };
  1106   1106   
  1107   1107   /*
................................................................................
  3697   3697   #define LOCATE_VIEW    0x01
  3698   3698   #define LOCATE_NOERR   0x02
  3699   3699   Table *sqlite3LocateTable(Parse*,u32 flags,const char*, const char*);
  3700   3700   Table *sqlite3LocateTableItem(Parse*,u32 flags,struct SrcList_item *);
  3701   3701   Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
  3702   3702   void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
  3703   3703   void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
  3704         -void sqlite3Vacuum(Parse*);
  3705         -int sqlite3RunVacuum(char**, sqlite3*);
         3704  +void sqlite3Vacuum(Parse*,Token*);
         3705  +int sqlite3RunVacuum(char**, sqlite3*, int);
  3706   3706   char *sqlite3NameFromToken(sqlite3*, Token*);
  3707   3707   int sqlite3ExprCompare(Expr*, Expr*, int);
  3708   3708   int sqlite3ExprListCompare(ExprList*, ExprList*, int);
  3709   3709   int sqlite3ExprImpliesExpr(Expr*, Expr*, int);
  3710   3710   void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
  3711   3711   void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
  3712   3712   int sqlite3ExprCoveredByIndex(Expr*, int iCur, Index *pIdx);

Changes to src/test1.c.

  7381   7381       return TCL_ERROR;
  7382   7382     }
  7383   7383     if( Tcl_GetIntFromObj(interp, objv[3], &v) ) return TCL_ERROR;
  7384   7384     sqlite3_db_config(db, aSetting[i].eVal, v, &v);
  7385   7385     Tcl_SetObjResult(interp, Tcl_NewIntObj(v));
  7386   7386     return TCL_OK;
  7387   7387   }
         7388  +
         7389  +/*
         7390  +** Change the name of the main database schema from "main" to "icecube".
         7391  +*/
         7392  +static int SQLITE_TCLAPI test_dbconfig_maindbname_icecube(
         7393  +  void * clientData,
         7394  +  Tcl_Interp *interp,
         7395  +  int objc,
         7396  +  Tcl_Obj *CONST objv[]
         7397  +){
         7398  +  int rc;
         7399  +  sqlite3 *db;
         7400  +  extern int getDbPointer(Tcl_Interp*, const char*, sqlite3**);
         7401  +  if( objc!=2 ){
         7402  +    Tcl_WrongNumArgs(interp, 1, objv, "DB");
         7403  +    return TCL_ERROR;
         7404  +  }else{
         7405  +    if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
         7406  +    rc = sqlite3_db_config(db, SQLITE_DBCONFIG_MAINDBNAME, "icecube");
         7407  +    Tcl_SetObjResult(interp, Tcl_NewIntObj(rc));
         7408  +    return TCL_OK;
         7409  +  }
         7410  +}
  7388   7411   
  7389   7412   /*
  7390   7413   ** Register commands with the TCL interpreter.
  7391   7414   */
  7392   7415   int Sqlitetest1_Init(Tcl_Interp *interp){
  7393   7416     extern int sqlite3_search_count;
  7394   7417     extern int sqlite3_found_count;
................................................................................
  7516   7539        { "sqlite3_thread_cleanup",        test_thread_cleanup,     0},
  7517   7540        { "sqlite3_pager_refcounts",       test_pager_refcounts,    0},
  7518   7541   
  7519   7542        { "sqlite3_load_extension",        test_load_extension,     0},
  7520   7543        { "sqlite3_enable_load_extension", test_enable_load,        0},
  7521   7544        { "sqlite3_extended_result_codes", test_extended_result_codes, 0},
  7522   7545        { "sqlite3_limit",                 test_limit,                 0},
         7546  +     { "dbconfig_maindbname_icecube",   test_dbconfig_maindbname_icecube },
  7523   7547   
  7524   7548        { "save_prng_state",               save_prng_state,    0 },
  7525   7549        { "restore_prng_state",            restore_prng_state, 0 },
  7526   7550        { "reset_prng_state",              reset_prng_state,   0 },
  7527   7551        { "database_never_corrupt",        database_never_corrupt, 0},
  7528   7552        { "database_may_be_corrupt",       database_may_be_corrupt, 0},
  7529   7553        { "optimization_control",          optimization_control,0},

Changes to src/test_fs.c.

   495    495     char *zPrefix;
   496    496     int nPrefix;
   497    497     const char *zDir;
   498    498     int nDir;
   499    499     char aWild[2] = { '\0', '\0' };
   500    500   
   501    501   #if SQLITE_OS_WIN
   502         -  zRoot = sqlite3_mprintf("%s%c", getenv("SystemDrive"), '/');
          502  +  const char *zDrive = windirent_getenv("fstreeDrive");
          503  +  if( zDrive==0 ){
          504  +    zDrive = windirent_getenv("SystemDrive");
          505  +  }
          506  +  zRoot = sqlite3_mprintf("%s%c", zDrive, '/');
   503    507     nRoot = sqlite3Strlen30(zRoot);
   504         -  zPrefix = sqlite3_mprintf("%s", getenv("SystemDrive"));
          508  +  zPrefix = sqlite3_mprintf("%s", zDrive);
   505    509     nPrefix = sqlite3Strlen30(zPrefix);
   506    510   #else
   507    511     zRoot = "/";
   508    512     nRoot = 1;
   509    513     zPrefix = "";
   510    514     nPrefix = 0;
   511    515   #endif

Changes to src/test_windirent.c.

    12     12   ** This file contains code to implement most of the opendir() family of
    13     13   ** POSIX functions on Win32 using the MSVCRT.
    14     14   */
    15     15   
    16     16   #if defined(_WIN32) && defined(_MSC_VER)
    17     17   
    18     18   #include "test_windirent.h"
           19  +
           20  +/*
           21  +** Implementation of the POSIX getenv() function using the Win32 API.
           22  +** This function is not thread-safe.
           23  +*/
           24  +const char *windirent_getenv(
           25  +  const char *name
           26  +){
           27  +  static char value[32768]; /* Maximum length, per MSDN */
           28  +  DWORD dwSize = sizeof(value) / sizeof(char); /* Size in chars */
           29  +  DWORD dwRet; /* Value returned by GetEnvironmentVariableA() */
           30  +
           31  +  memset(value, 0, sizeof(value));
           32  +  dwRet = GetEnvironmentVariableA(name, value, dwSize);
           33  +  if( dwRet==0 || dwRet>dwSize ){
           34  +    /*
           35  +    ** The function call to GetEnvironmentVariableA() failed -OR-
           36  +    ** the buffer is not large enough.  Either way, return NULL.
           37  +    */
           38  +    return 0;
           39  +  }else{
           40  +    /*
           41  +    ** The function call to GetEnvironmentVariableA() succeeded
           42  +    ** -AND- the buffer contains the entire value.
           43  +    */
           44  +    return value;
           45  +  }
           46  +}
    19     47   
    20     48   /*
    21     49   ** Implementation of the POSIX opendir() function using the MSVCRT.
    22     50   */
    23     51   LPDIR opendir(
    24     52     const char *dirname
    25     53   ){
................................................................................
    28     56     SIZE_T namesize = sizeof(data.name) / sizeof(data.name[0]);
    29     57   
    30     58     if( dirp==NULL ) return NULL;
    31     59     memset(dirp, 0, sizeof(DIR));
    32     60   
    33     61     /* TODO: Remove this if Unix-style root paths are not used. */
    34     62     if( sqlite3_stricmp(dirname, "/")==0 ){
    35         -    dirname = getenv("SystemDrive");
           63  +    dirname = windirent_getenv("SystemDrive");
    36     64     }
    37     65   
    38     66     _snprintf(data.name, namesize, "%s\\*", dirname);
    39     67     dirp->d_handle = _findfirst(data.name, &data);
    40     68   
    41     69     if( dirp->d_handle==BAD_INTPTR_T ){
    42     70       closedir(dirp);

Changes to src/test_windirent.h.

    88     88   
    89     89   struct DIR {
    90     90     intptr_t d_handle; /* Value returned by "_findfirst". */
    91     91     DIRENT d_first;    /* DIRENT constructed based on "_findfirst". */
    92     92     DIRENT d_next;     /* DIRENT constructed based on "_findnext". */
    93     93   };
    94     94   
           95  +/*
           96  +** Provide the function prototype for the POSIX compatiable getenv()
           97  +** function.  This function is not thread-safe.
           98  +*/
           99  +
          100  +extern const char *windirent_getenv(const char *name);
          101  +
    95    102   /*
    96    103   ** Finally, we can provide the function prototypes for the opendir(),
    97    104   ** readdir(), readdir_r(), and closedir() POSIX functions.
    98    105   */
    99    106   
   100    107   extern LPDIR opendir(const char *dirname);
   101    108   extern LPDIRENT readdir(LPDIR dirp);
   102    109   extern INT readdir_r(LPDIR dirp, LPDIRENT entry, LPDIRENT *result);
   103    110   extern INT closedir(LPDIR dirp);
   104    111   
   105    112   #endif /* defined(WIN32) && defined(_MSC_VER) */

Changes to src/tokenize.c.

   498    498       return SQLITE_NOMEM_BKPT;
   499    499     }
   500    500     assert( pParse->pNewTable==0 );
   501    501     assert( pParse->pNewTrigger==0 );
   502    502     assert( pParse->nVar==0 );
   503    503     assert( pParse->nzVar==0 );
   504    504     assert( pParse->azVar==0 );
   505         -  while( zSql[i]!=0 ){
          505  +  while( 1 ){
   506    506       assert( i>=0 );
          507  +    if( zSql[i]!=0 ){
   507    508       pParse->sLastToken.z = &zSql[i];
   508         -    pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
          509  +      pParse->sLastToken.n = sqlite3GetToken((u8*)&zSql[i],&tokenType);
   509    510       i += pParse->sLastToken.n;
   510    511       if( i>mxSqlLen ){
   511    512         pParse->rc = SQLITE_TOOBIG;
   512    513         break;
          514  +      }
          515  +    }else{
          516  +      /* Upon reaching the end of input, call the parser two more times
          517  +      ** with tokens TK_SEMI and 0, in that order. */
          518  +      if( lastTokenParsed==TK_SEMI ){
          519  +        tokenType = 0;
          520  +      }else if( lastTokenParsed==0 ){
          521  +        break;
          522  +      }else{
          523  +        tokenType = TK_SEMI;
          524  +      }
   513    525       }
   514    526       if( tokenType>=TK_SPACE ){
   515    527         assert( tokenType==TK_SPACE || tokenType==TK_ILLEGAL );
   516    528         if( db->u1.isInterrupted ){
   517    529           pParse->rc = SQLITE_INTERRUPT;
   518    530           break;
   519    531         }
................................................................................
   526    538         sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
   527    539         lastTokenParsed = tokenType;
   528    540         if( pParse->rc!=SQLITE_OK || db->mallocFailed ) break;
   529    541       }
   530    542     }
   531    543     assert( nErr==0 );
   532    544     pParse->zTail = &zSql[i];
   533         -  if( pParse->rc==SQLITE_OK && db->mallocFailed==0 ){
   534         -    assert( zSql[i]==0 );
   535         -    if( lastTokenParsed!=TK_SEMI ){
   536         -      sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
   537         -    }
   538         -    if( pParse->rc==SQLITE_OK && db->mallocFailed==0 ){
   539         -      sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
   540         -    }
   541         -  }
   542    545   #ifdef YYTRACKMAXSTACKDEPTH
   543    546     sqlite3_mutex_enter(sqlite3MallocMutex());
   544    547     sqlite3StatusHighwater(SQLITE_STATUS_PARSER_STACK,
   545    548         sqlite3ParserStackPeak(pEngine)
   546    549     );
   547    550     sqlite3_mutex_leave(sqlite3MallocMutex());
   548    551   #endif /* YYDEBUG */

Changes to src/treeview.c.

   116    116       }
   117    117       sqlite3TreeViewPop(pView);
   118    118     }
   119    119   }
   120    120   
   121    121   
   122    122   /*
   123         -** Generate a human-readable description of a the Select object.
          123  +** Generate a human-readable description of a Select object.
   124    124   */
   125    125   void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){
   126    126     int n = 0;
   127    127     int cnt = 0;
   128    128     pView = sqlite3TreeViewPush(pView, moreToFollow);
   129    129     if( p->pWith ){
   130    130       sqlite3TreeViewWith(pView, p->pWith, 1);

Changes to src/trigger.c.

   210    210       goto trigger_cleanup;
   211    211     }
   212    212     iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   213    213   
   214    214   #ifndef SQLITE_OMIT_AUTHORIZATION
   215    215     {
   216    216       int code = SQLITE_CREATE_TRIGGER;
   217         -    const char *zDb = db->aDb[iTabDb].zName;
   218         -    const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
          217  +    const char *zDb = db->aDb[iTabDb].zDbSName;
          218  +    const char *zDbTrig = isTemp ? db->aDb[1].zDbSName : zDb;
   219    219       if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
   220    220       if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
   221    221         goto trigger_cleanup;
   222    222       }
   223    223       if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
   224    224         goto trigger_cleanup;
   225    225       }
................................................................................
   305    305       /* Make an entry in the sqlite_master table */
   306    306       v = sqlite3GetVdbe(pParse);
   307    307       if( v==0 ) goto triggerfinish_cleanup;
   308    308       sqlite3BeginWriteOperation(pParse, 0, iDb);
   309    309       z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
   310    310       sqlite3NestedParse(pParse,
   311    311          "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
   312         -       db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
          312  +       db->aDb[iDb].zDbSName, SCHEMA_TABLE(iDb), zName,
   313    313          pTrig->table, z);
   314    314       sqlite3DbFree(db, z);
   315    315       sqlite3ChangeCookie(pParse, iDb);
   316    316       sqlite3VdbeAddParseSchemaOp(v, iDb,
   317    317           sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
   318    318     }
   319    319   
................................................................................
   494    494   
   495    495     assert( pName->nSrc==1 );
   496    496     zDb = pName->a[0].zDatabase;
   497    497     zName = pName->a[0].zName;
   498    498     assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
   499    499     for(i=OMIT_TEMPDB; i<db->nDb; i++){
   500    500       int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
   501         -    if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
          501  +    if( zDb && sqlite3StrICmp(db->aDb[j].zDbSName, zDb) ) continue;
   502    502       assert( sqlite3SchemaMutexHeld(db, j, 0) );
   503    503       pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName);
   504    504       if( pTrigger ) break;
   505    505     }
   506    506     if( !pTrigger ){
   507    507       if( !noErr ){
   508    508         sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
................................................................................
   540    540     assert( iDb>=0 && iDb<db->nDb );
   541    541     pTable = tableOfTrigger(pTrigger);
   542    542     assert( pTable );
   543    543     assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
   544    544   #ifndef SQLITE_OMIT_AUTHORIZATION
   545    545     {
   546    546       int code = SQLITE_DROP_TRIGGER;
   547         -    const char *zDb = db->aDb[iDb].zName;
          547  +    const char *zDb = db->aDb[iDb].zDbSName;
   548    548       const char *zTab = SCHEMA_TABLE(iDb);
   549    549       if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
   550    550       if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
   551    551         sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
   552    552         return;
   553    553       }
   554    554     }
................................................................................
   556    556   
   557    557     /* Generate code to destroy the database record of the trigger.
   558    558     */
   559    559     assert( pTable!=0 );
   560    560     if( (v = sqlite3GetVdbe(pParse))!=0 ){
   561    561       sqlite3NestedParse(pParse,
   562    562          "DELETE FROM %Q.%s WHERE name=%Q AND type='trigger'",
   563         -       db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pTrigger->zName
          563  +       db->aDb[iDb].zDbSName, SCHEMA_TABLE(iDb), pTrigger->zName
   564    564       );
   565    565       sqlite3ChangeCookie(pParse, iDb);
   566    566       sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
   567    567     }
   568    568   }
   569    569   
   570    570   /*
................................................................................
   659    659   
   660    660     pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
   661    661     if( pSrc ){
   662    662       assert( pSrc->nSrc>0 );
   663    663       pSrc->a[pSrc->nSrc-1].zName = sqlite3DbStrDup(db, pStep->zTarget);
   664    664       iDb = sqlite3SchemaToIndex(db, pStep->pTrig->pSchema);
   665    665       if( iDb==0 || iDb>=2 ){
          666  +      const char *zDb;
   666    667         assert( iDb<db->nDb );
   667         -      pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
          668  +      zDb = db->aDb[iDb].zDbSName;
          669  +      pSrc->a[pSrc->nSrc-1].zDatabase =  sqlite3DbStrDup(db, zDb);
   668    670       }
   669    671     }
   670    672     return pSrc;
   671    673   }
   672    674   
   673    675   /*
   674    676   ** Generate VDBE code for the statements inside the body of a single 

Changes to src/update.c.

   245    245         }
   246    246       }
   247    247   #ifndef SQLITE_OMIT_AUTHORIZATION
   248    248       {
   249    249         int rc;
   250    250         rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
   251    251                               j<0 ? "ROWID" : pTab->aCol[j].zName,
   252         -                            db->aDb[iDb].zName);
          252  +                            db->aDb[iDb].zDbSName);
   253    253         if( rc==SQLITE_DENY ){
   254    254           goto update_cleanup;
   255    255         }else if( rc==SQLITE_IGNORE ){
   256    256           aXRef[j] = -1;
   257    257         }
   258    258       }
   259    259   #endif

Changes to src/vacuum.c.

    14     14   ** Most of the code in this file may be omitted by defining the
    15     15   ** SQLITE_OMIT_VACUUM macro.
    16     16   */
    17     17   #include "sqliteInt.h"
    18     18   #include "vdbeInt.h"
    19     19   
    20     20   #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
    21         -/*
    22         -** Finalize a prepared statement.  If there was an error, store the
    23         -** text of the error message in *pzErrMsg.  Return the result code.
    24         -*/
    25         -static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
    26         -  int rc;
    27         -  rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
    28         -  if( rc ){
    29         -    sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
    30         -  }
    31         -  return rc;
    32         -}
    33     21   
    34     22   /*
    35         -** Execute zSql on database db. Return an error code.
           23  +** Execute zSql on database db.
           24  +**
           25  +** If zSql returns rows, then each row will have exactly one
           26  +** column.  (This will only happen if zSql begins with "SELECT".)
           27  +** Take each row of result and call execSql() again recursively.
           28  +**
           29  +** The execSqlF() routine does the same thing, except it accepts
           30  +** a format string as its third argument
    36     31   */
    37     32   static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
    38     33     sqlite3_stmt *pStmt;
    39         -  VVA_ONLY( int rc; )
    40         -  if( !zSql ){
    41         -    return SQLITE_NOMEM_BKPT;
    42         -  }
    43         -  if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
    44         -    sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
    45         -    return sqlite3_errcode(db);
    46         -  }
    47         -  VVA_ONLY( rc = ) sqlite3_step(pStmt);
    48         -  assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
    49         -  return vacuumFinalize(db, pStmt, pzErrMsg);
    50         -}
    51         -
    52         -/*
    53         -** Execute zSql on database db. The statement returns exactly
    54         -** one column. Execute this as SQL on the same database.
    55         -*/
    56         -static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
    57         -  sqlite3_stmt *pStmt;
    58     34     int rc;
    59     35   
    60         -  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
           36  +  /* printf("SQL: [%s]\n", zSql); fflush(stdout); */
           37  +  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
    61     38     if( rc!=SQLITE_OK ) return rc;
    62         -
    63         -  while( SQLITE_ROW==sqlite3_step(pStmt) ){
    64         -    rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
    65         -    if( rc!=SQLITE_OK ){
    66         -      vacuumFinalize(db, pStmt, pzErrMsg);
           39  +  while( SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
           40  +    const char *zSubSql = (const char*)sqlite3_column_text(pStmt,0);
           41  +    assert( sqlite3_strnicmp(zSql,"SELECT",6)==0 );
           42  +    if( zSubSql ){
           43  +      assert( zSubSql[0]!='S' );
           44  +      rc = execSql(db, pzErrMsg, zSubSql);
           45  +      if( rc!=SQLITE_OK ) break;
           46  +    }
           47  +  }
           48  +  assert( rc!=SQLITE_ROW );
           49  +  if( rc==SQLITE_DONE ) rc = SQLITE_OK;
           50  +  if( rc ){
           51  +    sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
           52  +  }
           53  +  (void)sqlite3_finalize(pStmt);
    67     54         return rc;
    68     55       }
    69         -  }
    70         -
    71         -  return vacuumFinalize(db, pStmt, pzErrMsg);
           56  +static int execSqlF(sqlite3 *db, char **pzErrMsg, const char *zSql, ...){
           57  +  char *z;
           58  +  va_list ap;
           59  +  int rc;
           60  +  va_start(ap, zSql);
           61  +  z = sqlite3VMPrintf(db, zSql, ap);
           62  +  va_end(ap);
           63  +  if( z==0 ) return SQLITE_NOMEM;
           64  +  rc = execSql(db, pzErrMsg, z);
           65  +  sqlite3DbFree(db, z);
           66  +  return rc;
    72     67   }
    73     68   
    74     69   /*
    75     70   ** The VACUUM command is used to clean up the database,
    76     71   ** collapse free space, etc.  It is modelled after the VACUUM command
    77     72   ** in PostgreSQL.  The VACUUM command works as follows:
    78     73   **
................................................................................
    97     92   ** the copy of step (3) were replaced by deleting the original database
    98     93   ** and renaming the transient database as the original.  But that will
    99     94   ** not work if other processes are attached to the original database.
   100     95   ** And a power loss in between deleting the original and renaming the
   101     96   ** transient would cause the database file to appear to be deleted
   102     97   ** following reboot.
   103     98   */
   104         -void sqlite3Vacuum(Parse *pParse){
           99  +void sqlite3Vacuum(Parse *pParse, Token *pNm){
   105    100     Vdbe *v = sqlite3GetVdbe(pParse);
   106         -  if( v ){
   107         -    sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
   108         -    sqlite3VdbeUsesBtree(v, 0);
          101  +  int iDb = pNm ? sqlite3TwoPartName(pParse, pNm, pNm, &pNm) : 0;
          102  +  if( v && (iDb>=2 || iDb==0) ){
          103  +    sqlite3VdbeAddOp1(v, OP_Vacuum, iDb);
          104  +    sqlite3VdbeUsesBtree(v, iDb);
   109    105     }
   110    106     return;
   111    107   }
   112    108   
   113    109   /*
   114    110   ** This routine implements the OP_Vacuum opcode of the VDBE.
   115    111   */
   116         -int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
          112  +int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db, int iDb){
   117    113     int rc = SQLITE_OK;     /* Return code from service routines */
   118    114     Btree *pMain;           /* The database being vacuumed */
   119    115     Btree *pTemp;           /* The temporary database we vacuum into */
   120         -  char *zSql = 0;         /* SQL statements */
   121    116     int saved_flags;        /* Saved value of the db->flags */
   122    117     int saved_nChange;      /* Saved value of db->nChange */
   123    118     int saved_nTotalChange; /* Saved value of db->nTotalChange */
   124    119     u8 saved_mTrace;        /* Saved trace settings */
   125    120     Db *pDb = 0;            /* Database to detach at end of vacuum */
   126    121     int isMemDb;            /* True if vacuuming a :memory: database */
   127    122     int nRes;               /* Bytes of reserved space at the end of each page */
   128    123     int nDb;                /* Number of attached databases */
          124  +  const char *zDbMain;    /* Schema name of database to vacuum */
   129    125   
   130    126     if( !db->autoCommit ){
   131    127       sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
   132    128       return SQLITE_ERROR;
   133    129     }
   134    130     if( db->nVdbeActive>1 ){
   135    131       sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
................................................................................
   139    135     /* Save the current value of the database flags so that it can be 
   140    136     ** restored before returning. Then set the writable-schema flag, and
   141    137     ** disable CHECK and foreign key constraints.  */
   142    138     saved_flags = db->flags;
   143    139     saved_nChange = db->nChange;
   144    140     saved_nTotalChange = db->nTotalChange;
   145    141     saved_mTrace = db->mTrace;
   146         -  db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
   147         -  db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
          142  +  db->flags |= (SQLITE_WriteSchema | SQLITE_IgnoreChecks
          143  +                 | SQLITE_PreferBuiltin | SQLITE_Vacuum);
          144  +  db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder | SQLITE_CountRows);
   148    145     db->mTrace = 0;
   149    146   
   150         -  pMain = db->aDb[0].pBt;
          147  +  zDbMain = db->aDb[iDb].zDbSName;
          148  +  pMain = db->aDb[iDb].pBt;
   151    149     isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
   152    150   
   153    151     /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
   154    152     ** can be set to 'off' for this file, as it is not recovered if a crash
   155    153     ** occurs anyway. The integrity of the database is maintained by a
   156    154     ** (possibly synchronous) transaction opened on the main database before
   157    155     ** sqlite3BtreeCopyFile() is called.
................................................................................
   161    159     ** that actually made the VACUUM run slower.  Very little journalling
   162    160     ** actually occurs when doing a vacuum since the vacuum_db is initially
   163    161     ** empty.  Only the journal header is written.  Apparently it takes more
   164    162     ** time to parse and run the PRAGMA to turn journalling off than it does
   165    163     ** to write the journal header file.
   166    164     */
   167    165     nDb = db->nDb;
   168         -  if( sqlite3TempInMemory(db) ){
   169         -    zSql = "ATTACH ':memory:' AS vacuum_db;";
   170         -  }else{
   171         -    zSql = "ATTACH '' AS vacuum_db;";
   172         -  }
   173         -  rc = execSql(db, pzErrMsg, zSql);
   174         -  if( db->nDb>nDb ){
   175         -    pDb = &db->aDb[db->nDb-1];
   176         -    assert( strcmp(pDb->zName,"vacuum_db")==0 );
   177         -  }
          166  +  rc = execSql(db, pzErrMsg, "ATTACH''AS vacuum_db");
   178    167     if( rc!=SQLITE_OK ) goto end_of_vacuum;
   179         -  pTemp = db->aDb[db->nDb-1].pBt;
          168  +  assert( (db->nDb-1)==nDb );
          169  +  pDb = &db->aDb[nDb];
          170  +  assert( strcmp(pDb->zDbSName,"vacuum_db")==0 );
          171  +  pTemp = pDb->pBt;
   180    172   
   181    173     /* The call to execSql() to attach the temp database has left the file
   182    174     ** locked (as there was more than one active statement when the transaction
   183    175     ** to read the schema was concluded. Unlock it here so that this doesn't
   184    176     ** cause problems for the call to BtreeSetPageSize() below.  */
   185    177     sqlite3BtreeCommit(pTemp);
   186    178   
................................................................................
   193    185       int nKey;
   194    186       char *zKey;
   195    187       sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
   196    188       if( nKey ) db->nextPagesize = 0;
   197    189     }
   198    190   #endif
   199    191   
   200         -  sqlite3BtreeSetCacheSize(pTemp, db->aDb[0].pSchema->cache_size);
          192  +  sqlite3BtreeSetCacheSize(pTemp, db->aDb[iDb].pSchema->cache_size);
   201    193     sqlite3BtreeSetSpillSize(pTemp, sqlite3BtreeSetSpillSize(pMain,0));
   202         -  rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
   203         -  if( rc!=SQLITE_OK ) goto end_of_vacuum;
          194  +  sqlite3BtreeSetPagerFlags(pTemp, PAGER_SYNCHRONOUS_OFF);
   204    195   
   205    196     /* Begin a transaction and take an exclusive lock on the main database
   206    197     ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
   207    198     ** to ensure that we do not try to change the page-size on a WAL database.
   208    199     */
   209         -  rc = execSql(db, pzErrMsg, "BEGIN;");
          200  +  rc = execSql(db, pzErrMsg, "BEGIN");
   210    201     if( rc!=SQLITE_OK ) goto end_of_vacuum;
   211    202     rc = sqlite3BtreeBeginTrans(pMain, 2);
   212    203     if( rc!=SQLITE_OK ) goto end_of_vacuum;
   213    204   
   214    205     /* Do not attempt to change the page size for a WAL database */
   215    206     if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
   216    207                                                  ==PAGER_JOURNALMODE_WAL ){
................................................................................
   229    220     sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
   230    221                                              sqlite3BtreeGetAutoVacuum(pMain));
   231    222   #endif
   232    223   
   233    224     /* Query the schema of the main database. Create a mirror schema
   234    225     ** in the temporary database.
   235    226     */
   236         -  rc = execExecSql(db, pzErrMsg,
   237         -      "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
   238         -      "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
   239         -      "   AND coalesce(rootpage,1)>0"
          227  +  db->init.iDb = nDb; /* force new CREATE statements into vacuum_db */
          228  +  rc = execSqlF(db, pzErrMsg,
          229  +      "SELECT sql FROM \"%w\".sqlite_master"
          230  +      " WHERE type='table'AND name<>'sqlite_sequence'"
          231  +      " AND coalesce(rootpage,1)>0",
          232  +      zDbMain
          233  +  );
          234  +  if( rc!=SQLITE_OK ) goto end_of_vacuum;
          235  +  rc = execSqlF(db, pzErrMsg,
          236  +      "SELECT sql FROM \"%w\".sqlite_master"
          237  +      " WHERE type='index' AND length(sql)>10",
          238  +      zDbMain
   240    239     );
   241    240     if( rc!=SQLITE_OK ) goto end_of_vacuum;
   242         -  rc = execExecSql(db, pzErrMsg,
   243         -      "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
   244         -      "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
   245         -  if( rc!=SQLITE_OK ) goto end_of_vacuum;
   246         -  rc = execExecSql(db, pzErrMsg,
   247         -      "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
   248         -      "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
   249         -  if( rc!=SQLITE_OK ) goto end_of_vacuum;
          241  +  db->init.iDb = 0;
   250    242   
   251    243     /* Loop through the tables in the main database. For each, do
   252    244     ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
   253    245     ** the contents to the temporary database.
   254    246     */
   255         -  assert( (db->flags & SQLITE_Vacuum)==0 );
   256         -  db->flags |= SQLITE_Vacuum;
   257         -  rc = execExecSql(db, pzErrMsg,
          247  +  rc = execSqlF(db, pzErrMsg,
   258    248         "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
   259         -      "|| ' SELECT * FROM main.' || quote(name) || ';'"
   260         -      "FROM main.sqlite_master "
   261         -      "WHERE type = 'table' AND name!='sqlite_sequence' "
   262         -      "  AND coalesce(rootpage,1)>0"
          249  +      "||' SELECT*FROM\"%w\".'||quote(name)"
          250  +      "FROM vacuum_db.sqlite_master "
          251  +      "WHERE type='table'AND coalesce(rootpage,1)>0",
          252  +      zDbMain
   263    253     );
   264    254     assert( (db->flags & SQLITE_Vacuum)!=0 );
   265    255     db->flags &= ~SQLITE_Vacuum;
   266    256     if( rc!=SQLITE_OK ) goto end_of_vacuum;
   267         -
   268         -  /* Copy over the sequence table
   269         -  */
   270         -  rc = execExecSql(db, pzErrMsg,
   271         -      "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
   272         -      "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
   273         -  );
   274         -  if( rc!=SQLITE_OK ) goto end_of_vacuum;
   275         -  rc = execExecSql(db, pzErrMsg,
   276         -      "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
   277         -      "|| ' SELECT * FROM main.' || quote(name) || ';' "
   278         -      "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
   279         -  );
   280         -  if( rc!=SQLITE_OK ) goto end_of_vacuum;
   281         -
   282    257   
   283    258     /* Copy the triggers, views, and virtual tables from the main database
   284    259     ** over to the temporary database.  None of these objects has any
   285    260     ** associated storage, so all we have to do is copy their entries
   286    261     ** from the SQLITE_MASTER table.
   287    262     */
   288         -  rc = execSql(db, pzErrMsg,
          263  +  rc = execSqlF(db, pzErrMsg,
   289    264         "INSERT INTO vacuum_db.sqlite_master "
   290         -      "  SELECT type, name, tbl_name, rootpage, sql"
   291         -      "    FROM main.sqlite_master"
   292         -      "   WHERE type='view' OR type='trigger'"
   293         -      "      OR (type='table' AND rootpage=0)"
          265  +      " SELECT*FROM \"%w\".sqlite_master"
          266  +      " WHERE type IN('view','trigger')"
          267  +      " OR(type='table'AND rootpage=0)",
          268  +      zDbMain
   294    269     );
   295    270     if( rc ) goto end_of_vacuum;
   296    271   
   297    272     /* At this point, there is a write transaction open on both the 
   298    273     ** vacuum database and the main database. Assuming no error occurs,
   299    274     ** both transactions are closed by this block - the main database
   300    275     ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
................................................................................
   340    315     }
   341    316   
   342    317     assert( rc==SQLITE_OK );
   343    318     rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
   344    319   
   345    320   end_of_vacuum:
   346    321     /* Restore the original value of db->flags */
          322  +  db->init.iDb = 0;
   347    323     db->flags = saved_flags;
   348    324     db->nChange = saved_nChange;
   349    325     db->nTotalChange = saved_nTotalChange;
   350    326     db->mTrace = saved_mTrace;
   351    327     sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
   352    328   
   353    329     /* Currently there is an SQL level transaction open on the vacuum

Changes to src/vdbe.c.

  1878   1878     UPDATE_MAX_BLOBSIZE(pIn1);
  1879   1879     if( rc ) goto abort_due_to_error;
  1880   1880     break;
  1881   1881   }
  1882   1882   #endif /* SQLITE_OMIT_CAST */
  1883   1883   
  1884   1884   /* Opcode: Lt P1 P2 P3 P4 P5
  1885         -** Synopsis: if r[P1]<r[P3] goto P2
         1885  +** Synopsis: IF r[P3]<r[P1]
  1886   1886   **
  1887   1887   ** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
  1888   1888   ** jump to address P2.  
  1889   1889   **
  1890   1890   ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
  1891   1891   ** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL 
  1892   1892   ** bit is clear then fall through if either operand is NULL.
................................................................................
  1913   1913   ** store a boolean result (either 0, or 1, or NULL) in register P2.
  1914   1914   **
  1915   1915   ** If the SQLITE_NULLEQ bit is set in P5, then NULL values are considered
  1916   1916   ** equal to one another, provided that they do not have their MEM_Cleared
  1917   1917   ** bit set.
  1918   1918   */
  1919   1919   /* Opcode: Ne P1 P2 P3 P4 P5
  1920         -** Synopsis: if r[P1]!=r[P3] goto P2
         1920  +** Synopsis: IF r[P3]!=r[P1]
  1921   1921   **
  1922   1922   ** This works just like the Lt opcode except that the jump is taken if
  1923   1923   ** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
  1924   1924   ** additional information.
  1925   1925   **
  1926   1926   ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
  1927   1927   ** true or false and is never NULL.  If both operands are NULL then the result
  1928   1928   ** of comparison is false.  If either operand is NULL then the result is true.
  1929   1929   ** If neither operand is NULL the result is the same as it would be if
  1930   1930   ** the SQLITE_NULLEQ flag were omitted from P5.
  1931   1931   */
  1932   1932   /* Opcode: Eq P1 P2 P3 P4 P5
  1933         -** Synopsis: if r[P1]==r[P3] goto P2
         1933  +** Synopsis: IF r[P3]==r[P1]
  1934   1934   **
  1935   1935   ** This works just like the Lt opcode except that the jump is taken if
  1936   1936   ** the operands in registers P1 and P3 are equal.
  1937   1937   ** See the Lt opcode for additional information.
  1938   1938   **
  1939   1939   ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
  1940   1940   ** true or false and is never NULL.  If both operands are NULL then the result
  1941   1941   ** of comparison is true.  If either operand is NULL then the result is false.
  1942   1942   ** If neither operand is NULL the result is the same as it would be if
  1943   1943   ** the SQLITE_NULLEQ flag were omitted from P5.
  1944   1944   */
  1945   1945   /* Opcode: Le P1 P2 P3 P4 P5
  1946         -** Synopsis: if r[P1]<=r[P3] goto P2
         1946  +** Synopsis: IF r[P3]<=r[P1]
  1947   1947   **
  1948   1948   ** This works just like the Lt opcode except that the jump is taken if
  1949   1949   ** the content of register P3 is less than or equal to the content of
  1950   1950   ** register P1.  See the Lt opcode for additional information.
  1951   1951   */
  1952   1952   /* Opcode: Gt P1 P2 P3 P4 P5
  1953         -** Synopsis: if r[P1]>r[P3] goto P2
         1953  +** Synopsis: IF r[P3]>r[P1]
  1954   1954   **
  1955   1955   ** This works just like the Lt opcode except that the jump is taken if
  1956   1956   ** the content of register P3 is greater than the content of
  1957   1957   ** register P1.  See the Lt opcode for additional information.
  1958   1958   */
  1959   1959   /* Opcode: Ge P1 P2 P3 P4 P5
  1960         -** Synopsis: if r[P1]>=r[P3] goto P2
         1960  +** Synopsis: IF r[P3]>=r[P1]
  1961   1961   **
  1962   1962   ** This works just like the Lt opcode except that the jump is taken if
  1963   1963   ** the content of register P3 is greater than or equal to the content of
  1964   1964   ** register P1.  See the Lt opcode for additional information.
  1965   1965   */
  1966   1966   case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
  1967   1967   case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
................................................................................
  4343   4343       assert( pOp->opcode==OP_InsertInt );
  4344   4344       x.nKey = pOp->p3;
  4345   4345     }
  4346   4346   
  4347   4347     if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
  4348   4348       assert( pC->isTable );
  4349   4349       assert( pC->iDb>=0 );
  4350         -    zDb = db->aDb[pC->iDb].zName;
         4350  +    zDb = db->aDb[pC->iDb].zDbSName;
  4351   4351       pTab = pOp->p4.pTab;
  4352   4352       assert( HasRowid(pTab) );
  4353   4353       op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
  4354   4354     }else{
  4355   4355       pTab = 0; /* Not needed.  Silence a comiler warning. */
  4356   4356       zDb = 0;  /* Not needed.  Silence a compiler warning. */
  4357   4357     }
................................................................................
  4460   4460     ** the name of the db to pass as to it. Also set local pTab to a copy
  4461   4461     ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was
  4462   4462     ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set 
  4463   4463     ** VdbeCursor.movetoTarget to the current rowid.  */
  4464   4464     if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
  4465   4465       assert( pC->iDb>=0 );
  4466   4466       assert( pOp->p4.pTab!=0 );
  4467         -    zDb = db->aDb[pC->iDb].zName;
         4467  +    zDb = db->aDb[pC->iDb].zDbSName;
  4468   4468       pTab = pOp->p4.pTab;
  4469   4469       if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){
  4470   4470         pC->movetoTarget = sqlite3BtreeIntegerKey(pC->uc.pCursor);
  4471   4471       }
  4472   4472     }else{
  4473   4473       zDb = 0;   /* Not needed.  Silence a compiler warning. */
  4474   4474       pTab = 0;  /* Not needed.  Silence a compiler warning. */
................................................................................
  5430   5430     /* Used to be a conditional */ {
  5431   5431       zMaster = SCHEMA_TABLE(iDb);
  5432   5432       initData.db = db;
  5433   5433       initData.iDb = pOp->p1;
  5434   5434       initData.pzErrMsg = &p->zErrMsg;
  5435   5435       zSql = sqlite3MPrintf(db,
  5436   5436          "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
  5437         -       db->aDb[iDb].zName, zMaster, pOp->p4.z);
         5437  +       db->aDb[iDb].zDbSName, zMaster, pOp->p4.z);
  5438   5438       if( zSql==0 ){
  5439   5439         rc = SQLITE_NOMEM_BKPT;
  5440   5440       }else{
  5441   5441         assert( db->init.busy==0 );
  5442   5442         db->init.busy = 1;
  5443   5443         initData.rc = SQLITE_OK;
  5444   5444         assert( !db->mallocFailed );
................................................................................
  6259   6259     sqlite3VdbeChangeEncoding(pOut, encoding);
  6260   6260     if( rc ) goto abort_due_to_error;
  6261   6261     break;
  6262   6262   };
  6263   6263   #endif /* SQLITE_OMIT_PRAGMA */
  6264   6264   
  6265   6265   #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  6266         -/* Opcode: Vacuum * * * * *
         6266  +/* Opcode: Vacuum P1 * * * *
  6267   6267   **
  6268         -** Vacuum the entire database.  This opcode will cause other virtual
  6269         -** machines to be created and run.  It may not be called from within
  6270         -** a transaction.
         6268  +** Vacuum the entire database P1.  P1 is 0 for "main", and 2 or more
         6269  +** for an attached database.  The "temp" database may not be vacuumed.
  6271   6270   */
  6272   6271   case OP_Vacuum: {
  6273   6272     assert( p->readOnly==0 );
  6274         -  rc = sqlite3RunVacuum(&p->zErrMsg, db);
         6273  +  rc = sqlite3RunVacuum(&p->zErrMsg, db, pOp->p1);
  6275   6274     if( rc ) goto abort_due_to_error;
  6276   6275     break;
  6277   6276   }
  6278   6277   #endif
  6279   6278   
  6280   6279   #if !defined(SQLITE_OMIT_AUTOVACUUM)
  6281   6280   /* Opcode: IncrVacuum P1 P2 * * *
................................................................................
  6814   6813     }
  6815   6814   #ifdef SQLITE_USE_FCNTL_TRACE
  6816   6815     zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
  6817   6816     if( zTrace ){
  6818   6817       int i;
  6819   6818       for(i=0; i<db->nDb; i++){
  6820   6819         if( DbMaskTest(p->btreeMask, i)==0 ) continue;
  6821         -      sqlite3_file_control(db, db->aDb[i].zName, SQLITE_FCNTL_TRACE, zTrace);
         6820  +      sqlite3_file_control(db, db->aDb[i].zDbSName, SQLITE_FCNTL_TRACE, zTrace);
  6822   6821       }
  6823   6822     }
  6824   6823   #endif /* SQLITE_USE_FCNTL_TRACE */
  6825   6824   #ifdef SQLITE_DEBUG
  6826   6825     if( (db->flags & SQLITE_SqlTrace)!=0
  6827   6826      && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  6828   6827     ){

Changes to src/vdbeapi.c.

   511    511       Btree *pBt = db->aDb[i].pBt;
   512    512       if( pBt ){
   513    513         int nEntry;
   514    514         sqlite3BtreeEnter(pBt);
   515    515         nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
   516    516         sqlite3BtreeLeave(pBt);
   517    517         if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
   518         -        rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
          518  +        rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zDbSName, nEntry);
   519    519         }
   520    520       }
   521    521     }
   522    522   #endif
   523    523     return rc;
   524    524   }
   525    525   

Changes to src/vdbeaux.c.

  1090   1090     char *zTemp,       /* Write result here */
  1091   1091     int nTemp          /* Space available in zTemp[] */
  1092   1092   ){
  1093   1093     const char *zOpName;
  1094   1094     const char *zSynopsis;
  1095   1095     int nOpName;
  1096   1096     int ii, jj;
         1097  +  char zAlt[50];
  1097   1098     zOpName = sqlite3OpcodeName(pOp->opcode);
  1098   1099     nOpName = sqlite3Strlen30(zOpName);
  1099   1100     if( zOpName[nOpName+1] ){
  1100   1101       int seenCom = 0;
  1101   1102       char c;
  1102   1103       zSynopsis = zOpName += nOpName + 1;
         1104  +    if( strncmp(zSynopsis,"IF ",3)==0 ){
         1105  +      if( pOp->p5 & SQLITE_STOREP2 ){
         1106  +        sqlite3_snprintf(sizeof(zAlt), zAlt, "r[P2] = (%s)", zSynopsis+3);
         1107  +      }else{
         1108  +        sqlite3_snprintf(sizeof(zAlt), zAlt, "if %s goto P2", zSynopsis+3);
         1109  +      }
         1110  +      zSynopsis = zAlt;
         1111  +    }
  1103   1112       for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
  1104   1113         if( c=='P' ){
  1105   1114           c = zSynopsis[++ii];
  1106   1115           if( c=='4' ){
  1107   1116             sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
  1108   1117           }else if( c=='X' ){
  1109   1118             sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);

Changes to src/vdbeblob.c.

   172    172           pParse->zErrMsg = 0;
   173    173         }
   174    174         rc = SQLITE_ERROR;
   175    175         sqlite3BtreeLeaveAll(db);
   176    176         goto blob_open_out;
   177    177       }
   178    178       pBlob->pTab = pTab;
   179         -    pBlob->zDb = db->aDb[sqlite3SchemaToIndex(db, pTab->pSchema)].zName;
          179  +    pBlob->zDb = db->aDb[sqlite3SchemaToIndex(db, pTab->pSchema)].zDbSName;
   180    180   
   181    181       /* Now search pTab for the exact column. */
   182    182       for(iCol=0; iCol<pTab->nCol; iCol++) {
   183    183         if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
   184    184           break;
   185    185         }
   186    186       }

Changes to src/vtab.c.

   340    340     /* Creating a virtual table invokes the authorization callback twice.
   341    341     ** The first invocation, to obtain permission to INSERT a row into the
   342    342     ** sqlite_master table, has already been made by sqlite3StartTable().
   343    343     ** The second call, to obtain permission to create the table, is made now.
   344    344     */
   345    345     if( pTable->azModuleArg ){
   346    346       sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName, 
   347         -            pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
          347  +            pTable->azModuleArg[0], pParse->db->aDb[iDb].zDbSName);
   348    348     }
   349    349   #endif
   350    350   }
   351    351   
   352    352   /*
   353    353   ** This routine takes the module argument that has been accumulating
   354    354   ** in pParse->zArg[] and appends it to the list of arguments on the
................................................................................
   404    404       ** by sqlite3StartTable().
   405    405       */
   406    406       iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   407    407       sqlite3NestedParse(pParse,
   408    408         "UPDATE %Q.%s "
   409    409            "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
   410    410          "WHERE rowid=#%d",
   411         -      db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
          411  +      db->aDb[iDb].zDbSName, SCHEMA_TABLE(iDb),
   412    412         pTab->zName,
   413    413         pTab->zName,
   414    414         zStmt,
   415    415         pParse->regRowid
   416    416       );
   417    417       sqlite3DbFree(db, zStmt);
   418    418       v = sqlite3GetVdbe(pParse);
................................................................................
   514    514       sqlite3DbFree(db, zModuleName);
   515    515       return SQLITE_NOMEM_BKPT;
   516    516     }
   517    517     pVTable->db = db;
   518    518     pVTable->pMod = pMod;
   519    519   
   520    520     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   521         -  pTab->azModuleArg[1] = db->aDb[iDb].zName;
          521  +  pTab->azModuleArg[1] = db->aDb[iDb].zDbSName;
   522    522   
   523    523     /* Invoke the virtual table constructor */
   524    524     assert( &db->pVtabCtx );
   525    525     assert( xConstruct );
   526    526     sCtx.pTab = pTab;
   527    527     sCtx.pVTable = pVTable;
   528    528     sCtx.pPrior = db->pVtabCtx;
................................................................................
   668    668     sqlite3VtabLock(pVTab);
   669    669   }
   670    670   
   671    671   /*
   672    672   ** This function is invoked by the vdbe to call the xCreate method
   673    673   ** of the virtual table named zTab in database iDb. 
   674    674   **
   675         -** If an error occurs, *pzErr is set to point an an English language
          675  +** If an error occurs, *pzErr is set to point to an English language
   676    676   ** description of the error and an SQLITE_XXX error code is returned.
   677    677   ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
   678    678   */
   679    679   int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
   680    680     int rc = SQLITE_OK;
   681    681     Table *pTab;
   682    682     Module *pMod;
   683    683     const char *zMod;
   684    684   
   685         -  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
          685  +  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);
   686    686     assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
   687    687   
   688    688     /* Locate the required virtual table module */
   689    689     zMod = pTab->azModuleArg[0];
   690    690     pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
   691    691   
   692    692     /* If the module has been registered and includes a Create method, 
................................................................................
   802    802   **
   803    803   ** This call is a no-op if zTab is not a virtual table.
   804    804   */
   805    805   int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
   806    806     int rc = SQLITE_OK;
   807    807     Table *pTab;
   808    808   
   809         -  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
          809  +  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);
   810    810     if( pTab!=0 && ALWAYS(pTab->pVTable!=0) ){
   811    811       VTable *p;
   812    812       int (*xDestroy)(sqlite3_vtab *);
   813    813       for(p=pTab->pVTable; p; p=p->pNext){
   814    814         assert( p->pVtab );
   815    815         if( p->pVtab->nRef>0 ){
   816    816           return SQLITE_LOCKED;

Changes to src/walker.c.

    37     37   ** and WRC_Continue to continue.
    38     38   */
    39     39   static SQLITE_NOINLINE int walkExpr(Walker *pWalker, Expr *pExpr){
    40     40     int rc;
    41     41     testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
    42     42     testcase( ExprHasProperty(pExpr, EP_Reduced) );
    43     43     rc = pWalker->xExprCallback(pWalker, pExpr);
    44         -  if( rc==WRC_Continue
    45         -              && !ExprHasProperty(pExpr,EP_TokenOnly) ){
    46         -    if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
    47         -    if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
           44  +  if( rc || ExprHasProperty(pExpr,EP_TokenOnly) ) return rc & WRC_Abort;
           45  +  if( pExpr->pLeft && walkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
           46  +  if( pExpr->pRight && walkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
    48     47       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
    49     48         if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
    50     49       }else{
    51     50         if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
    52     51       }
    53         -  }
    54         -  return rc & WRC_Abort;
           52  +  return WRC_Continue;
    55     53   }
    56     54   int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
    57     55     return pExpr ? walkExpr(pWalker,pExpr) : WRC_Continue;
    58     56   }
    59     57   
    60     58   /*
    61     59   ** Call sqlite3WalkExpr() for every expression in list p or until

Changes to src/where.c.

  3397   3397         if( MASKBIT(i) & obSat ) continue;
  3398   3398         pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
  3399   3399         if( pOBExpr->op!=TK_COLUMN ) continue;
  3400   3400         if( pOBExpr->iTable!=iCur ) continue;
  3401   3401         pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
  3402   3402                          ~ready, eqOpMask, 0);
  3403   3403         if( pTerm==0 ) continue;
         3404  +      if( pTerm->eOperator==WO_IN ){
         3405  +        /* IN terms are only valid for sorting in the ORDER BY LIMIT 
         3406  +        ** optimization, and then only if they are actually used
         3407  +        ** by the query plan */
         3408  +        assert( wctrlFlags & WHERE_ORDERBY_LIMIT );
         3409  +        for(j=0; j<pLoop->nLTerm && pTerm!=pLoop->aLTerm[j]; j++){}
         3410  +        if( j>=pLoop->nLTerm ) continue;
         3411  +      }
  3404   3412         if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){
  3405   3413           const char *z1, *z2;
  3406   3414           pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
  3407   3415           if( !pColl ) pColl = db->pDfltColl;
  3408   3416           z1 = pColl->zName;
  3409   3417           pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
  3410   3418           if( !pColl ) pColl = db->pDfltColl;

Changes to src/whereexpr.c.

   286    286   **
   287    287   ** If it is then return TRUE.  If not, return FALSE.
   288    288   */
   289    289   static int isMatchOfColumn(
   290    290     Expr *pExpr,                    /* Test this expression */
   291    291     unsigned char *peOp2            /* OUT: 0 for MATCH, or else an op2 value */
   292    292   ){
   293         -  struct Op2 {
          293  +  static const struct Op2 {
   294    294       const char *zOp;
   295    295       unsigned char eOp2;
   296    296     } aOp[] = {
   297    297       { "match",  SQLITE_INDEX_CONSTRAINT_MATCH },
   298    298       { "glob",   SQLITE_INDEX_CONSTRAINT_GLOB },
   299    299       { "like",   SQLITE_INDEX_CONSTRAINT_LIKE },
   300    300       { "regexp", SQLITE_INDEX_CONSTRAINT_REGEXP }
................................................................................
  1271   1271   
  1272   1272   /*
  1273   1273   ** These routines walk (recursively) an expression tree and generate
  1274   1274   ** a bitmask indicating which tables are used in that expression
  1275   1275   ** tree.
  1276   1276   */
  1277   1277   Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){
  1278         -  Bitmask mask = 0;
         1278  +  Bitmask mask;
  1279   1279     if( p==0 ) return 0;
  1280   1280     if( p->op==TK_COLUMN ){
  1281   1281       mask = sqlite3WhereGetMask(pMaskSet, p->iTable);
  1282   1282       return mask;
  1283   1283     }
  1284         -  mask = sqlite3WhereExprUsage(pMaskSet, p->pRight);
         1284  +  assert( !ExprHasProperty(p, EP_TokenOnly) );
         1285  +  mask = p->pRight ? sqlite3WhereExprUsage(pMaskSet, p->pRight) : 0;
  1285   1286     if( p->pLeft ) mask |= sqlite3WhereExprUsage(pMaskSet, p->pLeft);
  1286   1287     if( ExprHasProperty(p, EP_xIsSelect) ){
  1287   1288       mask |= exprSelectUsage(pMaskSet, p->x.pSelect);
  1288   1289     }else if( p->x.pList ){
  1289   1290       mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
  1290   1291     }
  1291   1292     return mask;

Changes to test/backup_malloc.test.

    79     79     if {$rc && ($errcode == "SQLITE_NOMEM" || $errcode == "SQLITE_IOERR_NOMEM")} {
    80     80       error "out of memory"
    81     81     }
    82     82   } -cleanup {
    83     83     catch { B finish }
    84     84     db2 close
    85     85   }
           86  +
           87  +reset_db
           88  +do_execsql_test 3.0 {
           89  +  PRAGMA page_size = 16384;
           90  +  BEGIN;
           91  +  CREATE TABLE t1(a, b);
           92  +  INSERT INTO t1 VALUES(1, 2);
           93  +  COMMIT;
           94  +}
           95  +
           96  +do_faultsim_test 3 -faults oom* -prep {
           97  +  catch { db close }
           98  +
           99  +  forcedelete test2.db
          100  +  sqlite3 db2 test2.db
          101  +  sqlite3 db test.db
          102  +  sqlite3_backup B db2 main db main
          103  +} -body {
          104  +
          105  +  set rc [B step 50]
          106  +  if {$rc == "SQLITE_NOMEM" || $rc == "SQLITE_IOERR_NOMEM"} {
          107  +    error "out of memory"
          108  +  }
          109  +
          110  +} -test {
          111  +  faultsim_test_result {0 {}} 
          112  +  faultsim_integrity_check
          113  +  
          114  +  # Finalize the backup.
          115  +  catch { B finish }
          116  +}
    86    117   
    87    118   finish_test

Changes to test/delete.test.

   384    384     set res [list]
   385    385     db eval { SELECT t5.rowid AS r, c, d FROM t5, t6 ORDER BY a } {
   386    386       if {$r==2} { db eval { DELETE FROM t5 WHERE rowid = 3 } }
   387    387       lappend res $r $c $d
   388    388     }
   389    389     set res
   390    390   } {1 a b 1 c d 2 a b 2 c d}
          391  +
          392  +do_execsql_test delete-10.0 {
          393  +  CREATE TABLE t1(a INT UNIQUE, b INT);
          394  +  INSERT INTO t1(a,b) VALUES('1','2');
          395  +  SELECT * FROM t1 WHERE a='1' AND b='2';
          396  +} {1 2}
          397  +
          398  +do_execsql_test delete-10.1 {
          399  +  DELETE FROM t1 WHERE a='1' AND b='2';
          400  +}
          401  +
          402  +do_execsql_test delete-10.2 {
          403  +  SELECT * FROM t1 WHERE a='1' AND b='2';
          404  +}
   391    405   
   392    406   
   393    407   finish_test

Changes to test/e_vacuum.test.

   198    198     ATTACH 'test.db2' AS aux;
   199    199     PRAGMA aux.page_size = 1024;
   200    200     CREATE TABLE aux.t3 AS SELECT * FROM t1;
   201    201     DELETE FROM t3;
   202    202   } {}
   203    203   set original_size [file size test.db2]
   204    204   
   205         -# Try everything we can think of to get the aux database vacuumed:
          205  +# Vacuuming the main database does not affect aux
   206    206   do_execsql_test e_vacuum-2.1.3 { VACUUM } {}
   207         -do_execsql_test e_vacuum-2.1.4 { VACUUM aux } {}
   208         -do_execsql_test e_vacuum-2.1.5 { VACUUM 'test.db2' } {}
   209         -
   210         -# Despite our efforts, space in the aux database has not been reclaimed:
   211    207   do_test e_vacuum-2.1.6 { expr {[file size test.db2]==$::original_size} } 1
   212    208   
   213    209   # EVIDENCE-OF: R-17495-17419 The VACUUM command may change the ROWIDs of
   214    210   # entries in any tables that do not have an explicit INTEGER PRIMARY
   215    211   # KEY.
   216    212   #
   217    213   #   Tests e_vacuum-3.1.1 - 3.1.2 demonstrate that rowids can change when

Changes to test/limit2.test.

    92     92   
    93     93     SELECT *, '|' FROM t200, t201 WHERE x=b ORDER BY y LIMIT 3;
    94     94   } {2 2 2 12345 |}
    95     95   do_execsql_test limit2-210 {
    96     96     SELECT *, '|' FROM t200 LEFT JOIN t201 ON x=b ORDER BY y LIMIT 3;
    97     97   } {1 1 {} {} | 3 3 {} {} | 4 4 {} {} |}
    98     98   
    99         -
           99  +# Bug in the ORDER BY LIMIT optimization reported on 2016-09-06.
          100  +# Ticket https://www.sqlite.org/src/info/559733b09e96
          101  +#
          102  +do_execsql_test limit2-300 {
          103  +  CREATE TABLE t300(a,b,c);
          104  +  CREATE INDEX t300x ON t300(a,b,c);
          105  +  INSERT INTO t300 VALUES(0,1,99),(0,1,0),(0,0,0);
          106  +  SELECT *,'.' FROM t300 WHERE a=0 AND (c=0 OR c=99) ORDER BY c DESC;
          107  +} {0 1 99 . 0 0 0 . 0 1 0 .}
          108  +do_execsql_test limit2-310 {
          109  +  SELECT *,'.' FROM t300 WHERE a=0 AND (c=0 OR c=99) ORDER BY c DESC LIMIT 1;
          110  +} {0 1 99 .}
   100    111   
   101    112   
   102    113   
   103    114   
   104    115   finish_test

Changes to test/misc8.test.

   103    103              (SELECT 0 AS i) AS x1,
   104    104              (SELECT 1) AS x2
   105    105            ) AS x3,
   106    106            (SELECT 6 AS j UNION ALL SELECT 7) AS x4
   107    107      WHERE i<rowid
   108    108      ORDER BY 1;
   109    109   } {0 1 6 0 1 7}
          110  +
          111  +# The SQLITE_DBCONFIG_MAINDBNAME interface
          112  +#
          113  +db close
          114  +forcedelete test.db test2.db
          115  +sqlite3 db test.db
          116  +do_execsql_test misc8-4.0 {
          117  +  CREATE TABLE t1(a,b,c);
          118  +  INSERT INTO t1 VALUES(1,2,3);
          119  +  ATTACH 'test2.db' AS aux2;
          120  +  CREATE TABLE aux2.t2(c,d,e);
          121  +  INSERT INTO t2 VALUES(4,5,6);
          122  +  SELECT * FROM t1, t2;
          123  +} {1 2 3 4 5 6}
          124  +do_execsql_test misc8-4.1 {
          125  +  PRAGMA database_list;
          126  +} {/0 main .* 2 aux2/}
          127  +dbconfig_maindbname_icecube db
          128  +do_execsql_test misc8-4.2 {
          129  +  SELECT name FROM icecube.sqlite_master;
          130  +} {t1}
          131  +do_execsql_test misc8-4.3 {
          132  +  PRAGMA database_list;
          133  +} {/0 icecube .* 2 aux2/}
          134  +
          135  +
   110    136   
   111    137   finish_test

Changes to test/shell4.test.

    14     14   #
    15     15   # 2015-03-19:  Added tests for .trace
    16     16   
    17     17   # Test plan:
    18     18   #
    19     19   #   shell4-1.*: Basic tests specific to the "stats" command.
    20     20   #   shell4-2.*: Basic tests for ".trace"
           21  +#   shell4-3.*: The ".read" command takes the shell out of interactive mode
    21     22   #
    22     23   set testdir [file dirname $argv0]
    23     24   source $testdir/tester.tcl
    24     25   set CLI [test_find_cli]
    25     26   db close
    26     27   forcedelete test.db test.db-journal test.db-wal
    27     28   sqlite3 db test.db
................................................................................
   120    121   } {0 {CREATE TABLE t1(x);
   121    122   SELECT * FROM t1;}}
   122    123   do_test shell4-2.5 {
   123    124     catchcmd ":memory:" "CREATE TABLE t1(x);\n.trace stdout\nSELECT * FROM t1;"
   124    125   } {0 {SELECT * FROM t1;}}
   125    126   }
   126    127   
          128  +do_test shell4-3.1 {
          129  +  set fd [open t1.txt wb]
          130  +  puts $fd "SELECT 'squirrel';"
          131  +  close $fd
          132  +  exec $::CLI :memory: --interactive ".read t1.txt"
          133  +} {squirrel}
          134  +do_test shell4-3.2 {
          135  +  set fd [open t1.txt wb]
          136  +  puts $fd "SELECT 'pound: \302\243';"
          137  +  close $fd
          138  +  exec $::CLI :memory: --interactive ".read t1.txt"
          139  +} {pound: £}
   127    140   
   128    141   finish_test

Changes to test/speed3.test.

   101    101     db_leave db
   102    102   # puts "1: [array get stats1]"
   103    103   # puts "2: [array get stats2]"
   104    104     puts "Incrvacuum: Read $stats1(read), wrote $stats1(write)"
   105    105     puts "Normal    : Read $stats2(read), wrote $stats2(write)"
   106    106   }
   107    107   
   108         -proc reset_db {} {
          108  +proc speed3_reset_db {} {
   109    109     db close
   110    110     sqlite3 db test.db
   111    111     db eval { 
   112    112       PRAGMA main.cache_size = 200000;
   113    113       PRAGMA main.auto_vacuum = 'incremental';
   114    114       ATTACH 'test2.db' AS 'aux'; 
   115    115       PRAGMA aux.auto_vacuum = 'none';
   116    116     }
   117    117   }
   118    118   
   119    119   forcedelete test2.db test2.db-journal
   120         -reset_db
          120  +speed3_reset_db
   121    121   
   122    122   # Set up a database in auto-vacuum mode and create a database schema.
   123    123   #
   124    124   do_test speed3-0.1 {
   125    125     execsql {
   126    126       CREATE TABLE main.t1(a INTEGER, b TEXT, c INTEGER);
   127    127     }
................................................................................
   150    150       PRAGMA aux.auto_vacuum;
   151    151     }
   152    152   } {2 0}
   153    153   
   154    154   # Delete all content in a table, one row at a time.
   155    155   #
   156    156   #io_log db
   157         -reset_db
          157  +speed3_reset_db
   158    158   speed_trial speed3-1.incrvacuum $::NROW row {DELETE FROM main.t1 WHERE 1}
   159    159   speed_trial speed3-1.normal     $::NROW row {DELETE FROM aux.t1 WHERE 1}
   160    160   io_log db
   161    161   
   162    162   # Select the "C" column (located at the far end of the overflow 
   163    163   # chain) from each table row.
   164    164   #
   165    165   #db eval {PRAGMA incremental_vacuum(500000)}
   166    166   populate_t1 db
   167         -reset_db
          167  +speed3_reset_db
   168    168   speed_trial speed3-2.incrvacuum $::NROW row {SELECT c FROM main.t1}
   169    169   speed_trial speed3-2.normal     $::NROW row {SELECT c FROM aux.t1}
   170    170   io_log db
   171    171   
   172    172   finish_test

Added test/vacuum5.test.

            1  +# 2016-08-19
            2  +#
            3  +# The author disclaims copyright to this source code.  In place of
            4  +# a legal notice, here is a blessing:
            5  +#
            6  +#    May you do good and not evil.
            7  +#    May you find forgiveness for yourself and forgive others.
            8  +#    May you share freely, never taking more than you give.
            9  +#
           10  +#***********************************************************************
           11  +# 
           12  +# This file implements a test for VACUUM on attached databases.
           13  +#
           14  +
           15  +set testdir [file dirname $argv0]
           16  +source $testdir/tester.tcl
           17  +
           18  +# If the VACUUM statement is disabled in the current build, skip all
           19  +# the tests in this file.
           20  +#
           21  +ifcapable !vacuum {
           22  +  finish_test
           23  +  return
           24  +}
           25  +
           26  +forcedelete test2.db test3.db
           27  +do_execsql_test vacuum5-1.1 {
           28  +  CREATE TABLE main.t1(a,b);
           29  +  WITH RECURSIVE c(x) AS (VALUES(1) UNION ALL SELECT x+1 FROM c WHERE x<1000)
           30  +    INSERT INTO t1(a,b) SELECT x, randomblob(1000) FROM c;
           31  +  CREATE TEMP TABLE ttemp(x,y);
           32  +  INSERT INTO ttemp SELECT * FROM t1;
           33  +  ATTACH 'test2.db' AS x2;
           34  +  ATTACH 'test3.db' AS x3;
           35  +  CREATE TABLE x2.t2(c,d);
           36  +  INSERT INTO t2 SELECT * FROM t1;
           37  +  CREATE TABLE x3.t3(e,f);
           38  +  INSERT INTO t3 SELECT * FROM t1;
           39  +  DELETE FROM t1 WHERE (rowid%3)!=0;
           40  +  DELETE FROM t2 WHERE (rowid%4)!=0;
           41  +  DELETE FROM t3 WHERE (rowid%5)!=0;
           42  +  PRAGMA main.integrity_check;
           43  +  PRAGMA x2.integrity_check;
           44  +  PRAGMA x3.integrity_check;
           45  +} {ok ok ok}
           46  +set size1 [file size test.db]
           47  +set size2 [file size test2.db]
           48  +set size3 [file size test3.db]
           49  +
           50  +do_execsql_test vacuum5-1.2.1 {
           51  +  VACUUM main;
           52  +} {}
           53  +do_test vacuum5-1.2.2 {
           54  +  expr {[file size test.db]<$size1}
           55  +} {1}
           56  +do_test vacuum5-1.2.3 {
           57  +  file size test2.db
           58  +} $size2
           59  +do_test vacuum5-1.2.4 {
           60  +  file size test3.db
           61  +} $size3
           62  +set size1 [file size test.db]
           63  +do_execsql_test vacuum-1.2.5 {
           64  +  DELETE FROM t1;
           65  +  PRAGMA main.integrity_check;
           66  +} {ok}
           67  +
           68  +do_execsql_test vacuum5-1.3.1 {
           69  +  VACUUM x2;
           70  +} {}
           71  +do_test vacuum5-1.3.2 {
           72  +  file size test.db
           73  +} $size1
           74  +do_test vacuum5-1.3.3 {
           75  +  expr {[file size test2.db]<$size2}
           76  +} 1
           77  +do_test vacuum5-1.3.4 {
           78  +  file size test3.db
           79  +} $size3
           80  +set size2 [file size test2.db]
           81  +do_execsql_test vacuum-1.3.5 {
           82  +  DELETE FROM t2;
           83  +  PRAGMA x2.integrity_check;
           84  +} {ok}
           85  +
           86  +do_execsql_test vacuum5-1.4.1 {
           87  +  VACUUM x3;
           88  +} {}
           89  +do_test vacuum5-1.3.2 {
           90  +  file size test.db
           91  +} $size1
           92  +do_test vacuum5-1.3.3 {
           93  +  file size test2.db
           94  +} $size2
           95  +do_test vacuum5-1.3.4 {
           96  +  expr {[file size test3.db]<$size3}
           97  +} 1
           98  +
           99  +# VACUUM is a no-op on the TEMP table
          100  +#
          101  +set sizeTemp [db one {PRAGMA temp.page_count}]
          102  +do_execsql_test vacuum5-1.4.1 {
          103  +  VACUUM temp;
          104  +} {}
          105  +do_execsql_test vacuum5-1.4.2 {
          106  +  PRAGMA temp.page_count;
          107  +} $sizeTemp
          108  +
          109  +do_catchsql_test vacuum5-2.0 {
          110  +  VACUUM olaf;
          111  +} {1 {unknown database olaf}}

Changes to test/vtabF.test.

    17     17   source $testdir/tester.tcl
    18     18   
    19     19   ifcapable !vtab||!schema_pragmas { finish_test ; return }
    20     20   
    21     21   # Register the echo module
    22     22   register_echo_module [sqlite3_connection_pointer db]
    23     23   
    24         -do_test vtabE-1.1 {
           24  +do_test vtabF-1.1 {
    25     25     execsql {
    26     26       CREATE TABLE t1(a, b);
    27     27       CREATE INDEX i1 ON t1(a);
    28     28       CREATE INDEX i2 ON t1(b);
    29     29       INSERT INTO t1 VALUES(10,110);
    30     30       INSERT INTO t1 VALUES(11,111);
    31     31       INSERT INTO t1 SELECT a+2, b+2 FROM t1;
................................................................................
    33     33       INSERT INTO t1 SELECT null, b+8 FROM t1;
    34     34       INSERT INTO t1 SELECT null, b+16 FROM t1;
    35     35       ANALYZE;
    36     36       CREATE VIRTUAL TABLE tv1 USING echo(t1);
    37     37       SELECT b FROM t1 WHERE a IS NOT NULL;
    38     38     }
    39     39   } {110 111 112 113}
    40         -do_test vtabE-1.2 {
           40  +do_test vtabF-1.2 {
    41     41     execsql {SELECT b FROM tv1 WHERE a IS NOT NULL}
    42     42   } {110 111 112 113}
    43     43   
    44     44   
    45     45   finish_test

Changes to test/vtabH.test.

   104    104         set ::gfunc
   105    105       } $cnt
   106    106     }
   107    107   }
   108    108   
   109    109   #-------------------------------------------------------------------------
   110    110   #
   111         -if {1} {
          111  +if {$tcl_platform(platform)=="windows"} {
          112  +  set drive [string range [pwd] 0 1]
          113  +  set ::env(fstreeDrive) $drive
          114  +}
          115  +if {$tcl_platform(platform)!="windows" || \
          116  +    [regexp -nocase -- {^[A-Z]:} $drive]} {
   112    117     reset_db
   113    118     register_fs_module db
   114    119     do_execsql_test 3.0 {
   115    120       SELECT name FROM fsdir WHERE dir = '.' AND name = 'test.db';
   116    121       SELECT name FROM fsdir WHERE dir = '.' AND name = '.'
   117    122     } {test.db .}
   118    123   
   119    124     proc list_root_files {} {
   120    125       if {$::tcl_platform(platform) eq "windows"} {
   121    126         set res [list]
   122         -      foreach name [glob -directory $::env(SystemDrive)/ -- *] {
          127  +      foreach name [glob -directory $::env(fstreeDrive)/ -- *] {
   123    128           if {[string index [file tail $name] 0] eq "."} continue
   124    129           lappend res $name
   125    130         }
   126    131         return $res
   127    132       } else {
   128    133         return [string map {/ {}} [glob /*]]
   129    134       }
................................................................................
   137    142           lappend res $name
   138    143         }
   139    144         return $res
   140    145       } else {
   141    146         return [glob -nocomplain $pattern]
   142    147       }
   143    148     }
          149  +
          150  +  # Read the first 5 entries from the root directory.  Except, ignore
          151  +  # files that contain the "$" character in their names as these are
          152  +  # special files on some Windows platforms.
          153  +  #
          154  +  set res [list]
          155  +  set root_files [list_root_files]
          156  +  set num_root_files [llength $root_files]
          157  +  set lim_root_files [expr {$num_root_files > 5 ? 5 : $num_root_files}]
          158  +  foreach p [lrange $root_files 0 [expr {$lim_root_files - 1}]] {
          159  +    if {$::tcl_platform(platform) eq "windows"} {
          160  +      if {[regexp {\$} $p]} {incr lim_root_files -1} else {lappend res $p}
          161  +    } else {
          162  +      lappend res "/$p"
          163  +    }
          164  +  }
          165  +  do_execsql_test 3.1 [subst {
          166  +    SELECT path FROM fstree WHERE path NOT GLOB '*\$*' LIMIT $lim_root_files;
          167  +  }] $res
   144    168   
   145    169     # Read all entries in the current directory.
   146    170     #
   147    171     proc contents {pattern} {
   148    172       set res [list]
   149    173       foreach f [list_files $pattern] {
   150    174         lappend res $f

Changes to tool/fuzzershell.c.

   308    308     }else{
   309    309       sqlite3_result_text(context, x.z, (int)x.nUsed, sqlite3_free);
   310    310     }
   311    311   }
   312    312   /* End of the eval() implementation
   313    313   ******************************************************************************/
   314    314   
          315  +/******************************************************************************
          316  +** The generate_series(START,END,STEP) eponymous table-valued function.
          317  +**
          318  +** This code is copy/pasted from ext/misc/series.c in the SQLite source tree.
          319  +*/
          320  +/* series_cursor is a subclass of sqlite3_vtab_cursor which will
          321  +** serve as the underlying representation of a cursor that scans
          322  +** over rows of the result
          323  +*/
          324  +typedef struct series_cursor series_cursor;
          325  +struct series_cursor {
          326  +  sqlite3_vtab_cursor base;  /* Base class - must be first */
          327  +  int isDesc;                /* True to count down rather than up */
          328  +  sqlite3_int64 iRowid;      /* The rowid */
          329  +  sqlite3_int64 iValue;      /* Current value ("value") */
          330  +  sqlite3_int64 mnValue;     /* Mimimum value ("start") */
          331  +  sqlite3_int64 mxValue;     /* Maximum value ("stop") */
          332  +  sqlite3_int64 iStep;       /* Increment ("step") */
          333  +};
          334  +
          335  +/*
          336  +** The seriesConnect() method is invoked to create a new
          337  +** series_vtab that describes the generate_series virtual table.
          338  +**
          339  +** Think of this routine as the constructor for series_vtab objects.
          340  +**
          341  +** All this routine needs to do is:
          342  +**
          343  +**    (1) Allocate the series_vtab object and initialize all fields.
          344  +**
          345  +**    (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
          346  +**        result set of queries against generate_series will look like.
          347  +*/
          348  +static int seriesConnect(
          349  +  sqlite3 *db,
          350  +  void *pAux,
          351  +  int argc, const char *const*argv,
          352  +  sqlite3_vtab **ppVtab,
          353  +  char **pzErr
          354  +){
          355  +  sqlite3_vtab *pNew;
          356  +  int rc;
          357  +
          358  +/* Column numbers */
          359  +#define SERIES_COLUMN_VALUE 0
          360  +#define SERIES_COLUMN_START 1
          361  +#define SERIES_COLUMN_STOP  2
          362  +#define SERIES_COLUMN_STEP  3
          363  +
          364  +  rc = sqlite3_declare_vtab(db,
          365  +     "CREATE TABLE x(value,start hidden,stop hidden,step hidden)");
          366  +  if( rc==SQLITE_OK ){
          367  +    pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
          368  +    if( pNew==0 ) return SQLITE_NOMEM;
          369  +    memset(pNew, 0, sizeof(*pNew));
          370  +  }
          371  +  return rc;
          372  +}
          373  +
          374  +/*
          375  +** This method is the destructor for series_cursor objects.
          376  +*/
          377  +static int seriesDisconnect(sqlite3_vtab *pVtab){
          378  +  sqlite3_free(pVtab);
          379  +  return SQLITE_OK;
          380  +}
          381  +
          382  +/*
          383  +** Constructor for a new series_cursor object.
          384  +*/
          385  +static int seriesOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
          386  +  series_cursor *pCur;
          387  +  pCur = sqlite3_malloc( sizeof(*pCur) );
          388  +  if( pCur==0 ) return SQLITE_NOMEM;
          389  +  memset(pCur, 0, sizeof(*pCur));
          390  +  *ppCursor = &pCur->base;
          391  +  return SQLITE_OK;
          392  +}
          393  +
          394  +/*
          395  +** Destructor for a series_cursor.
          396  +*/
          397  +static int seriesClose(sqlite3_vtab_cursor *cur){
          398  +  sqlite3_free(cur);
          399  +  return SQLITE_OK;
          400  +}
          401  +
          402  +
          403  +/*
          404  +** Advance a series_cursor to its next row of output.
          405  +*/
          406  +static int seriesNext(sqlite3_vtab_cursor *cur){
          407  +  series_cursor *pCur = (series_cursor*)cur;
          408  +  if( pCur->isDesc ){
          409  +    pCur->iValue -= pCur->iStep;
          410  +  }else{
          411  +    pCur->iValue += pCur->iStep;
          412  +  }
          413  +  pCur->iRowid++;
          414  +  return SQLITE_OK;
          415  +}
          416  +
          417  +/*
          418  +** Return values of columns for the row at which the series_cursor
          419  +** is currently pointing.
          420  +*/
          421  +static int seriesColumn(
          422  +  sqlite3_vtab_cursor *cur,   /* The cursor */
          423  +  sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
          424  +  int i                       /* Which column to return */
          425  +){
          426  +  series_cursor *pCur = (series_cursor*)cur;
          427  +  sqlite3_int64 x = 0;
          428  +  switch( i ){
          429  +    case SERIES_COLUMN_START:  x = pCur->mnValue; break;
          430  +    case SERIES_COLUMN_STOP:   x = pCur->mxValue; break;
          431  +    case SERIES_COLUMN_STEP:   x = pCur->iStep;   break;
          432  +    default:                   x = pCur->iValue;  break;
          433  +  }
          434  +  sqlite3_result_int64(ctx, x);
          435  +  return SQLITE_OK;
          436  +}
          437  +
          438  +/*
          439  +** Return the rowid for the current row.  In this implementation, the
          440  +** rowid is the same as the output value.
          441  +*/
          442  +static int seriesRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
          443  +  series_cursor *pCur = (series_cursor*)cur;
          444  +  *pRowid = pCur->iRowid;
          445  +  return SQLITE_OK;
          446  +}
          447  +
          448  +/*
          449  +** Return TRUE if the cursor has been moved off of the last
          450  +** row of output.
          451  +*/
          452  +static int seriesEof(sqlite3_vtab_cursor *cur){
          453  +  series_cursor *pCur = (series_cursor*)cur;
          454  +  if( pCur->isDesc ){
          455  +    return pCur->iValue < pCur->mnValue;
          456  +  }else{
          457  +    return pCur->iValue > pCur->mxValue;
          458  +  }
          459  +}
          460  +
          461  +/* True to cause run-time checking of the start=, stop=, and/or step= 
          462  +** parameters.  The only reason to do this is for testing the
          463  +** constraint checking logic for virtual tables in the SQLite core.
          464  +*/
          465  +#ifndef SQLITE_SERIES_CONSTRAINT_VERIFY
          466  +# define SQLITE_SERIES_CONSTRAINT_VERIFY 0
          467  +#endif
          468  +
          469  +/*
          470  +** This method is called to "rewind" the series_cursor object back
          471  +** to the first row of output.  This method is always called at least
          472  +** once prior to any call to seriesColumn() or seriesRowid() or 
          473  +** seriesEof().
          474  +**
          475  +** The query plan selected by seriesBestIndex is passed in the idxNum
          476  +** parameter.  (idxStr is not used in this implementation.)  idxNum
          477  +** is a bitmask showing which constraints are available:
          478  +**
          479  +**    1:    start=VALUE
          480  +**    2:    stop=VALUE
          481  +**    4:    step=VALUE
          482  +**
          483  +** Also, if bit 8 is set, that means that the series should be output
          484  +** in descending order rather than in ascending order.
          485  +**
          486  +** This routine should initialize the cursor and position it so that it
          487  +** is pointing at the first row, or pointing off the end of the table
          488  +** (so that seriesEof() will return true) if the table is empty.
          489  +*/
          490  +static int seriesFilter(
          491  +  sqlite3_vtab_cursor *pVtabCursor, 
          492  +  int idxNum, const char *idxStr,
          493  +  int argc, sqlite3_value **argv
          494  +){
          495  +  series_cursor *pCur = (series_cursor *)pVtabCursor;
          496  +  int i = 0;
          497  +  if( idxNum & 1 ){
          498  +    pCur->mnValue = sqlite3_value_int64(argv[i++]);
          499  +  }else{
          500  +    pCur->mnValue = 0;
          501  +  }
          502  +  if( idxNum & 2 ){
          503  +    pCur->mxValue = sqlite3_value_int64(argv[i++]);
          504  +  }else{
          505  +    pCur->mxValue = 0xffffffff;
          506  +  }
          507  +  if( idxNum & 4 ){
          508  +    pCur->iStep = sqlite3_value_int64(argv[i++]);
          509  +    if( pCur->iStep<1 ) pCur->iStep = 1;
          510  +  }else{
          511  +    pCur->iStep = 1;
          512  +  }
          513  +  if( idxNum & 8 ){
          514  +    pCur->isDesc = 1;
          515  +    pCur->iValue = pCur->mxValue;
          516  +    if( pCur->iStep>0 ){
          517  +      pCur->iValue -= (pCur->mxValue - pCur->mnValue)%pCur->iStep;
          518  +    }
          519  +  }else{
          520  +    pCur->isDesc = 0;
          521  +    pCur->iValue = pCur->mnValue;
          522  +  }
          523  +  pCur->iRowid = 1;
          524  +  return SQLITE_OK;
          525  +}
          526  +
          527  +/*
          528  +** SQLite will invoke this method one or more times while planning a query
          529  +** that uses the generate_series virtual table.  This routine needs to create
          530  +** a query plan for each invocation and compute an estimated cost for that
          531  +** plan.
          532  +**
          533  +** In this implementation idxNum is used to represent the
          534  +** query plan.  idxStr is unused.
          535  +**
          536  +** The query plan is represented by bits in idxNum:
          537  +**
          538  +**  (1)  start = $value  -- constraint exists
          539  +**  (2)  stop = $value   -- constraint exists
          540  +**  (4)  step = $value   -- constraint exists
          541  +**  (8)  output in descending order
          542  +*/
          543  +static int seriesBestIndex(
          544  +  sqlite3_vtab *tab,
          545  +  sqlite3_index_info *pIdxInfo
          546  +){
          547  +  int i;                 /* Loop over constraints */
          548  +  int idxNum = 0;        /* The query plan bitmask */
          549  +  int startIdx = -1;     /* Index of the start= constraint, or -1 if none */
          550  +  int stopIdx = -1;      /* Index of the stop= constraint, or -1 if none */
          551  +  int stepIdx = -1;      /* Index of the step= constraint, or -1 if none */
          552  +  int nArg = 0;          /* Number of arguments that seriesFilter() expects */
          553  +
          554  +  const struct sqlite3_index_constraint *pConstraint;
          555  +  pConstraint = pIdxInfo->aConstraint;
          556  +  for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
          557  +    if( pConstraint->usable==0 ) continue;
          558  +    if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
          559  +    switch( pConstraint->iColumn ){
          560  +      case SERIES_COLUMN_START:
          561  +        startIdx = i;
          562  +        idxNum |= 1;
          563  +        break;
          564  +      case SERIES_COLUMN_STOP:
          565  +        stopIdx = i;
          566  +        idxNum |= 2;
          567  +        break;
          568  +      case SERIES_COLUMN_STEP:
          569  +        stepIdx = i;
          570  +        idxNum |= 4;
          571  +        break;
          572  +    }
          573  +  }
          574  +  if( startIdx>=0 ){
          575  +    pIdxInfo->aConstraintUsage[startIdx].argvIndex = ++nArg;
          576  +    pIdxInfo->aConstraintUsage[startIdx].omit= !SQLITE_SERIES_CONSTRAINT_VERIFY;
          577  +  }
          578  +  if( stopIdx>=0 ){
          579  +    pIdxInfo->aConstraintUsage[stopIdx].argvIndex = ++nArg;
          580  +    pIdxInfo->aConstraintUsage[stopIdx].omit = !SQLITE_SERIES_CONSTRAINT_VERIFY;
          581  +  }
          582  +  if( stepIdx>=0 ){
          583  +    pIdxInfo->aConstraintUsage[stepIdx].argvIndex = ++nArg;
          584  +    pIdxInfo->aConstraintUsage[stepIdx].omit = !SQLITE_SERIES_CONSTRAINT_VERIFY;
          585  +  }
          586  +  if( (idxNum & 3)==3 ){
          587  +    /* Both start= and stop= boundaries are available.  This is the 
          588  +    ** the preferred case */
          589  +    pIdxInfo->estimatedCost = (double)(2 - ((idxNum&4)!=0));
          590  +    pIdxInfo->estimatedRows = 1000;
          591  +    if( pIdxInfo->nOrderBy==1 ){
          592  +      if( pIdxInfo->aOrderBy[0].desc ) idxNum |= 8;
          593  +      pIdxInfo->orderByConsumed = 1;
          594  +    }
          595  +  }else{
          596  +    /* If either boundary is missing, we have to generate a huge span
          597  +    ** of numbers.  Make this case very expensive so that the query
          598  +    ** planner will work hard to avoid it. */
          599  +    pIdxInfo->estimatedCost = (double)2147483647;
          600  +    pIdxInfo->estimatedRows = 2147483647;
          601  +  }
          602  +  pIdxInfo->idxNum = idxNum;
          603  +  return SQLITE_OK;
          604  +}
          605  +
          606  +/*
          607  +** This following structure defines all the methods for the 
          608  +** generate_series virtual table.
          609  +*/
          610  +static sqlite3_module seriesModule = {
          611  +  0,                         /* iVersion */
          612  +  0,                         /* xCreate */
          613  +  seriesConnect,             /* xConnect */
          614  +  seriesBestIndex,           /* xBestIndex */
          615  +  seriesDisconnect,          /* xDisconnect */
          616  +  0,                         /* xDestroy */
          617  +  seriesOpen,                /* xOpen - open a cursor */
          618  +  seriesClose,               /* xClose - close a cursor */
          619  +  seriesFilter,              /* xFilter - configure scan constraints */
          620  +  seriesNext,                /* xNext - advance a cursor */
          621  +  seriesEof,                 /* xEof - check for end of scan */
          622  +  seriesColumn,              /* xColumn - read data */
          623  +  seriesRowid,               /* xRowid - read data */
          624  +  0,                         /* xUpdate */
          625  +  0,                         /* xBegin */
          626  +  0,                         /* xSync */
          627  +  0,                         /* xCommit */
          628  +  0,                         /* xRollback */
          629  +  0,                         /* xFindMethod */
          630  +  0,                         /* xRename */
          631  +};
          632  +/* END the generate_series(START,END,STEP) implementation
          633  +*********************************************************************************/
          634  +
   315    635   /*
   316    636   ** Print sketchy documentation for this utility program
   317    637   */
   318    638   static void showHelp(void){
   319    639     printf("Usage: %s [options] ?FILE...?\n", g.zArgv0);
   320    640     printf(
   321    641   "Read SQL text from FILE... (or from standard input if FILE... is omitted)\n"
................................................................................
   725   1045             if( rc!=SQLITE_OK ) abendError("lookaside configuration filed: %d", rc);
   726   1046           }
   727   1047       #ifndef SQLITE_OMIT_TRACE
   728   1048           sqlite3_trace(db, verboseFlag ? traceCallback : traceNoop, 0);
   729   1049       #endif
   730   1050           sqlite3_create_function(db, "eval", 1, SQLITE_UTF8, 0, sqlEvalFunc, 0, 0);
   731   1051           sqlite3_create_function(db, "eval", 2, SQLITE_UTF8, 0, sqlEvalFunc, 0, 0);
         1052  +        sqlite3_create_module(db, "generate_series", &seriesModule, 0);
   732   1053           sqlite3_limit(db, SQLITE_LIMIT_LENGTH, 1000000);
   733   1054           if( zEncoding ) sqlexec(db, "PRAGMA encoding=%s", zEncoding);
   734   1055           if( pageSize ) sqlexec(db, "PRAGMA pagesize=%d", pageSize);
   735   1056           if( doAutovac ) sqlexec(db, "PRAGMA auto_vacuum=FULL");
   736   1057           iStart = timeOfDay();
   737   1058           g.bOomEnable = 1;
   738   1059           if( verboseFlag ){

Changes to tool/lemon.c.

   259    259     int prec;                /* Precedence if defined (-1 otherwise) */
   260    260     enum e_assoc assoc;      /* Associativity if precedence is defined */
   261    261     char *firstset;          /* First-set for all rules of this symbol */
   262    262     Boolean lambda;          /* True if NT and can generate an empty string */
   263    263     int useCnt;              /* Number of times used */
   264    264     char *destructor;        /* Code which executes whenever this symbol is
   265    265                              ** popped from the stack during error processing */
   266         -  int destLineno;          /* Line number for start of destructor */
          266  +  int destLineno;          /* Line number for start of destructor.  Set to
          267  +                           ** -1 for duplicate destructors. */
   267    268     char *datatype;          /* The data type of information held by this
   268    269                              ** object. Only used if type==NONTERMINAL */
   269    270     int dtnum;               /* The data type number.  In the parser, the value
   270    271                              ** stack is a union.  The .yy%d element of this
   271    272                              ** union is the correct data type for this object */
   272    273     /* The following fields are used by MULTITERMINALs only */
   273    274     int nsubsym;             /* Number of constituent symbols in the MULTI */
................................................................................
  4227   4228       }else{
  4228   4229         j++;
  4229   4230       }
  4230   4231     }
  4231   4232     fprintf(out, "};\n"); lineno++;
  4232   4233   
  4233   4234     /* Output the yy_shift_ofst[] table */
  4234         -  fprintf(out, "#define YY_SHIFT_USE_DFLT (%d)\n", mnTknOfst-1); lineno++;
  4235   4235     n = lemp->nxstate;
  4236   4236     while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
         4237  +  fprintf(out, "#define YY_SHIFT_USE_DFLT (%d)\n", lemp->nactiontab); lineno++;
  4237   4238     fprintf(out, "#define YY_SHIFT_COUNT (%d)\n", n-1); lineno++;
  4238   4239     fprintf(out, "#define YY_SHIFT_MIN   (%d)\n", mnTknOfst); lineno++;
  4239   4240     fprintf(out, "#define YY_SHIFT_MAX   (%d)\n", mxTknOfst); lineno++;
  4240   4241     fprintf(out, "static const %s yy_shift_ofst[] = {\n", 
  4241         -          minimum_size_type(mnTknOfst-1, mxTknOfst, &sz)); lineno++;
         4242  +       minimum_size_type(mnTknOfst, lemp->nterminal+lemp->nactiontab, &sz));
         4243  +       lineno++;
  4242   4244     lemp->tablesize += n*sz;
  4243   4245     for(i=j=0; i<n; i++){
  4244   4246       int ofst;
  4245   4247       stp = lemp->sorted[i];
  4246   4248       ofst = stp->iTknOfst;
  4247         -    if( ofst==NO_OFFSET ) ofst = mnTknOfst - 1;
         4249  +    if( ofst==NO_OFFSET ) ofst = lemp->nactiontab;
  4248   4250       if( j==0 ) fprintf(out," /* %5d */ ", i);
  4249   4251       fprintf(out, " %4d,", ofst);
  4250   4252       if( j==9 || i==n-1 ){
  4251   4253         fprintf(out, "\n"); lineno++;
  4252   4254         j = 0;
  4253   4255       }else{
  4254   4256         j++;
................................................................................
  4380   4382         emit_destructor_code(out,dflt_sp,lemp,&lineno);
  4381   4383       }
  4382   4384       fprintf(out,"      break;\n"); lineno++;
  4383   4385     }
  4384   4386     for(i=0; i<lemp->nsymbol; i++){
  4385   4387       struct symbol *sp = lemp->symbols[i];
  4386   4388       if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
         4389  +    if( sp->destLineno<0 ) continue;  /* Already emitted */
  4387   4390       fprintf(out,"    case %d: /* %s */\n", sp->index, sp->name); lineno++;
  4388   4391   
  4389   4392       /* Combine duplicate destructors into a single case */
  4390   4393       for(j=i+1; j<lemp->nsymbol; j++){
  4391   4394         struct symbol *sp2 = lemp->symbols[j];
  4392   4395         if( sp2 && sp2->type!=TERMINAL && sp2->destructor
  4393   4396             && sp2->dtnum==sp->dtnum
  4394   4397             && strcmp(sp->destructor,sp2->destructor)==0 ){
  4395   4398            fprintf(out,"    case %d: /* %s */\n",
  4396   4399                    sp2->index, sp2->name); lineno++;
  4397         -         sp2->destructor = 0;
         4400  +         sp2->destLineno = -1;  /* Avoid emitting this destructor again */
  4398   4401         }
  4399   4402       }
  4400   4403   
  4401   4404       emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
  4402   4405       fprintf(out,"      break;\n"); lineno++;
  4403   4406     }
  4404   4407     tplt_xfer(lemp->name,in,out,&lineno);

Changes to tool/lempar.c.

   112    112   **                                      token onto the stack and goto state N.
   113    113   **
   114    114   **   N between YY_MIN_SHIFTREDUCE       Shift to an arbitrary state then
   115    115   **     and YY_MAX_SHIFTREDUCE           reduce by rule N-YY_MIN_SHIFTREDUCE.
   116    116   **
   117    117   **   N between YY_MIN_REDUCE            Reduce by rule N-YY_MIN_REDUCE
   118    118   **     and YY_MAX_REDUCE
   119         -
          119  +**
   120    120   **   N == YY_ERROR_ACTION               A syntax error has occurred.
   121    121   **
   122    122   **   N == YY_ACCEPT_ACTION              The parser accepts its input.
   123    123   **
   124    124   **   N == YY_NO_ACTION                  No such action.  Denotes unused
   125    125   **                                      slots in the yy_action[] table.
   126    126   **
   127    127   ** The action table is constructed as a single large table named yy_action[].
   128         -** Given state S and lookahead X, the action is computed as
          128  +** Given state S and lookahead X, the action is computed as either:
   129    129   **
   130         -**      yy_action[ yy_shift_ofst[S] + X ]
          130  +**    (A)   N = yy_action[ yy_shift_ofst[S] + X ]
          131  +**    (B)   N = yy_default[S]
   131    132   **
   132         -** If the index value yy_shift_ofst[S]+X is out of range or if the value
   133         -** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
   134         -** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
   135         -** and that yy_default[S] should be used instead.  
          133  +** The (A) formula is preferred.  The B formula is used instead if:
          134  +**    (1)  The yy_shift_ofst[S]+X value is out of range, or
          135  +**    (2)  yy_lookahead[yy_shift_ofst[S]+X] is not equal to X, or
          136  +**    (3)  yy_shift_ofst[S] equal YY_SHIFT_USE_DFLT.
          137  +** (Implementation note: YY_SHIFT_USE_DFLT is chosen so that
          138  +** YY_SHIFT_USE_DFLT+X will be out of range for all possible lookaheads X.
          139  +** Hence only tests (1) and (2) need to be evaluated.)
   136    140   **
   137         -** The formula above is for computing the action when the lookahead is
          141  +** The formulas above are for computing the action when the lookahead is
   138    142   ** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
   139    143   ** a reduce action) then the yy_reduce_ofst[] array is used in place of
   140    144   ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
   141    145   ** YY_SHIFT_USE_DFLT.
   142    146   **
   143    147   ** The following are the tables generated in this section:
   144    148   **
................................................................................
   446    450     int i;
   447    451     int stateno = pParser->yytos->stateno;
   448    452    
   449    453     if( stateno>=YY_MIN_REDUCE ) return stateno;
   450    454     assert( stateno <= YY_SHIFT_COUNT );
   451    455     do{
   452    456       i = yy_shift_ofst[stateno];
   453         -    if( i==YY_SHIFT_USE_DFLT ) return yy_default[stateno];
   454    457       assert( iLookAhead!=YYNOCODE );
   455    458       i += iLookAhead;
   456    459       if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
   457         -      if( iLookAhead>0 ){
   458    460   #ifdef YYFALLBACK
   459    461           YYCODETYPE iFallback;            /* Fallback token */
   460    462           if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
   461    463                  && (iFallback = yyFallback[iLookAhead])!=0 ){
   462    464   #ifndef NDEBUG
   463    465             if( yyTraceFILE ){
   464    466               fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
................................................................................
   476    478             if( 
   477    479   #if YY_SHIFT_MIN+YYWILDCARD<0
   478    480               j>=0 &&
   479    481   #endif
   480    482   #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
   481    483               j<YY_ACTTAB_COUNT &&
   482    484   #endif
   483         -            yy_lookahead[j]==YYWILDCARD
          485  +          yy_lookahead[j]==YYWILDCARD && iLookAhead>0
   484    486             ){
   485    487   #ifndef NDEBUG
   486    488               if( yyTraceFILE ){
   487    489                 fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
   488    490                    yyTracePrompt, yyTokenName[iLookAhead],
   489    491                    yyTokenName[YYWILDCARD]);
   490    492               }
   491    493   #endif /* NDEBUG */
   492    494               return yy_action[j];
   493    495             }
   494    496           }
   495    497   #endif /* YYWILDCARD */
   496         -      }
   497    498         return yy_default[stateno];
   498    499       }else{
   499    500         return yy_action[i];
   500    501       }
   501    502     }while(1);
   502    503   }
   503    504   

Changes to tool/sqldiff.c.

  1175   1175     strPrintf(pSql, "SELECT ");
  1176   1176     strPrintfArray(pSql, ", ", "%s", azCol, -1);
  1177   1177     strPrintf(pSql, ", 0, ");       /* Set ota_control to 0 for an insert */
  1178   1178     strPrintfArray(pSql, ", ", "NULL", azCol, -1);
  1179   1179     strPrintf(pSql, " FROM aux.%Q AS n WHERE NOT EXISTS (\n", zTab);
  1180   1180     strPrintf(pSql, "    SELECT 1 FROM ", zTab);
  1181   1181     strPrintf(pSql, " main.%Q AS o WHERE ", zTab);
  1182         -  strPrintfArray(pSql, " AND ", "(n.%Q IS o.%Q)", azCol, nPK);
  1183         -  strPrintf(pSql, "\n)");
         1182  +  strPrintfArray(pSql, " AND ", "(n.%Q = o.%Q)", azCol, nPK);
         1183  +  strPrintf(pSql, "\n) AND ");
         1184  +  strPrintfArray(pSql, " AND ", "(n.%Q IS NOT NULL)", azCol, nPK);
  1184   1185   
  1185   1186     /* Deleted rows: */
  1186   1187     strPrintf(pSql, "\nUNION ALL\nSELECT ");
  1187   1188     strPrintfArray(pSql, ", ", "%s", azCol, nPK);
  1188   1189     if( azCol[nPK] ){
  1189   1190       strPrintf(pSql, ", ");
  1190   1191       strPrintfArray(pSql, ", ", "NULL", &azCol[nPK], -1);
  1191   1192     }
  1192   1193     strPrintf(pSql, ", 1, ");       /* Set ota_control to 1 for a delete */
  1193   1194     strPrintfArray(pSql, ", ", "NULL", azCol, -1);
  1194   1195     strPrintf(pSql, " FROM main.%Q AS n WHERE NOT EXISTS (\n", zTab);
  1195   1196     strPrintf(pSql, "    SELECT 1 FROM ", zTab);
  1196   1197     strPrintf(pSql, " aux.%Q AS o WHERE ", zTab);
  1197         -  strPrintfArray(pSql, " AND ", "(n.%Q IS o.%Q)", azCol, nPK);
  1198         -  strPrintf(pSql, "\n) ");
         1198  +  strPrintfArray(pSql, " AND ", "(n.%Q = o.%Q)", azCol, nPK);
         1199  +  strPrintf(pSql, "\n) AND ");
         1200  +  strPrintfArray(pSql, " AND ", "(n.%Q IS NOT NULL)", azCol, nPK);
  1199   1201   
  1200   1202     /* Updated rows. If all table columns are part of the primary key, there 
  1201   1203     ** can be no updates. In this case this part of the compound SELECT can
  1202   1204     ** be omitted altogether. */
  1203   1205     if( azCol[nPK] ){
  1204   1206       strPrintf(pSql, "\nUNION ALL\nSELECT ");
  1205   1207       strPrintfArray(pSql, ", ", "n.%s", azCol, nPK);
................................................................................
  1222   1224       strPrintfArray(pSql, ", ", "NULL", azCol, nPK);
  1223   1225       strPrintf(pSql, ",\n");
  1224   1226       strPrintfArray(pSql, " ,\n", 
  1225   1227           "    CASE WHEN n.%s IS o.%s THEN NULL ELSE o.%s END", &azCol[nPK], -1
  1226   1228       );
  1227   1229   
  1228   1230       strPrintf(pSql, "\nFROM main.%Q AS o, aux.%Q AS n\nWHERE ", zTab, zTab);
  1229         -    strPrintfArray(pSql, " AND ", "(n.%Q IS o.%Q)", azCol, nPK);
         1231  +    strPrintfArray(pSql, " AND ", "(n.%Q = o.%Q)", azCol, nPK);
  1230   1232       strPrintf(pSql, " AND ota_control LIKE '%%x%%'");
  1231   1233     }
  1232   1234   
  1233   1235     /* Now add an ORDER BY clause to sort everything by PK. */
  1234   1236     strPrintf(pSql, "\nORDER BY ");
  1235   1237     for(i=1; i<=nPK; i++) strPrintf(pSql, "%s%d", ((i>1)?", ":""), i);
  1236   1238   }
................................................................................
  1298   1300           if( i>0 ) fprintf(out, ", ");
  1299   1301           printQuoted(out, sqlite3_column_value(pStmt, i));
  1300   1302         }
  1301   1303       }else{
  1302   1304         char *zOtaControl;
  1303   1305         int nOtaControl = sqlite3_column_bytes(pStmt, nCol);
  1304   1306   
  1305         -      zOtaControl = (char*)sqlite3_malloc(nOtaControl);
         1307  +      zOtaControl = (char*)sqlite3_malloc(nOtaControl+1);
  1306   1308         memcpy(zOtaControl, sqlite3_column_text(pStmt, nCol), nOtaControl+1);
  1307   1309   
  1308   1310         for(i=0; i<nCol; i++){
  1309   1311           int bDone = 0;
  1310   1312           if( i>=nPK 
  1311   1313               && sqlite3_column_type(pStmt, i)==SQLITE_BLOB
  1312   1314               && sqlite3_column_type(pStmt, nCol+1+i)==SQLITE_BLOB