Fossil

Check-in Differences
Login

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

Difference From:

[862d630f] Fix typos in documentation text. (user: drh tags: trunk, date: 2018-06-14 19:33:01)

To:

[9718f3b0] Version 2.6 (user: drh tags: trunk, release, version-2.6, date: 2018-05-04 12:56:42)

Deleted Makefile.osx-jaguar.

     1         -#!/usr/bin/make
     2         -#
     3         -# This is a specially modified version of the Makefile that will build
     4         -# Fossil on Mac OSX Jaguar (10.2) circa 2002.  This Makefile is used for
     5         -# testing on an old PPC iBook.  The use of this old platform helps to verify
     6         -# Fossil and SQLite running on big-endian hardware.
     7         -#
     8         -# To build with this Makefile, run:
     9         -#
    10         -#     make -f Makefile.osx-jaguar
    11         -#
    12         -#
    13         -# This is the top-level makefile for Fossil when the build is occurring
    14         -# on a unix platform.  This works out-of-the-box on most unix platforms.
    15         -# But you are free to vary some of the definitions if desired.
    16         -#
    17         -#### The toplevel directory of the source tree.  Fossil can be built
    18         -#    in a directory that is separate from the source tree.  Just change
    19         -#    the following to point from the build directory to the src/ folder.
    20         -#
    21         -SRCDIR = ./src
    22         -
    23         -#### The directory into which object code files should be written.
    24         -#    Having a "./" prefix in the value of this variable breaks our use of the
    25         -#    "makeheaders" tool when running make on the MinGW platform, apparently
    26         -#    due to some command line argument manipulation performed automatically
    27         -#    by the shell.
    28         -#
    29         -#
    30         -OBJDIR = bld
    31         -
    32         -#### C Compiler and options for use in building executables that
    33         -#    will run on the platform that is doing the build.  This is used
    34         -#    to compile code-generator programs as part of the build process.
    35         -#    See TCC below for the C compiler for building the finished binary.
    36         -#
    37         -BCC = cc
    38         -
    39         -#### The suffix to add to final executable file.  When cross-compiling
    40         -#    to windows, make this ".exe".  Otherwise leave it blank.
    41         -#
    42         -E = 
    43         -
    44         -TCC = cc
    45         -
    46         -#### Tcl shell for use in running the fossil testsuite.  If you do not
    47         -#    care about testing the end result, this can be blank.
    48         -#
    49         -TCLSH = tclsh
    50         -
    51         -# LIB =	  -lz
    52         -LIB = compat/zlib/libz.a
    53         -TCC +=	  -g -O0 -DHAVE_AUTOCONFIG_H
    54         -TCC += -Icompat/zlib
    55         -TCC += -DSQLITE_WITHOUT_ZONEMALLOC
    56         -TCC += -D_BSD_SOURCE=1
    57         -TCC += -DWITHOUT_ICONV
    58         -TCC += -Dsocklen_t=int
    59         -TCC += -DSQLITE_MAX_MMAP_SIZE=0
    60         -INSTALLDIR = $(DESTDIR)/usr/local/bin
    61         -USE_SYSTEM_SQLITE = 
    62         -USE_LINENOISE = 1
    63         -# FOSSIL_ENABLE_TCL = @FOSSIL_ENABLE_TCL@
    64         -FOSSIL_ENABLE_TCL = 0
    65         -FOSSIL_ENABLE_MINIZ = 0
    66         -
    67         -include $(SRCDIR)/main.mk
    68         -
    69         -distclean: clean
    70         -	rm -f autoconfig.h config.log Makefile

Changes to src/add.c.

   251    251   ** Make arrangements to add one or more files or directories to the
   252    252   ** current checkout at the next commit.
   253    253   **
   254    254   ** When adding files or directories recursively, filenames that begin
   255    255   ** with "." are excluded by default.  To include such files, add
   256    256   ** the "--dotfiles" option to the command-line.
   257    257   **
   258         -** The --ignore and --clean options are comma-separated lists of glob patterns
          258  +** The --ignore and --clean options are comma-separate lists of glob patterns
   259    259   ** for files to be excluded.  Example:  '*.o,*.obj,*.exe'  If the --ignore
   260    260   ** option does not appear on the command line then the "ignore-glob" setting
   261    261   ** is used.  If the --clean option does not appear on the command line then
   262    262   ** the "clean-glob" setting is used.
   263    263   **
   264    264   ** If files are attempted to be added explicitly on the command line which
   265    265   ** match "ignore-glob", a confirmation is asked first. This can be prevented
................................................................................
   857    857   void mv_cmd(void){
   858    858     int i;
   859    859     int vid;
   860    860     int moveFiles;
   861    861     int dryRunFlag;
   862    862     int softFlag;
   863    863     int hardFlag;
   864         -  int origType;
   865         -  int destType;
   866    864     char *zDest;
   867    865     Blob dest;
   868    866     Stmt q;
   869    867   
   870    868     db_must_be_within_tree();
   871    869     dryRunFlag = find_option("dry-run","n",0)!=0;
   872    870     softFlag = find_option("soft",0,0)!=0;
................................................................................
   900    898     file_tree_name(zDest, &dest, 0, 1);
   901    899     db_multi_exec(
   902    900       "UPDATE vfile SET origname=pathname WHERE origname IS NULL;"
   903    901     );
   904    902     db_multi_exec(
   905    903       "CREATE TEMP TABLE mv(f TEXT UNIQUE ON CONFLICT IGNORE, t TEXT);"
   906    904     );
   907         -  if( g.argc!=4 ){
   908         -    origType = -1;
   909         -  }else{
   910         -    origType = (file_isdir(g.argv[2], RepoFILE) == 1);
   911         -  }
   912         -  destType = file_isdir(zDest, RepoFILE);
   913         -  if( origType==-1 && destType!=1 ){
   914         -    usage("OLDNAME NEWNAME");
   915         -  }else if( origType==1 && destType==2 ){
   916         -    fossil_fatal("cannot rename '%s' to '%s' since another file named"
   917         -                 " '%s' exists", g.argv[2], zDest, zDest);
   918         -  }else if( origType==0 && destType!=1 ){
          905  +  if( file_isdir(zDest, RepoFILE)!=1 ){
   919    906       Blob orig;
          907  +    if( g.argc!=4 ){
          908  +      usage("OLDNAME NEWNAME");
          909  +    }
   920    910       file_tree_name(g.argv[2], &orig, 0, 1);
   921    911       db_multi_exec(
   922    912         "INSERT INTO mv VALUES(%B,%B)", &orig, &dest
   923    913       );
   924    914     }else{
   925    915       if( blob_eq(&dest, ".") ){
   926    916         blob_reset(&dest);
................................................................................
   944    934         );
   945    935         while( db_step(&q)==SQLITE_ROW ){
   946    936           const char *zPath = db_column_text(&q, 0);
   947    937           int nPath = db_column_bytes(&q, 0);
   948    938           const char *zTail;
   949    939           if( nPath==nOrig ){
   950    940             zTail = file_tail(zPath);
   951         -        }else if( destType==1 ){
   952         -          zTail = &zPath[nOrig-strlen(file_tail(zOrig))];
   953    941           }else{
   954    942             zTail = &zPath[nOrig+1];
   955    943           }
   956    944           db_multi_exec(
   957    945             "INSERT INTO mv VALUES('%q','%q%q')",
   958    946             zPath, blob_str(&dest), zTail
   959    947           );

Changes to src/db.c.

  1090   1090   ** connection.  An error results in process abort.
  1091   1091   */
  1092   1092   LOCAL sqlite3 *db_open(const char *zDbName){
  1093   1093     int rc;
  1094   1094     sqlite3 *db;
  1095   1095   
  1096   1096     if( g.fSqlTrace ) fossil_trace("-- sqlite3_open: [%s]\n", zDbName);
  1097         -  if( strcmp(zDbName, g.nameOfExe)==0 ){
  1098         -    extern int sqlite3_appendvfs_init(
  1099         -      sqlite3 *, char **, const sqlite3_api_routines *
  1100         -    );
  1101         -    sqlite3_appendvfs_init(0,0,0);
  1102         -    g.zVfsName = "apndvfs";
  1103         -  }
  1104   1097     rc = sqlite3_open_v2(
  1105   1098          zDbName, &db,
  1106   1099          SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
  1107   1100          g.zVfsName
  1108   1101     );
  1109   1102     if( rc!=SQLITE_OK ){
  1110   1103       db_err("[%s]: %s", zDbName, sqlite3_errmsg(db));

Changes to src/etag.c.

   136    136   ** page generators that know a valid last-modified time.  This routine
   137    137   ** might generate a 304 Not Modified reply and exit(), never returning.
   138    138   ** Or, if not, it will cause a Last-Modified: header to be included in the
   139    139   ** reply.
   140    140   */
   141    141   void etag_last_modified(sqlite3_int64 mtime){
   142    142     const char *zIfModifiedSince;
   143         -  sqlite3_int64 x;
          143  +  sqlite3_int64 x, exeMtime;
   144    144     assert( iEtagMtime==0 );   /* Only call this routine once */
   145    145     assert( mtime>0 );         /* Only call with a valid mtime */
   146    146     iEtagMtime = mtime;
   147    147   
   148    148     /* Check to see the If-Modified-Since constraint is satisfied */
   149    149     zIfModifiedSince = P("HTTP_IF_MODIFIED_SINCE");
   150    150     if( zIfModifiedSince==0 ) return;
   151    151     x = cgi_rfc822_parsedate(zIfModifiedSince);
   152         -  if( x<mtime ) return;
          152  +  if( x<=0 || x>mtime ) return;
   153    153   
   154         -#if 0  
   155    154     /* If the Fossil executable is more recent than If-Modified-Since,
   156    155     ** go ahead and regenerate the resource. */
   157         -  if( file_mtime(g.nameOfExe, ExtFILE)>x ) return;
   158         -#endif
          156  +  exeMtime = file_mtime(g.nameOfExe, ExtFILE);
          157  +  if( exeMtime>x ) return;
   159    158   
   160    159     /* If we reach this point, it means that the resource has not changed
   161    160     ** and that we should generate a 304 Not Modified reply */
   162    161     cgi_reset_content();
   163    162     cgi_set_status(304, "Not Modified");
   164    163     cgi_reply();
   165    164     fossil_exit(0);

Changes to src/export.c.

   598    598     }
   599    599     db_finalize(&q);
   600    600     db_finalize(&q2);
   601    601     db_finalize(&q3);
   602    602   
   603    603     /* Output the commit records.
   604    604     */
   605         -  topological_sort_checkins(0);
   606    605     db_prepare(&q,
   607    606       "SELECT strftime('%%s',mtime), objid, coalesce(ecomment,comment),"
   608    607       "       coalesce(euser,user),"
   609    608       "       (SELECT value FROM tagxref WHERE rid=objid AND tagid=%d)"
   610         -    "  FROM toponode, event"
   611         -    " WHERE toponode.tid=event.objid"
   612         -    "   AND event.type='ci'"
   613         -    "   AND NOT EXISTS (SELECT 1 FROM oldcommit WHERE toponode.tid=rid)"
   614         -    " ORDER BY toponode.tseq ASC",
          609  +    "  FROM event"
          610  +    " WHERE type='ci' AND NOT EXISTS (SELECT 1 FROM oldcommit WHERE objid=rid)"
          611  +    " ORDER BY mtime ASC",
   615    612       TAG_BRANCH
   616    613     );
   617    614     db_prepare(&q2, "INSERT INTO oldcommit VALUES (:rid)");
   618    615     while( db_step(&q)==SQLITE_ROW ){
   619    616       Stmt q4;
   620    617       const char *zSecondsSince1970 = db_column_text(&q, 0);
   621    618       int ckinId = db_column_int(&q, 1);
................................................................................
   624    621       const char *zBranch = db_column_text(&q, 4);
   625    622       char *zMark;
   626    623   
   627    624       bag_insert(&vers, ckinId);
   628    625       db_bind_int(&q2, ":rid", ckinId);
   629    626       db_step(&q2);
   630    627       db_reset(&q2);
   631         -    if( zBranch==0 || fossil_strcmp(zBranch, "trunk")==0 ){
   632         -      zBranch = gexport.zTrunkName;
   633         -    }
          628  +    if( zBranch==0 || fossil_strcmp(zBranch, "trunk")==0 ) zBranch = gexport.zTrunkName;
   634    629       zMark = mark_name_from_rid(ckinId, &unused_mark);
   635    630       printf("commit refs/heads/");
   636    631       print_ref(zBranch);
   637    632       printf("\nmark %s\n", zMark);
   638    633       free(zMark);
   639    634       printf("committer");
   640    635       print_person(zUser);
................................................................................
   740    735       if( ferror(f)!=0 || fclose(f)!=0 ){
   741    736         fossil_fatal("error while writing %s", markfile_out);
   742    737       }
   743    738     }
   744    739     bag_clear(&blobs);
   745    740     bag_clear(&vers);
   746    741   }
   747         -
   748         -/*
   749         -** Construct the temporary table toposort as follows:
   750         -**
   751         -**     CREATE TEMP TABLE toponode(
   752         -**        tid INTEGER PRIMARY KEY,   -- Check-in id
   753         -**        tseq INT                   -- integer total order on check-ins.
   754         -**     );
   755         -**
   756         -** This table contains all check-ins of the repository in topological
   757         -** order.  "Topological order" means that every parent check-in comes
   758         -** before all of its children.  Topological order is *almost* the same
   759         -** thing as "ORDER BY event.mtime".  Differences only arrise when there
   760         -** are timewarps.  In as much as Git hates timewarps, we have to compute
   761         -** a correct topological order when doing an export.
   762         -**
   763         -** Since mtime is a usually already nearly in topological order, the
   764         -** algorithm is to start with mtime, then make adjustments as necessary
   765         -** for timewarps.  This is not a great algorithm for the general case,
   766         -** but it is very fast for the overwhelmingly common case where there
   767         -** are few timewarps.
   768         -*/
   769         -int topological_sort_checkins(int bVerbose){
   770         -  int nChange = 0;
   771         -  Stmt q1;
   772         -  Stmt chng;
   773         -  db_multi_exec(
   774         -    "CREATE TEMP TABLE toponode(\n"
   775         -    "  tid INTEGER PRIMARY KEY,\n"
   776         -    "  tseq INT\n"
   777         -    ");\n"
   778         -    "INSERT INTO toponode(tid,tseq) "
   779         -    " SELECT objid, CAST(mtime*8640000 AS int) FROM event WHERE type='ci';\n"
   780         -    "CREATE TEMP TABLE topolink(\n"
   781         -    "  tparent INT,\n"
   782         -    "  tchild INT,\n"
   783         -    "  PRIMARY KEY(tparent,tchild)\n"
   784         -    ") WITHOUT ROWID;"
   785         -    "INSERT INTO topolink(tparent,tchild)"
   786         -    "  SELECT pid, cid FROM plink;\n"
   787         -    "CREATE INDEX topolink_child ON topolink(tchild);\n"
   788         -  );
   789         -
   790         -  /* Find a timewarp instance */
   791         -  db_prepare(&q1,
   792         -    "SELECT P.tseq, C.tid, C.tseq\n"
   793         -    "  FROM toponode P, toponode C, topolink X\n"
   794         -    " WHERE X.tparent=P.tid\n"
   795         -    "   AND X.tchild=C.tid\n"
   796         -    "   AND P.tseq>=C.tseq;"
   797         -  );
   798         -
   799         -  /* Update the timestamp on :tid to have value :tseq */
   800         -  db_prepare(&chng,
   801         -    "UPDATE toponode SET tseq=:tseq WHERE tid=:tid"
   802         -  );
   803         -
   804         -  while( db_step(&q1)==SQLITE_ROW ){
   805         -    i64 iParentTime = db_column_int64(&q1, 0);
   806         -    int iChild = db_column_int(&q1, 1);
   807         -    i64 iChildTime = db_column_int64(&q1, 2);
   808         -    nChange++;
   809         -    if( nChange>10000 ){
   810         -      fossil_fatal("failed to fix all timewarps after 100000 attempts");
   811         -    }
   812         -    db_reset(&q1);
   813         -    db_bind_int64(&chng, ":tid", iChild);
   814         -    db_bind_int64(&chng, ":tseq", iParentTime+1);
   815         -    db_step(&chng);
   816         -    db_reset(&chng);
   817         -    if( bVerbose ){
   818         -      fossil_print("moving %d from %lld to %lld\n",
   819         -                   iChild, iChildTime, iParentTime+1);
   820         -    }
   821         -  }
   822         -
   823         -  db_finalize(&q1);
   824         -  db_finalize(&chng);
   825         -  return nChange;
   826         -}
   827         -
   828         -/*
   829         -** COMMAND: test-topological-sort
   830         -**
   831         -** Invoke the topological_sort_checkins() interface for testing
   832         -** purposes.
   833         -*/
   834         -void test_topological_sort(void){
   835         -  int n;
   836         -  db_find_and_open_repository(0, 0);
   837         -  n = topological_sort_checkins(1);
   838         -  fossil_print("%d reorderings required\n", n);
   839         -}

Changes to src/graph.c.

   532    532         }
   533    533       }
   534    534       mask = BIT(pRow->iRail);
   535    535       pRow->railInUse |= mask;
   536    536       if( pRow->pChild ){
   537    537         assignChildrenToRail(pRow);
   538    538       }else if( !omitDescenders && count_nonbranch_children(pRow->rid)!=0 ){
   539         -      if( !pRow->timeWarp ) riser_to_top(pRow);
          539  +      riser_to_top(pRow);
   540    540       }
   541    541       if( pParent ){
   542    542         for(pLoop=pParent->pPrev; pLoop && pLoop!=pRow; pLoop=pLoop->pPrev){
   543    543           pLoop->railInUse |= mask;
   544    544         }
   545    545       }
   546    546     }

Changes to src/info.c.

  1905   1905         if( iEnd<iStart ) iEnd = iStart;
  1906   1906         db_multi_exec(
  1907   1907           "INSERT OR REPLACE INTO lnos VALUES(%d,%d)", iStart, iEnd
  1908   1908         );
  1909   1909         iStart = iEnd = atoi(&zLn[i++]);
  1910   1910       }while( zLn[i] && iStart && iEnd );
  1911   1911     }
  1912         -  db_prepare(&q, "SELECT min(iStart), max(iEnd) FROM lnos");
         1912  +  db_prepare(&q, "SELECT min(iStart), iEnd FROM lnos");
  1913   1913     if( db_step(&q)==SQLITE_ROW ){
  1914   1914       iStart = db_column_int(&q, 0);
  1915   1915       iEnd = db_column_int(&q, 1);
  1916   1916       iTop = iStart - 15 + (iEnd-iStart)/4;
  1917   1917       if( iTop>iStart - 2 ) iTop = iStart-2;
  1918   1918     }
  1919   1919     db_finalize(&q);

Changes to src/json_timeline.c.

   316    316   ** or 0 for defaults.
   317    317   */
   318    318   cson_value * json_get_changed_files(int rid, int flags){
   319    319     cson_value * rowsV = NULL;
   320    320     cson_array * rows = NULL;
   321    321     Stmt q = empty_Stmt;
   322    322     db_prepare(&q,
   323         -         "SELECT (pid<=0) AS isnew,"
   324         -         "       (fid==0) AS isdel,"
   325         -         "       (SELECT name FROM filename WHERE fnid=mlink.fnid) AS name,"
   326         -         "       (SELECT uuid FROM blob WHERE rid=fid) as uuid,"
   327         -         "       (SELECT uuid FROM blob WHERE rid=pid) as parent,"
   328         -         "       blob.size as size"
   329         -         "  FROM mlink"
   330         -         " LEFT JOIN blob ON blob.rid=fid"
   331         -         " WHERE mid=%d AND pid!=fid"
   332         -         " AND NOT mlink.isaux"
   333         -         " ORDER BY name /*sort*/",
   334         -         rid
   335         -         );
          323  +           "SELECT (pid==0) AS isnew,"
          324  +           "       (fid==0) AS isdel,"
          325  +           "       (SELECT name FROM filename WHERE fnid=mlink.fnid) AS name,"
          326  +           "       blob.uuid as uuid,"
          327  +           "       (SELECT uuid FROM blob WHERE rid=pid) as parent,"
          328  +           "       blob.size as size"
          329  +           "  FROM mlink, blob"
          330  +           " WHERE mid=%d AND pid!=fid"
          331  +           " AND blob.rid=fid AND NOT mlink.isaux"
          332  +           " ORDER BY name /*sort*/",
          333  +             rid
          334  +             );
   336    335     while( (SQLITE_ROW == db_step(&q)) ){
   337    336       cson_value * rowV = cson_value_new_object();
   338    337       cson_object * row = cson_value_get_object(rowV);
   339    338       int const isNew = db_column_int(&q,0);
   340    339       int const isDel = db_column_int(&q,1);
   341    340       char * zDownload = NULL;
   342    341       if(!rowsV){

Changes to src/main.c.

   533    533     if( zValue ){
   534    534       g.comFmtFlags = atoi(zValue);
   535    535     }else{
   536    536       g.comFmtFlags = COMMENT_PRINT_DEFAULT;
   537    537     }
   538    538   }
   539    539   
   540         -/*
   541         -** Check to see if the Fossil binary contains an appended repository
   542         -** file using the appendvfs extension.  If so, change command-line arguments
   543         -** to cause Fossil to launch with "fossil ui" on that repo.
   544         -*/
   545         -static int fossilExeHasAppendedRepo(void){
   546         -  extern int deduceDatabaseType(const char*,int);
   547         -  if( 2==deduceDatabaseType(g.nameOfExe,0) ){
   548         -    static char *azAltArgv[] = { 0, "ui", 0, 0 };
   549         -    azAltArgv[0] = g.nameOfExe;
   550         -    azAltArgv[2] = g.nameOfExe;
   551         -    g.argv = azAltArgv;
   552         -    g.argc = 3;
   553         -    return 1;
   554         -  }else{
   555         -    return 0;
   556         -  }
   557         -}
   558         -
   559    540   /*
   560    541   ** This procedure runs first.
   561    542   */
   562    543   #if defined(_WIN32) && !defined(BROKEN_MINGW_CMDLINE)
   563    544   int _dowildcard = -1; /* This turns on command-line globbing in MinGW-w64 */
   564    545   int wmain(int argc, wchar_t **argv)
   565    546   #else
................................................................................
   615    596       }else{
   616    597         fossil_fatal("no such VFS: \"%s\"", g.zVfsName);
   617    598       }
   618    599     }
   619    600     if( fossil_getenv("GATEWAY_INTERFACE")!=0 && !find_option("nocgi", 0, 0)){
   620    601       zCmdName = "cgi";
   621    602       g.isHTTP = 1;
   622         -  }else if( g.argc<2 && !fossilExeHasAppendedRepo() ){
          603  +  }else if( g.argc<2 ){
   623    604       fossil_print(
   624    605          "Usage: %s COMMAND ...\n"
   625    606          "   or: %s help           -- for a list of common commands\n"
   626    607          "   or: %s help COMMAND   -- for help with the named command\n",
   627    608          g.argv[0], g.argv[0], g.argv[0]);
   628    609       fossil_print(
   629    610         "\nCommands and filenames may be passed on to fossil from a file\n"

Changes to src/manifest.c.

  1752   1752       db_reset(&u);
  1753   1753     }
  1754   1754     db_finalize(&q);
  1755   1755     db_finalize(&u);
  1756   1756     if( db_exists("SELECT 1 FROM time_fudge") ){
  1757   1757       db_multi_exec(
  1758   1758         "UPDATE event SET mtime=(SELECT m1 FROM time_fudge WHERE mid=objid)"
  1759         -      " WHERE objid IN (SELECT mid FROM time_fudge)"
  1760         -      " AND (mtime=omtime OR omtime IS NULL)"
         1759  +      " WHERE objid IN (SELECT mid FROM time_fudge);"
  1761   1760       );
  1762   1761     }
  1763   1762     db_multi_exec("DROP TABLE time_fudge;");
  1764   1763   
  1765   1764     db_end_transaction(0);
  1766   1765     manifest_crosslink_busy = 0;
  1767   1766     return ( rc!=TH_ERROR );
................................................................................
  1928   1927     int i, rc = TH_OK;
  1929   1928     Manifest *p;
  1930   1929     int parentid = 0;
  1931   1930     int permitHooks = (flags & MC_PERMIT_HOOKS);
  1932   1931     const char *zScript = 0;
  1933   1932     const char *zUuid = 0;
  1934   1933   
  1935         -  if( g.fSqlTrace ){
  1936         -    fossil_trace("-- manifest_crosslink(%d)\n", rid);
  1937         -  }
  1938   1934     if( (p = manifest_cache_find(rid))!=0 ){
  1939   1935       blob_reset(pContent);
  1940   1936     }else if( (p = manifest_parse(pContent, rid, 0))==0 ){
  1941   1937       assert( blob_is_reset(pContent) || pContent==0 );
  1942   1938       if( (flags & MC_NO_ERRORS)==0 ){
  1943   1939         fossil_error(1, "syntax error in manifest [%S]",
  1944   1940                      db_text(0, "SELECT uuid FROM blob WHERE rid=%d",rid));

Changes to src/merge.c.

   285    285       ** leaf that is (1) not the version currently checked out and (2)
   286    286       ** has not already been merged into the current checkout and (3)
   287    287       ** the leaf is not closed and (4) the leaf is in the same branch
   288    288       ** as the current checkout.
   289    289       */
   290    290       Stmt q;
   291    291       if( pickFlag || backoutFlag || integrateFlag){
   292         -      fossil_fatal("cannot use --backout, --cherrypick or --integrate "
   293         -                   "with a fork merge");
          292  +      fossil_fatal("cannot use --backout, --cherrypick or --integrate with a fork merge");
   294    293       }
   295    294       mid = fossil_find_nearest_fork(vid, db_open_local(0));
   296    295       if( mid==0 ){
   297    296         fossil_fatal("no unmerged forks of branch \"%s\"",
   298    297           db_text(0, "SELECT value FROM tagxref"
   299    298                      " WHERE tagid=%d AND rid=%d AND tagtype>0",
   300    299                      TAG_BRANCH, vid)
................................................................................
   324    323   
   325    324     if( zPivot ){
   326    325       pid = name_to_typed_rid(zPivot, "ci");
   327    326       if( pid==0 || !is_a_version(pid) ){
   328    327         fossil_fatal("not a version: %s", zPivot);
   329    328       }
   330    329       if( pickFlag ){
   331         -      fossil_fatal("incompatible options: --cherrypick and --baseline");
          330  +      fossil_fatal("incompatible options: --cherrypick & --baseline");
   332    331       }
   333    332     }
   334    333     if( pickFlag || backoutFlag ){
   335    334       if( integrateFlag ){
   336         -      fossil_fatal("incompatible options: --integrate and --cherrypick "
   337         -                   "with --backout");
          335  +      fossil_fatal("incompatible options: --integrate & --cherrypick or --backout");
   338    336       }
   339    337       pid = db_int(0, "SELECT pid FROM plink WHERE cid=%d AND isprim", mid);
   340    338       if( pid<=0 ){
   341    339         fossil_fatal("cannot find an ancestor for %s", g.argv[2]);
   342    340       }
   343    341     }else{
   344    342       if( !zPivot ){
................................................................................
   379    377       return;
   380    378     }
   381    379     if( integrateFlag && !is_a_leaf(mid)){
   382    380       fossil_warning("ignoring --integrate: %s is not a leaf", g.argv[2]);
   383    381       integrateFlag = 0;
   384    382     }
   385    383     if( verboseFlag ){
   386         -    print_checkin_description(mid, 12,
   387         -              integrateFlag ? "integrate:" : "merge-from:");
          384  +    print_checkin_description(mid, 12, integrateFlag?"integrate:":"merge-from:");
   388    385       print_checkin_description(pid, 12, "baseline:");
   389    386     }
   390    387     vfile_check_signature(vid, CKSIG_ENOTFILE);
   391    388     db_begin_transaction();
   392    389     if( !dryRunFlag ) undo_begin();
   393    390     if( load_vfile_from_rid(mid) && !forceMissingFlag ){
   394    391       fossil_fatal("missing content, unable to merge");

Changes to src/path.c.

   545    545       g.argv += 2;
   546    546       g.argc -= 2;
   547    547     }
   548    548   }
   549    549   
   550    550   /* Query to extract all rename operations */
   551    551   static const char zRenameQuery[] =
   552         -@ CREATE TEMP TABLE renames AS
   553    552   @ SELECT
   554         -@     datetime(event.mtime) AS date,
          553  +@     datetime(event.mtime),
   555    554   @     F.name AS old_name,
   556    555   @     T.name AS new_name,
   557         -@     blob.uuid AS checkin
   558         -@   FROM mlink, filename F, filename T, event, blob
   559         -@  WHERE coalesce(mlink.pfnid,0)!=0 AND mlink.pfnid!=mlink.fnid
   560         -@    AND F.fnid=mlink.pfnid
   561         -@    AND T.fnid=mlink.fnid
   562         -@    AND event.objid=mlink.mid
   563         -@    AND event.type='ci'
   564         -@    AND blob.rid=mlink.mid;
   565         -;
   566         -
   567         -/* Query to extract distinct rename operations */
   568         -static const char zDistinctRenameQuery[] =
   569         -@ CREATE TEMP TABLE renames AS
   570         -@ SELECT
   571         -@     min(datetime(event.mtime)) AS date,
   572         -@     F.name AS old_name,
   573         -@     T.name AS new_name,
   574         -@     blob.uuid AS checkin
          556  +@     blob.uuid
   575    557   @   FROM mlink, filename F, filename T, event, blob
   576    558   @  WHERE coalesce(mlink.pfnid,0)!=0 AND mlink.pfnid!=mlink.fnid
   577    559   @    AND F.fnid=mlink.pfnid
   578    560   @    AND T.fnid=mlink.fnid
   579    561   @    AND event.objid=mlink.mid
   580    562   @    AND event.type='ci'
   581    563   @    AND blob.rid=mlink.mid
   582         -@  GROUP BY 2, 3;
          564  +@  ORDER BY 1 DESC, 2;
   583    565   ;
   584    566   
   585    567   /*
   586    568   ** WEBPAGE: test-rename-list
   587    569   **
   588    570   ** Print a list of all file rename operations throughout history.
   589    571   ** This page is intended for for testing purposes only and may change
   590    572   ** or be discontinued without notice.
   591    573   */
   592    574   void test_rename_list_page(void){
   593    575     Stmt q;
   594         -  int nRename;
   595         -  int nCheckin;
   596    576   
   597    577     login_check_credentials();
   598    578     if( !g.perm.Read ){ login_needed(g.anon.Read); return; }
   599         -  if( P("all")!=0 ){
   600         -    style_header("List Of All Filename Changes");
   601         -    db_multi_exec("%s", zRenameQuery/*safe-for-%s*/);
   602         -    style_submenu_element("Distinct", "%R/test-rename-list");
   603         -  }else{
   604         -    style_header("List Of Distinct Filename Changes");
   605         -    db_multi_exec("%s", zDistinctRenameQuery/*safe-for-%s*/);
   606         -    style_submenu_element("All", "%R/test-rename-list?all");
   607         -  }
   608         -  nRename = db_int(0, "SELECT count(*) FROM renames;");
   609         -  nCheckin = db_int(0, "SELECT count(DISTINCT checkin) FROM renames;");
   610         -  db_prepare(&q, "SELECT date, old_name, new_name, checkin FROM renames"
   611         -                 " ORDER BY date DESC, old_name ASC");
   612         -  @ <h1>%d(nRename) filename changes in %d(nCheckin) check-ins</h1>
   613         -  @ <table class='sortable' data-column-types='tttt' data-init-sort='1'\
   614         -  @  border="1" cellpadding="2" cellspacing="0">
   615         -  @ <thead><tr><th>Date &amp; Time</th>
          579  +  style_header("List Of File Name Changes");
          580  +  @ <h3>NB: Experimental Page</h3>
          581  +  @ <table border="1" width="100%%">
          582  +  @ <tr><th>Date &amp; Time</th>
   616    583     @ <th>Old Name</th>
   617    584     @ <th>New Name</th>
   618         -  @ <th>Check-in</th></tr></thead><tbody>
          585  +  @ <th>Check-in</th></tr>
          586  +  db_prepare(&q, "%s", zRenameQuery/*safe-for-%s*/);
   619    587     while( db_step(&q)==SQLITE_ROW ){
   620    588       const char *zDate = db_column_text(&q, 0);
   621    589       const char *zOld = db_column_text(&q, 1);
   622    590       const char *zNew = db_column_text(&q, 2);
   623    591       const char *zUuid = db_column_text(&q, 3);
   624    592       @ <tr>
   625    593       @ <td>%z(href("%R/timeline?c=%t",zDate))%s(zDate)</a></td>
   626    594       @ <td>%z(href("%R/finfo?name=%t",zOld))%h(zOld)</a></td>
   627    595       @ <td>%z(href("%R/finfo?name=%t",zNew))%h(zNew)</a></td>
   628    596       @ <td>%z(href("%R/info/%!S",zUuid))%S(zUuid)</a></td></tr>
   629    597     }
   630         -  @ </tbody></table>
          598  +  @ </table>
   631    599     db_finalize(&q);
   632         -  style_table_sorter();
   633    600     style_footer();
   634    601   }

Changes to src/pivot.c.

    36     36   **
    37     37   ** The act of setting the primary resets the pivot-finding algorithm.
    38     38   */
    39     39   void pivot_set_primary(int rid){
    40     40     /* Set up table used to do the search */
    41     41     db_multi_exec(
    42     42       "CREATE TEMP TABLE IF NOT EXISTS aqueue("
    43         -    "  rid INTEGER,"              /* The record id for this version */
           43  +    "  rid INTEGER PRIMARY KEY,"  /* The record id for this version */
    44     44       "  mtime REAL,"               /* Time when this version was created */
    45     45       "  pending BOOLEAN,"          /* True if we have not check this one yet */
    46         -    "  src BOOLEAN,"               /* 1 for primary.  0 for others */
    47         -    "  PRIMARY KEY(rid,src)"
    48         -    ") WITHOUT ROWID;"
           46  +    "  src BOOLEAN"               /* 1 for primary.  0 for others */
           47  +    ");"
    49     48       "DELETE FROM aqueue;"
    50     49       "CREATE INDEX IF NOT EXISTS aqueue_idx1 ON aqueue(pending, mtime);"
    51     50     );
    52     51   
    53     52     /* Insert the primary record */
    54     53     db_multi_exec(
    55     54       "INSERT INTO aqueue(rid, mtime, pending, src)"
................................................................................
   117    116     db_prepare(&u1,
   118    117       "UPDATE aqueue SET pending=0 WHERE rid=:rid"
   119    118     );
   120    119   
   121    120     /* Add to the queue all ancestors of :rid.
   122    121     */
   123    122     db_prepare(&i1,
   124         -    "REPLACE INTO aqueue "
          123  +    "INSERT OR IGNORE INTO aqueue "
   125    124       "SELECT plink.pid,"
   126         -    "       coalesce((SELECT mtime FROM event X WHERE X.objid=plink.pid), 0.0),"
          125  +    "       coalesce((SELECT mtime FROM plink X WHERE X.cid=plink.pid), 0.0),"
   127    126       "       1,"
   128    127       "       aqueue.src "
   129    128       "  FROM plink, aqueue"
   130    129       " WHERE plink.cid=:rid"
   131    130       "   AND aqueue.rid=:rid %s",
   132    131       ignoreMerges ? "AND plink.isprim" : ""
   133    132     );

Changes to src/regexp.c.

   734    734   */
   735    735   int re_add_sql_func(sqlite3 *db){
   736    736     return sqlite3_create_function(db, "regexp", 2, SQLITE_UTF8, 0,
   737    737                                    re_sql_func, 0, 0);
   738    738   }
   739    739   
   740    740   /*
   741         -** Run a "grep" over a single file read from disk.
          741  +** Run a "grep" over a single file
   742    742   */
   743         -static void grep_file(ReCompiled *pRe, const char *zFile, FILE *in){
          743  +static void grep(ReCompiled *pRe, const char *zFile, FILE *in){
   744    744     int ln = 0;
   745    745     int n;
   746    746     char zLine[2000];
   747    747     while( fgets(zLine, sizeof(zLine), in) ){
   748    748       ln++;
   749    749       n = (int)strlen(zLine);
   750    750       while( n && (zLine[n-1]=='\n' || zLine[n-1]=='\r') ) n--;
   751    751       if( re_match(pRe, (const unsigned char*)zLine, n) ){
   752         -      fossil_print("%s:%d:%.*s\n", zFile, ln, n, zLine);
          752  +      printf("%s:%d:%.*s\n", zFile, ln, n, zLine);
   753    753       }
   754    754     }
   755    755   }
   756    756   
   757         -/*
   758         -** Flags for grep_buffer()
   759         -*/
   760         -#define GREP_EXISTS    0x001    /* If any match, print only the name and stop */
   761         -
   762         -/*
   763         -** Run a "grep" over a text file
   764         -*/
   765         -static int grep_buffer(
   766         -  ReCompiled *pRe,
   767         -  const char *zName,
   768         -  const char *z,
   769         -  u32 flags
   770         -){
   771         -  int i, j, n, ln, cnt;
   772         -  for(i=j=ln=cnt=0; z[i]; i=j+1){
   773         -    for(j=i; z[j] && z[j]!='\n'; j++){}
   774         -    n = j - i;
   775         -    if( z[j]=='\n' ) j++;
   776         -    ln++;
   777         -    if( re_match(pRe, (const unsigned char*)(z+i), j-i) ){
   778         -      cnt++;
   779         -      if( flags & GREP_EXISTS ){
   780         -        fossil_print("%s\n", zName);
   781         -        break;
   782         -      }
   783         -      fossil_print("%s:%d:%.*s\n", zName, ln, n, z+i);
   784         -    }
   785         -  }
   786         -  return cnt;
   787         -}
   788         -
   789    757   /*
   790    758   ** COMMAND: test-grep
   791    759   **
   792    760   ** Usage: %fossil test-grep REGEXP [FILE...]
   793    761   **
   794    762   ** Run a regular expression match over the named disk files, or against
   795    763   ** standard input if no disk files are named on the command-line.
................................................................................
   804    772     int ignoreCase = find_option("ignore-case","i",0)!=0;
   805    773     if( g.argc<3 ){
   806    774       usage("REGEXP [FILE...]");
   807    775     }
   808    776     zErr = re_compile(&pRe, g.argv[2], ignoreCase);
   809    777     if( zErr ) fossil_fatal("%s", zErr);
   810    778     if( g.argc==3 ){
   811         -    grep_file(pRe, "-", stdin);
          779  +    grep(pRe, "-", stdin);
   812    780     }else{
   813    781       int i;
   814    782       for(i=3; i<g.argc; i++){
   815    783         FILE *in = fossil_fopen(g.argv[i], "rb");
   816    784         if( in==0 ){
   817    785           fossil_warning("cannot open \"%s\"", g.argv[i]);
   818    786         }else{
   819         -        grep_file(pRe, g.argv[i], in);
          787  +        grep(pRe, g.argv[i], in);
   820    788           fclose(in);
   821    789         }
   822    790       }
   823    791     }
   824    792     re_free(pRe);
   825    793   }
   826         -
   827         -/*
   828         -** COMMAND: grep
   829         -**
   830         -** Usage: %fossil grep [OPTIONS] PATTERN FILENAME
   831         -**
   832         -** Run grep over all historic version of FILENAME
   833         -**
   834         -** Options:
   835         -**
   836         -**     -i|--ignore-case         Ignore case
   837         -**     -l|--files-with-matches  Print only filenames that match
   838         -**     -v|--verbose             Show each file as it is analyzed
   839         -*/
   840         -void re_grep_cmd(void){
   841         -  u32 flags = 0;
   842         -  int bVerbose = 0;
   843         -  ReCompiled *pRe;
   844         -  const char *zErr;
   845         -  int ignoreCase = 0;
   846         -  Blob fullName;
   847         -
   848         -  if( find_option("ignore-case","i",0)!=0 ) ignoreCase = 1;
   849         -  if( find_option("files-with-matches","l",0)!=0 ) flags |= GREP_EXISTS;
   850         -  if( find_option("verbose","v",0)!=0 ) bVerbose = 1;
   851         -  db_find_and_open_repository(0, 0);
   852         -  verify_all_options();
   853         -  if( g.argc<3 ){
   854         -    usage("REGEXP FILENAME");
   855         -  }
   856         -  zErr = re_compile(&pRe, g.argv[2], ignoreCase);
   857         -  if( zErr ) fossil_fatal("%s", zErr);
   858         -
   859         -  if( file_tree_name(g.argv[3], &fullName, 0, 0) ){
   860         -    int fnid = db_int(0, "SELECT fnid FROM filename WHERE name=%Q",
   861         -                      blob_str(&fullName));
   862         -    if( fnid ){
   863         -      Stmt q;
   864         -      add_content_sql_commands(g.db);
   865         -      db_prepare(&q,
   866         -        "SELECT content(ux), substr(ux,1,10) FROM ("
   867         -        "  SELECT blob.uuid AS ux, min(event.mtime) AS mx"
   868         -        "    FROM mlink, blob, event"
   869         -        "   WHERE mlink.mid=event.objid"
   870         -        "     AND mlink.fid=blob.rid"
   871         -        "     AND mlink.fnid=%d"
   872         -        "   GROUP BY blob.uuid"
   873         -        ") ORDER BY mx DESC;",
   874         -        fnid
   875         -      );
   876         -      while( db_step(&q)==SQLITE_ROW ){
   877         -        if( bVerbose ) fossil_print("%s:\n", db_column_text(&q,1));
   878         -        grep_buffer(pRe, db_column_text(&q,1), db_column_text(&q,0), flags);
   879         -      }
   880         -      db_finalize(&q);
   881         -    }
   882         -  }
   883         -}

Changes to src/shell.c.

  7615   7615       IdxHashEntry *pEntry;
  7616   7616       sqlite3_stmt *pExplain = 0;
  7617   7617       idxHashClear(&hIdx);
  7618   7618       rc = idxPrintfPrepareStmt(dbm, &pExplain, pzErr,
  7619   7619           "EXPLAIN QUERY PLAN %s", pStmt->zSql
  7620   7620       );
  7621   7621       while( rc==SQLITE_OK && sqlite3_step(pExplain)==SQLITE_ROW ){
  7622         -      /* int iId = sqlite3_column_int(pExplain, 0); */
  7623         -      /* int iParent = sqlite3_column_int(pExplain, 1); */
  7624         -      /* int iNotUsed = sqlite3_column_int(pExplain, 2); */
         7622  +      int iSelectid = sqlite3_column_int(pExplain, 0);
         7623  +      int iOrder = sqlite3_column_int(pExplain, 1);
         7624  +      int iFrom = sqlite3_column_int(pExplain, 2);
  7625   7625         const char *zDetail = (const char*)sqlite3_column_text(pExplain, 3);
  7626   7626         int nDetail = STRLEN(zDetail);
  7627   7627         int i;
  7628   7628   
  7629   7629         for(i=0; i<nDetail; i++){
  7630   7630           const char *zIdx = 0;
  7631   7631           if( memcmp(&zDetail[i], " USING INDEX ", 13)==0 ){
................................................................................
  7644   7644               idxHashAdd(&rc, &hIdx, zSql, 0);
  7645   7645               if( rc ) goto find_indexes_out;
  7646   7646             }
  7647   7647             break;
  7648   7648           }
  7649   7649         }
  7650   7650   
  7651         -      if( zDetail[0]!='-' ){
  7652         -        pStmt->zEQP = idxAppendText(&rc, pStmt->zEQP, "%s\n", zDetail);
  7653         -      }
         7651  +      pStmt->zEQP = idxAppendText(&rc, pStmt->zEQP, "%d|%d|%d|%s\n", 
         7652  +          iSelectid, iOrder, iFrom, zDetail
         7653  +      );
  7654   7654       }
  7655   7655   
  7656   7656       for(pEntry=hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
  7657   7657         pStmt->zIdx = idxAppendText(&rc, pStmt->zIdx, "%s;\n", pEntry->zKey);
  7658   7658       }
  7659   7659   
  7660   7660       idxFinalize(&rc, pExplain);
................................................................................
  8479   8479     sqlite3expert *pExpert;
  8480   8480     int bVerbose;
  8481   8481   };
  8482   8482   
  8483   8483   /* A single line in the EQP output */
  8484   8484   typedef struct EQPGraphRow EQPGraphRow;
  8485   8485   struct EQPGraphRow {
  8486         -  int iEqpId;           /* ID for this row */
  8487         -  int iParentId;        /* ID of the parent row */
         8486  +  int iSelectId;        /* The SelectID for this row */
  8488   8487     EQPGraphRow *pNext;   /* Next row in sequence */
  8489   8488     char zText[1];        /* Text to display for this row */
  8490   8489   };
  8491   8490   
  8492   8491   /* All EQP output is collected into an instance of the following */
  8493   8492   typedef struct EQPGraph EQPGraph;
  8494   8493   struct EQPGraph {
................................................................................
  8502   8501   ** instance of the following structure.
  8503   8502   */
  8504   8503   typedef struct ShellState ShellState;
  8505   8504   struct ShellState {
  8506   8505     sqlite3 *db;           /* The database */
  8507   8506     u8 autoExplain;        /* Automatically turn on .explain mode */
  8508   8507     u8 autoEQP;            /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
  8509         -  u8 autoEQPtest;        /* autoEQP is in test mode */
  8510   8508     u8 statsOn;            /* True to display memory stats before each finalize */
  8511   8509     u8 scanstatsOn;        /* True to display scan stats before each finalize */
  8512   8510     u8 openMode;           /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
  8513   8511     u8 doXdgOpen;          /* Invoke start/open/xdg-open in output_reset() */
  8514   8512     u8 nEqpLevel;          /* Depth of the EQP output graph */
  8515   8513     unsigned mEqpLines;    /* Mask of veritical lines in the EQP output graph */
  8516   8514     int outCount;          /* Revert to stdout when reaching zero */
................................................................................
  8553   8551   #endif
  8554   8552     ExpertInfo expert;        /* Valid if previous command was ".expert OPT..." */
  8555   8553   };
  8556   8554   
  8557   8555   
  8558   8556   /* Allowed values for ShellState.autoEQP
  8559   8557   */
  8560         -#define AUTOEQP_off      0           /* Automatic EXPLAIN QUERY PLAN is off */
  8561         -#define AUTOEQP_on       1           /* Automatic EQP is on */
  8562         -#define AUTOEQP_trigger  2           /* On and also show plans for triggers */
  8563         -#define AUTOEQP_full     3           /* Show full EXPLAIN */
         8558  +#define AUTOEQP_off      0
         8559  +#define AUTOEQP_on       1
         8560  +#define AUTOEQP_trigger  2
         8561  +#define AUTOEQP_full     3
  8564   8562   
  8565   8563   /* Allowed values for ShellState.openMode
  8566   8564   */
  8567   8565   #define SHELL_OPEN_UNSPEC     0      /* No open-mode specified */
  8568   8566   #define SHELL_OPEN_NORMAL     1      /* Normal database file */
  8569   8567   #define SHELL_OPEN_APPENDVFS  2      /* Use appendvfs */
  8570   8568   #define SHELL_OPEN_ZIPFILE    3      /* Use the zipfile virtual table */
................................................................................
  9167   9165     }
  9168   9166     return 1;
  9169   9167   }
  9170   9168   
  9171   9169   /*
  9172   9170   ** Add a new entry to the EXPLAIN QUERY PLAN data
  9173   9171   */
  9174         -static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
         9172  +static void eqp_append(ShellState *p, int iSelectId, const char *zText){
  9175   9173     EQPGraphRow *pNew;
  9176   9174     int nText = strlen30(zText);
  9177         -  if( p->autoEQPtest ){
  9178         -    utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
  9179         -  }
  9180   9175     pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
  9181   9176     if( pNew==0 ) shell_out_of_memory();
  9182         -  pNew->iEqpId = iEqpId;
  9183         -  pNew->iParentId = p2;
         9177  +  pNew->iSelectId = iSelectId;
  9184   9178     memcpy(pNew->zText, zText, nText+1);
  9185   9179     pNew->pNext = 0;
  9186   9180     if( p->sGraph.pLast ){
  9187   9181       p->sGraph.pLast->pNext = pNew;
  9188   9182     }else{
  9189   9183       p->sGraph.pRow = pNew;
  9190   9184     }
................................................................................
  9200   9194     for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
  9201   9195       pNext = pRow->pNext;
  9202   9196       sqlite3_free(pRow);
  9203   9197     }
  9204   9198     memset(&p->sGraph, 0, sizeof(p->sGraph));
  9205   9199   }
  9206   9200   
  9207         -/* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
         9201  +/* Return the next EXPLAIN QUERY PLAN line with iSelectId that occurs after
  9208   9202   ** pOld, or return the first such line if pOld is NULL
  9209   9203   */
  9210         -static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
         9204  +static EQPGraphRow *eqp_next_row(ShellState *p, int iSelectId, EQPGraphRow *pOld){
  9211   9205     EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
  9212         -  while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
         9206  +  while( pRow && pRow->iSelectId!=iSelectId ) pRow = pRow->pNext;
  9213   9207     return pRow;
  9214   9208   }
  9215   9209   
  9216         -/* Render a single level of the graph that has iEqpId as its parent.  Called
         9210  +/* Render a single level of the graph shell having iSelectId.  Called
  9217   9211   ** recursively to render sublevels.
  9218   9212   */
  9219         -static void eqp_render_level(ShellState *p, int iEqpId){
         9213  +static void eqp_render_level(ShellState *p, int iSelectId){
  9220   9214     EQPGraphRow *pRow, *pNext;
         9215  +  int i;
  9221   9216     int n = strlen30(p->sGraph.zPrefix);
  9222   9217     char *z;
  9223         -  for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
  9224         -    pNext = eqp_next_row(p, iEqpId, pRow);
         9218  +  for(pRow = eqp_next_row(p, iSelectId, 0); pRow; pRow = pNext){
         9219  +    pNext = eqp_next_row(p, iSelectId, pRow);
  9225   9220       z = pRow->zText;
  9226   9221       utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix, pNext ? "|--" : "`--", z);
  9227         -    if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){
         9222  +    if( n<sizeof(p->sGraph.zPrefix)-7 && (z = strstr(z, " SUBQUER"))!=0 ){
  9228   9223         memcpy(&p->sGraph.zPrefix[n], pNext ? "|  " : "   ", 4);
  9229         -      eqp_render_level(p, pRow->iEqpId);
         9224  +      if( strncmp(z, " SUBQUERY ", 9)==0 && (i = atoi(z+10))>iSelectId ){
         9225  +        eqp_render_level(p, i);
         9226  +      }else if( strncmp(z, " SUBQUERIES ", 12)==0 ){
         9227  +        i = atoi(z+12);
         9228  +        if( i>iSelectId ){
         9229  +          utf8_printf(p->out, "%s|--SUBQUERY %d\n", p->sGraph.zPrefix, i);
         9230  +          memcpy(&p->sGraph.zPrefix[n+3],"|  ",4);
         9231  +          eqp_render_level(p, i);
         9232  +        }
         9233  +        z = strstr(z, " AND ");
         9234  +        if( z && (i = atoi(z+5))>iSelectId ){
         9235  +          p->sGraph.zPrefix[n+3] = 0;
         9236  +          utf8_printf(p->out, "%s`--SUBQUERY %d\n", p->sGraph.zPrefix, i);
         9237  +          memcpy(&p->sGraph.zPrefix[n+3],"   ",4);
         9238  +          eqp_render_level(p, i);
         9239  +        }
         9240  +      }
  9230   9241         p->sGraph.zPrefix[n] = 0;
  9231   9242       }
  9232   9243     }
  9233   9244   }
  9234   9245   
  9235   9246   /*
  9236   9247   ** Display and reset the EXPLAIN QUERY PLAN data
................................................................................
  9601   9612           if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
  9602   9613           utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
  9603   9614         }
  9604   9615         utf8_printf(p->out, "%s", p->rowSeparator);
  9605   9616         break;
  9606   9617       }
  9607   9618       case MODE_EQP: {
  9608         -      eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
         9619  +      eqp_append(p, atoi(azArg[0]), azArg[3]);
  9609   9620         break;
  9610   9621       }
  9611   9622     }
  9612   9623     return 0;
  9613   9624   }
  9614   9625   
  9615   9626   /*
................................................................................
 10065  10076   static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
 10066  10077     const char *zSql;               /* The text of the SQL statement */
 10067  10078     const char *z;                  /* Used to check if this is an EXPLAIN */
 10068  10079     int *abYield = 0;               /* True if op is an OP_Yield */
 10069  10080     int nAlloc = 0;                 /* Allocated size of p->aiIndent[], abYield */
 10070  10081     int iOp;                        /* Index of operation in p->aiIndent[] */
 10071  10082   
 10072         -  const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext", 0 };
        10083  +  const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
        10084  +                           "NextIfOpen", "PrevIfOpen", 0 };
 10073  10085     const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
 10074  10086                               "Rewind", 0 };
 10075  10087     const char *azGoto[] = { "Goto", 0 };
 10076  10088   
 10077  10089     /* Try to figure out if this is really an EXPLAIN statement. If this
 10078  10090     ** cannot be verified, return early.  */
 10079  10091     if( sqlite3_column_count(pSql)!=8 ){
................................................................................
 10442  10454             sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
 10443  10455           }
 10444  10456           zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
 10445  10457           rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
 10446  10458           if( rc==SQLITE_OK ){
 10447  10459             while( sqlite3_step(pExplain)==SQLITE_ROW ){
 10448  10460               const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
 10449         -            int iEqpId = sqlite3_column_int(pExplain, 0);
 10450         -            int iParentId = sqlite3_column_int(pExplain, 1);
        10461  +            int iSelectId = sqlite3_column_int(pExplain, 0);
 10451  10462               if( zEQPLine[0]=='-' ) eqp_render(pArg);
 10452         -            eqp_append(pArg, iEqpId, iParentId, zEQPLine);
        10463  +            eqp_append(pArg, iSelectId, zEQPLine);
 10453  10464             }
 10454  10465             eqp_render(pArg);
 10455  10466           }
 10456  10467           sqlite3_finalize(pExplain);
 10457  10468           sqlite3_free(zEQP);
 10458  10469           if( pArg->autoEQP>=AUTOEQP_full ){
 10459  10470             /* Also do an EXPLAIN for ".eqp full" mode */
................................................................................
 10469  10480             sqlite3_free(zEQP);
 10470  10481           }
 10471  10482           if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
 10472  10483             sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
 10473  10484             /* Reprepare pStmt before reactiving trace modes */
 10474  10485             sqlite3_finalize(pStmt);
 10475  10486             sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
 10476         -          if( pArg ) pArg->pStmt = pStmt;
 10477  10487           }
 10478  10488           restore_debug_trace_modes();
 10479  10489         }
 10480  10490   
 10481  10491         if( pArg ){
 10482  10492           pArg->cMode = pArg->mode;
 10483  10493           if( pArg->autoExplain ){
................................................................................
 10821  10831   #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
 10822  10832     ".archive ...           Manage SQL archives: \".archive --help\" for details\n"
 10823  10833   #endif
 10824  10834   #ifndef SQLITE_OMIT_AUTHORIZATION
 10825  10835     ".auth ON|OFF           Show authorizer callbacks\n"
 10826  10836   #endif
 10827  10837     ".backup ?DB? FILE      Backup DB (default \"main\") to FILE\n"
 10828         -  "                         Add \"--append\" to open using appendvfs.\n"
 10829  10838     ".bail on|off           Stop after hitting an error.  Default OFF\n"
 10830  10839     ".binary on|off         Turn binary output on or off.  Default OFF\n"
 10831  10840     ".cd DIRECTORY          Change the working directory to DIRECTORY\n"
 10832  10841     ".changes on|off        Show number of rows changed by SQL\n"
 10833  10842     ".check GLOB            Fail if output since .testcase does not match\n"
 10834  10843     ".clone NEWDB           Clone data into NEWDB from the existing database\n"
 10835  10844     ".databases             List names and files of attached databases\n"
 10836         -  ".dbconfig ?op? ?val?   List or change sqlite3_db_config() options\n"
 10837  10845     ".dbinfo ?DB?           Show status information about the database\n"
 10838  10846     ".dump ?TABLE? ...      Dump the database in an SQL text format\n"
 10839  10847     "                         If TABLE specified, only dump tables matching\n"
 10840  10848     "                         LIKE pattern TABLE.\n"
 10841  10849     ".echo on|off           Turn command echo on or off\n"
 10842  10850     ".eqp on|off|full       Enable or disable automatic EXPLAIN QUERY PLAN\n"
 10843  10851     ".excel                 Display the output of next command in a spreadsheet\n"
................................................................................
 11039  11047   ** one of the SHELL_OPEN_* constants.
 11040  11048   **
 11041  11049   ** If the file does not exist or is empty but its name looks like a ZIP
 11042  11050   ** archive and the dfltZip flag is true, then assume it is a ZIP archive.
 11043  11051   ** Otherwise, assume an ordinary database regardless of the filename if
 11044  11052   ** the type cannot be determined from content.
 11045  11053   */
 11046         -int deduceDatabaseType(const char *zName, int dfltZip){
        11054  +static int deduceDatabaseType(const char *zName, int dfltZip){
 11047  11055     FILE *f = fopen(zName, "rb");
 11048  11056     size_t n;
 11049  11057     int rc = SHELL_OPEN_UNSPEC;
 11050  11058     char zBuf[100];
 11051  11059     if( f==0 ){
 11052         -    if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
 11053         -       return SHELL_OPEN_ZIPFILE;
 11054         -    }else{
 11055         -       return SHELL_OPEN_NORMAL;
 11056         -    }
        11060  +    if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ) return SHELL_OPEN_ZIPFILE;
        11061  +    return SHELL_OPEN_NORMAL;
 11057  11062     }
 11058  11063     fseek(f, -25, SEEK_END);
 11059  11064     n = fread(zBuf, 25, 1, f);
 11060  11065     if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
 11061  11066       rc = SHELL_OPEN_APPENDVFS;
 11062  11067     }else{
 11063  11068       fseek(f, -22, SEEK_END);
 11064  11069       n = fread(zBuf, 22, 1, f);
 11065  11070       if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
 11066  11071          && zBuf[3]==0x06 ){
 11067  11072         rc = SHELL_OPEN_ZIPFILE;
 11068  11073       }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
 11069         -      rc = SHELL_OPEN_ZIPFILE;
        11074  +      return SHELL_OPEN_ZIPFILE;
 11070  11075       }
 11071  11076     }
 11072  11077     fclose(f);
 11073  11078     return rc;  
 11074  11079   }
 11075  11080   
 11076         -/* Flags for open_db().
 11077         -**
 11078         -** The default behavior of open_db() is to exit(1) if the database fails to
 11079         -** open.  The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
 11080         -** but still returns without calling exit.
 11081         -**
 11082         -** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
 11083         -** ZIP archive if the file does not exist or is empty and its name matches
 11084         -** the *.zip pattern.
 11085         -*/
 11086         -#define OPEN_DB_KEEPALIVE   0x001   /* Return after error if true */
 11087         -#define OPEN_DB_ZIPFILE     0x002   /* Open as ZIP if name matches *.zip */
 11088         -
 11089  11081   /*
 11090  11082   ** Make sure the database is open.  If it is not, then open it.  If
 11091  11083   ** the database fails to open, print an error message and exit.
 11092  11084   */
 11093         -static void open_db(ShellState *p, int openFlags){
        11085  +static void open_db(ShellState *p, int keepAlive){
 11094  11086     if( p->db==0 ){
 11095         -    if( p->openMode==SHELL_OPEN_UNSPEC ){
 11096         -      if( p->zDbFilename==0 || p->zDbFilename[0]==0 ){
 11097         -        p->openMode = SHELL_OPEN_NORMAL;
 11098         -      }else{
 11099         -        p->openMode = (u8)deduceDatabaseType(p->zDbFilename, 
 11100         -                             (openFlags & OPEN_DB_ZIPFILE)!=0);
 11101         -      }
        11087  +    if( p->openMode==SHELL_OPEN_UNSPEC && access(p->zDbFilename,0)==0 ){
        11088  +      p->openMode = (u8)deduceDatabaseType(p->zDbFilename, 0);
 11102  11089       }
 11103  11090       switch( p->openMode ){
 11104  11091         case SHELL_OPEN_APPENDVFS: {
 11105  11092           sqlite3_open_v2(p->zDbFilename, &p->db, 
 11106  11093              SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, "apndvfs");
 11107  11094           break;
 11108  11095         }
................................................................................
 11120  11107           break;
 11121  11108         }
 11122  11109       }
 11123  11110       globalDb = p->db;
 11124  11111       if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
 11125  11112         utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
 11126  11113             p->zDbFilename, sqlite3_errmsg(p->db));
 11127         -      if( openFlags & OPEN_DB_KEEPALIVE ) return;
        11114  +      if( keepAlive ) return;
 11128  11115         exit(1);
 11129  11116       }
 11130  11117   #ifndef SQLITE_OMIT_LOAD_EXTENSION
 11131  11118       sqlite3_enable_load_extension(p->db, 1);
 11132  11119   #endif
 11133  11120       sqlite3_fileio_init(p->db, 0, 0);
 11134  11121       sqlite3_shathree_init(p->db, 0, 0);
................................................................................
 11154  11141            "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", p->zDbFilename);
 11155  11142         sqlite3_exec(p->db, zSql, 0, 0, 0);
 11156  11143         sqlite3_free(zSql);
 11157  11144       }
 11158  11145     }
 11159  11146   }
 11160  11147   
 11161         -/*
 11162         -** Attempt to close the databaes connection.  Report errors.
 11163         -*/
 11164         -void close_db(sqlite3 *db){
 11165         -  int rc = sqlite3_close(db);
 11166         -  if( rc ){
 11167         -    utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
 11168         -        rc, sqlite3_errmsg(db));
 11169         -  } 
 11170         -}
 11171         -
 11172  11148   #if HAVE_READLINE || HAVE_EDITLINE
 11173  11149   /*
 11174  11150   ** Readline completion callbacks
 11175  11151   */
 11176  11152   static char *readline_completion_generator(const char *text, int state){
 11177  11153     static sqlite3_stmt *pStmt = 0;
 11178  11154     char *zRet;
................................................................................
 11206  11182     int nLine = strlen30(zLine);
 11207  11183     int i, iStart;
 11208  11184     sqlite3_stmt *pStmt = 0;
 11209  11185     char *zSql;
 11210  11186     char zBuf[1000];
 11211  11187   
 11212  11188     if( nLine>sizeof(zBuf)-30 ) return;
 11213         -  if( zLine[0]=='.' || zLine[0]=='#') return;
        11189  +  if( zLine[0]=='.' ) return;
 11214  11190     for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
 11215  11191     if( i==nLine-1 ) return;
 11216  11192     iStart = i+1;
 11217  11193     memcpy(zBuf, zLine, iStart);
 11218  11194     zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
 11219  11195                            "  FROM completion(%Q,%Q) ORDER BY 1",
 11220  11196                            &zLine[iStart], zLine);
................................................................................
 11745  11721       sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
 11746  11722       sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
 11747  11723       tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
 11748  11724       tryToCloneSchema(p, newDb, "type!='table'", 0);
 11749  11725       sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
 11750  11726       sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
 11751  11727     }
 11752         -  close_db(newDb);
        11728  +  sqlite3_close(newDb);
 11753  11729   }
 11754  11730   
 11755  11731   /*
 11756  11732   ** Change the output file back to stdout.
 11757  11733   **
 11758  11734   ** If the p->doXdgOpen flag is set, that means the output was being
 11759  11735   ** redirected to a temporary file named by p->zTempFile.  In that case,
................................................................................
 12400  12376   typedef struct ArCommand ArCommand;
 12401  12377   struct ArCommand {
 12402  12378     u8 eCmd;                        /* An AR_CMD_* value */
 12403  12379     u8 bVerbose;                    /* True if --verbose */
 12404  12380     u8 bZip;                        /* True if the archive is a ZIP */
 12405  12381     u8 bDryRun;                     /* True if --dry-run */
 12406  12382     u8 bAppend;                     /* True if --append */
 12407         -  u8 fromCmdLine;                 /* Run from -A instead of .archive */
 12408  12383     int nArg;                       /* Number of command arguments */
 12409  12384     char *zSrcTable;                /* "sqlar", "zipfile($file)" or "zip" */
 12410  12385     const char *zFile;              /* --file argument, or NULL */
 12411  12386     const char *zDir;               /* --directory argument, or NULL */
 12412  12387     char **azArg;                   /* Array of command arguments */
 12413  12388     ShellState *p;                  /* Shell state */
 12414  12389     sqlite3 *db;                    /* Database containing the archive */
................................................................................
 12447  12422     return SQLITE_ERROR;
 12448  12423   }
 12449  12424   
 12450  12425   /*
 12451  12426   ** Print an error message for the .ar command to stderr and return 
 12452  12427   ** SQLITE_ERROR.
 12453  12428   */
 12454         -static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
        12429  +static int arErrorMsg(const char *zFmt, ...){
 12455  12430     va_list ap;
 12456  12431     char *z;
 12457  12432     va_start(ap, zFmt);
 12458  12433     z = sqlite3_vmprintf(zFmt, ap);
 12459  12434     va_end(ap);
 12460         -  utf8_printf(stderr, "Error: %s\n", z);
 12461         -  if( pAr->fromCmdLine ){
 12462         -    utf8_printf(stderr, "Use \"-A\" for more help\n");
 12463         -  }else{
 12464         -    utf8_printf(stderr, "Use \".archive --help\" for more help\n");
 12465         -  }
        12435  +  raw_printf(stderr, "Error: %s (try \".ar --help\")\n", z);
 12466  12436     sqlite3_free(z);
 12467  12437     return SQLITE_ERROR;
 12468  12438   }
 12469  12439   
 12470  12440   /*
 12471  12441   ** Values for ArCommand.eCmd.
 12472  12442   */
................................................................................
 12489  12459     switch( eSwitch ){
 12490  12460       case AR_CMD_CREATE:
 12491  12461       case AR_CMD_EXTRACT:
 12492  12462       case AR_CMD_LIST:
 12493  12463       case AR_CMD_UPDATE:
 12494  12464       case AR_CMD_HELP:
 12495  12465         if( pAr->eCmd ){
 12496         -        return arErrorMsg(pAr, "multiple command options");
        12466  +        return arErrorMsg("multiple command options");
 12497  12467         }
 12498  12468         pAr->eCmd = eSwitch;
 12499  12469         break;
 12500  12470   
 12501  12471       case AR_SWITCH_DRYRUN:
 12502  12472         pAr->bDryRun = 1;
 12503  12473         break;
................................................................................
 12549  12519     int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
 12550  12520     struct ArSwitch *pEnd = &aSwitch[nSwitch];
 12551  12521   
 12552  12522     if( nArg<=1 ){
 12553  12523       return arUsage(stderr);
 12554  12524     }else{
 12555  12525       char *z = azArg[1];
        12526  +    memset(pAr, 0, sizeof(ArCommand));
        12527  +
 12556  12528       if( z[0]!='-' ){
 12557  12529         /* Traditional style [tar] invocation */
 12558  12530         int i;
 12559  12531         int iArg = 2;
 12560  12532         for(i=0; z[i]; i++){
 12561  12533           const char *zArg = 0;
 12562  12534           struct ArSwitch *pOpt;
 12563  12535           for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
 12564  12536             if( z[i]==pOpt->cShort ) break;
 12565  12537           }
 12566  12538           if( pOpt==pEnd ){
 12567         -          return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
        12539  +          return arErrorMsg("unrecognized option: %c", z[i]);
 12568  12540           }
 12569  12541           if( pOpt->bArg ){
 12570  12542             if( iArg>=nArg ){
 12571         -            return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
        12543  +            return arErrorMsg("option requires an argument: %c",z[i]);
 12572  12544             }
 12573  12545             zArg = azArg[iArg++];
 12574  12546           }
 12575  12547           if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
 12576  12548         }
 12577  12549         pAr->nArg = nArg-iArg;
 12578  12550         if( pAr->nArg>0 ){
................................................................................
 12598  12570             for(i=1; i<n; i++){
 12599  12571               const char *zArg = 0;
 12600  12572               struct ArSwitch *pOpt;
 12601  12573               for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
 12602  12574                 if( z[i]==pOpt->cShort ) break;
 12603  12575               }
 12604  12576               if( pOpt==pEnd ){
 12605         -              return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
        12577  +              return arErrorMsg("unrecognized option: %c\n", z[i]);
 12606  12578               }
 12607  12579               if( pOpt->bArg ){
 12608  12580                 if( i<(n-1) ){
 12609  12581                   zArg = &z[i+1];
 12610  12582                   i = n;
 12611  12583                 }else{
 12612  12584                   if( iArg>=(nArg-1) ){
 12613         -                  return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
        12585  +                  return arErrorMsg("option requires an argument: %c\n",z[i]);
 12614  12586                   }
 12615  12587                   zArg = azArg[++iArg];
 12616  12588                 }
 12617  12589               }
 12618  12590               if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
 12619  12591             }
 12620  12592           }else if( z[2]=='\0' ){
................................................................................
 12628  12600             const char *zArg = 0;             /* Argument for option, if any */
 12629  12601             struct ArSwitch *pMatch = 0;      /* Matching option */
 12630  12602             struct ArSwitch *pOpt;            /* Iterator */
 12631  12603             for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
 12632  12604               const char *zLong = pOpt->zLong;
 12633  12605               if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
 12634  12606                 if( pMatch ){
 12635         -                return arErrorMsg(pAr, "ambiguous option: %s",z);
        12607  +                return arErrorMsg("ambiguous option: %s",z);
 12636  12608                 }else{
 12637  12609                   pMatch = pOpt;
 12638  12610                 }
 12639  12611               }
 12640  12612             }
 12641  12613   
 12642  12614             if( pMatch==0 ){
 12643         -            return arErrorMsg(pAr, "unrecognized option: %s", z);
        12615  +            return arErrorMsg("unrecognized option: %s", z);
 12644  12616             }
 12645  12617             if( pMatch->bArg ){
 12646  12618               if( iArg>=(nArg-1) ){
 12647         -              return arErrorMsg(pAr, "option requires an argument: %s", z);
        12619  +              return arErrorMsg("option requires an argument: %s", z);
 12648  12620               }
 12649  12621               zArg = azArg[++iArg];
 12650  12622             }
 12651  12623             if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
 12652  12624           }
 12653  12625         }
 12654  12626       }
................................................................................
 12769  12741           );
 12770  12742         }else{
 12771  12743           utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
 12772  12744         }
 12773  12745       }
 12774  12746     }
 12775  12747     shellFinalize(&rc, pSql);
 12776         -  sqlite3_free(zWhere);
 12777  12748     return rc;
 12778  12749   }
 12779  12750   
 12780  12751   
 12781  12752   /*
 12782  12753   ** Implementation of .ar "eXtract" command. 
 12783  12754   */
 12784  12755   static int arExtractCommand(ArCommand *pAr){
 12785  12756     const char *zSql1 = 
 12786  12757       "SELECT "
 12787  12758       " ($dir || name),"
 12788  12759       " writefile(($dir || name), %s, mode, mtime) "
 12789         -    "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
 12790         -    " AND name NOT GLOB '*..[/\\]*'";
        12760  +    "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)";
 12791  12761   
 12792  12762     const char *azExtraArg[] = { 
 12793  12763       "sqlar_uncompress(data, sz)",
 12794  12764       "data"
 12795  12765     };
 12796  12766   
 12797  12767     sqlite3_stmt *pSql = 0;
................................................................................
 12973  12943   }
 12974  12944   
 12975  12945   /*
 12976  12946   ** Implementation of ".ar" dot command.
 12977  12947   */
 12978  12948   static int arDotCommand(
 12979  12949     ShellState *pState,             /* Current shell tool state */
 12980         -  int fromCmdLine,                /* True if -A command-line option, not .ar cmd */
 12981  12950     char **azArg,                   /* Array of arguments passed to dot command */
 12982  12951     int nArg                        /* Number of entries in azArg[] */
 12983  12952   ){
 12984  12953     ArCommand cmd;
 12985  12954     int rc;
 12986  12955     memset(&cmd, 0, sizeof(cmd));
 12987         -  cmd.fromCmdLine = fromCmdLine;
 12988  12956     rc = arParseCommand(azArg, nArg, &cmd);
 12989  12957     if( rc==SQLITE_OK ){
 12990  12958       int eDbType = SHELL_OPEN_UNSPEC;
 12991  12959       cmd.p = pState;
 12992  12960       cmd.db = pState->db;
 12993  12961       if( cmd.zFile ){
 12994  12962         eDbType = deduceDatabaseType(cmd.zFile, 1);
................................................................................
 13027  12995         }
 13028  12996         sqlite3_fileio_init(cmd.db, 0, 0);
 13029  12997         sqlite3_sqlar_init(cmd.db, 0, 0);
 13030  12998         sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
 13031  12999                                 shellPutsFunc, 0, 0);
 13032  13000   
 13033  13001       }
 13034         -    if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
        13002  +    if( cmd.zSrcTable==0 && cmd.bZip==0 ){
 13035  13003         if( cmd.eCmd!=AR_CMD_CREATE
 13036  13004          && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
 13037  13005         ){
 13038  13006           utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
 13039  13007           rc = SQLITE_ERROR;
 13040  13008           goto end_ar_command;
 13041  13009         }
................................................................................
 13063  13031           assert( cmd.eCmd==AR_CMD_UPDATE );
 13064  13032           rc = arCreateOrUpdateCommand(&cmd, 1);
 13065  13033           break;
 13066  13034       }
 13067  13035     }
 13068  13036   end_ar_command:
 13069  13037     if( cmd.db!=pState->db ){
 13070         -    close_db(cmd.db);
        13038  +    sqlite3_close(cmd.db);
 13071  13039     }
 13072  13040     sqlite3_free(cmd.zSrcTable);
 13073  13041   
 13074  13042     return rc;
 13075  13043   }
 13076  13044   /* End of the ".archive" or ".ar" command logic
 13077  13045   **********************************************************************************/
................................................................................
 13143  13111       }
 13144  13112     }else
 13145  13113   #endif
 13146  13114   
 13147  13115   #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
 13148  13116     if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
 13149  13117       open_db(p, 0);
 13150         -    rc = arDotCommand(p, 0, azArg, nArg);
        13118  +    rc = arDotCommand(p, azArg, nArg);
 13151  13119     }else
 13152  13120   #endif
 13153  13121   
 13154  13122     if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
 13155  13123      || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
 13156  13124     ){
 13157  13125       const char *zDestFile = 0;
 13158  13126       const char *zDb = 0;
 13159  13127       sqlite3 *pDest;
 13160  13128       sqlite3_backup *pBackup;
 13161  13129       int j;
 13162         -    const char *zVfs = 0;
 13163  13130       for(j=1; j<nArg; j++){
 13164  13131         const char *z = azArg[j];
 13165  13132         if( z[0]=='-' ){
 13166         -        if( z[1]=='-' ) z++;
 13167         -        if( strcmp(z, "-append")==0 ){
 13168         -          zVfs = "apndvfs";
 13169         -        }else
        13133  +        while( z[0]=='-' ) z++;
        13134  +        /* No options to process at this time */
 13170  13135           {
 13171  13136             utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
 13172  13137             return 1;
 13173  13138           }
 13174  13139         }else if( zDestFile==0 ){
 13175  13140           zDestFile = azArg[j];
 13176  13141         }else if( zDb==0 ){
 13177  13142           zDb = zDestFile;
 13178  13143           zDestFile = azArg[j];
 13179  13144         }else{
 13180         -        raw_printf(stderr, "Usage: .backup ?DB? ?--append? FILENAME\n");
        13145  +        raw_printf(stderr, "too many arguments to .backup\n");
 13181  13146           return 1;
 13182  13147         }
 13183  13148       }
 13184  13149       if( zDestFile==0 ){
 13185  13150         raw_printf(stderr, "missing FILENAME argument on .backup\n");
 13186  13151         return 1;
 13187  13152       }
 13188  13153       if( zDb==0 ) zDb = "main";
 13189         -    rc = sqlite3_open_v2(zDestFile, &pDest, 
 13190         -                  SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
        13154  +    rc = sqlite3_open(zDestFile, &pDest);
 13191  13155       if( rc!=SQLITE_OK ){
 13192  13156         utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
 13193         -      close_db(pDest);
        13157  +      sqlite3_close(pDest);
 13194  13158         return 1;
 13195  13159       }
 13196  13160       open_db(p, 0);
 13197  13161       pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
 13198  13162       if( pBackup==0 ){
 13199  13163         utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
 13200         -      close_db(pDest);
        13164  +      sqlite3_close(pDest);
 13201  13165         return 1;
 13202  13166       }
 13203  13167       while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
 13204  13168       sqlite3_backup_finish(pBackup);
 13205  13169       if( rc==SQLITE_DONE ){
 13206  13170         rc = 0;
 13207  13171       }else{
 13208  13172         utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
 13209  13173         rc = 1;
 13210  13174       }
 13211         -    close_db(pDest);
        13175  +    sqlite3_close(pDest);
 13212  13176     }else
 13213  13177   
 13214  13178     if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
 13215  13179       if( nArg==2 ){
 13216  13180         bail_on_error = booleanValue(azArg[1]);
 13217  13181       }else{
 13218  13182         raw_printf(stderr, "Usage: .bail on|off\n");
................................................................................
 13316  13280       if( zErrMsg ){
 13317  13281         utf8_printf(stderr,"Error: %s\n", zErrMsg);
 13318  13282         sqlite3_free(zErrMsg);
 13319  13283         rc = 1;
 13320  13284       }
 13321  13285     }else
 13322  13286   
 13323         -  if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){
 13324         -    static const struct DbConfigChoices {const char *zName; int op;} aDbConfig[] = {
 13325         -        { "enable_fkey",      SQLITE_DBCONFIG_ENABLE_FKEY            },
 13326         -        { "enable_trigger",   SQLITE_DBCONFIG_ENABLE_TRIGGER         },
 13327         -        { "fts3_tokenizer",   SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER  },
 13328         -        { "load_extension",   SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION  },
 13329         -        { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE       },
 13330         -        { "enable_qpsg",      SQLITE_DBCONFIG_ENABLE_QPSG            },
 13331         -        { "trigger_eqp",      SQLITE_DBCONFIG_TRIGGER_EQP            },
 13332         -        { "reset_database",   SQLITE_DBCONFIG_RESET_DATABASE         },
 13333         -    };
 13334         -    int ii, v;
 13335         -    open_db(p, 0);
 13336         -    for(ii=0; ii<ArraySize(aDbConfig); ii++){
 13337         -      if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
 13338         -      if( nArg>=3 ){
 13339         -        sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
 13340         -      }
 13341         -      sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
 13342         -      utf8_printf(p->out, "%18s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
 13343         -      if( nArg>1 ) break;
 13344         -    }
 13345         -    if( nArg>1 && ii==ArraySize(aDbConfig) ){
 13346         -      utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
 13347         -      utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
 13348         -    }   
 13349         -  }else
 13350         -
 13351         -  if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){
        13287  +  if( c=='d' && strncmp(azArg[0], "dbinfo", n)==0 ){
 13352  13288       rc = shell_dbinfo_command(p, nArg, azArg);
 13353  13289     }else
 13354  13290   
 13355  13291     if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
 13356  13292       const char *zLike = 0;
 13357  13293       int i;
 13358  13294       int savedShowHeader = p->showHeader;
................................................................................
 13447  13383         raw_printf(stderr, "Usage: .echo on|off\n");
 13448  13384         rc = 1;
 13449  13385       }
 13450  13386     }else
 13451  13387   
 13452  13388     if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
 13453  13389       if( nArg==2 ){
 13454         -      p->autoEQPtest = 0;
 13455  13390         if( strcmp(azArg[1],"full")==0 ){
 13456  13391           p->autoEQP = AUTOEQP_full;
 13457  13392         }else if( strcmp(azArg[1],"trigger")==0 ){
 13458  13393           p->autoEQP = AUTOEQP_trigger;
 13459         -      }else if( strcmp(azArg[1],"test")==0 ){
 13460         -        p->autoEQP = AUTOEQP_on;
 13461         -        p->autoEQPtest = 1;
 13462  13394         }else{
 13463  13395           p->autoEQP = (u8)booleanValue(azArg[1]);
 13464  13396         }
 13465  13397       }else{
 13466  13398         raw_printf(stderr, "Usage: .eqp off|on|trigger|full\n");
 13467  13399         rc = 1;
 13468  13400       }
................................................................................
 13543  13475         raw_printf(p->out, "/* No STAT tables available */\n");
 13544  13476       }else{
 13545  13477         raw_printf(p->out, "ANALYZE sqlite_master;\n");
 13546  13478         sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
 13547  13479                      callback, &data, &zErrMsg);
 13548  13480         data.cMode = data.mode = MODE_Insert;
 13549  13481         data.zDestTable = "sqlite_stat1";
 13550         -      shell_exec(&data, "SELECT * FROM sqlite_stat1", &zErrMsg);
        13482  +      shell_exec(p, "SELECT * FROM sqlite_stat1", &zErrMsg);
 13551  13483         data.zDestTable = "sqlite_stat3";
 13552         -      shell_exec(&data, "SELECT * FROM sqlite_stat3", &zErrMsg);
        13484  +      shell_exec(p, "SELECT * FROM sqlite_stat3", &zErrMsg);
 13553  13485         data.zDestTable = "sqlite_stat4";
 13554         -      shell_exec(&data, "SELECT * FROM sqlite_stat4", &zErrMsg);
        13486  +      shell_exec(p, "SELECT * FROM sqlite_stat4", &zErrMsg);
 13555  13487         raw_printf(p->out, "ANALYZE sqlite_master;\n");
 13556  13488       }
 13557  13489     }else
 13558  13490   
 13559  13491     if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
 13560  13492       if( nArg==2 ){
 13561  13493         p->showHeader = booleanValue(azArg[1]);
................................................................................
 14020  13952   
 14021  13953     if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
 14022  13954       char *zNewFilename;  /* Name of the database file to open */
 14023  13955       int iName = 1;       /* Index in azArg[] of the filename */
 14024  13956       int newFlag = 0;     /* True to delete file before opening */
 14025  13957       /* Close the existing database */
 14026  13958       session_close_all(p);
 14027         -    close_db(p->db);
        13959  +    sqlite3_close(p->db);
 14028  13960       p->db = 0;
 14029  13961       p->zDbFilename = 0;
 14030  13962       sqlite3_free(p->zFreeOnClose);
 14031  13963       p->zFreeOnClose = 0;
 14032  13964       p->openMode = SHELL_OPEN_UNSPEC;
 14033  13965       /* Check for command-line arguments */
 14034  13966       for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
................................................................................
 14050  13982         }
 14051  13983       }
 14052  13984       /* If a filename is specified, try to open it first */
 14053  13985       zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
 14054  13986       if( zNewFilename ){
 14055  13987         if( newFlag ) shellDeleteFile(zNewFilename);
 14056  13988         p->zDbFilename = zNewFilename;
 14057         -      open_db(p, OPEN_DB_KEEPALIVE);
        13989  +      open_db(p, 1);
 14058  13990         if( p->db==0 ){
 14059  13991           utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
 14060  13992           sqlite3_free(zNewFilename);
 14061  13993         }else{
 14062  13994           p->zFreeOnClose = zNewFilename;
 14063  13995         }
 14064  13996       }
................................................................................
 14200  14132         raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
 14201  14133         rc = 1;
 14202  14134         goto meta_command_exit;
 14203  14135       }
 14204  14136       rc = sqlite3_open(zSrcFile, &pSrc);
 14205  14137       if( rc!=SQLITE_OK ){
 14206  14138         utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
 14207         -      close_db(pSrc);
        14139  +      sqlite3_close(pSrc);
 14208  14140         return 1;
 14209  14141       }
 14210  14142       open_db(p, 0);
 14211  14143       pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
 14212  14144       if( pBackup==0 ){
 14213  14145         utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
 14214         -      close_db(pSrc);
        14146  +      sqlite3_close(pSrc);
 14215  14147         return 1;
 14216  14148       }
 14217  14149       while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
 14218  14150             || rc==SQLITE_BUSY  ){
 14219  14151         if( rc==SQLITE_BUSY ){
 14220  14152           if( nTimeout++ >= 3 ) break;
 14221  14153           sqlite3_sleep(100);
................................................................................
 14227  14159       }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
 14228  14160         raw_printf(stderr, "Error: source database is busy\n");
 14229  14161         rc = 1;
 14230  14162       }else{
 14231  14163         utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
 14232  14164         rc = 1;
 14233  14165       }
 14234         -    close_db(pSrc);
        14166  +    sqlite3_close(pSrc);
 14235  14167     }else
 14236  14168   
 14237  14169     if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
 14238  14170       if( nArg==2 ){
 14239  14171         p->scanstatsOn = (u8)booleanValue(azArg[1]);
 14240  14172   #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
 14241  14173         raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
................................................................................
 14747  14679           if( strcmp(z,"debug")==0 ){
 14748  14680             bDebug = 1;
 14749  14681           }else
 14750  14682           {
 14751  14683             utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
 14752  14684                         azArg[i], azArg[0]);
 14753  14685             raw_printf(stderr, "Should be one of: --schema"
 14754         -                             " --sha3-224 --sha3-256 --sha3-384 --sha3-512\n");
        14686  +                             " --sha3-224 --sha3-255 --sha3-384 --sha3-512\n");
 14755  14687             rc = 1;
 14756  14688             goto meta_command_exit;
 14757  14689           }
 14758  14690         }else if( zLike ){
 14759  14691           raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
 14760  14692           rc = 1;
 14761  14693           goto meta_command_exit;
................................................................................
 14911  14843       char **azResult;
 14912  14844       int nRow, nAlloc;
 14913  14845       int ii;
 14914  14846       ShellText s;
 14915  14847       initText(&s);
 14916  14848       open_db(p, 0);
 14917  14849       rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
 14918         -    if( rc ){
 14919         -      sqlite3_finalize(pStmt);
 14920         -      return shellDatabaseError(p->db);
 14921         -    }
        14850  +    if( rc ) return shellDatabaseError(p->db);
 14922  14851   
 14923  14852       if( nArg>2 && c=='i' ){
 14924  14853         /* It is an historical accident that the .indexes command shows an error
 14925  14854         ** when called with the wrong number of arguments whereas the .tables
 14926  14855         ** command does not. */
 14927  14856         raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
 14928  14857         rc = 1;
 14929         -      sqlite3_finalize(pStmt);
 14930  14858         goto meta_command_exit;
 14931  14859       }
 14932  14860       for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
 14933  14861         const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
 14934  14862         if( zDbName==0 ) continue;
 14935  14863         if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
 14936  14864         if( sqlite3_stricmp(zDbName, "main")==0 ){
................................................................................
 15439  15367     zSql[nSql+1] = 0;
 15440  15368     rc = sqlite3_complete(zSql);
 15441  15369     zSql[nSql] = 0;
 15442  15370     return rc;
 15443  15371   }
 15444  15372   
 15445  15373   /*
 15446         -** Run a single line of SQL.  Return the number of errors.
        15374  +** Run a single line of SQL
 15447  15375   */
 15448  15376   static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
 15449  15377     int rc;
 15450  15378     char *zErrMsg = 0;
 15451  15379   
 15452  15380     open_db(p, 0);
 15453  15381     if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
................................................................................
 15512  15440         seenInterrupt = 0;
 15513  15441       }
 15514  15442       lineno++;
 15515  15443       if( nSql==0 && _all_whitespace(zLine) ){
 15516  15444         if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
 15517  15445         continue;
 15518  15446       }
 15519         -    if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
        15447  +    if( zLine && zLine[0]=='.' && nSql==0 ){
 15520  15448         if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
 15521         -      if( zLine[0]=='.' ){
 15522         -        rc = do_meta_command(zLine, p);
 15523         -        if( rc==2 ){ /* exit requested */
 15524         -          break;
 15525         -        }else if( rc ){
 15526         -          errCnt++;
 15527         -        }
        15449  +      rc = do_meta_command(zLine, p);
        15450  +      if( rc==2 ){ /* exit requested */
        15451  +        break;
        15452  +      }else if( rc ){
        15453  +        errCnt++;
 15528  15454         }
 15529  15455         continue;
 15530  15456       }
 15531  15457       if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
 15532  15458         memcpy(zLine,";",2);
 15533  15459       }
 15534  15460       nLine = strlen30(zLine);
................................................................................
 15562  15488         }
 15563  15489       }else if( nSql && _all_whitespace(zSql) ){
 15564  15490         if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
 15565  15491         nSql = 0;
 15566  15492       }
 15567  15493     }
 15568  15494     if( nSql && !_all_whitespace(zSql) ){
 15569         -    errCnt += runOneSqlLine(p, zSql, in, startline);
        15495  +    runOneSqlLine(p, zSql, in, startline);
 15570  15496     }
 15571  15497     free(zSql);
 15572  15498     free(zLine);
 15573  15499     return errCnt>0;
 15574  15500   }
 15575  15501   
 15576  15502   /*
................................................................................
 15742  15668   
 15743  15669   /*
 15744  15670   ** Internal check:  Verify that the SQLite is uninitialized.  Print a
 15745  15671   ** error message if it is initialized.
 15746  15672   */
 15747  15673   static void verify_uninitialized(void){
 15748  15674     if( sqlite3_config(-1)==SQLITE_MISUSE ){
 15749         -    utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
        15675  +    utf8_printf(stdout, "WARNING: attempt to configuration SQLite after"
 15750  15676                           " initialization.\n");
 15751  15677     }
 15752  15678   }
 15753  15679   
 15754  15680   /*
 15755  15681   ** Initialize the state information in data
 15756  15682   */
................................................................................
 15823  15749     int i;
 15824  15750     int rc = 0;
 15825  15751     int warnInmemoryDb = 0;
 15826  15752     int readStdin = 1;
 15827  15753     int nCmd = 0;
 15828  15754     char **azCmd = 0;
 15829  15755     const char *zVfs = 0;           /* Value of -vfs command-line option */
 15830         -#if !SQLITE_SHELL_IS_UTF8
 15831         -  char **argvToFree = 0;
 15832         -  int argcToFree = 0;
 15833         -#endif
 15834  15756   
 15835  15757     setBinaryMode(stdin, 0);
 15836  15758     setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
 15837  15759     stdin_is_interactive = isatty(0);
 15838  15760     stdout_is_console = isatty(1);
 15839  15761   
 15840  15762   #if USE_SYSTEM_SQLITE+0!=1
................................................................................
 15850  15772     ** The SQLite memory allocator subsystem has to be enabled in order to
 15851  15773     ** do this.  But we want to run an sqlite3_shutdown() afterwards so that
 15852  15774     ** subsequent sqlite3_config() calls will work.  So copy all results into
 15853  15775     ** memory that does not come from the SQLite memory allocator.
 15854  15776     */
 15855  15777   #if !SQLITE_SHELL_IS_UTF8
 15856  15778     sqlite3_initialize();
 15857         -  argvToFree = malloc(sizeof(argv[0])*argc*2);
 15858         -  argcToFree = argc;
 15859         -  argv = argvToFree + argc;
        15779  +  argv = malloc(sizeof(argv[0])*argc);
 15860  15780     if( argv==0 ) shell_out_of_memory();
 15861  15781     for(i=0; i<argc; i++){
 15862  15782       char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
 15863  15783       int n;
 15864  15784       if( z==0 ) shell_out_of_memory();
 15865  15785       n = (int)strlen(z);
 15866  15786       argv[i] = malloc( n+1 );
 15867  15787       if( argv[i]==0 ) shell_out_of_memory();
 15868  15788       memcpy(argv[i], z, n+1);
 15869         -    argvToFree[i] = argv[i];
 15870  15789       sqlite3_free(z);
 15871  15790     }
 15872  15791     sqlite3_shutdown();
 15873  15792   #endif
 15874  15793   
 15875  15794     assert( argc>=1 && argv && argv[0] );
 15876  15795     Argv0 = argv[0];
................................................................................
 16184  16103   #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
 16185  16104       }else if( strncmp(z, "-A", 2)==0 ){
 16186  16105         if( nCmd>0 ){
 16187  16106           utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
 16188  16107                               " with \"%s\"\n", z);
 16189  16108           return 1;
 16190  16109         }
 16191         -      open_db(&data, OPEN_DB_ZIPFILE);
        16110  +      open_db(&data, 0);
 16192  16111         if( z[2] ){
 16193  16112           argv[i] = &z[2];
 16194         -        arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
        16113  +        arDotCommand(&data, argv+(i-1), argc-(i-1));
 16195  16114         }else{
 16196         -        arDotCommand(&data, 1, argv+i, argc-i);
        16115  +        arDotCommand(&data, argv+i, argc-i);
 16197  16116         }
 16198  16117         readStdin = 0;
 16199  16118         break;
 16200  16119   #endif
 16201  16120       }else{
 16202  16121         utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
 16203  16122         raw_printf(stderr,"Use -help for a list of options.\n");
................................................................................
 16268  16187       }else{
 16269  16188         rc = process_input(&data, stdin);
 16270  16189       }
 16271  16190     }
 16272  16191     set_table_name(&data, 0);
 16273  16192     if( data.db ){
 16274  16193       session_close_all(&data);
 16275         -    close_db(data.db);
        16194  +    sqlite3_close(data.db);
 16276  16195     }
 16277  16196     sqlite3_free(data.zFreeOnClose);
 16278  16197     find_home_dir(1);
 16279  16198     output_reset(&data);
 16280  16199     data.doXdgOpen = 0;
 16281  16200     clearTempFile(&data);
 16282  16201   #if !SQLITE_SHELL_IS_UTF8
 16283         -  for(i=0; i<argcToFree; i++) free(argvToFree[i]);
 16284         -  free(argvToFree);
        16202  +  for(i=0; i<argc; i++) free(argv[i]);
        16203  +  free(argv);
 16285  16204   #endif
 16286         -  /* Clear the global data structure so that valgrind will detect memory
 16287         -  ** leaks */
 16288         -  memset(&data, 0, sizeof(data));
 16289  16205     return rc;
 16290  16206   }

Changes to src/skins.c.

   932    932     @ </p>
   933    933     @
   934    934     @ <a name='step2'></a>
   935    935     @ <h1>Step 2: Authenticate</h1>
   936    936     @
   937    937     if( isSetup ){
   938    938       @ <p>As an administrator, you can make any edits you like to this or
   939         -    @ any other skin.  You can also authorize other users to edit this
   940         -    @ skin.  Any user whose login name matches the comma-separated list
          939  +    @ any other skin.  You can also authorized other users to edit this
          940  +    @ skin.  Any user whose login name matches the comma-separate list
   941    941       @ of GLOB expressions below is given special permission to edit
   942    942       @ the draft%d(iSkin) skin:
   943    943       @
   944    944       @ <form method='POST' action='%R/setup_skin#step2' id='f02'>
   945    945       @ <p class='skinInput'>
   946    946       @ <input type='hidden' name='sk' value='%d(iSkin)'>
   947    947       @ Authorized editors for skin draft%d(iSkin):

Changes to src/sqlite3.c.

  1148   1148   **
  1149   1149   ** See also: [sqlite3_libversion()],
  1150   1150   ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
  1151   1151   ** [sqlite_version()] and [sqlite_source_id()].
  1152   1152   */
  1153   1153   #define SQLITE_VERSION        "3.24.0"
  1154   1154   #define SQLITE_VERSION_NUMBER 3024000
  1155         -#define SQLITE_SOURCE_ID      "2018-06-04 19:24:41 c7ee0833225bfd8c5ec2f9bf62b97c4e04d03bd9566366d5221ac8fb199a87ca"
         1155  +#define SQLITE_SOURCE_ID      "2018-04-26 18:34:26 9fd0faf517993587d2f54212638545fc85fbbc84a031bcfae8c1e5894825d83b"
  1156   1156   
  1157   1157   /*
  1158   1158   ** CAPI3REF: Run-Time Library Version Numbers
  1159   1159   ** KEYWORDS: sqlite3_version sqlite3_sourceid
  1160   1160   **
  1161   1161   ** These interfaces provide the same information as the [SQLITE_VERSION],
  1162   1162   ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
................................................................................
  1527   1527   #define SQLITE_IOERR_CONVPATH          (SQLITE_IOERR | (26<<8))
  1528   1528   #define SQLITE_IOERR_VNODE             (SQLITE_IOERR | (27<<8))
  1529   1529   #define SQLITE_IOERR_AUTH              (SQLITE_IOERR | (28<<8))
  1530   1530   #define SQLITE_IOERR_BEGIN_ATOMIC      (SQLITE_IOERR | (29<<8))
  1531   1531   #define SQLITE_IOERR_COMMIT_ATOMIC     (SQLITE_IOERR | (30<<8))
  1532   1532   #define SQLITE_IOERR_ROLLBACK_ATOMIC   (SQLITE_IOERR | (31<<8))
  1533   1533   #define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))
  1534         -#define SQLITE_LOCKED_VTAB             (SQLITE_LOCKED |  (2<<8))
  1535   1534   #define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))
  1536   1535   #define SQLITE_BUSY_SNAPSHOT           (SQLITE_BUSY   |  (2<<8))
  1537   1536   #define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
  1538   1537   #define SQLITE_CANTOPEN_ISDIR          (SQLITE_CANTOPEN | (2<<8))
  1539   1538   #define SQLITE_CANTOPEN_FULLPATH       (SQLITE_CANTOPEN | (3<<8))
  1540   1539   #define SQLITE_CANTOPEN_CONVPATH       (SQLITE_CANTOPEN | (4<<8))
  1541   1540   #define SQLITE_CORRUPT_VTAB            (SQLITE_CORRUPT | (1<<8))
  1542         -#define SQLITE_CORRUPT_SEQUENCE        (SQLITE_CORRUPT | (2<<8))
  1543   1541   #define SQLITE_READONLY_RECOVERY       (SQLITE_READONLY | (1<<8))
  1544   1542   #define SQLITE_READONLY_CANTLOCK       (SQLITE_READONLY | (2<<8))
  1545   1543   #define SQLITE_READONLY_ROLLBACK       (SQLITE_READONLY | (3<<8))
  1546   1544   #define SQLITE_READONLY_DBMOVED        (SQLITE_READONLY | (4<<8))
  1547   1545   #define SQLITE_READONLY_CANTINIT       (SQLITE_READONLY | (5<<8))
  1548   1546   #define SQLITE_READONLY_DIRECTORY      (SQLITE_READONLY | (6<<8))
  1549   1547   #define SQLITE_ABORT_ROLLBACK          (SQLITE_ABORT | (2<<8))
................................................................................
  3137   3135   ** behavior. The first parameter passed to this operation is an integer -
  3138   3136   ** positive to enable output for trigger programs, or zero to disable it,
  3139   3137   ** or negative to leave the setting unchanged.
  3140   3138   ** The second parameter is a pointer to an integer into which is written 
  3141   3139   ** 0 or 1 to indicate whether output-for-triggers has been disabled - 0 if 
  3142   3140   ** it is not disabled, 1 if it is.  
  3143   3141   ** </dd>
  3144         -**
  3145         -** <dt>SQLITE_DBCONFIG_RESET_DATABASE</dt>
  3146         -** <dd> Set the SQLITE_DBCONFIG_RESET_DATABASE flag and then run
  3147         -** [VACUUM] in order to reset a database back to an empty database
  3148         -** with no schema and no content. The following process works even for
  3149         -** a badly corrupted database file:
  3150         -** <ol>
  3151         -** <li> sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0);
  3152         -** <li> [sqlite3_exec](db, "[VACUUM]", 0, 0, 0);
  3153         -** <li> sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0);
  3154         -** </ol>
  3155         -** Because resetting a database is destructive and irreversible, the
  3156         -** process requires the use of this obscure API and multiple steps to help
  3157         -** ensure that it does not happen by accident.
  3158         -** </dd>
  3159   3142   ** </dl>
  3160   3143   */
  3161   3144   #define SQLITE_DBCONFIG_MAINDBNAME            1000 /* const char* */
  3162   3145   #define SQLITE_DBCONFIG_LOOKASIDE             1001 /* void* int int */
  3163   3146   #define SQLITE_DBCONFIG_ENABLE_FKEY           1002 /* int int* */
  3164   3147   #define SQLITE_DBCONFIG_ENABLE_TRIGGER        1003 /* int int* */
  3165   3148   #define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */
  3166   3149   #define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */
  3167   3150   #define SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      1006 /* int int* */
  3168   3151   #define SQLITE_DBCONFIG_ENABLE_QPSG           1007 /* int int* */
  3169   3152   #define SQLITE_DBCONFIG_TRIGGER_EQP           1008 /* int int* */
  3170         -#define SQLITE_DBCONFIG_RESET_DATABASE        1009 /* int int* */
  3171         -#define SQLITE_DBCONFIG_MAX                   1009 /* Largest DBCONFIG */
         3153  +#define SQLITE_DBCONFIG_MAX                   1008 /* Largest DBCONFIG */
  3172   3154   
  3173   3155   /*
  3174   3156   ** CAPI3REF: Enable Or Disable Extended Result Codes
  3175   3157   ** METHOD: sqlite3
  3176   3158   **
  3177   3159   ** ^The sqlite3_extended_result_codes() routine enables or disables the
  3178   3160   ** [extended result codes] feature of SQLite. ^The extended result
................................................................................
  6550   6532   ** using [sqlite3_free].
  6551   6533   ** Hence, if this variable is modified directly, either it should be
  6552   6534   ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  6553   6535   ** or else the use of the [data_store_directory pragma] should be avoided.
  6554   6536   */
  6555   6537   SQLITE_API char *sqlite3_data_directory;
  6556   6538   
  6557         -/*
  6558         -** CAPI3REF: Win32 Specific Interface
  6559         -**
  6560         -** These interfaces are available only on Windows.  The
  6561         -** [sqlite3_win32_set_directory] interface is used to set the value associated
  6562         -** with the [sqlite3_temp_directory] or [sqlite3_data_directory] variable, to
  6563         -** zValue, depending on the value of the type parameter.  The zValue parameter
  6564         -** should be NULL to cause the previous value to be freed via [sqlite3_free];
  6565         -** a non-NULL value will be copied into memory obtained from [sqlite3_malloc]
  6566         -** prior to being used.  The [sqlite3_win32_set_directory] interface returns
  6567         -** [SQLITE_OK] to indicate success, [SQLITE_ERROR] if the type is unsupported,
  6568         -** or [SQLITE_NOMEM] if memory could not be allocated.  The value of the
  6569         -** [sqlite3_data_directory] variable is intended to act as a replacement for
  6570         -** the current directory on the sub-platforms of Win32 where that concept is
  6571         -** not present, e.g. WinRT and UWP.  The [sqlite3_win32_set_directory8] and
  6572         -** [sqlite3_win32_set_directory16] interfaces behave exactly the same as the
  6573         -** sqlite3_win32_set_directory interface except the string parameter must be
  6574         -** UTF-8 or UTF-16, respectively.
  6575         -*/
  6576         -SQLITE_API int sqlite3_win32_set_directory(
  6577         -  unsigned long type, /* Identifier for directory being set or reset */
  6578         -  void *zValue        /* New value for directory being set or reset */
  6579         -);
  6580         -SQLITE_API int sqlite3_win32_set_directory8(unsigned long type, const char *zValue);
  6581         -SQLITE_API int sqlite3_win32_set_directory16(unsigned long type, const void *zValue);
  6582         -
  6583         -/*
  6584         -** CAPI3REF: Win32 Directory Types
  6585         -**
  6586         -** These macros are only available on Windows.  They define the allowed values
  6587         -** for the type argument to the [sqlite3_win32_set_directory] interface.
  6588         -*/
  6589         -#define SQLITE_WIN32_DATA_DIRECTORY_TYPE  1
  6590         -#define SQLITE_WIN32_TEMP_DIRECTORY_TYPE  2
  6591         -
  6592   6539   /*
  6593   6540   ** CAPI3REF: Test For Auto-Commit Mode
  6594   6541   ** KEYWORDS: {autocommit mode}
  6595   6542   ** METHOD: sqlite3
  6596   6543   **
  6597   6544   ** ^The sqlite3_get_autocommit() interface returns non-zero or
  6598   6545   ** zero if the given database connection is or is not in autocommit mode,
................................................................................
  7317   7264     int idxFlags;              /* Mask of SQLITE_INDEX_SCAN_* flags */
  7318   7265     /* Fields below are only available in SQLite 3.10.0 and later */
  7319   7266     sqlite3_uint64 colUsed;    /* Input: Mask of columns used by statement */
  7320   7267   };
  7321   7268   
  7322   7269   /*
  7323   7270   ** CAPI3REF: Virtual Table Scan Flags
  7324         -**
  7325         -** Virtual table implementations are allowed to set the 
  7326         -** [sqlite3_index_info].idxFlags field to some combination of
  7327         -** these bits.
  7328   7271   */
  7329   7272   #define SQLITE_INDEX_SCAN_UNIQUE      1     /* Scan visits at most 1 row */
  7330   7273   
  7331   7274   /*
  7332   7275   ** CAPI3REF: Virtual Table Constraint Operator Codes
  7333   7276   **
  7334   7277   ** These macros defined the allowed values for the
................................................................................
  8142   8085   ** parsing ambiguity.  For example, the statement
  8143   8086   ** "CREATE TABLE BEGIN(REPLACE,PRAGMA,END);" is accepted by SQLite, and
  8144   8087   ** creates a new table named "BEGIN" with three columns named
  8145   8088   ** "REPLACE", "PRAGMA", and "END".  Nevertheless, best practice is to avoid
  8146   8089   ** using keywords as identifiers.  Common techniques used to avoid keyword
  8147   8090   ** name collisions include:
  8148   8091   ** <ul>
  8149         -** <li> Put all identifier names inside double-quotes.  This is the official
         8092  +** <li> Put all indentifier names inside double-quotes.  This is the official
  8150   8093   **      SQL way to escape identifier names.
  8151   8094   ** <li> Put identifier names inside &#91;...&#93;.  This is not standard SQL,
  8152   8095   **      but it is what SQL Server does and so lots of programmers use this
  8153   8096   **      technique.
  8154   8097   ** <li> Begin every identifier with the letter "Z" as no SQL keywords start
  8155   8098   **      with "Z".
  8156   8099   ** <li> Include a digit somewhere in every identifier name.
................................................................................
  8161   8104   ** SQLite is compiled with the [-DSQLITE_OMIT_VACUUM] option.  Also,
  8162   8105   ** new keywords may be added to future releases of SQLite.
  8163   8106   */
  8164   8107   SQLITE_API int sqlite3_keyword_count(void);
  8165   8108   SQLITE_API int sqlite3_keyword_name(int,const char**,int*);
  8166   8109   SQLITE_API int sqlite3_keyword_check(const char*,int);
  8167   8110   
  8168         -/*
  8169         -** CAPI3REF: Dynamic String Object
  8170         -** KEYWORDS: {dynamic string}
  8171         -**
  8172         -** An instance of the sqlite3_str object contains a dynamically-sized
  8173         -** string under construction.
  8174         -**
  8175         -** The lifecycle of an sqlite3_str object is as follows:
  8176         -** <ol>
  8177         -** <li> ^The sqlite3_str object is created using [sqlite3_str_new()].
  8178         -** <li> ^Text is appended to the sqlite3_str object using various
  8179         -** methods, such as [sqlite3_str_appendf()].
  8180         -** <li> ^The sqlite3_str object is destroyed and the string it created
  8181         -** is returned using the [sqlite3_str_finish()] interface.
  8182         -** </ol>
  8183         -*/
  8184         -typedef struct sqlite3_str sqlite3_str;
  8185         -
  8186         -/*
  8187         -** CAPI3REF: Create A New Dynamic String Object
  8188         -** CONSTRUCTOR: sqlite3_str
  8189         -**
  8190         -** ^The [sqlite3_str_new(D)] interface allocates and initializes
  8191         -** a new [sqlite3_str] object.  To avoid memory leaks, the object returned by
  8192         -** [sqlite3_str_new()] must be freed by a subsequent call to 
  8193         -** [sqlite3_str_finish(X)].
  8194         -**
  8195         -** ^The [sqlite3_str_new(D)] interface always returns a pointer to a
  8196         -** valid [sqlite3_str] object, though in the event of an out-of-memory
  8197         -** error the returned object might be a special singleton that will
  8198         -** silently reject new text, always return SQLITE_NOMEM from 
  8199         -** [sqlite3_str_errcode()], always return 0 for 
  8200         -** [sqlite3_str_length()], and always return NULL from
  8201         -** [sqlite3_str_finish(X)].  It is always safe to use the value
  8202         -** returned by [sqlite3_str_new(D)] as the sqlite3_str parameter
  8203         -** to any of the other [sqlite3_str] methods.
  8204         -**
  8205         -** The D parameter to [sqlite3_str_new(D)] may be NULL.  If the
  8206         -** D parameter in [sqlite3_str_new(D)] is not NULL, then the maximum
  8207         -** length of the string contained in the [sqlite3_str] object will be
  8208         -** the value set for [sqlite3_limit](D,[SQLITE_LIMIT_LENGTH]) instead
  8209         -** of [SQLITE_MAX_LENGTH].
  8210         -*/
  8211         -SQLITE_API sqlite3_str *sqlite3_str_new(sqlite3*);
  8212         -
  8213         -/*
  8214         -** CAPI3REF: Finalize A Dynamic String
  8215         -** DESTRUCTOR: sqlite3_str
  8216         -**
  8217         -** ^The [sqlite3_str_finish(X)] interface destroys the sqlite3_str object X
  8218         -** and returns a pointer to a memory buffer obtained from [sqlite3_malloc64()]
  8219         -** that contains the constructed string.  The calling application should
  8220         -** pass the returned value to [sqlite3_free()] to avoid a memory leak.
  8221         -** ^The [sqlite3_str_finish(X)] interface may return a NULL pointer if any
  8222         -** errors were encountered during construction of the string.  ^The
  8223         -** [sqlite3_str_finish(X)] interface will also return a NULL pointer if the
  8224         -** string in [sqlite3_str] object X is zero bytes long.
  8225         -*/
  8226         -SQLITE_API char *sqlite3_str_finish(sqlite3_str*);
  8227         -
  8228         -/*
  8229         -** CAPI3REF: Add Content To A Dynamic String
  8230         -** METHOD: sqlite3_str
  8231         -**
  8232         -** These interfaces add content to an sqlite3_str object previously obtained
  8233         -** from [sqlite3_str_new()].
  8234         -**
  8235         -** ^The [sqlite3_str_appendf(X,F,...)] and 
  8236         -** [sqlite3_str_vappendf(X,F,V)] interfaces uses the [built-in printf]
  8237         -** functionality of SQLite to append formatted text onto the end of 
  8238         -** [sqlite3_str] object X.
  8239         -**
  8240         -** ^The [sqlite3_str_append(X,S,N)] method appends exactly N bytes from string S
  8241         -** onto the end of the [sqlite3_str] object X.  N must be non-negative.
  8242         -** S must contain at least N non-zero bytes of content.  To append a
  8243         -** zero-terminated string in its entirety, use the [sqlite3_str_appendall()]
  8244         -** method instead.
  8245         -**
  8246         -** ^The [sqlite3_str_appendall(X,S)] method appends the complete content of
  8247         -** zero-terminated string S onto the end of [sqlite3_str] object X.
  8248         -**
  8249         -** ^The [sqlite3_str_appendchar(X,N,C)] method appends N copies of the
  8250         -** single-byte character C onto the end of [sqlite3_str] object X.
  8251         -** ^This method can be used, for example, to add whitespace indentation.
  8252         -**
  8253         -** ^The [sqlite3_str_reset(X)] method resets the string under construction
  8254         -** inside [sqlite3_str] object X back to zero bytes in length.  
  8255         -**
  8256         -** These methods do not return a result code.  ^If an error occurs, that fact
  8257         -** is recorded in the [sqlite3_str] object and can be recovered by a
  8258         -** subsequent call to [sqlite3_str_errcode(X)].
  8259         -*/
  8260         -SQLITE_API void sqlite3_str_appendf(sqlite3_str*, const char *zFormat, ...);
  8261         -SQLITE_API void sqlite3_str_vappendf(sqlite3_str*, const char *zFormat, va_list);
  8262         -SQLITE_API void sqlite3_str_append(sqlite3_str*, const char *zIn, int N);
  8263         -SQLITE_API void sqlite3_str_appendall(sqlite3_str*, const char *zIn);
  8264         -SQLITE_API void sqlite3_str_appendchar(sqlite3_str*, int N, char C);
  8265         -SQLITE_API void sqlite3_str_reset(sqlite3_str*);
  8266         -
  8267         -/*
  8268         -** CAPI3REF: Status Of A Dynamic String
  8269         -** METHOD: sqlite3_str
  8270         -**
  8271         -** These interfaces return the current status of an [sqlite3_str] object.
  8272         -**
  8273         -** ^If any prior errors have occurred while constructing the dynamic string
  8274         -** in sqlite3_str X, then the [sqlite3_str_errcode(X)] method will return
  8275         -** an appropriate error code.  ^The [sqlite3_str_errcode(X)] method returns
  8276         -** [SQLITE_NOMEM] following any out-of-memory error, or
  8277         -** [SQLITE_TOOBIG] if the size of the dynamic string exceeds
  8278         -** [SQLITE_MAX_LENGTH], or [SQLITE_OK] if there have been no errors.
  8279         -**
  8280         -** ^The [sqlite3_str_length(X)] method returns the current length, in bytes,
  8281         -** of the dynamic string under construction in [sqlite3_str] object X.
  8282         -** ^The length returned by [sqlite3_str_length(X)] does not include the
  8283         -** zero-termination byte.
  8284         -**
  8285         -** ^The [sqlite3_str_value(X)] method returns a pointer to the current
  8286         -** content of the dynamic string under construction in X.  The value
  8287         -** returned by [sqlite3_str_value(X)] is managed by the sqlite3_str object X
  8288         -** and might be freed or altered by any subsequent method on the same
  8289         -** [sqlite3_str] object.  Applications must not used the pointer returned
  8290         -** [sqlite3_str_value(X)] after any subsequent method call on the same
  8291         -** object.  ^Applications may change the content of the string returned
  8292         -** by [sqlite3_str_value(X)] as long as they do not write into any bytes
  8293         -** outside the range of 0 to [sqlite3_str_length(X)] and do not read or
  8294         -** write any byte after any subsequent sqlite3_str method call.
  8295         -*/
  8296         -SQLITE_API int sqlite3_str_errcode(sqlite3_str*);
  8297         -SQLITE_API int sqlite3_str_length(sqlite3_str*);
  8298         -SQLITE_API char *sqlite3_str_value(sqlite3_str*);
  8299         -
  8300   8111   /*
  8301   8112   ** CAPI3REF: SQLite Runtime Status
  8302   8113   **
  8303   8114   ** ^These interfaces are used to retrieve runtime status information
  8304   8115   ** about the performance of SQLite, and optionally to reset various
  8305   8116   ** highwater marks.  ^The first argument is an integer code for
  8306   8117   ** the specific parameter to measure.  ^(Recognized integer codes
................................................................................
  9562   9373   /*
  9563   9374   ** CAPI3REF: Determine If Virtual Table Column Access Is For UPDATE
  9564   9375   **
  9565   9376   ** If the sqlite3_vtab_nochange(X) routine is called within the [xColumn]
  9566   9377   ** method of a [virtual table], then it returns true if and only if the
  9567   9378   ** column is being fetched as part of an UPDATE operation during which the
  9568   9379   ** column value will not change.  Applications might use this to substitute
  9569         -** a return value that is less expensive to compute and that the corresponding
  9570         -** [xUpdate] method understands as a "no-change" value.
         9380  +** a lighter-weight value to return that the corresponding [xUpdate] method
         9381  +** understands as a "no-change" value.
  9571   9382   **
  9572   9383   ** If the [xColumn] method calls sqlite3_vtab_nochange() and finds that
  9573         -** the column is not changed by the UPDATE statement, then the xColumn
         9384  +** the column is not changed by the UPDATE statement, they the xColumn
  9574   9385   ** method can optionally return without setting a result, without calling
  9575   9386   ** any of the [sqlite3_result_int|sqlite3_result_xxxxx() interfaces].
  9576   9387   ** In that case, [sqlite3_value_nochange(X)] will return true for the
  9577   9388   ** same column in the [xUpdate] method.
  9578   9389   */
  9579   9390   SQLITE_API int sqlite3_vtab_nochange(sqlite3_context*);
  9580   9391   
................................................................................
 10061   9872   ** to the contiguous memory representation of the database that SQLite
 10062   9873   ** is currently using for that database, or NULL if the no such contiguous
 10063   9874   ** memory representation of the database exists.  A contiguous memory
 10064   9875   ** representation of the database will usually only exist if there has
 10065   9876   ** been a prior call to [sqlite3_deserialize(D,S,...)] with the same
 10066   9877   ** values of D and S.
 10067   9878   ** The size of the database is written into *P even if the 
 10068         -** SQLITE_SERIALIZE_NOCOPY bit is set but no contiguous copy
         9879  +** SQLITE_SERIALIZE_NOCOPY bit is set but no contigious copy
 10069   9880   ** of the database exists.
 10070   9881   **
 10071   9882   ** A call to sqlite3_serialize(D,S,P,F) might return NULL even if the
 10072   9883   ** SQLITE_SERIALIZE_NOCOPY bit is omitted from argument F if a memory
 10073   9884   ** allocation error occurs.
 10074   9885   **
 10075   9886   ** This interface is only available if SQLite is compiled with the
................................................................................
 13875  13686   typedef struct PrintfArguments PrintfArguments;
 13876  13687   typedef struct RowSet RowSet;
 13877  13688   typedef struct Savepoint Savepoint;
 13878  13689   typedef struct Select Select;
 13879  13690   typedef struct SQLiteThread SQLiteThread;
 13880  13691   typedef struct SelectDest SelectDest;
 13881  13692   typedef struct SrcList SrcList;
 13882         -typedef struct sqlite3_str StrAccum; /* Internal alias for sqlite3_str */
        13693  +typedef struct StrAccum StrAccum;
 13883  13694   typedef struct Table Table;
 13884  13695   typedef struct TableLock TableLock;
 13885  13696   typedef struct Token Token;
 13886  13697   typedef struct TreeView TreeView;
 13887  13698   typedef struct Trigger Trigger;
 13888  13699   typedef struct TriggerPrg TriggerPrg;
 13889  13700   typedef struct TriggerStep TriggerStep;
................................................................................
 14167  13978   #define BTREE_AUXDELETE    0x04  /* not the primary delete operation */
 14168  13979   #define BTREE_APPEND       0x08  /* Insert is likely an append */
 14169  13980   
 14170  13981   /* An instance of the BtreePayload object describes the content of a single
 14171  13982   ** entry in either an index or table btree.
 14172  13983   **
 14173  13984   ** Index btrees (used for indexes and also WITHOUT ROWID tables) contain
 14174         -** an arbitrary key and no data.  These btrees have pKey,nKey set to the
 14175         -** key and the pData,nData,nZero fields are uninitialized.  The aMem,nMem
 14176         -** fields give an array of Mem objects that are a decomposition of the key.
 14177         -** The nMem field might be zero, indicating that no decomposition is available.
        13985  +** an arbitrary key and no data.  These btrees have pKey,nKey set to their
        13986  +** key and pData,nData,nZero set to zero.
 14178  13987   **
 14179  13988   ** Table btrees (used for rowid tables) contain an integer rowid used as
 14180  13989   ** the key and passed in the nKey field.  The pKey field is zero.  
 14181  13990   ** pData,nData hold the content of the new entry.  nZero extra zero bytes
 14182  13991   ** are appended to the end of the content when constructing the entry.
 14183         -** The aMem,nMem fields are uninitialized for table btrees.
 14184         -**
 14185         -** Field usage summary:
 14186         -**
 14187         -**               Table BTrees                   Index Btrees
 14188         -**
 14189         -**   pKey        always NULL                    encoded key
 14190         -**   nKey        the ROWID                      length of pKey
 14191         -**   pData       data                           not used
 14192         -**   aMem        not used                       decomposed key value
 14193         -**   nMem        not used                       entries in aMem
 14194         -**   nData       length of pData                not used
 14195         -**   nZero       extra zeros after pData        not used
 14196  13992   **
 14197  13993   ** This object is used to pass information into sqlite3BtreeInsert().  The
 14198  13994   ** same information used to be passed as five separate parameters.  But placing
 14199  13995   ** the information into this object helps to keep the interface more 
 14200  13996   ** organized and understandable, and it also helps the resulting code to
 14201  13997   ** run a little faster by using fewer registers for parameter passing.
 14202  13998   */
 14203  13999   struct BtreePayload {
 14204  14000     const void *pKey;       /* Key content for indexes.  NULL for tables */
 14205  14001     sqlite3_int64 nKey;     /* Size of pKey for indexes.  PRIMARY KEY for tabs */
 14206         -  const void *pData;      /* Data for tables. */
        14002  +  const void *pData;      /* Data for tables.  NULL for indexes */
 14207  14003     sqlite3_value *aMem;    /* First of nMem value in the unpacked pKey */
 14208  14004     u16 nMem;               /* Number of aMem[] value.  Might be zero */
 14209  14005     int nData;              /* Size of pData.  0 if none. */
 14210  14006     int nZero;              /* Extra zero data appended after pData,nData */
 14211  14007   };
 14212  14008   
 14213  14009   SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const BtreePayload *pPayload,
................................................................................
 14644  14440   #define OP_Function0     164 /* synopsis: r[P3]=func(r[P2@P5])             */
 14645  14441   #define OP_PureFunc      165
 14646  14442   #define OP_Function      166 /* synopsis: r[P3]=func(r[P2@P5])             */
 14647  14443   #define OP_Trace         167
 14648  14444   #define OP_CursorHint    168
 14649  14445   #define OP_Noop          169
 14650  14446   #define OP_Explain       170
 14651         -#define OP_Abortable     171
 14652  14447   
 14653  14448   /* Properties such as "out2" or "jump" that are specified in
 14654  14449   ** comments following the "case" for each opcode in the vdbe.c
 14655  14450   ** are encoded into bitvectors as follows:
 14656  14451   */
 14657  14452   #define OPFLG_JUMP        0x01  /* jump:  P2 holds jmp target */
 14658  14453   #define OPFLG_IN1         0x02  /* in1:   P1 is an input */
................................................................................
 14678  14473   /* 112 */ 0x00, 0x00, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00,\
 14679  14474   /* 120 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00,\
 14680  14475   /* 128 */ 0x04, 0x04, 0x00, 0x00, 0x10, 0x10, 0x10, 0x00,\
 14681  14476   /* 136 */ 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
 14682  14477   /* 144 */ 0x00, 0x06, 0x10, 0x00, 0x04, 0x1a, 0x00, 0x00,\
 14683  14478   /* 152 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
 14684  14479   /* 160 */ 0x00, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,\
 14685         -/* 168 */ 0x00, 0x00, 0x00, 0x00,}
        14480  +/* 168 */ 0x00, 0x00, 0x00,}
 14686  14481   
 14687  14482   /* The sqlite3P2Values() routine is able to run faster if it knows
 14688  14483   ** the value of the largest JUMP opcode.  The smaller the maximum
 14689  14484   ** JUMP opcode the better, so the mkopcodeh.tcl script that
 14690  14485   ** generated this include file strives to group all JUMP opcodes
 14691  14486   ** together near the beginning of the list.
 14692  14487   */
................................................................................
 14720  14515   #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
 14721  14516   SQLITE_PRIVATE   void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N);
 14722  14517   SQLITE_PRIVATE   void sqlite3VdbeVerifyNoResultRow(Vdbe *p);
 14723  14518   #else
 14724  14519   # define sqlite3VdbeVerifyNoMallocRequired(A,B)
 14725  14520   # define sqlite3VdbeVerifyNoResultRow(A)
 14726  14521   #endif
 14727         -#if defined(SQLITE_DEBUG)
 14728         -SQLITE_PRIVATE   void sqlite3VdbeVerifyAbortable(Vdbe *p, int);
 14729         -#else
 14730         -# define sqlite3VdbeVerifyAbortable(A,B)
 14731         -#endif
 14732         -SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp,int iLineno);
 14733         -#ifndef SQLITE_OMIT_EXPLAIN
 14734         -SQLITE_PRIVATE   void sqlite3VdbeExplain(Parse*,u8,const char*,...);
 14735         -SQLITE_PRIVATE   void sqlite3VdbeExplainPop(Parse*);
 14736         -SQLITE_PRIVATE   int sqlite3VdbeExplainParent(Parse*);
 14737         -# define ExplainQueryPlan(P)        sqlite3VdbeExplain P
 14738         -# define ExplainQueryPlanPop(P)     sqlite3VdbeExplainPop(P)
 14739         -# define ExplainQueryPlanParent(P)  sqlite3VdbeExplainParent(P)
 14740         -#else
 14741         -# define ExplainQueryPlan(P)
 14742         -# define ExplainQueryPlanPop(P)
 14743         -# define ExplainQueryPlanParent(P) 0
 14744         -#endif
        14522  +SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp, int iLineno);
 14745  14523   SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
 14746  14524   SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe*, u32 addr, u8);
 14747  14525   SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
 14748  14526   SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
 14749  14527   SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
 14750  14528   SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u16 P5);
 14751  14529   SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
................................................................................
 16041  15819   #define SQLITE_EnableTrigger  0x00040000  /* True to enable triggers */
 16042  15820   #define SQLITE_DeferFKs       0x00080000  /* Defer all FK constraints */
 16043  15821   #define SQLITE_QueryOnly      0x00100000  /* Disable database changes */
 16044  15822   #define SQLITE_CellSizeCk     0x00200000  /* Check btree cell sizes on load */
 16045  15823   #define SQLITE_Fts3Tokenizer  0x00400000  /* Enable fts3_tokenizer(2) */
 16046  15824   #define SQLITE_EnableQPSG     0x00800000  /* Query Planner Stability Guarantee*/
 16047  15825   #define SQLITE_TriggerEQP     0x01000000  /* Show trigger EXPLAIN QUERY PLAN */
 16048         -#define SQLITE_ResetDatabase  0x02000000  /* Reset the database */
 16049  15826   
 16050  15827   /* Flags used only if debugging */
 16051  15828   #ifdef SQLITE_DEBUG
 16052  15829   #define SQLITE_SqlTrace       0x08000000  /* Debug print SQL as it executes */
 16053  15830   #define SQLITE_VdbeListing    0x10000000  /* Debug listings of VDBE programs */
 16054  15831   #define SQLITE_VdbeTrace      0x20000000  /* True to trace VDBE execution */
 16055  15832   #define SQLITE_VdbeAddopTrace 0x40000000  /* Trace sqlite3VdbeAddOp() calls */
................................................................................
 17144  16921         unsigned notIndexed :1;    /* True if there is a NOT INDEXED clause */
 17145  16922         unsigned isIndexedBy :1;   /* True if there is an INDEXED BY clause */
 17146  16923         unsigned isTabFunc :1;     /* True if table-valued-function syntax */
 17147  16924         unsigned isCorrelated :1;  /* True if sub-query is correlated */
 17148  16925         unsigned viaCoroutine :1;  /* Implemented as a co-routine */
 17149  16926         unsigned isRecursive :1;   /* True for recursive reference in WITH */
 17150  16927       } fg;
        16928  +#ifndef SQLITE_OMIT_EXPLAIN
        16929  +    u8 iSelectId;     /* If pSelect!=0, the id of the sub-select in EQP */
        16930  +#endif
 17151  16931       int iCursor;      /* The VDBE cursor number used to access this table */
 17152  16932       Expr *pOn;        /* The ON clause of a join */
 17153  16933       IdList *pUsing;   /* The USING clause of a join */
 17154  16934       Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
 17155  16935       union {
 17156  16936         char *zIndexedBy;    /* Identifier from "INDEXED BY <zIndex>" clause */
 17157  16937         ExprList *pFuncArg;  /* Arguments to table-valued-function */
................................................................................
 17291  17071     int iIdxCur;              /* Index of the first index cursor */
 17292  17072   };
 17293  17073   
 17294  17074   /*
 17295  17075   ** An instance of the following structure contains all information
 17296  17076   ** needed to generate code for a single SELECT statement.
 17297  17077   **
 17298         -** See the header comment on the computeLimitRegisters() routine for a
 17299         -** detailed description of the meaning of the iLimit and iOffset fields.
        17078  +** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
        17079  +** If there is a LIMIT clause, the parser sets nLimit to the value of the
        17080  +** limit and nOffset to the value of the offset (or 0 if there is not
        17081  +** offset).  But later on, nLimit and nOffset become the memory locations
        17082  +** in the VDBE that record the limit and offset counters.
 17300  17083   **
 17301  17084   ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
 17302  17085   ** These addresses must be stored so that we can go back and fill in
 17303  17086   ** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
 17304  17087   ** the number of columns in P2 can be computed at the same time
 17305  17088   ** as the OP_OpenEphm instruction is coded because not
 17306  17089   ** enough information about the compound query is known at that point.
................................................................................
 17312  17095     ExprList *pEList;      /* The fields of the result */
 17313  17096     u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
 17314  17097     LogEst nSelectRow;     /* Estimated number of result rows */
 17315  17098     u32 selFlags;          /* Various SF_* values */
 17316  17099     int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
 17317  17100   #if SELECTTRACE_ENABLED
 17318  17101     char zSelName[12];     /* Symbolic name of this SELECT use for debugging */
        17102  +  u32 iSelectId;         /* EXPLAIN QUERY PLAN select ID */
 17319  17103   #endif
 17320  17104     int addrOpenEphm[2];   /* OP_OpenEphem opcodes related to this select */
 17321  17105     SrcList *pSrc;         /* The FROM clause */
 17322  17106     Expr *pWhere;          /* The WHERE clause */
 17323  17107     ExprList *pGroupBy;    /* The GROUP BY clause */
 17324  17108     Expr *pHaving;         /* The HAVING clause */
 17325  17109     ExprList *pOrderBy;    /* The ORDER BY clause */
................................................................................
 17352  17136   #define SF_NestedFrom     0x00800  /* Part of a parenthesized FROM clause */
 17353  17137   #define SF_MinMaxAgg      0x01000  /* Aggregate containing min() or max() */
 17354  17138   #define SF_Recursive      0x02000  /* The recursive part of a recursive CTE */
 17355  17139   #define SF_FixedLimit     0x04000  /* nSelectRow set by a constant LIMIT */
 17356  17140   #define SF_MaybeConvert   0x08000  /* Need convertCompoundSelectToSubquery() */
 17357  17141   #define SF_Converted      0x10000  /* By convertCompoundSelectToSubquery() */
 17358  17142   #define SF_IncludeHidden  0x20000  /* Include hidden columns in output */
 17359         -#define SF_ComplexResult  0x40000  /* Result contains subquery or function */
        17143  +#define SF_ComplexResult  0x40000  /* Result set contains subquery or function */
        17144  +
 17360  17145   
 17361  17146   /*
 17362  17147   ** The results of a SELECT can be distributed in several ways, as defined
 17363  17148   ** by one of the following macros.  The "SRT" prefix means "SELECT Result
 17364  17149   ** Type".
 17365  17150   **
 17366  17151   **     SRT_Union       Store results as a key in a temporary index
................................................................................
 17622  17407     u8 explain;               /* True if the EXPLAIN flag is found on the query */
 17623  17408   #ifndef SQLITE_OMIT_VIRTUALTABLE
 17624  17409     u8 declareVtab;           /* True if inside sqlite3_declare_vtab() */
 17625  17410     int nVtabLock;            /* Number of virtual tables to lock */
 17626  17411   #endif
 17627  17412     int nHeight;              /* Expression tree height of current sub-select */
 17628  17413   #ifndef SQLITE_OMIT_EXPLAIN
 17629         -  int addrExplain;          /* Address of current OP_Explain opcode */
        17414  +  int iSelectId;            /* ID of current select for EXPLAIN output */
        17415  +  int iNextSelectId;        /* Next available select ID for EXPLAIN output */
 17630  17416   #endif
 17631  17417     VList *pVList;            /* Mapping between variable names and numbers */
 17632  17418     Vdbe *pReprepare;         /* VM being reprepared (sqlite3Reprepare()) */
 17633  17419     const char *zTail;        /* All SQL text past the last semicolon parsed */
 17634  17420     Table *pNewTable;         /* A table being constructed by CREATE TABLE */
 17635  17421     Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
 17636  17422     const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
................................................................................
 17808  17594     const Token *pName; /* Name of the container - used for error messages */
 17809  17595   };
 17810  17596   
 17811  17597   /*
 17812  17598   ** An objected used to accumulate the text of a string where we
 17813  17599   ** do not necessarily know how big the string will be in the end.
 17814  17600   */
 17815         -struct sqlite3_str {
        17601  +struct StrAccum {
 17816  17602     sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
 17817  17603     char *zText;         /* The string collected so far */
 17818  17604     u32  nAlloc;         /* Amount of space allocated in zText */
 17819  17605     u32  mxAlloc;        /* Maximum allowed allocation.  0 for no malloc usage */
 17820  17606     u32  nChar;          /* Length of the string so far */
 17821         -  u8   accError;       /* SQLITE_NOMEM or SQLITE_TOOBIG */
        17607  +  u8   accError;       /* STRACCUM_NOMEM or STRACCUM_TOOBIG */
 17822  17608     u8   printfFlags;    /* SQLITE_PRINTF flags below */
 17823  17609   };
        17610  +#define STRACCUM_NOMEM   1
        17611  +#define STRACCUM_TOOBIG  2
 17824  17612   #define SQLITE_PRINTF_INTERNAL 0x01  /* Internal-use-only converters allowed */
 17825  17613   #define SQLITE_PRINTF_SQLFUNC  0x02  /* SQL function arguments to VXPrintf */
 17826  17614   #define SQLITE_PRINTF_MALLOCED 0x04  /* True if xText is allocated space */
 17827  17615   
 17828  17616   #define isMalloced(X)  (((X)->printfFlags & SQLITE_PRINTF_MALLOCED)!=0)
 17829  17617   
 17830  17618   
................................................................................
 18185  17973   */
 18186  17974   struct PrintfArguments {
 18187  17975     int nArg;                /* Total number of arguments */
 18188  17976     int nUsed;               /* Number of arguments used so far */
 18189  17977     sqlite3_value **apArg;   /* The argument values */
 18190  17978   };
 18191  17979   
        17980  +SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, const char*, va_list);
        17981  +SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
 18192  17982   SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
 18193  17983   SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
 18194  17984   #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
 18195  17985   SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
 18196  17986   #endif
 18197  17987   #if defined(SQLITE_TEST)
 18198  17988   SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
................................................................................
 18701  18491   SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
 18702  18492   #endif
 18703  18493   SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
 18704  18494     void (*)(sqlite3_context*,int,sqlite3_value **),
 18705  18495     void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
 18706  18496     FuncDestructor *pDestructor
 18707  18497   );
 18708         -SQLITE_PRIVATE void sqlite3NoopDestructor(void*);
 18709  18498   SQLITE_PRIVATE void sqlite3OomFault(sqlite3*);
 18710  18499   SQLITE_PRIVATE void sqlite3OomClear(sqlite3*);
 18711  18500   SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
 18712  18501   SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
 18713  18502   
 18714  18503   SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int);
        18504  +SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
        18505  +SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum*,const char*);
        18506  +SQLITE_PRIVATE void sqlite3AppendChar(StrAccum*,int,char);
 18715  18507   SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
        18508  +SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
 18716  18509   SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
 18717  18510   SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
 18718  18511   
 18719  18512   SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
 18720  18513   SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
 18721  18514   
 18722  18515   #ifndef SQLITE_OMIT_SUBQUERY
................................................................................
 18804  18597   SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
 18805  18598   SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
 18806  18599   SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
 18807  18600   SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
 18808  18601   SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
 18809  18602   SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
 18810  18603   SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
        18604  +SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
 18811  18605   SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
 18812  18606   SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
 18813  18607   SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
 18814  18608   SQLITE_PRIVATE void sqlite3ParserReset(Parse*);
 18815  18609   SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
 18816  18610   SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
 18817  18611   SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
................................................................................
 19733  19527     VList *pVList;          /* Name of variables */
 19734  19528   #ifndef SQLITE_OMIT_TRACE
 19735  19529     i64 startTime;          /* Time when query started - used for profiling */
 19736  19530   #endif
 19737  19531     int nOp;                /* Number of instructions in the program */
 19738  19532   #ifdef SQLITE_DEBUG
 19739  19533     int rcApp;              /* errcode set by sqlite3_result_error_code() */
 19740         -  u32 nWrite;             /* Number of write operations that have occurred */
 19741  19534   #endif
 19742  19535     u16 nResColumn;         /* Number of columns in one row of the result set */
 19743  19536     u8 errorAction;         /* Recovery action to do in case of an error */
 19744  19537     u8 minWriteFileFormat;  /* Minimum file format for writable database files */
 19745  19538     u8 prepFlags;           /* SQLITE_PREPARE_* flags */
 19746  19539     bft expired:1;          /* True if the VM needs to be recompiled */
 19747  19540     bft doingRerun:1;       /* True if rerunning after an auto-reprepare */
................................................................................
 19869  19662   SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
 19870  19663   SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
 19871  19664   SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *);
 19872  19665   SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *, int *);
 19873  19666   SQLITE_PRIVATE int sqlite3VdbeSorterWrite(const VdbeCursor *, Mem *);
 19874  19667   SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);
 19875  19668   
 19876         -#ifdef SQLITE_DEBUG
 19877         -SQLITE_PRIVATE   void sqlite3VdbeIncrWriteCounter(Vdbe*, VdbeCursor*);
 19878         -SQLITE_PRIVATE   void sqlite3VdbeAssertAbortable(Vdbe*);
 19879         -#else
 19880         -# define sqlite3VdbeIncrWriteCounter(V,C)
 19881         -# define sqlite3VdbeAssertAbortable(V)
 19882         -#endif
 19883         -
 19884  19669   #if !defined(SQLITE_OMIT_SHARED_CACHE) 
 19885  19670   SQLITE_PRIVATE   void sqlite3VdbeEnter(Vdbe*);
 19886  19671   #else
 19887  19672   # define sqlite3VdbeEnter(X)
 19888  19673   #endif
 19889  19674   
 19890  19675   #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
................................................................................
 24568  24353   SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
 24569  24354     assert( p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld );
 24570  24355     return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
 24571  24356   }
 24572  24357   #endif
 24573  24358   
 24574  24359   #endif /* !defined(SQLITE_MUTEX_OMIT) */
        24360  +
 24575  24361   
 24576  24362   /************** End of mutex.c ***********************************************/
 24577  24363   /************** Begin file mutex_noop.c **************************************/
 24578  24364   /*
 24579  24365   ** 2008 October 07
 24580  24366   **
 24581  24367   ** The author disclaims copyright to this source code.  In place of
................................................................................
 26732  26518   }
 26733  26519   #endif /* SQLITE_OMIT_FLOATING_POINT */
 26734  26520   
 26735  26521   /*
 26736  26522   ** Set the StrAccum object to an error mode.
 26737  26523   */
 26738  26524   static void setStrAccumError(StrAccum *p, u8 eError){
 26739         -  assert( eError==SQLITE_NOMEM || eError==SQLITE_TOOBIG );
        26525  +  assert( eError==STRACCUM_NOMEM || eError==STRACCUM_TOOBIG );
 26740  26526     p->accError = eError;
 26741  26527     p->nAlloc = 0;
 26742  26528   }
 26743  26529   
 26744  26530   /*
 26745  26531   ** Extra argument values from a PrintfArguments object
 26746  26532   */
................................................................................
 26766  26552   # define SQLITE_PRINT_BUF_SIZE 70
 26767  26553   #endif
 26768  26554   #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
 26769  26555   
 26770  26556   /*
 26771  26557   ** Render a string given by "fmt" into the StrAccum object.
 26772  26558   */
 26773         -SQLITE_API void sqlite3_str_vappendf(
 26774         -  sqlite3_str *pAccum,       /* Accumulate results here */
        26559  +SQLITE_PRIVATE void sqlite3VXPrintf(
        26560  +  StrAccum *pAccum,          /* Accumulate results here */
 26775  26561     const char *fmt,           /* Format string */
 26776  26562     va_list ap                 /* arguments */
 26777  26563   ){
 26778  26564     int c;                     /* Next character in the format string */
 26779  26565     char *bufpt;               /* Pointer to the conversion buffer */
 26780  26566     int precision;             /* Precision of the current field */
 26781  26567     int length;                /* Length of the field */
................................................................................
 26824  26610       if( c!='%' ){
 26825  26611         bufpt = (char *)fmt;
 26826  26612   #if HAVE_STRCHRNUL
 26827  26613         fmt = strchrnul(fmt, '%');
 26828  26614   #else
 26829  26615         do{ fmt++; }while( *fmt && *fmt != '%' );
 26830  26616   #endif
 26831         -      sqlite3_str_append(pAccum, bufpt, (int)(fmt - bufpt));
        26617  +      sqlite3StrAccumAppend(pAccum, bufpt, (int)(fmt - bufpt));
 26832  26618         if( *fmt==0 ) break;
 26833  26619       }
 26834  26620       if( (c=(*++fmt))==0 ){
 26835         -      sqlite3_str_append(pAccum, "%", 1);
        26621  +      sqlite3StrAccumAppend(pAccum, "%", 1);
 26836  26622         break;
 26837  26623       }
 26838  26624       /* Find out what flags are present */
 26839  26625       flag_leftjustify = flag_prefix = cThousand =
 26840  26626        flag_alternateform = flag_altform2 = flag_zeropad = 0;
 26841  26627       done = 0;
 26842  26628       do{
................................................................................
 27006  26792           if( precision<etBUFSIZE-10-etBUFSIZE/3 ){
 27007  26793             nOut = etBUFSIZE;
 27008  26794             zOut = buf;
 27009  26795           }else{
 27010  26796             u64 n = (u64)precision + 10 + precision/3;
 27011  26797             zOut = zExtra = sqlite3Malloc( n );
 27012  26798             if( zOut==0 ){
 27013         -            setStrAccumError(pAccum, SQLITE_NOMEM);
        26799  +            setStrAccumError(pAccum, STRACCUM_NOMEM);
 27014  26800               return;
 27015  26801             }
 27016  26802             nOut = (int)n;
 27017  26803           }
 27018  26804           bufpt = &zOut[nOut-1];
 27019  26805           if( xtype==etORDINAL ){
 27020  26806             static const char zOrd[] = "thstndrd";
................................................................................
 27131  26917           }else{
 27132  26918             e2 = exp;
 27133  26919           }
 27134  26920           if( MAX(e2,0)+(i64)precision+(i64)width > etBUFSIZE - 15 ){
 27135  26921             bufpt = zExtra 
 27136  26922                 = sqlite3Malloc( MAX(e2,0)+(i64)precision+(i64)width+15 );
 27137  26923             if( bufpt==0 ){
 27138         -            setStrAccumError(pAccum, SQLITE_NOMEM);
        26924  +            setStrAccumError(pAccum, STRACCUM_NOMEM);
 27139  26925               return;
 27140  26926             }
 27141  26927           }
 27142  26928           zOut = bufpt;
 27143  26929           nsd = 16 + flag_altform2*10;
 27144  26930           flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
 27145  26931           /* The sign in front of the number */
................................................................................
 27263  27049               buf[3] = 0x80 + (u8)(ch & 0x3f);
 27264  27050               length = 4;
 27265  27051             }
 27266  27052           }
 27267  27053           if( precision>1 ){
 27268  27054             width -= precision-1;
 27269  27055             if( width>1 && !flag_leftjustify ){
 27270         -            sqlite3_str_appendchar(pAccum, width-1, ' ');
        27056  +            sqlite3AppendChar(pAccum, width-1, ' ');
 27271  27057               width = 0;
 27272  27058             }
 27273  27059             while( precision-- > 1 ){
 27274         -            sqlite3_str_append(pAccum, buf, length);
        27060  +            sqlite3StrAccumAppend(pAccum, buf, length);
 27275  27061             }
 27276  27062           }
 27277  27063           bufpt = buf;
 27278  27064           flag_altform2 = 1;
 27279  27065           goto adjust_width_for_utf8;
 27280  27066         case etSTRING:
 27281  27067         case etDYNSTRING:
................................................................................
 27353  27139             }
 27354  27140           }
 27355  27141           needQuote = !isnull && xtype==etSQLESCAPE2;
 27356  27142           n += i + 3;
 27357  27143           if( n>etBUFSIZE ){
 27358  27144             bufpt = zExtra = sqlite3Malloc( n );
 27359  27145             if( bufpt==0 ){
 27360         -            setStrAccumError(pAccum, SQLITE_NOMEM);
        27146  +            setStrAccumError(pAccum, STRACCUM_NOMEM);
 27361  27147               return;
 27362  27148             }
 27363  27149           }else{
 27364  27150             bufpt = buf;
 27365  27151           }
 27366  27152           j = 0;
 27367  27153           if( needQuote ) bufpt[j++] = q;
................................................................................
 27377  27163         }
 27378  27164         case etTOKEN: {
 27379  27165           Token *pToken;
 27380  27166           if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
 27381  27167           pToken = va_arg(ap, Token*);
 27382  27168           assert( bArgList==0 );
 27383  27169           if( pToken && pToken->n ){
 27384         -          sqlite3_str_append(pAccum, (const char*)pToken->z, pToken->n);
        27170  +          sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
 27385  27171           }
 27386  27172           length = width = 0;
 27387  27173           break;
 27388  27174         }
 27389  27175         case etSRCLIST: {
 27390  27176           SrcList *pSrc;
 27391  27177           int k;
................................................................................
 27393  27179           if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
 27394  27180           pSrc = va_arg(ap, SrcList*);
 27395  27181           k = va_arg(ap, int);
 27396  27182           pItem = &pSrc->a[k];
 27397  27183           assert( bArgList==0 );
 27398  27184           assert( k>=0 && k<pSrc->nSrc );
 27399  27185           if( pItem->zDatabase ){
 27400         -          sqlite3_str_appendall(pAccum, pItem->zDatabase);
 27401         -          sqlite3_str_append(pAccum, ".", 1);
        27186  +          sqlite3StrAccumAppendAll(pAccum, pItem->zDatabase);
        27187  +          sqlite3StrAccumAppend(pAccum, ".", 1);
 27402  27188           }
 27403         -        sqlite3_str_appendall(pAccum, pItem->zName);
        27189  +        sqlite3StrAccumAppendAll(pAccum, pItem->zName);
 27404  27190           length = width = 0;
 27405  27191           break;
 27406  27192         }
 27407  27193         default: {
 27408  27194           assert( xtype==etINVALID );
 27409  27195           return;
 27410  27196         }
................................................................................
 27415  27201       ** the output.  Both length and width are in bytes, not characters,
 27416  27202       ** at this point.  If the "!" flag was present on string conversions
 27417  27203       ** indicating that width and precision should be expressed in characters,
 27418  27204       ** then the values have been translated prior to reaching this point.
 27419  27205       */
 27420  27206       width -= length;
 27421  27207       if( width>0 ){
 27422         -      if( !flag_leftjustify ) sqlite3_str_appendchar(pAccum, width, ' ');
 27423         -      sqlite3_str_append(pAccum, bufpt, length);
 27424         -      if( flag_leftjustify ) sqlite3_str_appendchar(pAccum, width, ' ');
        27208  +      if( !flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
        27209  +      sqlite3StrAccumAppend(pAccum, bufpt, length);
        27210  +      if( flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
 27425  27211       }else{
 27426         -      sqlite3_str_append(pAccum, bufpt, length);
        27212  +      sqlite3StrAccumAppend(pAccum, bufpt, length);
 27427  27213       }
 27428  27214   
 27429  27215       if( zExtra ){
 27430  27216         sqlite3DbFree(pAccum->db, zExtra);
 27431  27217         zExtra = 0;
 27432  27218       }
 27433  27219     }/* End for loop over the format string */
................................................................................
 27440  27226   ** Return the number of bytes of text that StrAccum is able to accept
 27441  27227   ** after the attempted enlargement.  The value returned might be zero.
 27442  27228   */
 27443  27229   static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
 27444  27230     char *zNew;
 27445  27231     assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */
 27446  27232     if( p->accError ){
 27447         -    testcase(p->accError==SQLITE_TOOBIG);
 27448         -    testcase(p->accError==SQLITE_NOMEM);
        27233  +    testcase(p->accError==STRACCUM_TOOBIG);
        27234  +    testcase(p->accError==STRACCUM_NOMEM);
 27449  27235       return 0;
 27450  27236     }
 27451  27237     if( p->mxAlloc==0 ){
 27452  27238       N = p->nAlloc - p->nChar - 1;
 27453         -    setStrAccumError(p, SQLITE_TOOBIG);
        27239  +    setStrAccumError(p, STRACCUM_TOOBIG);
 27454  27240       return N;
 27455  27241     }else{
 27456  27242       char *zOld = isMalloced(p) ? p->zText : 0;
 27457  27243       i64 szNew = p->nChar;
 27458  27244       szNew += N + 1;
 27459  27245       if( szNew+p->nChar<=p->mxAlloc ){
 27460  27246         /* Force exponential buffer size growth as long as it does not overflow,
 27461  27247         ** to avoid having to call this routine too often */
 27462  27248         szNew += p->nChar;
 27463  27249       }
 27464  27250       if( szNew > p->mxAlloc ){
 27465         -      sqlite3_str_reset(p);
 27466         -      setStrAccumError(p, SQLITE_TOOBIG);
        27251  +      sqlite3StrAccumReset(p);
        27252  +      setStrAccumError(p, STRACCUM_TOOBIG);
 27467  27253         return 0;
 27468  27254       }else{
 27469  27255         p->nAlloc = (int)szNew;
 27470  27256       }
 27471  27257       if( p->db ){
 27472  27258         zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
 27473  27259       }else{
................................................................................
 27476  27262       if( zNew ){
 27477  27263         assert( p->zText!=0 || p->nChar==0 );
 27478  27264         if( !isMalloced(p) && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
 27479  27265         p->zText = zNew;
 27480  27266         p->nAlloc = sqlite3DbMallocSize(p->db, zNew);
 27481  27267         p->printfFlags |= SQLITE_PRINTF_MALLOCED;
 27482  27268       }else{
 27483         -      sqlite3_str_reset(p);
 27484         -      setStrAccumError(p, SQLITE_NOMEM);
        27269  +      sqlite3StrAccumReset(p);
        27270  +      setStrAccumError(p, STRACCUM_NOMEM);
 27485  27271         return 0;
 27486  27272       }
 27487  27273     }
 27488  27274     return N;
 27489  27275   }
 27490  27276   
 27491  27277   /*
 27492  27278   ** Append N copies of character c to the given string buffer.
 27493  27279   */
 27494         -SQLITE_API void sqlite3_str_appendchar(sqlite3_str *p, int N, char c){
        27280  +SQLITE_PRIVATE void sqlite3AppendChar(StrAccum *p, int N, char c){
 27495  27281     testcase( p->nChar + (i64)N > 0x7fffffff );
 27496  27282     if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
 27497  27283       return;
 27498  27284     }
 27499  27285     while( (N--)>0 ) p->zText[p->nChar++] = c;
 27500  27286   }
 27501  27287   
 27502  27288   /*
 27503  27289   ** The StrAccum "p" is not large enough to accept N new bytes of z[].
 27504  27290   ** So enlarge if first, then do the append.
 27505  27291   **
 27506         -** This is a helper routine to sqlite3_str_append() that does special-case
        27292  +** This is a helper routine to sqlite3StrAccumAppend() that does special-case
 27507  27293   ** work (enlarging the buffer) using tail recursion, so that the
 27508         -** sqlite3_str_append() routine can use fast calling semantics.
        27294  +** sqlite3StrAccumAppend() routine can use fast calling semantics.
 27509  27295   */
 27510  27296   static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
 27511  27297     N = sqlite3StrAccumEnlarge(p, N);
 27512  27298     if( N>0 ){
 27513  27299       memcpy(&p->zText[p->nChar], z, N);
 27514  27300       p->nChar += N;
 27515  27301     }
 27516  27302   }
 27517  27303   
 27518  27304   /*
 27519  27305   ** Append N bytes of text from z to the StrAccum object.  Increase the
 27520  27306   ** size of the memory allocation for StrAccum if necessary.
 27521  27307   */
 27522         -SQLITE_API void sqlite3_str_append(sqlite3_str *p, const char *z, int N){
        27308  +SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
 27523  27309     assert( z!=0 || N==0 );
 27524  27310     assert( p->zText!=0 || p->nChar==0 || p->accError );
 27525  27311     assert( N>=0 );
 27526  27312     assert( p->accError==0 || p->nAlloc==0 );
 27527  27313     if( p->nChar+N >= p->nAlloc ){
 27528  27314       enlargeAndAppend(p,z,N);
 27529  27315     }else if( N ){
................................................................................
 27532  27318       memcpy(&p->zText[p->nChar-N], z, N);
 27533  27319     }
 27534  27320   }
 27535  27321   
 27536  27322   /*
 27537  27323   ** Append the complete text of zero-terminated string z[] to the p string.
 27538  27324   */
 27539         -SQLITE_API void sqlite3_str_appendall(sqlite3_str *p, const char *z){
 27540         -  sqlite3_str_append(p, z, sqlite3Strlen30(z));
        27325  +SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum *p, const char *z){
        27326  +  sqlite3StrAccumAppend(p, z, sqlite3Strlen30(z));
 27541  27327   }
 27542  27328   
 27543  27329   
 27544  27330   /*
 27545  27331   ** Finish off a string by making sure it is zero-terminated.
 27546  27332   ** Return a pointer to the resulting string.  Return a NULL
 27547  27333   ** pointer if any kind of error was encountered.
................................................................................
 27550  27336     char *zText;
 27551  27337     assert( p->mxAlloc>0 && !isMalloced(p) );
 27552  27338     zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
 27553  27339     if( zText ){
 27554  27340       memcpy(zText, p->zText, p->nChar+1);
 27555  27341       p->printfFlags |= SQLITE_PRINTF_MALLOCED;
 27556  27342     }else{
 27557         -    setStrAccumError(p, SQLITE_NOMEM);
        27343  +    setStrAccumError(p, STRACCUM_NOMEM);
 27558  27344     }
 27559  27345     p->zText = zText;
 27560  27346     return zText;
 27561  27347   }
 27562  27348   SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
 27563  27349     if( p->zText ){
 27564  27350       p->zText[p->nChar] = 0;
................................................................................
 27565  27351       if( p->mxAlloc>0 && !isMalloced(p) ){
 27566  27352         return strAccumFinishRealloc(p);
 27567  27353       }
 27568  27354     }
 27569  27355     return p->zText;
 27570  27356   }
 27571  27357   
 27572         -/*
 27573         -** This singleton is an sqlite3_str object that is returned if
 27574         -** sqlite3_malloc() fails to provide space for a real one.  This
 27575         -** sqlite3_str object accepts no new text and always returns
 27576         -** an SQLITE_NOMEM error.
 27577         -*/
 27578         -static sqlite3_str sqlite3OomStr = {
 27579         -   0, 0, 0, 0, 0, SQLITE_NOMEM, 0
 27580         -};
 27581         -
 27582         -/* Finalize a string created using sqlite3_str_new().
 27583         -*/
 27584         -SQLITE_API char *sqlite3_str_finish(sqlite3_str *p){
 27585         -  char *z;
 27586         -  if( p!=0 && p!=&sqlite3OomStr ){
 27587         -    z = sqlite3StrAccumFinish(p);
 27588         -    sqlite3_free(p);
 27589         -  }else{
 27590         -    z = 0;
 27591         -  }
 27592         -  return z;
 27593         -}
 27594         -
 27595         -/* Return any error code associated with p */
 27596         -SQLITE_API int sqlite3_str_errcode(sqlite3_str *p){
 27597         -  return p ? p->accError : SQLITE_NOMEM;
 27598         -}
 27599         -
 27600         -/* Return the current length of p in bytes */
 27601         -SQLITE_API int sqlite3_str_length(sqlite3_str *p){
 27602         -  return p ? p->nChar : 0;
 27603         -}
 27604         -
 27605         -/* Return the current value for p */
 27606         -SQLITE_API char *sqlite3_str_value(sqlite3_str *p){
 27607         -  if( p==0 || p->nChar==0 ) return 0;
 27608         -  p->zText[p->nChar] = 0;
 27609         -  return p->zText;
 27610         -}
 27611         -
 27612  27358   /*
 27613  27359   ** Reset an StrAccum string.  Reclaim all malloced memory.
 27614  27360   */
 27615         -SQLITE_API void sqlite3_str_reset(StrAccum *p){
        27361  +SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
 27616  27362     if( isMalloced(p) ){
 27617  27363       sqlite3DbFree(p->db, p->zText);
 27618  27364       p->printfFlags &= ~SQLITE_PRINTF_MALLOCED;
 27619  27365     }
 27620         -  p->nAlloc = 0;
 27621         -  p->nChar = 0;
 27622  27366     p->zText = 0;
 27623  27367   }
 27624  27368   
 27625  27369   /*
 27626  27370   ** Initialize a string accumulator.
 27627  27371   **
 27628  27372   ** p:     The accumulator to be initialized.
................................................................................
 27642  27386     p->nAlloc = n;
 27643  27387     p->mxAlloc = mx;
 27644  27388     p->nChar = 0;
 27645  27389     p->accError = 0;
 27646  27390     p->printfFlags = 0;
 27647  27391   }
 27648  27392   
 27649         -/* Allocate and initialize a new dynamic string object */
 27650         -SQLITE_API sqlite3_str *sqlite3_str_new(sqlite3 *db){
 27651         -  sqlite3_str *p = sqlite3_malloc64(sizeof(*p));
 27652         -  if( p ){
 27653         -    sqlite3StrAccumInit(p, 0, 0, 0,
 27654         -            db ? db->aLimit[SQLITE_LIMIT_LENGTH] : SQLITE_MAX_LENGTH);
 27655         -  }else{
 27656         -    p = &sqlite3OomStr;
 27657         -  }
 27658         -  return p;
 27659         -}
 27660         -
 27661  27393   /*
 27662  27394   ** Print into memory obtained from sqliteMalloc().  Use the internal
 27663  27395   ** %-conversion extensions.
 27664  27396   */
 27665  27397   SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
 27666  27398     char *z;
 27667  27399     char zBase[SQLITE_PRINT_BUF_SIZE];
 27668  27400     StrAccum acc;
 27669  27401     assert( db!=0 );
 27670  27402     sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase),
 27671  27403                         db->aLimit[SQLITE_LIMIT_LENGTH]);
 27672  27404     acc.printfFlags = SQLITE_PRINTF_INTERNAL;
 27673         -  sqlite3_str_vappendf(&acc, zFormat, ap);
        27405  +  sqlite3VXPrintf(&acc, zFormat, ap);
 27674  27406     z = sqlite3StrAccumFinish(&acc);
 27675         -  if( acc.accError==SQLITE_NOMEM ){
        27407  +  if( acc.accError==STRACCUM_NOMEM ){
 27676  27408       sqlite3OomFault(db);
 27677  27409     }
 27678  27410     return z;
 27679  27411   }
 27680  27412   
 27681  27413   /*
 27682  27414   ** Print into memory obtained from sqliteMalloc().  Use the internal
................................................................................
 27706  27438       return 0;
 27707  27439     }
 27708  27440   #endif
 27709  27441   #ifndef SQLITE_OMIT_AUTOINIT
 27710  27442     if( sqlite3_initialize() ) return 0;
 27711  27443   #endif
 27712  27444     sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
 27713         -  sqlite3_str_vappendf(&acc, zFormat, ap);
        27445  +  sqlite3VXPrintf(&acc, zFormat, ap);
 27714  27446     z = sqlite3StrAccumFinish(&acc);
 27715  27447     return z;
 27716  27448   }
 27717  27449   
 27718  27450   /*
 27719  27451   ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
 27720  27452   ** %-conversion extensions.
................................................................................
 27751  27483     if( zBuf==0 || zFormat==0 ) {
 27752  27484       (void)SQLITE_MISUSE_BKPT;
 27753  27485       if( zBuf ) zBuf[0] = 0;
 27754  27486       return zBuf;
 27755  27487     }
 27756  27488   #endif
 27757  27489     sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
 27758         -  sqlite3_str_vappendf(&acc, zFormat, ap);
        27490  +  sqlite3VXPrintf(&acc, zFormat, ap);
 27759  27491     zBuf[acc.nChar] = 0;
 27760  27492     return zBuf;
 27761  27493   }
 27762  27494   SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
 27763  27495     char *z;
 27764  27496     va_list ap;
 27765  27497     va_start(ap,zFormat);
................................................................................
 27773  27505   ** We house it in a separate routine from sqlite3_log() to avoid using
 27774  27506   ** stack space on small-stack systems when logging is disabled.
 27775  27507   **
 27776  27508   ** sqlite3_log() must render into a static buffer.  It cannot dynamically
 27777  27509   ** allocate memory because it might be called while the memory allocator
 27778  27510   ** mutex is held.
 27779  27511   **
 27780         -** sqlite3_str_vappendf() might ask for *temporary* memory allocations for
        27512  +** sqlite3VXPrintf() might ask for *temporary* memory allocations for
 27781  27513   ** certain format characters (%q) or for very large precisions or widths.
 27782  27514   ** Care must be taken that any sqlite3_log() calls that occur while the
 27783  27515   ** memory mutex is held do not use these mechanisms.
 27784  27516   */
 27785  27517   static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
 27786  27518     StrAccum acc;                          /* String accumulator */
 27787  27519     char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
 27788  27520   
 27789  27521     sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0);
 27790         -  sqlite3_str_vappendf(&acc, zFormat, ap);
        27522  +  sqlite3VXPrintf(&acc, zFormat, ap);
 27791  27523     sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
 27792  27524                              sqlite3StrAccumFinish(&acc));
 27793  27525   }
 27794  27526   
 27795  27527   /*
 27796  27528   ** Format and write a message to the log if logging is enabled.
 27797  27529   */
................................................................................
 27812  27544   */
 27813  27545   SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
 27814  27546     va_list ap;
 27815  27547     StrAccum acc;
 27816  27548     char zBuf[500];
 27817  27549     sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
 27818  27550     va_start(ap,zFormat);
 27819         -  sqlite3_str_vappendf(&acc, zFormat, ap);
        27551  +  sqlite3VXPrintf(&acc, zFormat, ap);
 27820  27552     va_end(ap);
 27821  27553     sqlite3StrAccumFinish(&acc);
 27822  27554   #ifdef SQLITE_OS_TRACE_PROC
 27823  27555     {
 27824  27556       extern void SQLITE_OS_TRACE_PROC(const char *zBuf, int nBuf);
 27825  27557       SQLITE_OS_TRACE_PROC(zBuf, sizeof(zBuf));
 27826  27558     }
................................................................................
 27829  27561     fflush(stdout);
 27830  27562   #endif
 27831  27563   }
 27832  27564   #endif
 27833  27565   
 27834  27566   
 27835  27567   /*
 27836         -** variable-argument wrapper around sqlite3_str_vappendf(). The bFlags argument
        27568  +** variable-argument wrapper around sqlite3VXPrintf().  The bFlags argument
 27837  27569   ** can contain the bit SQLITE_PRINTF_INTERNAL enable internal formats.
 27838  27570   */
 27839         -SQLITE_API void sqlite3_str_appendf(StrAccum *p, const char *zFormat, ...){
        27571  +SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
 27840  27572     va_list ap;
 27841  27573     va_start(ap,zFormat);
 27842         -  sqlite3_str_vappendf(p, zFormat, ap);
        27574  +  sqlite3VXPrintf(p, zFormat, ap);
 27843  27575     va_end(ap);
 27844  27576   }
 27845  27577   
 27846  27578   /************** End of printf.c **********************************************/
 27847  27579   /************** Begin file treeview.c ****************************************/
 27848  27580   /*
 27849  27581   ** 2015-06-08
................................................................................
 27901  27633     va_list ap;
 27902  27634     int i;
 27903  27635     StrAccum acc;
 27904  27636     char zBuf[500];
 27905  27637     sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
 27906  27638     if( p ){
 27907  27639       for(i=0; i<p->iLevel && i<sizeof(p->bLine)-1; i++){
 27908         -      sqlite3_str_append(&acc, p->bLine[i] ? "|   " : "    ", 4);
        27640  +      sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|   " : "    ", 4);
 27909  27641       }
 27910         -    sqlite3_str_append(&acc, p->bLine[i] ? "|-- " : "'-- ", 4);
        27642  +    sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|-- " : "'-- ", 4);
 27911  27643     }
 27912  27644     if( zFormat!=0 ){
 27913  27645       va_start(ap, zFormat);
 27914         -    sqlite3_str_vappendf(&acc, zFormat, ap);
        27646  +    sqlite3VXPrintf(&acc, zFormat, ap);
 27915  27647       va_end(ap);
 27916  27648       assert( acc.nChar>0 );
 27917         -    sqlite3_str_append(&acc, "\n", 1);
        27649  +    sqlite3StrAccumAppend(&acc, "\n", 1);
 27918  27650     }
 27919  27651     sqlite3StrAccumFinish(&acc);
 27920  27652     fprintf(stdout,"%s", zBuf);
 27921  27653     fflush(stdout);
 27922  27654   }
 27923  27655   
 27924  27656   /*
................................................................................
 27944  27676     if( pWith->nCte>0 ){
 27945  27677       pView = sqlite3TreeViewPush(pView, 1);
 27946  27678       for(i=0; i<pWith->nCte; i++){
 27947  27679         StrAccum x;
 27948  27680         char zLine[1000];
 27949  27681         const struct Cte *pCte = &pWith->a[i];
 27950  27682         sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
 27951         -      sqlite3_str_appendf(&x, "%s", pCte->zName);
        27683  +      sqlite3XPrintf(&x, "%s", pCte->zName);
 27952  27684         if( pCte->pCols && pCte->pCols->nExpr>0 ){
 27953  27685           char cSep = '(';
 27954  27686           int j;
 27955  27687           for(j=0; j<pCte->pCols->nExpr; j++){
 27956         -          sqlite3_str_appendf(&x, "%c%s", cSep, pCte->pCols->a[j].zName);
        27688  +          sqlite3XPrintf(&x, "%c%s", cSep, pCte->pCols->a[j].zName);
 27957  27689             cSep = ',';
 27958  27690           }
 27959         -        sqlite3_str_appendf(&x, ")");
        27691  +        sqlite3XPrintf(&x, ")");
 27960  27692         }
 27961         -      sqlite3_str_appendf(&x, " AS");
        27693  +      sqlite3XPrintf(&x, " AS");
 27962  27694         sqlite3StrAccumFinish(&x);
 27963  27695         sqlite3TreeViewItem(pView, zLine, i<pWith->nCte-1);
 27964  27696         sqlite3TreeViewSelect(pView, pCte->pSelect, 0);
 27965  27697         sqlite3TreeViewPop(pView);
 27966  27698       }
 27967  27699       sqlite3TreeViewPop(pView);
 27968  27700     }
................................................................................
 27984  27716       sqlite3TreeViewWith(pView, p->pWith, 1);
 27985  27717       cnt = 1;
 27986  27718       sqlite3TreeViewPush(pView, 1);
 27987  27719     }
 27988  27720     do{
 27989  27721   #if SELECTTRACE_ENABLED
 27990  27722       sqlite3TreeViewLine(pView,
 27991         -      "SELECT%s%s (%s/%p) selFlags=0x%x nSelectRow=%d",
        27723  +      "SELECT%s%s (%s/%d/%p) selFlags=0x%x nSelectRow=%d",
 27992  27724         ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""),
 27993  27725         ((p->selFlags & SF_Aggregate) ? " agg_flag" : ""),
 27994         -      p->zSelName, p, p->selFlags,
        27726  +      p->zSelName, p->iSelectId, p, p->selFlags,
 27995  27727         (int)p->nSelectRow
 27996  27728       );
 27997  27729   #else
 27998  27730       sqlite3TreeViewLine(pView, "SELECT%s%s (0x%p) selFlags=0x%x nSelectRow=%d",
 27999  27731         ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""),
 28000  27732         ((p->selFlags & SF_Aggregate) ? " agg_flag" : ""), p, p->selFlags,
 28001  27733         (int)p->nSelectRow
................................................................................
 28019  27751         pView = sqlite3TreeViewPush(pView, (n--)>0);
 28020  27752         sqlite3TreeViewLine(pView, "FROM");
 28021  27753         for(i=0; i<p->pSrc->nSrc; i++){
 28022  27754           struct SrcList_item *pItem = &p->pSrc->a[i];
 28023  27755           StrAccum x;
 28024  27756           char zLine[100];
 28025  27757           sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
 28026         -        sqlite3_str_appendf(&x, "{%d,*}", pItem->iCursor);
        27758  +        sqlite3XPrintf(&x, "{%d,*}", pItem->iCursor);
 28027  27759           if( pItem->zDatabase ){
 28028         -          sqlite3_str_appendf(&x, " %s.%s", pItem->zDatabase, pItem->zName);
        27760  +          sqlite3XPrintf(&x, " %s.%s", pItem->zDatabase, pItem->zName);
 28029  27761           }else if( pItem->zName ){
 28030         -          sqlite3_str_appendf(&x, " %s", pItem->zName);
        27762  +          sqlite3XPrintf(&x, " %s", pItem->zName);
 28031  27763           }
 28032  27764           if( pItem->pTab ){
 28033         -          sqlite3_str_appendf(&x, " tabname=%Q", pItem->pTab->zName);
        27765  +          sqlite3XPrintf(&x, " tabname=%Q", pItem->pTab->zName);
 28034  27766           }
 28035  27767           if( pItem->zAlias ){
 28036         -          sqlite3_str_appendf(&x, " (AS %s)", pItem->zAlias);
        27768  +          sqlite3XPrintf(&x, " (AS %s)", pItem->zAlias);
 28037  27769           }
 28038  27770           if( pItem->fg.jointype & JT_LEFT ){
 28039         -          sqlite3_str_appendf(&x, " LEFT-JOIN");
        27771  +          sqlite3XPrintf(&x, " LEFT-JOIN");
 28040  27772           }
 28041  27773           sqlite3StrAccumFinish(&x);
 28042  27774           sqlite3TreeViewItem(pView, zLine, i<p->pSrc->nSrc-1); 
 28043  27775           if( pItem->pSelect ){
 28044  27776             sqlite3TreeViewSelect(pView, pItem->pSelect, 0);
 28045  27777           }
 28046  27778           if( pItem->fg.isTabFunc ){
................................................................................
 31448  31180       /* 164 */ "Function0"        OpHelp("r[P3]=func(r[P2@P5])"),
 31449  31181       /* 165 */ "PureFunc"         OpHelp(""),
 31450  31182       /* 166 */ "Function"         OpHelp("r[P3]=func(r[P2@P5])"),
 31451  31183       /* 167 */ "Trace"            OpHelp(""),
 31452  31184       /* 168 */ "CursorHint"       OpHelp(""),
 31453  31185       /* 169 */ "Noop"             OpHelp(""),
 31454  31186       /* 170 */ "Explain"          OpHelp(""),
 31455         -    /* 171 */ "Abortable"        OpHelp(""),
 31456  31187     };
 31457  31188     return azName[i];
 31458  31189   }
 31459  31190   #endif
 31460  31191   
 31461  31192   /************** End of opcodes.c *********************************************/
 31462  31193   /************** Begin file os_unix.c *****************************************/
................................................................................
 35435  35166         /* The code below is handling the return value of osFallocate() 
 35436  35167         ** correctly. posix_fallocate() is defined to "returns zero on success, 
 35437  35168         ** or an error number on  failure". See the manpage for details. */
 35438  35169         int err;
 35439  35170         do{
 35440  35171           err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
 35441  35172         }while( err==EINTR );
 35442         -      if( err && err!=EINVAL ) return SQLITE_IOERR_WRITE;
        35173  +      if( err ) return SQLITE_IOERR_WRITE;
 35443  35174   #else
 35444  35175         /* If the OS does not have posix_fallocate(), fake it. Write a 
 35445  35176         ** single byte to the last byte in each block that falls entirely
 35446  35177         ** within the extended region. Then, if required, a single byte
 35447  35178         ** at offset (nSize-1), to set the size of the file correctly.
 35448  35179         ** This is a similar technique to that used by glibc on systems
 35449  35180         ** that do not have a real fallocate() call.
................................................................................
 39960  39691   /*
 39961  39692    * The size of the buffer used by sqlite3_win32_write_debug().
 39962  39693    */
 39963  39694   #ifndef SQLITE_WIN32_DBG_BUF_SIZE
 39964  39695   #  define SQLITE_WIN32_DBG_BUF_SIZE   ((int)(4096-sizeof(DWORD)))
 39965  39696   #endif
 39966  39697   
        39698  +/*
        39699  + * The value used with sqlite3_win32_set_directory() to specify that
        39700  + * the data directory should be changed.
        39701  + */
        39702  +#ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
        39703  +#  define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
        39704  +#endif
        39705  +
        39706  +/*
        39707  + * The value used with sqlite3_win32_set_directory() to specify that
        39708  + * the temporary directory should be changed.
        39709  + */
        39710  +#ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
        39711  +#  define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
        39712  +#endif
        39713  +
 39967  39714   /*
 39968  39715    * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
 39969  39716    * various Win32 API heap functions instead of our own.
 39970  39717    */
 39971  39718   #ifdef SQLITE_WIN32_MALLOC
 39972  39719   
 39973  39720   /*
................................................................................
 41556  41303   #ifndef SQLITE_OMIT_AUTOINIT
 41557  41304     if( sqlite3_initialize() ) return 0;
 41558  41305   #endif
 41559  41306     return winUtf8ToMbcs(zText, useAnsi);
 41560  41307   }
 41561  41308   
 41562  41309   /*
 41563         -** This function is the same as sqlite3_win32_set_directory (below); however,
 41564         -** it accepts a UTF-8 string.
        41310  +** This function sets the data directory or the temporary directory based on
        41311  +** the provided arguments.  The type argument must be 1 in order to set the
        41312  +** data directory or 2 in order to set the temporary directory.  The zValue
        41313  +** argument is the name of the directory to use.  The return value will be
        41314  +** SQLITE_OK if successful.
 41565  41315   */
 41566         -SQLITE_API int sqlite3_win32_set_directory8(
 41567         -  unsigned long type, /* Identifier for directory being set or reset */
 41568         -  const char *zValue  /* New value for directory being set or reset */
 41569         -){
        41316  +SQLITE_API int sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
 41570  41317     char **ppDirectory = 0;
 41571  41318   #ifndef SQLITE_OMIT_AUTOINIT
 41572  41319     int rc = sqlite3_initialize();
 41573  41320     if( rc ) return rc;
 41574  41321   #endif
 41575  41322     if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
 41576  41323       ppDirectory = &sqlite3_data_directory;
................................................................................
 41578  41325       ppDirectory = &sqlite3_temp_directory;
 41579  41326     }
 41580  41327     assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
 41581  41328             || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
 41582  41329     );
 41583  41330     assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
 41584  41331     if( ppDirectory ){
 41585         -    char *zCopy = 0;
        41332  +    char *zValueUtf8 = 0;
 41586  41333       if( zValue && zValue[0] ){
 41587         -      zCopy = sqlite3_mprintf("%s", zValue);
 41588         -      if ( zCopy==0 ){
        41334  +      zValueUtf8 = winUnicodeToUtf8(zValue);
        41335  +      if ( zValueUtf8==0 ){
 41589  41336           return SQLITE_NOMEM_BKPT;
 41590  41337         }
 41591  41338       }
 41592  41339       sqlite3_free(*ppDirectory);
 41593         -    *ppDirectory = zCopy;
        41340  +    *ppDirectory = zValueUtf8;
 41594  41341       return SQLITE_OK;
 41595  41342     }
 41596  41343     return SQLITE_ERROR;
 41597  41344   }
 41598  41345   
 41599         -/*
 41600         -** This function is the same as sqlite3_win32_set_directory (below); however,
 41601         -** it accepts a UTF-16 string.
 41602         -*/
 41603         -SQLITE_API int sqlite3_win32_set_directory16(
 41604         -  unsigned long type, /* Identifier for directory being set or reset */
 41605         -  const void *zValue  /* New value for directory being set or reset */
 41606         -){
 41607         -  int rc;
 41608         -  char *zUtf8 = 0;
 41609         -  if( zValue ){
 41610         -    zUtf8 = sqlite3_win32_unicode_to_utf8(zValue);
 41611         -    if( zUtf8==0 ) return SQLITE_NOMEM_BKPT;
 41612         -  }
 41613         -  rc = sqlite3_win32_set_directory8(type, zUtf8);
 41614         -  if( zUtf8 ) sqlite3_free(zUtf8);
 41615         -  return rc;
 41616         -}
 41617         -
 41618         -/*
 41619         -** This function sets the data directory or the temporary directory based on
 41620         -** the provided arguments.  The type argument must be 1 in order to set the
 41621         -** data directory or 2 in order to set the temporary directory.  The zValue
 41622         -** argument is the name of the directory to use.  The return value will be
 41623         -** SQLITE_OK if successful.
 41624         -*/
 41625         -SQLITE_API int sqlite3_win32_set_directory(
 41626         -  unsigned long type, /* Identifier for directory being set or reset */
 41627         -  void *zValue        /* New value for directory being set or reset */
 41628         -){
 41629         -  return sqlite3_win32_set_directory16(type, zValue);
 41630         -}
 41631         -
 41632  41346   /*
 41633  41347   ** The return value of winGetLastErrorMsg
 41634  41348   ** is zero if the error message fits in the buffer, or non-zero
 41635  41349   ** otherwise (if the message was truncated).
 41636  41350   */
 41637  41351   static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
 41638  41352     /* FormatMessage returns 0 on failure.  Otherwise it
................................................................................
 62891  62605   **
 62892  62606   ** Calling this routine with a NULL cursor pointer returns false.
 62893  62607   **
 62894  62608   ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
 62895  62609   ** back to where it ought to be if this routine returns true.
 62896  62610   */
 62897  62611   SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
 62898         -  assert( EIGHT_BYTE_ALIGNMENT(pCur)
 62899         -       || pCur==sqlite3BtreeFakeValidCursor() );
 62900         -  assert( offsetof(BtCursor, eState)==0 );
 62901         -  assert( sizeof(pCur->eState)==1 );
 62902         -  return CURSOR_VALID != *(u8*)pCur;
        62612  +  return pCur->eState!=CURSOR_VALID;
 62903  62613   }
 62904  62614   
 62905  62615   /*
 62906  62616   ** Return a pointer to a fake BtCursor object that will always answer
 62907  62617   ** false to the sqlite3BtreeCursorHasMoved() routine above.  The fake
 62908  62618   ** cursor returned must not be used with any other Btree interface.
 62909  62619   */
................................................................................
 65002  64712             pDb->safety_level | (db->flags & PAGER_FLAGS_MASK));
 65003  64713       }
 65004  64714     }
 65005  64715   }
 65006  64716   #else
 65007  64717   # define setDefaultSyncFlag(pBt,safety_level)
 65008  64718   #endif
 65009         -
 65010         -/* Forward declaration */
 65011         -static int newDatabase(BtShared*);
 65012         -
 65013  64719   
 65014  64720   /*
 65015  64721   ** Get a reference to pPage1 of the database file.  This will
 65016  64722   ** also acquire a readlock on that file.
 65017  64723   **
 65018  64724   ** SQLITE_OK is returned on success.  If the file is not a
 65019  64725   ** well-formed database file, then SQLITE_CORRUPT is returned.
................................................................................
 65038  64744     ** a valid database file. 
 65039  64745     */
 65040  64746     nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
 65041  64747     sqlite3PagerPagecount(pBt->pPager, &nPageFile);
 65042  64748     if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
 65043  64749       nPage = nPageFile;
 65044  64750     }
 65045         -  if( (pBt->db->flags & SQLITE_ResetDatabase)!=0 ){
 65046         -    nPage = 0;
 65047         -  }
 65048  64751     if( nPage>0 ){
 65049  64752       u32 pageSize;
 65050  64753       u32 usableSize;
 65051  64754       u8 *page1 = pPage1->aData;
 65052  64755       rc = SQLITE_NOTADB;
 65053  64756       /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
 65054  64757       ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
................................................................................
 68257  67960     u32 ovflPageSize;
 68258  67961   
 68259  67962     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 68260  67963     pPage->xParseCell(pPage, pCell, pInfo);
 68261  67964     if( pInfo->nLocal==pInfo->nPayload ){
 68262  67965       return SQLITE_OK;  /* No overflow pages. Return without doing anything */
 68263  67966     }
 68264         -  testcase( pCell + pInfo->nSize == pPage->aDataEnd );
 68265         -  testcase( pCell + (pInfo->nSize-1) == pPage->aDataEnd );
 68266         -  if( pCell + pInfo->nSize > pPage->aDataEnd ){
        67967  +  if( pCell+pInfo->nSize-1 > pPage->aData+pPage->maskPage ){
 68267  67968       /* Cell extends past end of page */
 68268  67969       return SQLITE_CORRUPT_PAGE(pPage);
 68269  67970     }
 68270  67971     ovflPgno = get4byte(pCell + pInfo->nSize - 4);
 68271  67972     pBt = pPage->pBt;
 68272  67973     assert( pBt->usableSize > 4 );
 68273  67974     ovflPageSize = pBt->usableSize - 4;
................................................................................
 70185  69886   
 70186  69887     if( pFree ){
 70187  69888       sqlite3PageFree(pFree);
 70188  69889     }
 70189  69890     return rc;
 70190  69891   }
 70191  69892   
 70192         -/* Overwrite content from pX into pDest.  Only do the write if the
 70193         -** content is different from what is already there.
 70194         -*/
 70195         -static int btreeOverwriteContent(
 70196         -  MemPage *pPage,           /* MemPage on which writing will occur */
 70197         -  u8 *pDest,                /* Pointer to the place to start writing */
 70198         -  const BtreePayload *pX,   /* Source of data to write */
 70199         -  int iOffset,              /* Offset of first byte to write */
 70200         -  int iAmt                  /* Number of bytes to be written */
 70201         -){
 70202         -  int nData = pX->nData - iOffset;
 70203         -  if( nData<=0 ){
 70204         -    /* Overwritting with zeros */
 70205         -    int i;
 70206         -    for(i=0; i<iAmt && pDest[i]==0; i++){}
 70207         -    if( i<iAmt ){
 70208         -      int rc = sqlite3PagerWrite(pPage->pDbPage);
 70209         -      if( rc ) return rc;
 70210         -      memset(pDest + i, 0, iAmt - i);
 70211         -    }
 70212         -  }else{
 70213         -    if( nData<iAmt ){
 70214         -      /* Mixed read data and zeros at the end.  Make a recursive call
 70215         -      ** to write the zeros then fall through to write the real data */
 70216         -      int rc = btreeOverwriteContent(pPage, pDest+nData, pX, iOffset+nData,
 70217         -                                 iAmt-nData);
 70218         -      if( rc ) return rc;
 70219         -      iAmt = nData;
 70220         -    }
 70221         -    if( memcmp(pDest, ((u8*)pX->pData) + iOffset, iAmt)!=0 ){
 70222         -      int rc = sqlite3PagerWrite(pPage->pDbPage);
 70223         -      if( rc ) return rc;
 70224         -      memcpy(pDest, ((u8*)pX->pData) + iOffset, iAmt);
 70225         -    }
 70226         -  }
 70227         -  return SQLITE_OK;
 70228         -}
 70229         -
 70230         -/*
 70231         -** Overwrite the cell that cursor pCur is pointing to with fresh content
 70232         -** contained in pX.
 70233         -*/
 70234         -static int btreeOverwriteCell(BtCursor *pCur, const BtreePayload *pX){
 70235         -  int iOffset;                        /* Next byte of pX->pData to write */
 70236         -  int nTotal = pX->nData + pX->nZero; /* Total bytes of to write */
 70237         -  int rc;                             /* Return code */
 70238         -  MemPage *pPage = pCur->pPage;       /* Page being written */
 70239         -  BtShared *pBt;                      /* Btree */
 70240         -  Pgno ovflPgno;                      /* Next overflow page to write */
 70241         -  u32 ovflPageSize;                   /* Size to write on overflow page */
 70242         -
 70243         -  if( pCur->info.pPayload + pCur->info.nLocal > pPage->aDataEnd ){
 70244         -    return SQLITE_CORRUPT_BKPT;
 70245         -  }
 70246         -  /* Overwrite the local portion first */
 70247         -  rc = btreeOverwriteContent(pPage, pCur->info.pPayload, pX,
 70248         -                             0, pCur->info.nLocal);
 70249         -  if( rc ) return rc;
 70250         -  if( pCur->info.nLocal==nTotal ) return SQLITE_OK;
 70251         -
 70252         -  /* Now overwrite the overflow pages */
 70253         -  iOffset = pCur->info.nLocal;
 70254         -  assert( nTotal>=0 );
 70255         -  assert( iOffset>=0 );
 70256         -  ovflPgno = get4byte(pCur->info.pPayload + iOffset);
 70257         -  pBt = pPage->pBt;
 70258         -  ovflPageSize = pBt->usableSize - 4;
 70259         -  do{
 70260         -    rc = btreeGetPage(pBt, ovflPgno, &pPage, 0);
 70261         -    if( rc ) return rc;
 70262         -    if( sqlite3PagerPageRefcount(pPage->pDbPage)!=1 ){
 70263         -      rc = SQLITE_CORRUPT_BKPT;
 70264         -    }else{
 70265         -      if( iOffset+ovflPageSize<(u32)nTotal ){
 70266         -        ovflPgno = get4byte(pPage->aData);
 70267         -      }else{
 70268         -        ovflPageSize = nTotal - iOffset;
 70269         -      }
 70270         -      rc = btreeOverwriteContent(pPage, pPage->aData+4, pX,
 70271         -                                 iOffset, ovflPageSize);
 70272         -    }
 70273         -    sqlite3PagerUnref(pPage->pDbPage);
 70274         -    if( rc ) return rc;
 70275         -    iOffset += ovflPageSize;
 70276         -  }while( iOffset<nTotal );
 70277         -  return SQLITE_OK;    
 70278         -}
 70279         -
 70280  69893   
 70281  69894   /*
 70282  69895   ** Insert a new record into the BTree.  The content of the new record
 70283  69896   ** is described by the pX object.  The pCur cursor is used only to
 70284  69897   ** define what table the record should be inserted into, and is left
 70285  69898   ** pointing at a random location.
 70286  69899   **
................................................................................
 70363  69976     if( pCur->pKeyInfo==0 ){
 70364  69977       assert( pX->pKey==0 );
 70365  69978       /* If this is an insert into a table b-tree, invalidate any incrblob 
 70366  69979       ** cursors open on the row being replaced */
 70367  69980       invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0);
 70368  69981   
 70369  69982       /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing 
 70370         -    ** to a row with the same key as the new entry being inserted.
 70371         -    */
 70372         -#ifdef SQLITE_DEBUG
 70373         -    if( flags & BTREE_SAVEPOSITION ){
 70374         -      assert( pCur->curFlags & BTCF_ValidNKey );
 70375         -      assert( pX->nKey==pCur->info.nKey );
 70376         -      assert( pCur->info.nSize!=0 );
 70377         -      assert( loc==0 );
 70378         -    }
 70379         -#endif
        69983  +    ** to a row with the same key as the new entry being inserted.  */
        69984  +    assert( (flags & BTREE_SAVEPOSITION)==0 || 
        69985  +            ((pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey) );
 70380  69986   
 70381         -    /* On the other hand, BTREE_SAVEPOSITION==0 does not imply
 70382         -    ** that the cursor is not pointing to a row to be overwritten.
 70383         -    ** So do a complete check.
 70384         -    */
        69987  +    /* If the cursor is currently on the last row and we are appending a
        69988  +    ** new row onto the end, set the "loc" to avoid an unnecessary
        69989  +    ** btreeMoveto() call */
 70385  69990       if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){
 70386         -      /* The cursor is pointing to the entry that is to be
 70387         -      ** overwritten */
 70388         -      assert( pX->nData>=0 && pX->nZero>=0 );
 70389         -      if( pCur->info.nSize!=0
 70390         -       && pCur->info.nPayload==(u32)pX->nData+pX->nZero
 70391         -      ){
 70392         -        /* New entry is the same size as the old.  Do an overwrite */
 70393         -        return btreeOverwriteCell(pCur, pX);
 70394         -      }
 70395         -      assert( loc==0 );
        69991  +      loc = 0;
 70396  69992       }else if( loc==0 ){
 70397         -      /* The cursor is *not* pointing to the cell to be overwritten, nor
 70398         -      ** to an adjacent cell.  Move the cursor so that it is pointing either
 70399         -      ** to the cell to be overwritten or an adjacent cell.
 70400         -      */
 70401  69993         rc = sqlite3BtreeMovetoUnpacked(pCur, 0, pX->nKey, flags!=0, &loc);
 70402  69994         if( rc ) return rc;
 70403  69995       }
 70404         -  }else{
 70405         -    /* This is an index or a WITHOUT ROWID table */
 70406         -
 70407         -    /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing 
 70408         -    ** to a row with the same key as the new entry being inserted.
 70409         -    */
 70410         -    assert( (flags & BTREE_SAVEPOSITION)==0 || loc==0 );
 70411         -
 70412         -    /* If the cursor is not already pointing either to the cell to be
 70413         -    ** overwritten, or if a new cell is being inserted, if the cursor is
 70414         -    ** not pointing to an immediately adjacent cell, then move the cursor
 70415         -    ** so that it does.
 70416         -    */
 70417         -    if( loc==0 && (flags & BTREE_SAVEPOSITION)==0 ){
 70418         -      if( pX->nMem ){
 70419         -        UnpackedRecord r;
 70420         -        r.pKeyInfo = pCur->pKeyInfo;
 70421         -        r.aMem = pX->aMem;
 70422         -        r.nField = pX->nMem;
 70423         -        r.default_rc = 0;
 70424         -        r.errCode = 0;
 70425         -        r.r1 = 0;
 70426         -        r.r2 = 0;
 70427         -        r.eqSeen = 0;
 70428         -        rc = sqlite3BtreeMovetoUnpacked(pCur, &r, 0, flags!=0, &loc);
 70429         -      }else{
 70430         -        rc = btreeMoveto(pCur, pX->pKey, pX->nKey, flags!=0, &loc);
 70431         -      }
 70432         -      if( rc ) return rc;
 70433         -    }
 70434         -
 70435         -    /* If the cursor is currently pointing to an entry to be overwritten
 70436         -    ** and the new content is the same as as the old, then use the
 70437         -    ** overwrite optimization.
 70438         -    */
 70439         -    if( loc==0 ){
 70440         -      getCellInfo(pCur);
 70441         -      if( pCur->info.nKey==pX->nKey ){
 70442         -        BtreePayload x2;
 70443         -        x2.pData = pX->pKey;
 70444         -        x2.nData = pX->nKey;
 70445         -        x2.nZero = 0;
 70446         -        return btreeOverwriteCell(pCur, &x2);
 70447         -      }
 70448         -    }
 70449         -
        69996  +  }else if( loc==0 && (flags & BTREE_SAVEPOSITION)==0 ){
        69997  +    if( pX->nMem ){
        69998  +      UnpackedRecord r;
        69999  +      r.pKeyInfo = pCur->pKeyInfo;
        70000  +      r.aMem = pX->aMem;
        70001  +      r.nField = pX->nMem;
        70002  +      r.default_rc = 0;
        70003  +      r.errCode = 0;
        70004  +      r.r1 = 0;
        70005  +      r.r2 = 0;
        70006  +      r.eqSeen = 0;
        70007  +      rc = sqlite3BtreeMovetoUnpacked(pCur, &r, 0, flags!=0, &loc);
        70008  +    }else{
        70009  +      rc = btreeMoveto(pCur, pX->pKey, pX->nKey, flags!=0, &loc);
        70010  +    }
        70011  +    if( rc ) return rc;
 70450  70012     }
 70451  70013     assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
 70452  70014   
 70453  70015     pPage = pCur->pPage;
 70454  70016     assert( pPage->intKey || pX->nKey>=0 );
 70455  70017     assert( pPage->leaf || !pPage->intKey );
 70456  70018   
................................................................................
 71281  70843   ){
 71282  70844     va_list ap;
 71283  70845     if( !pCheck->mxErr ) return;
 71284  70846     pCheck->mxErr--;
 71285  70847     pCheck->nErr++;
 71286  70848     va_start(ap, zFormat);
 71287  70849     if( pCheck->errMsg.nChar ){
 71288         -    sqlite3_str_append(&pCheck->errMsg, "\n", 1);
        70850  +    sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
 71289  70851     }
 71290  70852     if( pCheck->zPfx ){
 71291         -    sqlite3_str_appendf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2);
        70853  +    sqlite3XPrintf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2);
 71292  70854     }
 71293         -  sqlite3_str_vappendf(&pCheck->errMsg, zFormat, ap);
        70855  +  sqlite3VXPrintf(&pCheck->errMsg, zFormat, ap);
 71294  70856     va_end(ap);
 71295         -  if( pCheck->errMsg.accError==SQLITE_NOMEM ){
        70857  +  if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
 71296  70858       pCheck->mallocFailed = 1;
 71297  70859     }
 71298  70860   }
 71299  70861   #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
 71300  70862   
 71301  70863   #ifndef SQLITE_OMIT_INTEGRITY_CHECK
 71302  70864   
................................................................................
 71872  71434   
 71873  71435     /* Clean  up and report errors.
 71874  71436     */
 71875  71437   integrity_ck_cleanup:
 71876  71438     sqlite3PageFree(sCheck.heap);
 71877  71439     sqlite3_free(sCheck.aPgRef);
 71878  71440     if( sCheck.mallocFailed ){
 71879         -    sqlite3_str_reset(&sCheck.errMsg);
        71441  +    sqlite3StrAccumReset(&sCheck.errMsg);
 71880  71442       sCheck.nErr++;
 71881  71443     }
 71882  71444     *pnErr = sCheck.nErr;
 71883         -  if( sCheck.nErr==0 ) sqlite3_str_reset(&sCheck.errMsg);
        71445  +  if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
 71884  71446     /* Make sure this analysis did not leave any unref() pages. */
 71885  71447     assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
 71886  71448     sqlite3BtreeLeave(p);
 71887  71449     return sqlite3StrAccumFinish(&sCheck.errMsg);
 71888  71450   }
 71889  71451   #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
 71890  71452   
................................................................................
 73776  73338     }else{
 73777  73339       pMem->u.i = val;
 73778  73340       pMem->flags = MEM_Int;
 73779  73341     }
 73780  73342   }
 73781  73343   
 73782  73344   /* A no-op destructor */
 73783         -SQLITE_PRIVATE void sqlite3NoopDestructor(void *p){ UNUSED_PARAMETER(p); }
        73345  +static void sqlite3NoopDestructor(void *p){ UNUSED_PARAMETER(p); }
 73784  73346   
 73785  73347   /*
 73786  73348   ** Set the value stored in *pMem should already be a NULL.
 73787  73349   ** Also store a pointer to go with it.
 73788  73350   */
 73789  73351   SQLITE_PRIVATE void sqlite3VdbeMemSetPointer(
 73790  73352     Mem *pMem,
................................................................................
 75122  74684     int p4type          /* P4 operand type */
 75123  74685   ){
 75124  74686     char *p4copy = sqlite3DbMallocRawNN(sqlite3VdbeDb(p), 8);
 75125  74687     if( p4copy ) memcpy(p4copy, zP4, 8);
 75126  74688     return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type);
 75127  74689   }
 75128  74690   
 75129         -#ifndef SQLITE_OMIT_EXPLAIN
 75130         -/*
 75131         -** Return the address of the current EXPLAIN QUERY PLAN baseline.
 75132         -** 0 means "none".
 75133         -*/
 75134         -SQLITE_PRIVATE int sqlite3VdbeExplainParent(Parse *pParse){
 75135         -  VdbeOp *pOp;
 75136         -  if( pParse->addrExplain==0 ) return 0;
 75137         -  pOp = sqlite3VdbeGetOp(pParse->pVdbe, pParse->addrExplain);
 75138         -  return pOp->p2;
 75139         -}
 75140         -
 75141         -/*
 75142         -** Add a new OP_Explain opcode.
 75143         -**
 75144         -** If the bPush flag is true, then make this opcode the parent for
 75145         -** subsequent Explains until sqlite3VdbeExplainPop() is called.
 75146         -*/
 75147         -SQLITE_PRIVATE void sqlite3VdbeExplain(Parse *pParse, u8 bPush, const char *zFmt, ...){
 75148         -  if( pParse->explain==2 ){
 75149         -    char *zMsg;
 75150         -    Vdbe *v = pParse->pVdbe;
 75151         -    va_list ap;
 75152         -    int iThis;
 75153         -    va_start(ap, zFmt);
 75154         -    zMsg = sqlite3VMPrintf(pParse->db, zFmt, ap);
 75155         -    va_end(ap);
 75156         -    v = pParse->pVdbe;
 75157         -    iThis = v->nOp;
 75158         -    sqlite3VdbeAddOp4(v, OP_Explain, iThis, pParse->addrExplain, 0,
 75159         -                      zMsg, P4_DYNAMIC);
 75160         -    if( bPush) pParse->addrExplain = iThis;
 75161         -  }
 75162         -}
 75163         -
 75164         -/*
 75165         -** Pop the EXPLAIN QUERY PLAN stack one level.
 75166         -*/
 75167         -SQLITE_PRIVATE void sqlite3VdbeExplainPop(Parse *pParse){
 75168         -  pParse->addrExplain = sqlite3VdbeExplainParent(pParse);
 75169         -}
 75170         -#endif /* SQLITE_OMIT_EXPLAIN */
 75171         -
 75172  74691   /*
 75173  74692   ** Add an OP_ParseSchema opcode.  This routine is broken out from
 75174  74693   ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
 75175  74694   ** as having been used.
 75176  74695   **
 75177  74696   ** The zWhere string must have been obtained from sqlite3_malloc().
 75178  74697   ** This routine will take ownership of the allocated memory.
................................................................................
 75422  74941     ** true for this case to prevent the assert() in the callers frame
 75423  74942     ** from failing.  */
 75424  74943     return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter
 75425  74944                 || (hasCreateTable && hasInitCoroutine) );
 75426  74945   }
 75427  74946   #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
 75428  74947   
 75429         -#ifdef SQLITE_DEBUG
 75430         -/*
 75431         -** Increment the nWrite counter in the VDBE if the cursor is not an
 75432         -** ephemeral cursor, or if the cursor argument is NULL.
 75433         -*/
 75434         -SQLITE_PRIVATE void sqlite3VdbeIncrWriteCounter(Vdbe *p, VdbeCursor *pC){
 75435         -  if( pC==0
 75436         -   || (pC->eCurType!=CURTYPE_SORTER
 75437         -       && pC->eCurType!=CURTYPE_PSEUDO
 75438         -       && !pC->isEphemeral)
 75439         -  ){
 75440         -    p->nWrite++;
 75441         -  }
 75442         -}
 75443         -#endif
 75444         -
 75445         -#ifdef SQLITE_DEBUG
 75446         -/*
 75447         -** Assert if an Abort at this point in time might result in a corrupt
 75448         -** database.
 75449         -*/
 75450         -SQLITE_PRIVATE void sqlite3VdbeAssertAbortable(Vdbe *p){
 75451         -  assert( p->nWrite==0 || p->usesStmtJournal );
 75452         -}
 75453         -#endif
 75454         -
 75455  74948   /*
 75456  74949   ** This routine is called after all opcodes have been inserted.  It loops
 75457  74950   ** through all the opcodes and fixes up some details.
 75458  74951   **
 75459  74952   ** (1) For each jump instruction with a negative P2 value (a label)
 75460  74953   **     resolve the P2 value to an actual address.
 75461  74954   **
................................................................................
 75605  75098   #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
 75606  75099   SQLITE_PRIVATE void sqlite3VdbeVerifyNoResultRow(Vdbe *p){
 75607  75100     int i;
 75608  75101     for(i=0; i<p->nOp; i++){
 75609  75102       assert( p->aOp[i].opcode!=OP_ResultRow );
 75610  75103     }
 75611  75104   }
 75612         -#endif
 75613         -
 75614         -/*
 75615         -** Generate code (a single OP_Abortable opcode) that will
 75616         -** verify that the VDBE program can safely call Abort in the current
 75617         -** context.
 75618         -*/
 75619         -#if defined(SQLITE_DEBUG)
 75620         -SQLITE_PRIVATE void sqlite3VdbeVerifyAbortable(Vdbe *p, int onError){
 75621         -  if( onError==OE_Abort ) sqlite3VdbeAddOp0(p, OP_Abortable);
 75622         -}
 75623  75105   #endif
 75624  75106   
 75625  75107   /*
 75626  75108   ** This function returns a pointer to the array of opcodes associated with
 75627  75109   ** the Vdbe passed as the first argument. It is the callers responsibility
 75628  75110   ** to arrange for the returned array to be eventually freed using the 
 75629  75111   ** vdbeFreeOpArray() function.
................................................................................
 76162  75644   ** Translate the P4.pExpr value for an OP_CursorHint opcode into text
 76163  75645   ** that can be displayed in the P4 column of EXPLAIN output.
 76164  75646   */
 76165  75647   static void displayP4Expr(StrAccum *p, Expr *pExpr){
 76166  75648     const char *zOp = 0;
 76167  75649     switch( pExpr->op ){
 76168  75650       case TK_STRING:
 76169         -      sqlite3_str_appendf(p, "%Q", pExpr->u.zToken);
        75651  +      sqlite3XPrintf(p, "%Q", pExpr->u.zToken);
 76170  75652         break;
 76171  75653       case TK_INTEGER:
 76172         -      sqlite3_str_appendf(p, "%d", pExpr->u.iValue);
        75654  +      sqlite3XPrintf(p, "%d", pExpr->u.iValue);
 76173  75655         break;
 76174  75656       case TK_NULL:
 76175         -      sqlite3_str_appendf(p, "NULL");
        75657  +      sqlite3XPrintf(p, "NULL");
 76176  75658         break;
 76177  75659       case TK_REGISTER: {
 76178         -      sqlite3_str_appendf(p, "r[%d]", pExpr->iTable);
        75660  +      sqlite3XPrintf(p, "r[%d]", pExpr->iTable);
 76179  75661         break;
 76180  75662       }
 76181  75663       case TK_COLUMN: {
 76182  75664         if( pExpr->iColumn<0 ){
 76183         -        sqlite3_str_appendf(p, "rowid");
        75665  +        sqlite3XPrintf(p, "rowid");
 76184  75666         }else{
 76185         -        sqlite3_str_appendf(p, "c%d", (int)pExpr->iColumn);
        75667  +        sqlite3XPrintf(p, "c%d", (int)pExpr->iColumn);
 76186  75668         }
 76187  75669         break;
 76188  75670       }
 76189  75671       case TK_LT:      zOp = "LT";      break;
 76190  75672       case TK_LE:      zOp = "LE";      break;
 76191  75673       case TK_GT:      zOp = "GT";      break;
 76192  75674       case TK_GE:      zOp = "GE";      break;
................................................................................
 76210  75692       case TK_UPLUS:   zOp = "PLUS";    break;
 76211  75693       case TK_BITNOT:  zOp = "BITNOT";  break;
 76212  75694       case TK_NOT:     zOp = "NOT";     break;
 76213  75695       case TK_ISNULL:  zOp = "ISNULL";  break;
 76214  75696       case TK_NOTNULL: zOp = "NOTNULL"; break;
 76215  75697   
 76216  75698       default:
 76217         -      sqlite3_str_appendf(p, "%s", "expr");
        75699  +      sqlite3XPrintf(p, "%s", "expr");
 76218  75700         break;
 76219  75701     }
 76220  75702   
 76221  75703     if( zOp ){
 76222         -    sqlite3_str_appendf(p, "%s(", zOp);
        75704  +    sqlite3XPrintf(p, "%s(", zOp);
 76223  75705       displayP4Expr(p, pExpr->pLeft);
 76224  75706       if( pExpr->pRight ){
 76225         -      sqlite3_str_append(p, ",", 1);
        75707  +      sqlite3StrAccumAppend(p, ",", 1);
 76226  75708         displayP4Expr(p, pExpr->pRight);
 76227  75709       }
 76228         -    sqlite3_str_append(p, ")", 1);
        75710  +    sqlite3StrAccumAppend(p, ")", 1);
 76229  75711     }
 76230  75712   }
 76231  75713   #endif /* VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS) */
 76232  75714   
 76233  75715   
 76234  75716   #if VDBE_DISPLAY_P4
 76235  75717   /*
................................................................................
 76242  75724     assert( nTemp>=20 );
 76243  75725     sqlite3StrAccumInit(&x, 0, zTemp, nTemp, 0);
 76244  75726     switch( pOp->p4type ){
 76245  75727       case P4_KEYINFO: {
 76246  75728         int j;
 76247  75729         KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
 76248  75730         assert( pKeyInfo->aSortOrder!=0 );
 76249         -      sqlite3_str_appendf(&x, "k(%d", pKeyInfo->nKeyField);
        75731  +      sqlite3XPrintf(&x, "k(%d", pKeyInfo->nKeyField);
 76250  75732         for(j=0; j<pKeyInfo->nKeyField; j++){
 76251  75733           CollSeq *pColl = pKeyInfo->aColl[j];
 76252  75734           const char *zColl = pColl ? pColl->zName : "";
 76253  75735           if( strcmp(zColl, "BINARY")==0 ) zColl = "B";
 76254         -        sqlite3_str_appendf(&x, ",%s%s", 
 76255         -               pKeyInfo->aSortOrder[j] ? "-" : "", zColl);
        75736  +        sqlite3XPrintf(&x, ",%s%s", pKeyInfo->aSortOrder[j] ? "-" : "", zColl);
 76256  75737         }
 76257         -      sqlite3_str_append(&x, ")", 1);
        75738  +      sqlite3StrAccumAppend(&x, ")", 1);
 76258  75739         break;
 76259  75740       }
 76260  75741   #ifdef SQLITE_ENABLE_CURSOR_HINTS
 76261  75742       case P4_EXPR: {
 76262  75743         displayP4Expr(&x, pOp->p4.pExpr);
 76263  75744         break;
 76264  75745       }
 76265  75746   #endif
 76266  75747       case P4_COLLSEQ: {
 76267  75748         CollSeq *pColl = pOp->p4.pColl;
 76268         -      sqlite3_str_appendf(&x, "(%.20s)", pColl->zName);
        75749  +      sqlite3XPrintf(&x, "(%.20s)", pColl->zName);
 76269  75750         break;
 76270  75751       }
 76271  75752       case P4_FUNCDEF: {
 76272  75753         FuncDef *pDef = pOp->p4.pFunc;
 76273         -      sqlite3_str_appendf(&x, "%s(%d)", pDef->zName, pDef->nArg);
        75754  +      sqlite3XPrintf(&x, "%s(%d)", pDef->zName, pDef->nArg);
 76274  75755         break;
 76275  75756       }
 76276  75757   #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
 76277  75758       case P4_FUNCCTX: {
 76278  75759         FuncDef *pDef = pOp->p4.pCtx->pFunc;
 76279         -      sqlite3_str_appendf(&x, "%s(%d)", pDef->zName, pDef->nArg);
        75760  +      sqlite3XPrintf(&x, "%s(%d)", pDef->zName, pDef->nArg);
 76280  75761         break;
 76281  75762       }
 76282  75763   #endif
 76283  75764       case P4_INT64: {
 76284         -      sqlite3_str_appendf(&x, "%lld", *pOp->p4.pI64);
        75765  +      sqlite3XPrintf(&x, "%lld", *pOp->p4.pI64);
 76285  75766         break;
 76286  75767       }
 76287  75768       case P4_INT32: {
 76288         -      sqlite3_str_appendf(&x, "%d", pOp->p4.i);
        75769  +      sqlite3XPrintf(&x, "%d", pOp->p4.i);
 76289  75770         break;
 76290  75771       }
 76291  75772       case P4_REAL: {
 76292         -      sqlite3_str_appendf(&x, "%.16g", *pOp->p4.pReal);
        75773  +      sqlite3XPrintf(&x, "%.16g", *pOp->p4.pReal);
 76293  75774         break;
 76294  75775       }
 76295  75776       case P4_MEM: {
 76296  75777         Mem *pMem = pOp->p4.pMem;
 76297  75778         if( pMem->flags & MEM_Str ){
 76298  75779           zP4 = pMem->z;
 76299  75780         }else if( pMem->flags & MEM_Int ){
 76300         -        sqlite3_str_appendf(&x, "%lld", pMem->u.i);
        75781  +        sqlite3XPrintf(&x, "%lld", pMem->u.i);
 76301  75782         }else if( pMem->flags & MEM_Real ){
 76302         -        sqlite3_str_appendf(&x, "%.16g", pMem->u.r);
        75783  +        sqlite3XPrintf(&x, "%.16g", pMem->u.r);
 76303  75784         }else if( pMem->flags & MEM_Null ){
 76304  75785           zP4 = "NULL";
 76305  75786         }else{
 76306  75787           assert( pMem->flags & MEM_Blob );
 76307  75788           zP4 = "(blob)";
 76308  75789         }
 76309  75790         break;
 76310  75791       }
 76311  75792   #ifndef SQLITE_OMIT_VIRTUALTABLE
 76312  75793       case P4_VTAB: {
 76313  75794         sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
 76314         -      sqlite3_str_appendf(&x, "vtab:%p", pVtab);
        75795  +      sqlite3XPrintf(&x, "vtab:%p", pVtab);
 76315  75796         break;
 76316  75797       }
 76317  75798   #endif
 76318  75799       case P4_INTARRAY: {
 76319  75800         int i;
 76320  75801         int *ai = pOp->p4.ai;
 76321  75802         int n = ai[0];   /* The first element of an INTARRAY is always the
 76322  75803                          ** count of the number of elements to follow */
 76323  75804         for(i=1; i<=n; i++){
 76324         -        sqlite3_str_appendf(&x, ",%d", ai[i]);
        75805  +        sqlite3XPrintf(&x, ",%d", ai[i]);
 76325  75806         }
 76326  75807         zTemp[0] = '[';
 76327         -      sqlite3_str_append(&x, "]", 1);
        75808  +      sqlite3StrAccumAppend(&x, "]", 1);
 76328  75809         break;
 76329  75810       }
 76330  75811       case P4_SUBPROGRAM: {
 76331         -      sqlite3_str_appendf(&x, "program");
        75812  +      sqlite3XPrintf(&x, "program");
 76332  75813         break;
 76333  75814       }
 76334  75815       case P4_DYNBLOB:
 76335  75816       case P4_ADVANCE: {
 76336  75817         zTemp[0] = 0;
 76337  75818         break;
 76338  75819       }
 76339  75820       case P4_TABLE: {
 76340         -      sqlite3_str_appendf(&x, "%s", pOp->p4.pTab->zName);
        75821  +      sqlite3XPrintf(&x, "%s", pOp->p4.pTab->zName);
 76341  75822         break;
 76342  75823       }
 76343  75824       default: {
 76344  75825         zP4 = pOp->p4.z;
 76345  75826         if( zP4==0 ){
 76346  75827           zP4 = zTemp;
 76347  75828           zTemp[0] = 0;
................................................................................
 77851  77332     if( p->aMem ){
 77852  77333       for(i=0; i<p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
 77853  77334     }
 77854  77335   #endif
 77855  77336     sqlite3DbFree(db, p->zErrMsg);
 77856  77337     p->zErrMsg = 0;
 77857  77338     p->pResultSet = 0;
 77858         -#ifdef SQLITE_DEBUG
 77859         -  p->nWrite = 0;
 77860         -#endif
 77861  77339   
 77862  77340     /* Save profiling information from this VDBE run.
 77863  77341     */
 77864  77342   #ifdef VDBE_PROFILE
 77865  77343     {
 77866  77344       FILE *out = fopen("vdbe_profile.out", "a");
 77867  77345       if( out ){
................................................................................
 78776  78254       if( x<r ) return -1;
 78777  78255       if( x>r ) return +1;
 78778  78256       return 0;
 78779  78257     }else{
 78780  78258       i64 y;
 78781  78259       double s;
 78782  78260       if( r<-9223372036854775808.0 ) return +1;
 78783         -    if( r>=9223372036854775808.0 ) return -1;
        78261  +    if( r>9223372036854775807.0 ) return -1;
 78784  78262       y = (i64)r;
 78785  78263       if( i<y ) return -1;
 78786         -    if( i>y ) return +1;
        78264  +    if( i>y ){
        78265  +      if( y==SMALLEST_INT64 && r>0.0 ) return -1;
        78266  +      return +1;
        78267  +    }
 78787  78268       s = (double)i;
 78788  78269       if( s<r ) return -1;
 78789  78270       if( s>r ) return +1;
 78790  78271       return 0;
 78791  78272     }
 78792  78273   }
 78793  78274   
................................................................................
 80456  79937   #endif
 80457  79938     if( *piTime==0 ){
 80458  79939       rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime);
 80459  79940       if( rc ) *piTime = 0;
 80460  79941     }
 80461  79942     return *piTime;
 80462  79943   }
        79944  +
        79945  +/*
        79946  +** The following is the implementation of an SQL function that always
        79947  +** fails with an error message stating that the function is used in the
        79948  +** wrong context.  The sqlite3_overload_function() API might construct
        79949  +** SQL function that use this routine so that the functions will exist
        79950  +** for name resolution but are actually overloaded by the xFindFunction
        79951  +** method of virtual tables.
        79952  +*/
        79953  +SQLITE_PRIVATE void sqlite3InvalidFunction(
        79954  +  sqlite3_context *context,  /* The function calling context */
        79955  +  int NotUsed,               /* Number of arguments to the function */
        79956  +  sqlite3_value **NotUsed2   /* Value of each argument */
        79957  +){
        79958  +  const char *zName = context->pFunc->zName;
        79959  +  char *zErr;
        79960  +  UNUSED_PARAMETER2(NotUsed, NotUsed2);
        79961  +  zErr = sqlite3_mprintf(
        79962  +      "unable to use function %s in the requested context", zName);
        79963  +  sqlite3_result_error(context, zErr, -1);
        79964  +  sqlite3_free(zErr);
        79965  +}
 80463  79966   
 80464  79967   /*
 80465  79968   ** Create a new aggregate context for p and return a pointer to
 80466  79969   ** its pMem->z element.
 80467  79970   */
 80468  79971   static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){
 80469  79972     Mem *pMem = p->pMem;
................................................................................
 81724  81227     db = p->db;
 81725  81228     sqlite3StrAccumInit(&out, 0, zBase, sizeof(zBase), 
 81726  81229                         db->aLimit[SQLITE_LIMIT_LENGTH]);
 81727  81230     if( db->nVdbeExec>1 ){
 81728  81231       while( *zRawSql ){
 81729  81232         const char *zStart = zRawSql;
 81730  81233         while( *(zRawSql++)!='\n' && *zRawSql );
 81731         -      sqlite3_str_append(&out, "-- ", 3);
        81234  +      sqlite3StrAccumAppend(&out, "-- ", 3);
 81732  81235         assert( (zRawSql - zStart) > 0 );
 81733         -      sqlite3_str_append(&out, zStart, (int)(zRawSql-zStart));
        81236  +      sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
 81734  81237       }
 81735  81238     }else if( p->nVar==0 ){
 81736         -    sqlite3_str_append(&out, zRawSql, sqlite3Strlen30(zRawSql));
        81239  +    sqlite3StrAccumAppend(&out, zRawSql, sqlite3Strlen30(zRawSql));
 81737  81240     }else{
 81738  81241       while( zRawSql[0] ){
 81739  81242         n = findNextHostParameter(zRawSql, &nToken);
 81740  81243         assert( n>0 );
 81741         -      sqlite3_str_append(&out, zRawSql, n);
        81244  +      sqlite3StrAccumAppend(&out, zRawSql, n);
 81742  81245         zRawSql += n;
 81743  81246         assert( zRawSql[0] || nToken==0 );
 81744  81247         if( nToken==0 ) break;
 81745  81248         if( zRawSql[0]=='?' ){
 81746  81249           if( nToken>1 ){
 81747  81250             assert( sqlite3Isdigit(zRawSql[1]) );
 81748  81251             sqlite3GetInt32(&zRawSql[1], &idx);
................................................................................
 81760  81263           assert( idx>0 );
 81761  81264         }
 81762  81265         zRawSql += nToken;
 81763  81266         nextIndex = idx + 1;
 81764  81267         assert( idx>0 && idx<=p->nVar );
 81765  81268         pVar = &p->aVar[idx-1];
 81766  81269         if( pVar->flags & MEM_Null ){
 81767         -        sqlite3_str_append(&out, "NULL", 4);
        81270  +        sqlite3StrAccumAppend(&out, "NULL", 4);
 81768  81271         }else if( pVar->flags & MEM_Int ){
 81769         -        sqlite3_str_appendf(&out, "%lld", pVar->u.i);
        81272  +        sqlite3XPrintf(&out, "%lld", pVar->u.i);
 81770  81273         }else if( pVar->flags & MEM_Real ){
 81771         -        sqlite3_str_appendf(&out, "%!.15g", pVar->u.r);
        81274  +        sqlite3XPrintf(&out, "%!.15g", pVar->u.r);
 81772  81275         }else if( pVar->flags & MEM_Str ){
 81773  81276           int nOut;  /* Number of bytes of the string text to include in output */
 81774  81277   #ifndef SQLITE_OMIT_UTF16
 81775  81278           u8 enc = ENC(db);
 81776  81279           if( enc!=SQLITE_UTF8 ){
 81777  81280             memset(&utf8, 0, sizeof(utf8));
 81778  81281             utf8.db = db;
 81779  81282             sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
 81780  81283             if( SQLITE_NOMEM==sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8) ){
 81781         -            out.accError = SQLITE_NOMEM;
        81284  +            out.accError = STRACCUM_NOMEM;
 81782  81285               out.nAlloc = 0;
 81783  81286             }
 81784  81287             pVar = &utf8;
 81785  81288           }
 81786  81289   #endif
 81787  81290           nOut = pVar->n;
 81788  81291   #ifdef SQLITE_TRACE_SIZE_LIMIT
 81789  81292           if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
 81790  81293             nOut = SQLITE_TRACE_SIZE_LIMIT;
 81791  81294             while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
 81792  81295           }
 81793  81296   #endif    
 81794         -        sqlite3_str_appendf(&out, "'%.*q'", nOut, pVar->z);
        81297  +        sqlite3XPrintf(&out, "'%.*q'", nOut, pVar->z);
 81795  81298   #ifdef SQLITE_TRACE_SIZE_LIMIT
 81796  81299           if( nOut<pVar->n ){
 81797         -          sqlite3_str_appendf(&out, "/*+%d bytes*/", pVar->n-nOut);
        81300  +          sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
 81798  81301           }
 81799  81302   #endif
 81800  81303   #ifndef SQLITE_OMIT_UTF16
 81801  81304           if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
 81802  81305   #endif
 81803  81306         }else if( pVar->flags & MEM_Zero ){
 81804         -        sqlite3_str_appendf(&out, "zeroblob(%d)", pVar->u.nZero);
        81307  +        sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
 81805  81308         }else{
 81806  81309           int nOut;  /* Number of bytes of the blob to include in output */
 81807  81310           assert( pVar->flags & MEM_Blob );
 81808         -        sqlite3_str_append(&out, "x'", 2);
        81311  +        sqlite3StrAccumAppend(&out, "x'", 2);
 81809  81312           nOut = pVar->n;
 81810  81313   #ifdef SQLITE_TRACE_SIZE_LIMIT
 81811  81314           if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
 81812  81315   #endif
 81813  81316           for(i=0; i<nOut; i++){
 81814         -          sqlite3_str_appendf(&out, "%02x", pVar->z[i]&0xff);
        81317  +          sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
 81815  81318           }
 81816         -        sqlite3_str_append(&out, "'", 1);
        81319  +        sqlite3StrAccumAppend(&out, "'", 1);
 81817  81320   #ifdef SQLITE_TRACE_SIZE_LIMIT
 81818  81321           if( nOut<pVar->n ){
 81819         -          sqlite3_str_appendf(&out, "/*+%d bytes*/", pVar->n-nOut);
        81322  +          sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
 81820  81323           }
 81821  81324   #endif
 81822  81325         }
 81823  81326       }
 81824  81327     }
 81825         -  if( out.accError ) sqlite3_str_reset(&out);
        81328  +  if( out.accError ) sqlite3StrAccumReset(&out);
 81826  81329     return sqlite3StrAccumFinish(&out);
 81827  81330   }
 81828  81331   
 81829  81332   #endif /* #ifndef SQLITE_OMIT_TRACE */
 81830  81333   
 81831  81334   /************** End of vdbetrace.c *******************************************/
 81832  81335   /************** Begin file vdbe.c ********************************************/
................................................................................
 82832  82335   ** Check the value in register P3.  If it is NULL then Halt using
 82833  82336   ** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
 82834  82337   ** value in register P3 is not NULL, then this routine is a no-op.
 82835  82338   ** The P5 parameter should be 1.
 82836  82339   */
 82837  82340   case OP_HaltIfNull: {      /* in3 */
 82838  82341     pIn3 = &aMem[pOp->p3];
 82839         -#ifdef SQLITE_DEBUG
 82840         -  if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); }
 82841         -#endif
 82842  82342     if( (pIn3->flags & MEM_Null)==0 ) break;
 82843  82343     /* Fall through into OP_Halt */
 82844  82344   }
 82845  82345   
 82846  82346   /* Opcode:  Halt P1 P2 * P4 P5
 82847  82347   **
 82848  82348   ** Exit immediately.  All open cursors, etc are closed
................................................................................
 82874  82374   ** is the same as executing Halt.
 82875  82375   */
 82876  82376   case OP_Halt: {
 82877  82377     VdbeFrame *pFrame;
 82878  82378     int pcx;
 82879  82379   
 82880  82380     pcx = (int)(pOp - aOp);
 82881         -#ifdef SQLITE_DEBUG
 82882         -  if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); }
 82883         -#endif
 82884  82381     if( pOp->p1==SQLITE_OK && p->pFrame ){
 82885  82382       /* Halt the sub-program. Return control to the parent frame. */
 82886  82383       pFrame = p->pFrame;
 82887  82384       p->pFrame = pFrame->pParent;
 82888  82385       p->nFrame--;
 82889  82386       sqlite3VdbeSetChanges(db, p->nChange);
 82890  82387       pcx = sqlite3VdbeFrameRestore(pFrame);
................................................................................
 85247  84744   ** size, and so forth.  P1==0 is the main database file and P1==1 is the 
 85248  84745   ** database file used to store temporary tables.
 85249  84746   **
 85250  84747   ** A transaction must be started before executing this opcode.
 85251  84748   */
 85252  84749   case OP_SetCookie: {
 85253  84750     Db *pDb;
 85254         -
 85255         -  sqlite3VdbeIncrWriteCounter(p, 0);
 85256  84751     assert( pOp->p2<SQLITE_N_BTREE_META );
 85257  84752     assert( pOp->p1>=0 && pOp->p1<db->nDb );
 85258  84753     assert( DbMaskTest(p->btreeMask, pOp->p1) );
 85259  84754     assert( p->readOnly==0 );
 85260  84755     pDb = &db->aDb[pOp->p1];
 85261  84756     assert( pDb->pBt!=0 );
 85262  84757     assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
................................................................................
 86212  85707     VdbeFrame *pFrame;     /* Root frame of VDBE */
 86213  85708   
 86214  85709     v = 0;
 86215  85710     res = 0;
 86216  85711     pOut = out2Prerelease(p, pOp);
 86217  85712     assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 86218  85713     pC = p->apCsr[pOp->p1];
        85714  +  if( !pC->isTable ){
        85715  +    rc = SQLITE_CORRUPT_BKPT;
        85716  +    goto abort_due_to_error;
        85717  +  }
 86219  85718     assert( pC!=0 );
 86220         -  assert( pC->isTable );
 86221  85719     assert( pC->eCurType==CURTYPE_BTREE );
 86222  85720     assert( pC->uc.pCursor!=0 );
 86223  85721     {
 86224  85722       /* The next rowid or record number (different terms for the same
 86225  85723       ** thing) is obtained in a two-step algorithm.
 86226  85724       **
 86227  85725       ** First we attempt to find the largest existing rowid and add one
................................................................................
 86382  85880     pC = p->apCsr[pOp->p1];
 86383  85881     assert( pC!=0 );
 86384  85882     assert( pC->eCurType==CURTYPE_BTREE );
 86385  85883     assert( pC->uc.pCursor!=0 );
 86386  85884     assert( (pOp->p5 & OPFLAG_ISNOOP) || pC->isTable );
 86387  85885     assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC );
 86388  85886     REGISTER_TRACE(pOp->p2, pData);
 86389         -  sqlite3VdbeIncrWriteCounter(p, pC);
 86390  85887   
 86391  85888     if( pOp->opcode==OP_Insert ){
 86392  85889       pKey = &aMem[pOp->p3];
 86393  85890       assert( pKey->flags & MEM_Int );
 86394  85891       assert( memIsValid(pKey) );
 86395  85892       REGISTER_TRACE(pOp->p3, pKey);
 86396  85893       x.nKey = pKey->u.i;
................................................................................
 86497  85994     opflags = pOp->p2;
 86498  85995     assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 86499  85996     pC = p->apCsr[pOp->p1];
 86500  85997     assert( pC!=0 );
 86501  85998     assert( pC->eCurType==CURTYPE_BTREE );
 86502  85999     assert( pC->uc.pCursor!=0 );
 86503  86000     assert( pC->deferredMoveto==0 );
 86504         -  sqlite3VdbeIncrWriteCounter(p, pC);
 86505  86001   
 86506  86002   #ifdef SQLITE_DEBUG
 86507  86003     if( pOp->p4type==P4_TABLE && HasRowid(pOp->p4.pTab) && pOp->p5==0 ){
 86508  86004       /* If p5 is zero, the seek operation that positioned the cursor prior to
 86509  86005       ** OP_Delete will have also set the pC->movetoTarget field to the rowid of
 86510  86006       ** the row that is being deleted */
 86511  86007       i64 iKey = sqlite3BtreeIntegerKey(pC->uc.pCursor);
................................................................................
 86666  86162   **
 86667  86163   ** If cursor P1 is an index, then the content is the key of the row.
 86668  86164   ** If cursor P2 is a table, then the content extracted is the data.
 86669  86165   **
 86670  86166   ** If the P1 cursor must be pointing to a valid row (not a NULL row)
 86671  86167   ** of a real table, not a pseudo-table.
 86672  86168   **
 86673         -** If P3!=0 then this opcode is allowed to make an ephemeral pointer
        86169  +** If P3!=0 then this opcode is allowed to make an ephermeral pointer
 86674  86170   ** into the database page.  That means that the content of the output
 86675  86171   ** register will be invalidated as soon as the cursor moves - including
 86676         -** moves caused by other cursors that "save" the current cursors
        86172  +** moves caused by other cursors that "save" the the current cursors
 86677  86173   ** position in order that they can write to the same table.  If P3==0
 86678  86174   ** then a copy of the data is made into memory.  P3!=0 is faster, but
 86679  86175   ** P3==0 is safer.
 86680  86176   **
 86681  86177   ** If P3!=0 then the content of the P2 register is unsuitable for use
 86682  86178   ** in OP_Result and any OP_Result will invalidate the P2 register content.
 86683  86179   ** The P2 register content is invalidated by opcodes like OP_Function or
................................................................................
 87116  86612   case OP_SorterInsert:       /* in2 */
 87117  86613   case OP_IdxInsert: {        /* in2 */
 87118  86614     VdbeCursor *pC;
 87119  86615     BtreePayload x;
 87120  86616   
 87121  86617     assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 87122  86618     pC = p->apCsr[pOp->p1];
 87123         -  sqlite3VdbeIncrWriteCounter(p, pC);
 87124  86619     assert( pC!=0 );
 87125  86620     assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
 87126  86621     pIn2 = &aMem[pOp->p2];
 87127  86622     assert( pIn2->flags & MEM_Blob );
 87128  86623     if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
 87129  86624     assert( pC->eCurType==CURTYPE_BTREE || pOp->opcode==OP_SorterInsert );
 87130  86625     assert( pC->isTable==0 );
................................................................................
 87163  86658   
 87164  86659     assert( pOp->p3>0 );
 87165  86660     assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 );
 87166  86661     assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 87167  86662     pC = p->apCsr[pOp->p1];
 87168  86663     assert( pC!=0 );
 87169  86664     assert( pC->eCurType==CURTYPE_BTREE );
 87170         -  sqlite3VdbeIncrWriteCounter(p, pC);
 87171  86665     pCrsr = pC->uc.pCursor;
 87172  86666     assert( pCrsr!=0 );
 87173  86667     assert( pOp->p5==0 );
 87174  86668     r.pKeyInfo = pC->pKeyInfo;
 87175  86669     r.nField = (u16)pOp->p3;
 87176  86670     r.default_rc = 0;
 87177  86671     r.aMem = &aMem[pOp->p2];
................................................................................
 87386  86880   **
 87387  86881   ** See also: Clear
 87388  86882   */
 87389  86883   case OP_Destroy: {     /* out2 */
 87390  86884     int iMoved;
 87391  86885     int iDb;
 87392  86886   
 87393         -  sqlite3VdbeIncrWriteCounter(p, 0);
 87394  86887     assert( p->readOnly==0 );
 87395  86888     assert( pOp->p1>1 );
 87396  86889     pOut = out2Prerelease(p, pOp);
 87397  86890     pOut->flags = MEM_Null;
 87398  86891     if( db->nVdbeRead > db->nVDestroy+1 ){
 87399  86892       rc = SQLITE_LOCKED;
 87400  86893       p->errorAction = OE_Abort;
................................................................................
 87436  86929   ** also incremented by the number of rows in the table being cleared.
 87437  86930   **
 87438  86931   ** See also: Destroy
 87439  86932   */
 87440  86933   case OP_Clear: {
 87441  86934     int nChange;
 87442  86935    
 87443         -  sqlite3VdbeIncrWriteCounter(p, 0);
 87444  86936     nChange = 0;
 87445  86937     assert( p->readOnly==0 );
 87446  86938     assert( DbMaskTest(p->btreeMask, pOp->p2) );
 87447  86939     rc = sqlite3BtreeClearTable(
 87448  86940         db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
 87449  86941     );
 87450  86942     if( pOp->p3 ){
................................................................................
 87486  86978   
 87487  86979   /* Opcode: CreateBtree P1 P2 P3 * *
 87488  86980   ** Synopsis: r[P2]=root iDb=P1 flags=P3
 87489  86981   **
 87490  86982   ** Allocate a new b-tree in the main database file if P1==0 or in the
 87491  86983   ** TEMP database file if P1==1 or in an attached database if
 87492  86984   ** P1>1.  The P3 argument must be 1 (BTREE_INTKEY) for a rowid table
 87493         -** it must be 2 (BTREE_BLOBKEY) for an index or WITHOUT ROWID table.
        86985  +** it must be 2 (BTREE_BLOBKEY) for a index or WITHOUT ROWID table.
 87494  86986   ** The root page number of the new b-tree is stored in register P2.
 87495  86987   */
 87496  86988   case OP_CreateBtree: {          /* out2 */
 87497  86989     int pgno;
 87498  86990     Db *pDb;
 87499  86991   
 87500         -  sqlite3VdbeIncrWriteCounter(p, 0);
 87501  86992     pOut = out2Prerelease(p, pOp);
 87502  86993     pgno = 0;
 87503  86994     assert( pOp->p3==BTREE_INTKEY || pOp->p3==BTREE_BLOBKEY );
 87504  86995     assert( pOp->p1>=0 && pOp->p1<db->nDb );
 87505  86996     assert( DbMaskTest(p->btreeMask, pOp->p1) );
 87506  86997     assert( p->readOnly==0 );
 87507  86998     pDb = &db->aDb[pOp->p1];
................................................................................
 87513  87004   }
 87514  87005   
 87515  87006   /* Opcode: SqlExec * * * P4 *
 87516  87007   **
 87517  87008   ** Run the SQL statement or statements specified in the P4 string.
 87518  87009   */
 87519  87010   case OP_SqlExec: {
 87520         -  sqlite3VdbeIncrWriteCounter(p, 0);
 87521  87011     db->nSqlExec++;
 87522  87012     rc = sqlite3_exec(db, pOp->p4.z, 0, 0, 0);
 87523  87013     db->nSqlExec--;
 87524  87014     if( rc ) goto abort_due_to_error;
 87525  87015     break;
 87526  87016   }
 87527  87017   
................................................................................
 87603  87093   ** Remove the internal (in-memory) data structures that describe
 87604  87094   ** the table named P4 in database P1.  This is called after a table
 87605  87095   ** is dropped from disk (using the Destroy opcode) in order to keep 
 87606  87096   ** the internal representation of the
 87607  87097   ** schema consistent with what is on disk.
 87608  87098   */
 87609  87099   case OP_DropTable: {
 87610         -  sqlite3VdbeIncrWriteCounter(p, 0);
 87611  87100     sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
 87612  87101     break;
 87613  87102   }
 87614  87103   
 87615  87104   /* Opcode: DropIndex P1 * * P4 *
 87616  87105   **
 87617  87106   ** Remove the internal (in-memory) data structures that describe
 87618  87107   ** the index named P4 in database P1.  This is called after an index
 87619  87108   ** is dropped from disk (using the Destroy opcode)
 87620  87109   ** in order to keep the internal representation of the
 87621  87110   ** schema consistent with what is on disk.
 87622  87111   */
 87623  87112   case OP_DropIndex: {
 87624         -  sqlite3VdbeIncrWriteCounter(p, 0);
 87625  87113     sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
 87626  87114     break;
 87627  87115   }
 87628  87116   
 87629  87117   /* Opcode: DropTrigger P1 * * P4 *
 87630  87118   **
 87631  87119   ** Remove the internal (in-memory) data structures that describe
 87632  87120   ** the trigger named P4 in database P1.  This is called after a trigger
 87633  87121   ** is dropped from disk (using the Destroy opcode) in order to keep 
 87634  87122   ** the internal representation of the
 87635  87123   ** schema consistent with what is on disk.
 87636  87124   */
 87637  87125   case OP_DropTrigger: {
 87638         -  sqlite3VdbeIncrWriteCounter(p, 0);
 87639  87126     sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
 87640  87127     break;
 87641  87128   }
 87642  87129   
 87643  87130   
 87644  87131   #ifndef SQLITE_OMIT_INTEGRITY_CHECK
 87645  87132   /* Opcode: IntegrityCk P1 P2 P3 P4 P5
................................................................................
 88678  88165   **
 88679  88166   ** Store in register P3 the value of the P2-th column of
 88680  88167   ** the current row of the virtual-table of cursor P1.
 88681  88168   **
 88682  88169   ** If the VColumn opcode is being used to fetch the value of
 88683  88170   ** an unchanging column during an UPDATE operation, then the P5
 88684  88171   ** value is 1.  Otherwise, P5 is 0.  The P5 value is returned
 88685         -** by sqlite3_vtab_nochange() routine and can be used
        88172  +** by sqlite3_vtab_nochange() routine can can be used
 88686  88173   ** by virtual table implementations to return special "no-change"
 88687  88174   ** marks which can be more efficient, depending on the virtual table.
 88688  88175   */
 88689  88176   case OP_VColumn: {
 88690  88177     sqlite3_vtab *pVtab;
 88691  88178     const sqlite3_module *pModule;
 88692  88179     Mem *pDest;
................................................................................
 88841  88328     Mem **apArg;
 88842  88329     Mem *pX;
 88843  88330   
 88844  88331     assert( pOp->p2==1        || pOp->p5==OE_Fail   || pOp->p5==OE_Rollback 
 88845  88332          || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
 88846  88333     );
 88847  88334     assert( p->readOnly==0 );
 88848         -  sqlite3VdbeIncrWriteCounter(p, 0);
 88849  88335     pVtab = pOp->p4.pVtab->pVtab;
 88850  88336     if( pVtab==0 || NEVER(pVtab->pModule==0) ){
 88851  88337       rc = SQLITE_LOCKED;
 88852  88338       goto abort_due_to_error;
 88853  88339     }
 88854  88340     pModule = pVtab->pModule;
 88855  88341     nArg = pOp->p2;
................................................................................
 89159  88645       sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,
 89160  88646                              pOp->p4.pExpr, aMem);
 89161  88647     }
 89162  88648     break;
 89163  88649   }
 89164  88650   #endif /* SQLITE_ENABLE_CURSOR_HINTS */
 89165  88651   
 89166         -#ifdef SQLITE_DEBUG
 89167         -/* Opcode:  Abortable   * * * * *
 89168         -**
 89169         -** Verify that an Abort can happen.  Assert if an Abort at this point
 89170         -** might cause database corruption.  This opcode only appears in debugging
 89171         -** builds.
 89172         -**
 89173         -** An Abort is safe if either there have been no writes, or if there is
 89174         -** an active statement journal.
 89175         -*/
 89176         -case OP_Abortable: {
 89177         -  sqlite3VdbeAssertAbortable(p);
 89178         -  break;
 89179         -}
 89180         -#endif
 89181         -
 89182  88652   /* Opcode: Noop * * * * *
 89183  88653   **
 89184  88654   ** Do nothing.  This instruction is often useful as a jump
 89185  88655   ** destination.
 89186  88656   */
 89187  88657   /*
 89188  88658   ** The magic Explain opcode are only inserted when explain==2 (which
 89189  88659   ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
 89190  88660   ** This opcode records information from the optimizer.  It is the
 89191  88661   ** the same as a no-op.  This opcodesnever appears in a real VM program.
 89192  88662   */
 89193         -default: {          /* This is really OP_Noop, OP_Explain */
        88663  +default: {          /* This is really OP_Noop and OP_Explain */
 89194  88664     assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
 89195         -
 89196  88665     break;
 89197  88666   }
 89198  88667   
 89199  88668   /*****************************************************************************
 89200  88669   ** The cases of the switch statement above this line should all be indented
 89201  88670   ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
 89202  88671   ** readability.  From this point on down, the normal indentation rules are
................................................................................
 93233  92702     sqlite3 *db;           /* The database connection */
 93234  92703   
 93235  92704     assert( iCol>=0 && iCol<pEList->nExpr );
 93236  92705     pOrig = pEList->a[iCol].pExpr;
 93237  92706     assert( pOrig!=0 );
 93238  92707     db = pParse->db;
 93239  92708     pDup = sqlite3ExprDup(db, pOrig, 0);
 93240         -  if( pDup!=0 ){
 93241         -    if( zType[0]!='G' ) incrAggFunctionDepth(pDup, nSubquery);
 93242         -    if( pExpr->op==TK_COLLATE ){
 93243         -      pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
 93244         -    }
 93245         -    ExprSetProperty(pDup, EP_Alias);
 93246         -
 93247         -    /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This 
 93248         -    ** prevents ExprDelete() from deleting the Expr structure itself,
 93249         -    ** allowing it to be repopulated by the memcpy() on the following line.
 93250         -    ** The pExpr->u.zToken might point into memory that will be freed by the
 93251         -    ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
 93252         -    ** make a copy of the token before doing the sqlite3DbFree().
 93253         -    */
 93254         -    ExprSetProperty(pExpr, EP_Static);
 93255         -    sqlite3ExprDelete(db, pExpr);
 93256         -    memcpy(pExpr, pDup, sizeof(*pExpr));
 93257         -    if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
 93258         -      assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
 93259         -      pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
 93260         -      pExpr->flags |= EP_MemToken;
 93261         -    }
 93262         -    sqlite3DbFree(db, pDup);
 93263         -  }
 93264         -  ExprSetProperty(pExpr, EP_Alias);
        92709  +  if( pDup==0 ) return;
        92710  +  if( zType[0]!='G' ) incrAggFunctionDepth(pDup, nSubquery);
        92711  +  if( pExpr->op==TK_COLLATE ){
        92712  +    pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
        92713  +  }
        92714  +  ExprSetProperty(pDup, EP_Alias);
        92715  +
        92716  +  /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This 
        92717  +  ** prevents ExprDelete() from deleting the Expr structure itself,
        92718  +  ** allowing it to be repopulated by the memcpy() on the following line.
        92719  +  ** The pExpr->u.zToken might point into memory that will be freed by the
        92720  +  ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
        92721  +  ** make a copy of the token before doing the sqlite3DbFree().
        92722  +  */
        92723  +  ExprSetProperty(pExpr, EP_Static);
        92724  +  sqlite3ExprDelete(db, pExpr);
        92725  +  memcpy(pExpr, pDup, sizeof(*pExpr));
        92726  +  if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
        92727  +    assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
        92728  +    pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
        92729  +    pExpr->flags |= EP_MemToken;
        92730  +  }
        92731  +  sqlite3DbFree(db, pDup);
 93265  92732   }
 93266  92733   
 93267  92734   
 93268  92735   /*
 93269  92736   ** Return TRUE if the name zCol occurs anywhere in the USING clause.
 93270  92737   **
 93271  92738   ** Return FALSE if the USING clause is NULL or if it does not contain
................................................................................
 93509  92976           if( iCol<pTab->nCol ){
 93510  92977             cnt++;
 93511  92978   #ifndef SQLITE_OMIT_UPSERT
 93512  92979             if( pExpr->iTable==2 ){
 93513  92980               testcase( iCol==(-1) );
 93514  92981               pExpr->iTable = pNC->uNC.pUpsert->regData + iCol;
 93515  92982               eNewExprOp = TK_REGISTER;
 93516         -            ExprSetProperty(pExpr, EP_Alias);
 93517  92983             }else
 93518  92984   #endif /* SQLITE_OMIT_UPSERT */
 93519  92985             {
 93520  92986   #ifndef SQLITE_OMIT_TRIGGER
 93521  92987               if( iCol<0 ){
 93522  92988                 pExpr->affinity = SQLITE_AFF_INTEGER;
 93523  92989               }else if( pExpr->iTable==0 ){
................................................................................
 97154  96620               if( aiMap ) aiMap[i] = j;
 97155  96621             }
 97156  96622     
 97157  96623             assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) );
 97158  96624             if( colUsed==(MASKBIT(nExpr)-1) ){
 97159  96625               /* If we reach this point, that means the index pIdx is usable */
 97160  96626               int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
 97161         -            ExplainQueryPlan((pParse, 0,
 97162         -                              "USING INDEX %s FOR IN-OPERATOR",pIdx->zName));
        96627  +#ifndef SQLITE_OMIT_EXPLAIN
        96628  +            sqlite3VdbeAddOp4(v, OP_Explain, 0, 0, 0,
        96629  +              sqlite3MPrintf(db, "USING INDEX %s FOR IN-OPERATOR",pIdx->zName),
        96630  +              P4_DYNAMIC);
        96631  +#endif
 97163  96632               sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
 97164  96633               sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
 97165  96634               VdbeComment((v, "%s", pIdx->zName));
 97166  96635               assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
 97167  96636               eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
 97168  96637     
 97169  96638               if( prRhsHasNull ){
................................................................................
 97387  96856           **
 97388  96857           ** Generate code to write the results of the select into the temporary
 97389  96858           ** table allocated and opened above.
 97390  96859           */
 97391  96860           Select *pSelect = pExpr->x.pSelect;
 97392  96861           ExprList *pEList = pSelect->pEList;
 97393  96862   
 97394         -        ExplainQueryPlan((pParse, 1, "%sLIST SUBQUERY",
 97395         -            jmpIfDynamic>=0?"":"CORRELATED "
 97396         -        ));
        96863  +#ifndef SQLITE_OMIT_EXPLAIN
        96864  +        if( pParse->explain==2 ){
        96865  +          char *zMsg = sqlite3MPrintf(pParse->db, "EXECUTE %sLIST SUBQUERY %d",
        96866  +            jmpIfDynamic>=0?"":"CORRELATED ",
        96867  +            pParse->iNextSelectId
        96868  +          );
        96869  +          sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg,
        96870  +                            P4_DYNAMIC);
        96871  +        }
        96872  +#endif
        96873  +
 97397  96874           assert( !isRowid );
 97398  96875           /* If the LHS and RHS of the IN operator do not match, that
 97399  96876           ** error will have been caught long before we reach this point. */
 97400  96877           if( ALWAYS(pEList->nExpr==nVal) ){
 97401  96878             SelectDest dest;
 97402  96879             int i;
 97403  96880             sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
................................................................................
 97509  96986         int nReg;                             /* Registers to allocate */
 97510  96987         Expr *pLimit;                         /* New limit expression */
 97511  96988   
 97512  96989         testcase( pExpr->op==TK_EXISTS );
 97513  96990         testcase( pExpr->op==TK_SELECT );
 97514  96991         assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
 97515  96992         assert( ExprHasProperty(pExpr, EP_xIsSelect) );
        96993  +
        96994  +#ifndef SQLITE_OMIT_EXPLAIN
        96995  +      if( pParse->explain==2 ){
        96996  +        char *zMsg = sqlite3MPrintf(pParse->db, "EXECUTE %sSCALAR SUBQUERY %d",
        96997  +            jmpIfDynamic>=0?"":"CORRELATED ",
        96998  +            pParse->iNextSelectId
        96999  +        );
        97000  +        sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg,
        97001  +                          P4_DYNAMIC);
        97002  +      }
        97003  +#endif
 97516  97004   
 97517  97005         pSel = pExpr->x.pSelect;
 97518         -      ExplainQueryPlan((pParse, 1, "%sSCALAR SUBQUERY",
 97519         -            jmpIfDynamic>=0?"":"CORRELATED "));
 97520  97006         nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;
 97521  97007         sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);
 97522  97008         pParse->nMem += nReg;
 97523  97009         if( pExpr->op==TK_SELECT ){
 97524  97010           dest.eDest = SRT_Mem;
 97525  97011           dest.iSdst = dest.iSDParm;
 97526  97012           dest.nSdst = nReg;
................................................................................
 98275  97761   
 98276  97762     assert( target>0 && target<=pParse->nMem );
 98277  97763     if( v==0 ){
 98278  97764       assert( pParse->db->mallocFailed );
 98279  97765       return 0;
 98280  97766     }
 98281  97767   
 98282         -expr_code_doover:
 98283  97768     if( pExpr==0 ){
 98284  97769       op = TK_NULL;
 98285  97770     }else{
 98286  97771       op = pExpr->op;
 98287  97772     }
 98288  97773     switch( op ){
 98289  97774       case TK_AGG_COLUMN: {
................................................................................
 98736  98221       case TK_BETWEEN: {
 98737  98222         exprCodeBetween(pParse, pExpr, target, 0, 0);
 98738  98223         return target;
 98739  98224       }
 98740  98225       case TK_SPAN:
 98741  98226       case TK_COLLATE: 
 98742  98227       case TK_UPLUS: {
 98743         -      pExpr = pExpr->pLeft;
 98744         -      goto expr_code_doover; /* 2018-04-28: Prevent deep recursion. OSSFuzz. */
        98228  +      return sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
 98745  98229       }
 98746  98230   
 98747  98231       case TK_TRIGGER: {
 98748  98232         /* If the opcode is TK_TRIGGER, then the expression is a reference
 98749  98233         ** to a column in the new.* or old.* pseudo-tables available to
 98750  98234         ** trigger programs. In this case Expr.iTable is set to 1 for the
 98751  98235         ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
................................................................................
103793 103277     sqlite3 *db = pParse->db;
103794 103278     Table *pTab = 0;      /* The table being read */
103795 103279     const char *zCol;     /* Name of the column of the table */
103796 103280     int iSrc;             /* Index in pTabList->a[] of table being read */
103797 103281     int iDb;              /* The index of the database the expression refers to */
103798 103282     int iCol;             /* Index of column in table */
103799 103283   
103800         -  assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
103801 103284     if( db->xAuth==0 ) return;
103802 103285     iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
103803 103286     if( iDb<0 ){
103804 103287       /* An attempt to read a column out of a subquery or other
103805 103288       ** temporary table. */
103806 103289       return;
103807 103290     }
103808 103291   
       103292  +  assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
103809 103293     if( pExpr->op==TK_TRIGGER ){
103810 103294       pTab = pParse->pTriggerTab;
103811 103295     }else{
103812 103296       assert( pTabList );
103813 103297       for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
103814 103298         if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
103815 103299           pTab = pTabList->a[iSrc].pTab;
................................................................................
106760 106244                       sqlite3KeyInfoRef(pKey), P4_KEYINFO);
106761 106245   
106762 106246     /* Open the table. Loop through all rows of the table, inserting index
106763 106247     ** records into the sorter. */
106764 106248     sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
106765 106249     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
106766 106250     regRecord = sqlite3GetTempReg(pParse);
106767         -  sqlite3MultiWrite(pParse);
106768 106251   
106769 106252     sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
106770 106253     sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
106771 106254     sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
106772 106255     sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
106773 106256     sqlite3VdbeJumpHere(v, addr1);
106774 106257     if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
106775 106258     sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, 
106776 106259                       (char *)pKey, P4_KEYINFO);
106777 106260     sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
106778 106261   
106779 106262     addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
106780 106263     if( IsUniqueIndex(pIndex) ){
106781         -    int j2 = sqlite3VdbeGoto(v, 1);
       106264  +    int j2 = sqlite3VdbeCurrentAddr(v) + 3;
       106265  +    sqlite3VdbeGoto(v, j2);
106782 106266       addr2 = sqlite3VdbeCurrentAddr(v);
106783         -    sqlite3VdbeVerifyAbortable(v, OE_Abort);
106784 106267       sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
106785 106268                            pIndex->nKeyCol); VdbeCoverage(v);
106786 106269       sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
106787         -    sqlite3VdbeJumpHere(v, j2);
106788 106270     }else{
106789 106271       addr2 = sqlite3VdbeCurrentAddr(v);
106790 106272     }
106791 106273     sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
106792 106274     sqlite3VdbeAddOp1(v, OP_SeekEnd, iIdx);
106793 106275     sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
106794 106276     sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
................................................................................
106943 106425     assert( pTab!=0 );
106944 106426     assert( pParse->nErr==0 );
106945 106427     if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 
106946 106428          && db->init.busy==0
106947 106429   #if SQLITE_USER_AUTHENTICATION
106948 106430          && sqlite3UserAuthTable(pTab->zName)==0
106949 106431   #endif
106950         -#ifdef SQLITE_ALLOW_SQLITE_MASTER_INDEX
106951         -       && sqlite3StrICmp(&pTab->zName[7],"master")!=0
106952         -#endif
106953         -       && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0
106954         - ){
       106432  +       && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
106955 106433       sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
106956 106434       goto exit_create_index;
106957 106435     }
106958 106436   #ifndef SQLITE_OMIT_VIEW
106959 106437     if( pTab->pSelect ){
106960 106438       sqlite3ErrorMsg(pParse, "views may not be indexed");
106961 106439       goto exit_create_index;
................................................................................
108126 107604     char *zErr;
108127 107605     int j;
108128 107606     StrAccum errMsg;
108129 107607     Table *pTab = pIdx->pTable;
108130 107608   
108131 107609     sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, 200);
108132 107610     if( pIdx->aColExpr ){
108133         -    sqlite3_str_appendf(&errMsg, "index '%q'", pIdx->zName);
       107611  +    sqlite3XPrintf(&errMsg, "index '%q'", pIdx->zName);
108134 107612     }else{
108135 107613       for(j=0; j<pIdx->nKeyCol; j++){
108136 107614         char *zCol;
108137 107615         assert( pIdx->aiColumn[j]>=0 );
108138 107616         zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
108139         -      if( j ) sqlite3_str_append(&errMsg, ", ", 2);
108140         -      sqlite3_str_appendall(&errMsg, pTab->zName);
108141         -      sqlite3_str_append(&errMsg, ".", 1);
108142         -      sqlite3_str_appendall(&errMsg, zCol);
       107617  +      if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
       107618  +      sqlite3StrAccumAppendAll(&errMsg, pTab->zName);
       107619  +      sqlite3StrAccumAppend(&errMsg, ".", 1);
       107620  +      sqlite3StrAccumAppendAll(&errMsg, zCol);
108143 107621       }
108144 107622     }
108145 107623     zErr = sqlite3StrAccumFinish(&errMsg);
108146 107624     sqlite3HaltConstraint(pParse, 
108147 107625       IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY 
108148 107626                               : SQLITE_CONSTRAINT_UNIQUE,
108149 107627       onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
................................................................................
108821 108299     /* If the createFlag parameter is true and the search did not reveal an
108822 108300     ** exact match for the name, number of arguments and encoding, then add a
108823 108301     ** new entry to the hash table and return it.
108824 108302     */
108825 108303     if( createFlag && bestScore<FUNC_PERFECT_MATCH && 
108826 108304         (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
108827 108305       FuncDef *pOther;
108828         -    u8 *z;
108829 108306       pBest->zName = (const char*)&pBest[1];
108830 108307       pBest->nArg = (u16)nArg;
108831 108308       pBest->funcFlags = enc;
108832 108309       memcpy((char*)&pBest[1], zName, nName+1);
108833         -    for(z=(u8*)pBest->zName; *z; z++) *z = sqlite3UpperToLower[*z];
108834 108310       pOther = (FuncDef*)sqlite3HashInsert(&db->aFunc, pBest->zName, pBest);
108835 108311       if( pOther==pBest ){
108836 108312         sqlite3DbFree(db, pBest);
108837 108313         sqlite3OomFault(db);
108838 108314         return 0;
108839 108315       }else{
108840 108316         pBest->pNext = pOther;
................................................................................
109459 108935       }  
109460 108936     
109461 108937       /* Delete the row */
109462 108938   #ifndef SQLITE_OMIT_VIRTUALTABLE
109463 108939       if( IsVirtual(pTab) ){
109464 108940         const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
109465 108941         sqlite3VtabMakeWritable(pParse, pTab);
       108942  +      sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
       108943  +      sqlite3VdbeChangeP5(v, OE_Abort);
109466 108944         assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
109467 108945         sqlite3MayAbort(pParse);
109468         -      if( eOnePass==ONEPASS_SINGLE ){
109469         -        sqlite3VdbeAddOp1(v, OP_Close, iTabCur);
109470         -        if( sqlite3IsToplevel(pParse) ){
109471         -          pParse->isMultiWrite = 0;
109472         -        }
       108946  +      if( eOnePass==ONEPASS_SINGLE && sqlite3IsToplevel(pParse) ){
       108947  +        pParse->isMultiWrite = 0;
109473 108948         }
109474         -      sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
109475         -      sqlite3VdbeChangeP5(v, OE_Abort);
109476 108949       }else
109477 108950   #endif
109478 108951       {
109479 108952         int count = (pParse->nested==0);    /* True to count changes */
109480 108953         sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
109481 108954             iKey, nKey, count, OE_Default, eOnePass, aiCurOnePass[1]);
109482 108955       }
................................................................................
110110 109583   
110111 109584     if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
110112 109585       x.nArg = argc-1;
110113 109586       x.nUsed = 0;
110114 109587       x.apArg = argv+1;
110115 109588       sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
110116 109589       str.printfFlags = SQLITE_PRINTF_SQLFUNC;
110117         -    sqlite3_str_appendf(&str, zFormat, &x);
       109590  +    sqlite3XPrintf(&str, zFormat, &x);
110118 109591       n = str.nChar;
110119 109592       sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
110120 109593                           SQLITE_DYNAMIC);
110121 109594     }
110122 109595   }
110123 109596   
110124 109597   /*
................................................................................
111513 110986         if( argc==2 ){
111514 110987           zSep = (char*)sqlite3_value_text(argv[1]);
111515 110988           nSep = sqlite3_value_bytes(argv[1]);
111516 110989         }else{
111517 110990           zSep = ",";
111518 110991           nSep = 1;
111519 110992         }
111520         -      if( zSep ) sqlite3_str_append(pAccum, zSep, nSep);
       110993  +      if( zSep ) sqlite3StrAccumAppend(pAccum, zSep, nSep);
111521 110994       }
111522 110995       zVal = (char*)sqlite3_value_text(argv[0]);
111523 110996       nVal = sqlite3_value_bytes(argv[0]);
111524         -    if( zVal ) sqlite3_str_append(pAccum, zVal, nVal);
       110997  +    if( zVal ) sqlite3StrAccumAppend(pAccum, zVal, nVal);
111525 110998     }
111526 110999   }
111527 111000   static void groupConcatFinalize(sqlite3_context *context){
111528 111001     StrAccum *pAccum;
111529 111002     pAccum = sqlite3_aggregate_context(context, 0);
111530 111003     if( pAccum ){
111531         -    if( pAccum->accError==SQLITE_TOOBIG ){
       111004  +    if( pAccum->accError==STRACCUM_TOOBIG ){
111532 111005         sqlite3_result_error_toobig(context);
111533         -    }else if( pAccum->accError==SQLITE_NOMEM ){
       111006  +    }else if( pAccum->accError==STRACCUM_NOMEM ){
111534 111007         sqlite3_result_error_nomem(context);
111535 111008       }else{    
111536 111009         sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1, 
111537 111010                             sqlite3_free);
111538 111011       }
111539 111012     }
111540 111013   }
................................................................................
112103 111576     int isIgnore          /* If true, pretend pTab contains all NULL values */
112104 111577   ){
112105 111578     int i;                                    /* Iterator variable */
112106 111579     Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
112107 111580     int iCur = pParse->nTab - 1;              /* Cursor number to use */
112108 111581     int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
112109 111582   
112110         -  sqlite3VdbeVerifyAbortable(v,
112111         -    (!pFKey->isDeferred
112112         -      && !(pParse->db->flags & SQLITE_DeferFKs)
112113         -      && !pParse->pToplevel 
112114         -      && !pParse->isMultiWrite) ? OE_Abort : OE_Ignore);
112115         -
112116 111583     /* If nIncr is less than zero, then check at runtime if there are any
112117 111584     ** outstanding constraints to resolve. If there are not, there is no need
112118 111585     ** to check if deleting this row resolves any outstanding violations.
112119 111586     **
112120 111587     ** Check if any of the key columns in the child table row are NULL. If 
112121 111588     ** any are, then the constraint is considered satisfied. No need to 
112122 111589     ** search for a matching row in the parent table.  */
................................................................................
112516 111983       ** transactions are not able to rollback schema changes.  
112517 111984       **
112518 111985       ** If the SQLITE_DeferFKs flag is set, then this is not required, as
112519 111986       ** the statement transaction will not be rolled back even if FK
112520 111987       ** constraints are violated.
112521 111988       */
112522 111989       if( (db->flags & SQLITE_DeferFKs)==0 ){
112523         -      sqlite3VdbeVerifyAbortable(v, OE_Abort);
112524 111990         sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
112525 111991         VdbeCoverage(v);
112526 111992         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
112527 111993             OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
112528 111994       }
112529 111995   
112530 111996       if( iSkip ){
................................................................................
113429 112895   */
113430 112896   static int autoIncBegin(
113431 112897     Parse *pParse,      /* Parsing context */
113432 112898     int iDb,            /* Index of the database holding pTab */
113433 112899     Table *pTab         /* The table we are writing to */
113434 112900   ){
113435 112901     int memId = 0;      /* Register holding maximum rowid */
113436         -  assert( pParse->db->aDb[iDb].pSchema!=0 );
113437 112902     if( (pTab->tabFlags & TF_Autoincrement)!=0
113438 112903      && (pParse->db->mDbFlags & DBFLAG_Vacuum)==0
113439 112904     ){
113440 112905       Parse *pToplevel = sqlite3ParseToplevel(pParse);
113441 112906       AutoincInfo *pInfo;
113442         -    Table *pSeqTab = pParse->db->aDb[iDb].pSchema->pSeqTab;
113443         -
113444         -    /* Verify that the sqlite_sequence table exists and is an ordinary
113445         -    ** rowid table with exactly two columns.
113446         -    ** Ticket d8dc2b3a58cd5dc2918a1d4acb 2018-05-23 */
113447         -    if( pSeqTab==0
113448         -     || !HasRowid(pSeqTab)
113449         -     || IsVirtual(pSeqTab)
113450         -     || pSeqTab->nCol!=2
113451         -    ){
113452         -      pParse->nErr++;
113453         -      pParse->rc = SQLITE_CORRUPT_SEQUENCE;
113454         -      return 0;
113455         -    }
113456 112907   
113457 112908       pInfo = pToplevel->pAinc;
113458 112909       while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
113459 112910       if( pInfo==0 ){
113460 112911         pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
113461 112912         if( pInfo==0 ) return 0;
113462 112913         pInfo->pNext = pToplevel->pAinc;
................................................................................
114623 114074       pParse->iSelfTab = -(regNewData+1);
114624 114075       onError = overrideError!=OE_Default ? overrideError : OE_Abort;
114625 114076       for(i=0; i<pCheck->nExpr; i++){
114626 114077         int allOk;
114627 114078         Expr *pExpr = pCheck->a[i].pExpr;
114628 114079         if( aiChng && checkConstraintUnchanged(pExpr, aiChng, pkChng) ) continue;
114629 114080         allOk = sqlite3VdbeMakeLabel(v);
114630         -      sqlite3VdbeVerifyAbortable(v, onError);
114631 114081         sqlite3ExprIfTrue(pParse, pExpr, allOk, SQLITE_JUMPIFNULL);
114632 114082         if( onError==OE_Ignore ){
114633 114083           sqlite3VdbeGoto(v, ignoreDest);
114634 114084         }else{
114635 114085           char *zName = pCheck->a[i].zName;
114636 114086           if( zName==0 ) zName = pTab->zName;
114637 114087           if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
................................................................................
114733 114183         sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
114734 114184         VdbeCoverage(v);
114735 114185       }
114736 114186   
114737 114187       /* Check to see if the new rowid already exists in the table.  Skip
114738 114188       ** the following conflict logic if it does not. */
114739 114189       VdbeNoopComment((v, "uniqueness check for ROWID"));
114740         -    sqlite3VdbeVerifyAbortable(v, onError);
114741 114190       sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
114742 114191       VdbeCoverage(v);
114743 114192   
114744 114193       switch( onError ){
114745 114194         default: {
114746 114195           onError = OE_Abort;
114747 114196           /* Fall thru into the next case */
................................................................................
114946 114395       ){
114947 114396         sqlite3VdbeResolveLabel(v, addrUniqueOk);
114948 114397         continue;
114949 114398       }
114950 114399   
114951 114400       /* Check to see if the new index entry will be unique */
114952 114401       sqlite3ExprCachePush(pParse);
114953         -    sqlite3VdbeVerifyAbortable(v, onError);
114954 114402       sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
114955 114403                            regIdx, pIdx->nKeyCol); VdbeCoverage(v);
114956 114404   
114957 114405       /* Generate code to handle collisions */
114958 114406       regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
114959 114407       if( isUpdate || onError==OE_Replace ){
114960 114408         if( HasRowid(pTab) ){
................................................................................
115033 114481           testcase( onError==OE_Ignore );
115034 114482           sqlite3VdbeGoto(v, ignoreDest);
115035 114483           break;
115036 114484         }
115037 114485         default: {
115038 114486           Trigger *pTrigger = 0;
115039 114487           assert( onError==OE_Replace );
       114488  +        sqlite3MultiWrite(pParse);
115040 114489           if( db->flags&SQLITE_RecTriggers ){
115041 114490             pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
115042 114491           }
115043         -        if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
115044         -          sqlite3MultiWrite(pParse);
115045         -        }
115046 114492           sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
115047 114493               regR, nPkField, 0, OE_Replace,
115048 114494               (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur);
115049 114495           seenReplace = 1;
115050 114496           break;
115051 114497         }
115052 114498       }
................................................................................
115558 115004     }
115559 115005     if( HasRowid(pSrc) ){
115560 115006       u8 insFlags;
115561 115007       sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
115562 115008       emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
115563 115009       if( pDest->iPKey>=0 ){
115564 115010         addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
115565         -      sqlite3VdbeVerifyAbortable(v, onError);
115566 115011         addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
115567 115012         VdbeCoverage(v);
115568 115013         sqlite3RowidConstraint(pParse, onError, pDest);
115569 115014         sqlite3VdbeJumpHere(v, addr2);
115570 115015         autoIncStep(pParse, regAutoinc, regRowid);
115571 115016       }else if( pDest->pIndex==0 ){
115572 115017         addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
................................................................................
116116 115561                         sqlite3_stmt**,const void**);
116117 115562     int (*bind_pointer)(sqlite3_stmt*,int,void*,const char*,void(*)(void*));
116118 115563     void (*result_pointer)(sqlite3_context*,void*,const char*,void(*)(void*));
116119 115564     void *(*value_pointer)(sqlite3_value*,const char*);
116120 115565     int (*vtab_nochange)(sqlite3_context*);
116121 115566     int (*value_nochange)(sqlite3_value*);
116122 115567     const char *(*vtab_collation)(sqlite3_index_info*,int);
116123         -  /* Version 3.24.0 and later */
116124         -  int (*keyword_count)(void);
116125         -  int (*keyword_name)(int,const char**,int*);
116126         -  int (*keyword_check)(const char*,int);
116127         -  sqlite3_str *(*str_new)(sqlite3*);
116128         -  char *(*str_finish)(sqlite3_str*);
116129         -  void (*str_appendf)(sqlite3_str*, const char *zFormat, ...);
116130         -  void (*str_vappendf)(sqlite3_str*, const char *zFormat, va_list);
116131         -  void (*str_append)(sqlite3_str*, const char *zIn, int N);
116132         -  void (*str_appendall)(sqlite3_str*, const char *zIn);
116133         -  void (*str_appendchar)(sqlite3_str*, int N, char C);
116134         -  void (*str_reset)(sqlite3_str*);
116135         -  int (*str_errcode)(sqlite3_str*);
116136         -  int (*str_length)(sqlite3_str*);
116137         -  char *(*str_value)(sqlite3_str*);
116138 115568   };
116139 115569   
116140 115570   /*
116141 115571   ** This is the function signature used for all extension entry points.  It
116142 115572   ** is also defined in the file "loadext.c".
116143 115573   */
116144 115574   typedef int (*sqlite3_loadext_entry)(
................................................................................
116401 115831   #define sqlite3_bind_pointer           sqlite3_api->bind_pointer
116402 115832   #define sqlite3_result_pointer         sqlite3_api->result_pointer
116403 115833   #define sqlite3_value_pointer          sqlite3_api->value_pointer
116404 115834   /* Version 3.22.0 and later */
116405 115835   #define sqlite3_vtab_nochange          sqlite3_api->vtab_nochange
116406 115836   #define sqlite3_value_nochange         sqlite3_api->value_nochange
116407 115837   #define sqlite3_vtab_collation         sqlite3_api->vtab_collation
116408         -/* Version 3.24.0 and later */
116409         -#define sqlite3_keyword_count          sqlite3_api->keyword_count
116410         -#define sqlite3_keyword_name           sqlite3_api->keyword_name
116411         -#define sqlite3_keyword_check          sqlite3_api->keyword_check
116412         -#define sqlite3_str_new                sqlite3_api->str_new
116413         -#define sqlite3_str_finish             sqlite3_api->str_finish
116414         -#define sqlite3_str_appendf            sqlite3_api->str_appendf
116415         -#define sqlite3_str_vappendf           sqlite3_api->str_vappendf
116416         -#define sqlite3_str_append             sqlite3_api->str_append
116417         -#define sqlite3_str_appendall          sqlite3_api->str_appendall
116418         -#define sqlite3_str_appendchar         sqlite3_api->str_appendchar
116419         -#define sqlite3_str_reset              sqlite3_api->str_reset
116420         -#define sqlite3_str_errcode            sqlite3_api->str_errcode
116421         -#define sqlite3_str_length             sqlite3_api->str_length
116422         -#define sqlite3_str_value              sqlite3_api->str_value
116423 115838   #endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */
116424 115839   
116425 115840   #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
116426 115841     /* This case when the file really is being compiled as a loadable 
116427 115842     ** extension */
116428 115843   # define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api=0;
116429 115844   # define SQLITE_EXTENSION_INIT2(v)  sqlite3_api=v;
................................................................................
116854 116269     sqlite3_prepare16_v3,
116855 116270     sqlite3_bind_pointer,
116856 116271     sqlite3_result_pointer,
116857 116272     sqlite3_value_pointer,
116858 116273     /* Version 3.22.0 and later */
116859 116274     sqlite3_vtab_nochange,
116860 116275     sqlite3_value_nochange,
116861         -  sqlite3_vtab_collation,
116862         -  /* Version 3.24.0 and later */
116863         -  sqlite3_keyword_count,
116864         -  sqlite3_keyword_name,
116865         -  sqlite3_keyword_check,
116866         -  sqlite3_str_new,
116867         -  sqlite3_str_finish,
116868         -  sqlite3_str_appendf,
116869         -  sqlite3_str_vappendf,
116870         -  sqlite3_str_append,
116871         -  sqlite3_str_appendall,
116872         -  sqlite3_str_appendchar,
116873         -  sqlite3_str_reset,
116874         -  sqlite3_str_errcode,
116875         -  sqlite3_str_length,
116876         -  sqlite3_str_value
       116276  +  sqlite3_vtab_collation
116877 116277   };
116878 116278   
116879 116279   /*
116880 116280   ** Attempt to load an SQLite extension library contained in the file
116881 116281   ** zFile.  The entry point is zProc.  zProc may be 0 in which case a
116882 116282   ** default entry point name (sqlite3_extension_init) is used.  Use
116883 116283   ** of the default name is recommended.
................................................................................
116935 116335   
116936 116336     zEntry = zProc ? zProc : "sqlite3_extension_init";
116937 116337   
116938 116338     handle = sqlite3OsDlOpen(pVfs, zFile);
116939 116339   #if SQLITE_OS_UNIX || SQLITE_OS_WIN
116940 116340     for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
116941 116341       char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
       116342  +    int bExists = 0;
116942 116343       if( zAltFile==0 ) return SQLITE_NOMEM_BKPT;
116943         -    handle = sqlite3OsDlOpen(pVfs, zAltFile);
       116344  +    sqlite3OsAccess(pVfs, zAltFile, SQLITE_ACCESS_EXISTS, &bExists);
       116345  +    if( bExists )  handle = sqlite3OsDlOpen(pVfs, zAltFile);
116944 116346       sqlite3_free(zAltFile);
116945 116347     }
116946 116348   #endif
116947 116349     if( handle==0 ){
116948 116350       if( pzErrMsg ){
116949 116351         *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
116950 116352         if( zErrmsg ){
................................................................................
120108 119510     char cSep = '(';
120109 119511     StrAccum acc;
120110 119512     char zBuf[200];
120111 119513   
120112 119514     UNUSED_PARAMETER(argc);
120113 119515     UNUSED_PARAMETER(argv);
120114 119516     sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
120115         -  sqlite3_str_appendall(&acc, "CREATE TABLE x");
       119517  +  sqlite3StrAccumAppendAll(&acc, "CREATE TABLE x");
120116 119518     for(i=0, j=pPragma->iPragCName; i<pPragma->nPragCName; i++, j++){
120117         -    sqlite3_str_appendf(&acc, "%c\"%s\"", cSep, pragCName[j]);
       119519  +    sqlite3XPrintf(&acc, "%c\"%s\"", cSep, pragCName[j]);
120118 119520       cSep = ',';
120119 119521     }
120120 119522     if( i==0 ){
120121         -    sqlite3_str_appendf(&acc, "(\"%s\"", pPragma->zName);
       119523  +    sqlite3XPrintf(&acc, "(\"%s\"", pPragma->zName);
120122 119524       cSep = ',';
120123 119525       i++;
120124 119526     }
120125 119527     j = 0;
120126 119528     if( pPragma->mPragFlg & PragFlg_Result1 ){
120127         -    sqlite3_str_appendall(&acc, ",arg HIDDEN");
       119529  +    sqlite3StrAccumAppendAll(&acc, ",arg HIDDEN");
120128 119530       j++;
120129 119531     }
120130 119532     if( pPragma->mPragFlg & (PragFlg_SchemaOpt|PragFlg_SchemaReq) ){
120131         -    sqlite3_str_appendall(&acc, ",schema HIDDEN");
       119533  +    sqlite3StrAccumAppendAll(&acc, ",schema HIDDEN");
120132 119534       j++;
120133 119535     }
120134         -  sqlite3_str_append(&acc, ")", 1);
       119536  +  sqlite3StrAccumAppend(&acc, ")", 1);
120135 119537     sqlite3StrAccumFinish(&acc);
120136 119538     assert( strlen(zBuf) < sizeof(zBuf)-1 );
120137 119539     rc = sqlite3_declare_vtab(db, zBuf);
120138 119540     if( rc==SQLITE_OK ){
120139 119541       pTab = (PragmaVtab*)sqlite3_malloc(sizeof(PragmaVtab));
120140 119542       if( pTab==0 ){
120141 119543         rc = SQLITE_NOMEM;
................................................................................
120279 119681         pCsr->azArg[j] = sqlite3_mprintf("%s", zText);
120280 119682         if( pCsr->azArg[j]==0 ){
120281 119683           return SQLITE_NOMEM;
120282 119684         }
120283 119685       }
120284 119686     }
120285 119687     sqlite3StrAccumInit(&acc, 0, 0, 0, pTab->db->aLimit[SQLITE_LIMIT_SQL_LENGTH]);
120286         -  sqlite3_str_appendall(&acc, "PRAGMA ");
       119688  +  sqlite3StrAccumAppendAll(&acc, "PRAGMA ");
120287 119689     if( pCsr->azArg[1] ){
120288         -    sqlite3_str_appendf(&acc, "%Q.", pCsr->azArg[1]);
       119690  +    sqlite3XPrintf(&acc, "%Q.", pCsr->azArg[1]);
120289 119691     }
120290         -  sqlite3_str_appendall(&acc, pTab->pName->zName);
       119692  +  sqlite3StrAccumAppendAll(&acc, pTab->pName->zName);
120291 119693     if( pCsr->azArg[0] ){
120292         -    sqlite3_str_appendf(&acc, "=%Q", pCsr->azArg[0]);
       119694  +    sqlite3XPrintf(&acc, "=%Q", pCsr->azArg[0]);
120293 119695     }
120294 119696     zSql = sqlite3StrAccumFinish(&acc);
120295 119697     if( zSql==0 ) return SQLITE_NOMEM;
120296 119698     rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pPragma, 0);
120297 119699     sqlite3_free(zSql);
120298 119700     if( rc!=SQLITE_OK ){
120299 119701       pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
................................................................................
120599 120001     **
120600 120002     ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
120601 120003     ** the possible values of meta[4].
120602 120004     */
120603 120005     for(i=0; i<ArraySize(meta); i++){
120604 120006       sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
120605 120007     }
120606         -  if( (db->flags & SQLITE_ResetDatabase)!=0 ){
120607         -    memset(meta, 0, sizeof(meta));
120608         -  }
120609 120008     pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
120610 120009   
120611 120010     /* If opening a non-empty database, check the text encoding. For the
120612 120011     ** main database, set sqlite3.enc to the encoding of the main database.
120613 120012     ** For an attached db, it is an error if the encoding is not the same
120614 120013     ** as sqlite3.enc.
120615 120014     */
................................................................................
120999 120398     }
121000 120399     rc = sParse.rc;
121001 120400   
121002 120401   #ifndef SQLITE_OMIT_EXPLAIN
121003 120402     if( rc==SQLITE_OK && sParse.pVdbe && sParse.explain ){
121004 120403       static const char * const azColName[] = {
121005 120404          "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
121006         -       "id", "parent", "notused", "detail"
       120405  +       "selectid", "order", "from", "detail"
121007 120406       };
121008 120407       int iFirst, mx;
121009 120408       if( sParse.explain==2 ){
121010 120409         sqlite3VdbeSetNumCols(sParse.pVdbe, 4);
121011 120410         iFirst = 8;
121012 120411         mx = 12;
121013 120412       }else{
................................................................................
121313 120712   /*
121314 120713   ** Trace output macros
121315 120714   */
121316 120715   #if SELECTTRACE_ENABLED
121317 120716   /***/ int sqlite3SelectTrace = 0;
121318 120717   # define SELECTTRACE(K,P,S,X)  \
121319 120718     if(sqlite3SelectTrace&(K))   \
121320         -    sqlite3DebugPrintf("%s/%d/%p: ",(S)->zSelName,(P)->addrExplain,(S)),\
       120719  +    sqlite3DebugPrintf("%s/%d/%p: ",(S)->zSelName,(P)->iSelectId,(S)),\
121321 120720       sqlite3DebugPrintf X
121322 120721   #else
121323 120722   # define SELECTTRACE(K,P,S,X)
121324 120723   #endif
121325 120724   
121326 120725   
121327 120726   /*
................................................................................
121370 120769     u8 nDefer;            /* Number of valid entries in aDefer[] */
121371 120770     struct DeferredCsr {
121372 120771       Table *pTab;        /* Table definition */
121373 120772       int iCsr;           /* Cursor number for table */
121374 120773       int nKey;           /* Number of PK columns for table pTab (>=1) */
121375 120774     } aDefer[4];
121376 120775   #endif
121377         -  struct RowLoadInfo *pDeferredRowLoad;  /* Deferred row loading info or NULL */
121378 120776   };
121379 120777   #define SORTFLAG_UseSorter  0x01   /* Use SorterOpen instead of OpenEphemeral */
121380 120778   
121381 120779   /*
121382 120780   ** Delete all the content of a Select structure.  Deallocate the structure
121383 120781   ** itself only if bFree is true.
121384 120782   */
................................................................................
121829 121227   static KeyInfo *keyInfoFromExprList(
121830 121228     Parse *pParse,       /* Parsing context */
121831 121229     ExprList *pList,     /* Form the KeyInfo object from this ExprList */
121832 121230     int iStart,          /* Begin with this column of pList */
121833 121231     int nExtra           /* Add this many extra columns to the end */
121834 121232   );
121835 121233   
121836         -/*
121837         -** An instance of this object holds information (beyond pParse and pSelect)
121838         -** needed to load the next result row that is to be added to the sorter.
121839         -*/
121840         -typedef struct RowLoadInfo RowLoadInfo;
121841         -struct RowLoadInfo {
121842         -  int regResult;               /* Store results in array of registers here */
121843         -  u8 ecelFlags;                /* Flag argument to ExprCodeExprList() */
121844         -#ifdef SQLITE_ENABLE_SORTER_REFERENCES
121845         -  ExprList *pExtra;            /* Extra columns needed by sorter refs */
121846         -  int regExtraResult;          /* Where to load the extra columns */
121847         -#endif
121848         -};
121849         -
121850         -/*
121851         -** This routine does the work of loading query data into an array of
121852         -** registers so that it can be added to the sorter.
121853         -*/
121854         -static void innerLoopLoadRow(
121855         -  Parse *pParse,             /* Statement under construction */
121856         -  Select *pSelect,           /* The query being coded */
121857         -  RowLoadInfo *pInfo         /* Info needed to complete the row load */
121858         -){
121859         -  sqlite3ExprCodeExprList(pParse, pSelect->pEList, pInfo->regResult,
121860         -                          0, pInfo->ecelFlags);
121861         -#ifdef SQLITE_ENABLE_SORTER_REFERENCES
121862         -  if( pInfo->pExtra ){
121863         -    sqlite3ExprCodeExprList(pParse, pInfo->pExtra, pInfo->regExtraResult, 0, 0);
121864         -    sqlite3ExprListDelete(pParse->db, pInfo->pExtra);
121865         -  }
121866         -#endif
121867         -}
121868         -
121869         -/*
121870         -** Code the OP_MakeRecord instruction that generates the entry to be
121871         -** added into the sorter.
121872         -**
121873         -** Return the register in which the result is stored.
121874         -*/
121875         -static int makeSorterRecord(
121876         -  Parse *pParse,
121877         -  SortCtx *pSort,
121878         -  Select *pSelect,
121879         -  int regBase,
121880         -  int nBase
121881         -){
121882         -  int nOBSat = pSort->nOBSat;
121883         -  Vdbe *v = pParse->pVdbe;
121884         -  int regOut = ++pParse->nMem;
121885         -  if( pSort->pDeferredRowLoad ){
121886         -    innerLoopLoadRow(pParse, pSelect, pSort->pDeferredRowLoad);
121887         -  }
121888         -  sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regOut);
121889         -  return regOut;
121890         -}
121891         -
121892 121234   /*
121893 121235   ** Generate code that will push the record in registers regData
121894 121236   ** through regData+nData-1 onto the sorter.
121895 121237   */
121896 121238   static void pushOntoSorter(
121897 121239     Parse *pParse,         /* Parser context */
121898 121240     SortCtx *pSort,        /* Information about the ORDER BY clause */
121899 121241     Select *pSelect,       /* The whole SELECT statement */
121900 121242     int regData,           /* First register holding data to be sorted */
121901 121243     int regOrigData,       /* First register holding data before packing */
121902         -  int nData,             /* Number of elements in the regData data array */
       121244  +  int nData,             /* Number of elements in the data array */
121903 121245     int nPrefixReg         /* No. of reg prior to regData available for use */
121904 121246   ){
121905 121247     Vdbe *v = pParse->pVdbe;                         /* Stmt under construction */
121906 121248     int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
121907 121249     int nExpr = pSort->pOrderBy->nExpr;              /* No. of ORDER BY terms */
121908 121250     int nBase = nExpr + bSeq + nData;                /* Fields in sorter record */
121909 121251     int regBase;                                     /* Regs for sorter record */
121910         -  int regRecord = 0;                               /* Assembled sorter record */
       121252  +  int regRecord = ++pParse->nMem;                  /* Assembled sorter record */
121911 121253     int nOBSat = pSort->nOBSat;                      /* ORDER BY terms to skip */
121912 121254     int op;                            /* Opcode to add sorter record to sorter */
121913 121255     int iLimit;                        /* LIMIT counter */
121914         -  int iSkip = 0;                     /* End of the sorter insert loop */
121915 121256   
121916 121257     assert( bSeq==0 || bSeq==1 );
121917         -
121918         -  /* Three cases:
121919         -  **   (1) The data to be sorted has already been packed into a Record
121920         -  **       by a prior OP_MakeRecord.  In this case nData==1 and regData
121921         -  **       will be completely unrelated to regOrigData.
121922         -  **   (2) All output columns are included in the sort record.  In that
121923         -  **       case regData==regOrigData.
121924         -  **   (3) Some output columns are omitted from the sort record due to
121925         -  **       the SQLITE_ENABLE_SORTER_REFERENCE optimization, or due to the
121926         -  **       SQLITE_ECEL_OMITREF optimization, or due to the 
121927         -  **       SortCtx.pDeferredRowLoad optimiation.  In any of these cases
121928         -  **       regOrigData is 0 to prevent this routine from trying to copy
121929         -  **       values that might not yet exist.
121930         -  */
121931 121258     assert( nData==1 || regData==regOrigData || regOrigData==0 );
121932         -
121933 121259     if( nPrefixReg ){
121934 121260       assert( nPrefixReg==nExpr+bSeq );
121935         -    regBase = regData - nPrefixReg;
       121261  +    regBase = regData - nExpr - bSeq;
121936 121262     }else{
121937 121263       regBase = pParse->nMem + 1;
121938 121264       pParse->nMem += nBase;
121939 121265     }
121940 121266     assert( pSelect->iOffset==0 || pSelect->iLimit!=0 );
121941 121267     iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit;
121942 121268     pSort->labelDone = sqlite3VdbeMakeLabel(v);
................................................................................
121952 121278       int regPrevKey;   /* The first nOBSat columns of the previous row */
121953 121279       int addrFirst;    /* Address of the OP_IfNot opcode */
121954 121280       int addrJmp;      /* Address of the OP_Jump opcode */
121955 121281       VdbeOp *pOp;      /* Opcode that opens the sorter */
121956 121282       int nKey;         /* Number of sorting key columns, including OP_Sequence */
121957 121283       KeyInfo *pKI;     /* Original KeyInfo on the sorter table */
121958 121284   
121959         -    regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase);
       121285  +    sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat,regRecord);
121960 121286       regPrevKey = pParse->nMem+1;
121961 121287       pParse->nMem += pSort->nOBSat;
121962 121288       nKey = nExpr - pSort->nOBSat + bSeq;
121963 121289       if( bSeq ){
121964 121290         addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr); 
121965 121291       }else{
121966 121292         addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
................................................................................
122003 121329       ** If the new record does not need to be inserted into the sorter,
122004 121330       ** jump to the next iteration of the loop. Or, if the
122005 121331       ** pSort->bOrderedInnerLoop flag is set to indicate that the inner
122006 121332       ** loop delivers items in sorted order, jump to the next iteration
122007 121333       ** of the outer loop.
122008 121334       */
122009 121335       int iCsr = pSort->iECursor;
       121336  +    int iJmp = sqlite3VdbeCurrentAddr(v)+5+(nOBSat<=0)+pSort->bOrderedInnerLoop;
       121337  +    assert( pSort->bOrderedInnerLoop==0 || pSort->bOrderedInnerLoop==1 );
122010 121338       sqlite3VdbeAddOp2(v, OP_IfNotZero, iLimit, sqlite3VdbeCurrentAddr(v)+4);
122011 121339       VdbeCoverage(v);
122012 121340       sqlite3VdbeAddOp2(v, OP_Last, iCsr, 0);
122013         -    iSkip = sqlite3VdbeAddOp4Int(v, OP_IdxLE,
122014         -                                 iCsr, 0, regBase+nOBSat, nExpr-nOBSat);
       121341  +    sqlite3VdbeAddOp4Int(v, OP_IdxLE, iCsr, iJmp, regBase+nOBSat, nExpr-nOBSat);
122015 121342       VdbeCoverage(v);
122016 121343       sqlite3VdbeAddOp1(v, OP_Delete, iCsr);
122017 121344     }
122018         -  if( regRecord==0 ){
122019         -    regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase);
       121345  +  if( nOBSat<=0 ){
       121346  +    sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat,regRecord);
122020 121347     }
122021 121348     if( pSort->sortFlags & SORTFLAG_UseSorter ){
122022 121349       op = OP_SorterInsert;
122023 121350     }else{
122024 121351       op = OP_IdxInsert;
122025 121352     }
122026 121353     sqlite3VdbeAddOp4Int(v, op, pSort->iECursor, regRecord,
122027 121354                          regBase+nOBSat, nBase-nOBSat);
122028         -  if( iSkip ){
122029         -    assert( pSort->bOrderedInnerLoop==0 || pSort->bOrderedInnerLoop==1 );
122030         -    sqlite3VdbeChangeP2(v, iSkip,
122031         -         sqlite3VdbeCurrentAddr(v) + pSort->bOrderedInnerLoop);
122032         -  }
122033 121355   }
122034 121356   
122035 121357   /*
122036 121358   ** Add code to implement the OFFSET
122037 121359   */
122038 121360   static void codeOffset(
122039 121361     Vdbe *v,          /* Generate code into this VM */
................................................................................
122109 121431     int nDefer = 0;
122110 121432     ExprList *pExtra = 0;
122111 121433     for(i=0; i<pEList->nExpr; i++){
122112 121434       struct ExprList_item *pItem = &pEList->a[i];
122113 121435       if( pItem->u.x.iOrderByCol==0 ){
122114 121436         Expr *pExpr = pItem->pExpr;
122115 121437         Table *pTab = pExpr->pTab;
122116         -      if( pExpr->op==TK_COLUMN && pExpr->iColumn>=0 && pTab && !IsVirtual(pTab)
       121438  +      if( pExpr->op==TK_COLUMN && pTab && !IsVirtual(pTab)
122117 121439          && (pTab->aCol[pExpr->iColumn].colFlags & COLFLAG_SORTERREF)
       121440  +#if 0
       121441  +          && pTab->pSchema && pTab->pSelect==0 && !IsVirtual(pTab)
       121442  +#endif
122118 121443         ){
122119 121444           int j;
122120 121445           for(j=0; j<nDefer; j++){
122121 121446             if( pSort->aDefer[j].iCsr==pExpr->iTable ) break;
122122 121447           }
122123 121448           if( j==nDefer ){
122124 121449             if( nDefer==ArraySize(pSort->aDefer) ){
................................................................................
122177 121502     Vdbe *v = pParse->pVdbe;
122178 121503     int i;
122179 121504     int hasDistinct;            /* True if the DISTINCT keyword is present */
122180 121505     int eDest = pDest->eDest;   /* How to dispose of results */
122181 121506     int iParm = pDest->iSDParm; /* First argument to disposal method */
122182 121507     int nResultCol;             /* Number of result columns */
122183 121508     int nPrefixReg = 0;         /* Number of extra registers before regResult */
122184         -  RowLoadInfo sRowLoadInfo;   /* Info for deferred row loading */
122185 121509   
122186 121510     /* Usually, regResult is the first cell in an array of memory cells
122187 121511     ** containing the current result row. In this case regOrig is set to the
122188 121512     ** same value. However, if the results are being sent to the sorter, the
122189 121513     ** values for any expressions that are also part of the sort-key are omitted
122190 121514     ** from this array. In this case regOrig is set to zero.  */
122191 121515     int regResult;              /* Start of memory holding current results */
................................................................................
122230 121554     }else if( eDest!=SRT_Exists ){
122231 121555   #ifdef SQLITE_ENABLE_SORTER_REFERENCES
122232 121556       ExprList *pExtra = 0;
122233 121557   #endif
122234 121558       /* If the destination is an EXISTS(...) expression, the actual
122235 121559       ** values returned by the SELECT are not required.
122236 121560       */
122237         -    u8 ecelFlags;    /* "ecel" is an abbreviation of "ExprCodeExprList" */
122238         -    ExprList *pEList;
       121561  +    u8 ecelFlags;
122239 121562       if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){
122240 121563         ecelFlags = SQLITE_ECEL_DUP;
122241 121564       }else{
122242 121565         ecelFlags = 0;
122243 121566       }
122244 121567       if( pSort && hasDistinct==0 && eDest!=SRT_EphemTab && eDest!=SRT_Table ){
122245 121568         /* For each expression in p->pEList that is a copy of an expression in
122246 121569         ** the ORDER BY clause (pSort->pOrderBy), set the associated 
122247 121570         ** iOrderByCol value to one more than the index of the ORDER BY 
122248 121571         ** expression within the sort-key that pushOntoSorter() will generate.
122249 121572         ** This allows the p->pEList field to be omitted from the sorted record,
122250 121573         ** saving space and CPU cycles.  */
122251 121574         ecelFlags |= (SQLITE_ECEL_OMITREF|SQLITE_ECEL_REF);
122252         -
122253 121575         for(i=pSort->nOBSat; i<pSort->pOrderBy->nExpr; i++){
122254 121576           int j;
122255 121577           if( (j = pSort->pOrderBy->a[i].u.x.iOrderByCol)>0 ){
122256 121578             p->pEList->a[j-1].u.x.iOrderByCol = i+1-pSort->nOBSat;
122257 121579           }
122258 121580         }
122259 121581   #ifdef SQLITE_ENABLE_SORTER_REFERENCES
................................................................................
122266 121588           ** composite primary keys in the SortCtx.aDefer[] array.  */
122267 121589           VdbeOp *pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
122268 121590           pOp->p2 += (pExtra->nExpr - pSort->nDefer);
122269 121591           pOp->p4.pKeyInfo->nAllField += (pExtra->nExpr - pSort->nDefer);
122270 121592           pParse->nMem += pExtra->nExpr;
122271 121593         }
122272 121594   #endif
122273         -
122274         -      /* Adjust nResultCol to account for columns that are omitted
122275         -      ** from the sorter by the optimizations in this branch */
122276         -      pEList = p->pEList;
122277         -      for(i=0; i<pEList->nExpr; i++){
122278         -        if( pEList->a[i].u.x.iOrderByCol>0
122279         -#ifdef SQLITE_ENABLE_SORTER_REFERENCES
122280         -         || pEList->a[i].bSorterRef
122281         -#endif
122282         -        ){
122283         -          nResultCol--;
122284         -          regOrig = 0;
122285         -        }
122286         -      }
122287         -
122288         -      testcase( regOrig );
122289         -      testcase( eDest==SRT_Set );
122290         -      testcase( eDest==SRT_Mem );
122291         -      testcase( eDest==SRT_Coroutine );
122292         -      testcase( eDest==SRT_Output );
       121595  +      regOrig = 0;
122293 121596         assert( eDest==SRT_Set || eDest==SRT_Mem 
122294 121597              || eDest==SRT_Coroutine || eDest==SRT_Output );
122295 121598       }
122296         -    sRowLoadInfo.regResult = regResult;
122297         -    sRowLoadInfo.ecelFlags = ecelFlags;
       121599  +    nResultCol = sqlite3ExprCodeExprList(pParse,p->pEList,regResult,
       121600  +                                         0,ecelFlags);
122298 121601   #ifdef SQLITE_ENABLE_SORTER_REFERENCES
122299         -    sRowLoadInfo.pExtra = pExtra;
122300         -    sRowLoadInfo.regExtraResult = regResult + nResultCol;
122301         -    if( pExtra ) nResultCol += pExtra->nExpr;
       121602  +    if( pExtra ){
       121603  +      nResultCol += sqlite3ExprCodeExprList(
       121604  +          pParse, pExtra, regResult + nResultCol, 0, 0
       121605  +      );
       121606  +      sqlite3ExprListDelete(pParse->db, pExtra);
       121607  +    }
122302 121608   #endif
122303         -    if( p->iLimit
122304         -     && (ecelFlags & SQLITE_ECEL_OMITREF)!=0 
122305         -     && nPrefixReg>0
122306         -    ){
122307         -      assert( pSort!=0 );
122308         -      assert( hasDistinct==0 );
122309         -      pSort->pDeferredRowLoad = &sRowLoadInfo;
122310         -      regOrig = 0;
122311         -    }else{
122312         -      innerLoopLoadRow(pParse, p, &sRowLoadInfo);
122313         -    }
122314 121609     }
122315 121610   
122316 121611     /* If the DISTINCT keyword was present on the SELECT statement
122317 121612     ** and this row has been seen before, then do not make this row
122318 121613     ** part of the result.
122319 121614     */
122320 121615     if( hasDistinct ){
................................................................................
122422 121717           sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
122423 121718           VdbeCoverage(v);
122424 121719           sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm+1, r1,regResult,nResultCol);
122425 121720           assert( pSort==0 );
122426 121721         }
122427 121722   #endif
122428 121723         if( pSort ){
122429         -        assert( regResult==regOrig );
122430         -        pushOntoSorter(pParse, pSort, p, r1+nPrefixReg, regOrig, 1, nPrefixReg);
       121724  +        pushOntoSorter(pParse, pSort, p, r1+nPrefixReg,regResult,1,nPrefixReg);
122431 121725         }else{
122432 121726           int r2 = sqlite3GetTempReg(pParse);
122433 121727           sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
122434 121728           sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
122435 121729           sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
122436 121730           sqlite3ReleaseTempReg(pParse, r2);
122437 121731         }
................................................................................
122690 121984   **
122691 121985   **   "USE TEMP B-TREE FOR xxx"
122692 121986   **
122693 121987   ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
122694 121988   ** is determined by the zUsage argument.
122695 121989   */
122696 121990   static void explainTempTable(Parse *pParse, const char *zUsage){
122697         -  ExplainQueryPlan((pParse, 0, "USE TEMP B-TREE FOR %s", zUsage));
       121991  +  if( pParse->explain==2 ){
       121992  +    Vdbe *v = pParse->pVdbe;
       121993  +    char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
       121994  +    sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
       121995  +  }
122698 121996   }
122699 121997   
122700 121998   /*
122701 121999   ** Assign expression b to lvalue a. A second, no-op, version of this macro
122702 122000   ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
122703 122001   ** in sqlite3Select() to assign values to structure member variables that
122704 122002   ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
................................................................................
122708 122006   
122709 122007   #else
122710 122008   /* No-op versions of the explainXXX() functions and macros. */
122711 122009   # define explainTempTable(y,z)
122712 122010   # define explainSetInteger(y,z)
122713 122011   #endif
122714 122012   
       122013  +#if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
       122014  +/*
       122015  +** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
       122016  +** is a no-op. Otherwise, it adds a single row of output to the EQP result,
       122017  +** where the caption is of one of the two forms:
       122018  +**
       122019  +**   "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
       122020  +**   "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
       122021  +**
       122022  +** where iSub1 and iSub2 are the integers passed as the corresponding
       122023  +** function parameters, and op is the text representation of the parameter
       122024  +** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
       122025  +** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is 
       122026  +** false, or the second form if it is true.
       122027  +*/
       122028  +static void explainComposite(
       122029  +  Parse *pParse,                  /* Parse context */
       122030  +  int op,                         /* One of TK_UNION, TK_EXCEPT etc. */
       122031  +  int iSub1,                      /* Subquery id 1 */
       122032  +  int iSub2,                      /* Subquery id 2 */
       122033  +  int bUseTmp                     /* True if a temp table was used */
       122034  +){
       122035  +  assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
       122036  +  if( pParse->explain==2 ){
       122037  +    Vdbe *v = pParse->pVdbe;
       122038  +    char *zMsg = sqlite3MPrintf(
       122039  +        pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
       122040  +        bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
       122041  +    );
       122042  +    sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
       122043  +  }
       122044  +}
       122045  +#else
       122046  +/* No-op versions of the explainXXX() functions and macros. */
       122047  +# define explainComposite(v,w,x,y,z)
       122048  +#endif
122715 122049   
122716 122050   /*
122717 122051   ** If the inner loop was generated using a non-null pOrderBy argument,
122718 122052   ** then the results were placed in a sorter.  After the loop is terminated
122719 122053   ** we need to run the sorter and output the results.  The following
122720 122054   ** routine generates the code needed to do that.
122721 122055   */
................................................................................
123157 122491   #ifndef SQLITE_OMIT_EXPLAIN
123158 122492     /* If this is an EXPLAIN, skip this step */
123159 122493     if( pParse->explain ){
123160 122494       return;
123161 122495     }
123162 122496   #endif
123163 122497   
123164         -  if( pParse->colNamesSet ) return;
       122498  +  if( pParse->colNamesSet || db->mallocFailed ) return;
123165 122499     /* Column names are determined by the left-most term of a compound select */
123166 122500     while( pSelect->pPrior ) pSelect = pSelect->pPrior;
123167 122501     SELECTTRACE(1,pParse,pSelect,("generating column names\n"));
123168 122502     pTabList = pSelect->pSrc;
123169 122503     pEList = pSelect->pEList;
123170 122504     assert( v!=0 );
123171 122505     assert( pTabList!=0 );
................................................................................
123684 123018     }
123685 123019   
123686 123020     /* Detach the ORDER BY clause from the compound SELECT */
123687 123021     p->pOrderBy = 0;
123688 123022   
123689 123023     /* Store the results of the setup-query in Queue. */
123690 123024     pSetup->pNext = 0;
123691         -  ExplainQueryPlan((pParse, 1, "SETUP"));
123692 123025     rc = sqlite3Select(pParse, pSetup, &destQueue);
123693 123026     pSetup->pNext = p;
123694 123027     if( rc ) goto end_of_recursive_query;
123695 123028   
123696 123029     /* Find the next row in the Queue and output that row */
123697 123030     addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
123698 123031   
................................................................................
123719 123052     /* Execute the recursive SELECT taking the single row in Current as
123720 123053     ** the value for the recursive-table. Store the results in the Queue.
123721 123054     */
123722 123055     if( p->selFlags & SF_Aggregate ){
123723 123056       sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported");
123724 123057     }else{
123725 123058       p->pPrior = 0;
123726         -    ExplainQueryPlan((pParse, 1, "RECURSIVE STEP"));
123727 123059       sqlite3Select(pParse, p, &destQueue);
123728 123060       assert( p->pPrior==0 );
123729 123061       p->pPrior = pSetup;
123730 123062     }
123731 123063   
123732 123064     /* Keep running the loop until the Queue is empty */
123733 123065     sqlite3VdbeGoto(v, addrTop);
................................................................................
123765 123097   ** Since the limit is exactly 1, we only need to evalutes the left-most VALUES.
123766 123098   */
123767 123099   static int multiSelectValues(
123768 123100     Parse *pParse,        /* Parsing context */
123769 123101     Select *p,            /* The right-most of SELECTs to be coded */
123770 123102     SelectDest *pDest     /* What to do with query results */
123771 123103   ){
       123104  +  Select *pPrior;
       123105  +  Select *pRightmost = p;
123772 123106     int nRow = 1;
123773 123107     int rc = 0;
123774         -  int bShowAll = p->pLimit==0;
123775 123108     assert( p->selFlags & SF_MultiValue );
123776 123109     do{
123777 123110       assert( p->selFlags & SF_Values );
123778 123111       assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
123779 123112       assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
123780 123113       if( p->pPrior==0 ) break;
123781 123114       assert( p->pPrior->pNext==p );
123782 123115       p = p->pPrior;
123783         -    nRow += bShowAll;
       123116  +    nRow++;
123784 123117     }while(1);
123785         -  ExplainQueryPlan((pParse, 0, "SCAN %d CONSTANT ROW%s", nRow,
123786         -                    nRow==1 ? "" : "S"));
123787 123118     while( p ){
123788         -    selectInnerLoop(pParse, p, -1, 0, 0, pDest, 1, 1);
123789         -    if( !bShowAll ) break;
       123119  +    pPrior = p->pPrior;
       123120  +    p->pPrior = 0;
       123121  +    rc = sqlite3Select(pParse, p, pDest);
       123122  +    p->pPrior = pPrior;
       123123  +    if( rc || pRightmost->pLimit ) break;
123790 123124       p->nSelectRow = nRow;
123791 123125       p = p->pNext;
123792 123126     }
123793 123127     return rc;
123794 123128   }
123795 123129   
123796 123130   /*
................................................................................
123831 123165   ){
123832 123166     int rc = SQLITE_OK;   /* Success code from a subroutine */
123833 123167     Select *pPrior;       /* Another SELECT immediately to our left */
123834 123168     Vdbe *v;              /* Generate code to this VDBE */
123835 123169     SelectDest dest;      /* Alternative data destination */
123836 123170     Select *pDelete = 0;  /* Chain of simple selects to delete */
123837 123171     sqlite3 *db;          /* Database connection */
       123172  +#ifndef SQLITE_OMIT_EXPLAIN
       123173  +  int iSub1 = 0;        /* EQP id of left-hand query */
       123174  +  int iSub2 = 0;        /* EQP id of right-hand query */
       123175  +#endif
123838 123176   
123839 123177     /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
123840 123178     ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
123841 123179     */
123842 123180     assert( p && p->pPrior );  /* Calling function guarantees this much */
123843 123181     assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
123844 123182     db = pParse->db;
................................................................................
123881 123219     }else
123882 123220   #endif
123883 123221   
123884 123222     /* Compound SELECTs that have an ORDER BY clause are handled separately.
123885 123223     */
123886 123224     if( p->pOrderBy ){
123887 123225       return multiSelectOrderBy(pParse, p, pDest);
123888         -  }else{
123889         -
123890         -#ifndef SQLITE_OMIT_EXPLAIN
123891         -    if( pPrior->pPrior==0 ){
123892         -      ExplainQueryPlan((pParse, 1, "COMPOUND QUERY"));
123893         -      ExplainQueryPlan((pParse, 1, "LEFT-MOST SUBQUERY"));
123894         -    }
123895         -#endif
123896         -
123897         -    /* Generate code for the left and right SELECT statements.
123898         -    */
123899         -    switch( p->op ){
123900         -      case TK_ALL: {
123901         -        int addr = 0;
123902         -        int nLimit;
123903         -        assert( !pPrior->pLimit );
123904         -        pPrior->iLimit = p->iLimit;
123905         -        pPrior->iOffset = p->iOffset;
123906         -        pPrior->pLimit = p->pLimit;
123907         -        rc = sqlite3Select(pParse, pPrior, &dest);
123908         -        p->pLimit = 0;
123909         -        if( rc ){
123910         -          goto multi_select_end;
123911         -        }
123912         -        p->pPrior = 0;
123913         -        p->iLimit = pPrior->iLimit;
123914         -        p->iOffset = pPrior->iOffset;
123915         -        if( p->iLimit ){
123916         -          addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
123917         -          VdbeComment((v, "Jump ahead if LIMIT reached"));
123918         -          if( p->iOffset ){
123919         -            sqlite3VdbeAddOp3(v, OP_OffsetLimit,
123920         -                              p->iLimit, p->iOffset+1, p->iOffset);
123921         -          }
123922         -        }
123923         -        ExplainQueryPlan((pParse, 1, "UNION ALL"));
123924         -        rc = sqlite3Select(pParse, p, &dest);
123925         -        testcase( rc!=SQLITE_OK );
123926         -        pDelete = p->pPrior;
123927         -        p->pPrior = pPrior;
123928         -        p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
123929         -        if( pPrior->pLimit
123930         -         && sqlite3ExprIsInteger(pPrior->pLimit->pLeft, &nLimit)
123931         -         && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit) 
123932         -        ){
123933         -          p->nSelectRow = sqlite3LogEst((u64)nLimit);
123934         -        }
123935         -        if( addr ){
123936         -          sqlite3VdbeJumpHere(v, addr);
123937         -        }
123938         -        break;
123939         -      }
123940         -      case TK_EXCEPT:
123941         -      case TK_UNION: {
123942         -        int unionTab;    /* Cursor number of the temp table holding result */
123943         -        u8 op = 0;       /* One of the SRT_ operations to apply to self */
123944         -        int priorOp;     /* The SRT_ operation to apply to prior selects */
123945         -        Expr *pLimit;    /* Saved values of p->nLimit  */
123946         -        int addr;
123947         -        SelectDest uniondest;
123948         -  
123949         -        testcase( p->op==TK_EXCEPT );
123950         -        testcase( p->op==TK_UNION );
123951         -        priorOp = SRT_Union;
123952         -        if( dest.eDest==priorOp ){
123953         -          /* We can reuse a temporary table generated by a SELECT to our
123954         -          ** right.
123955         -          */
123956         -          assert( p->pLimit==0 );      /* Not allowed on leftward elements */
123957         -          unionTab = dest.iSDParm;
123958         -        }else{
123959         -          /* We will need to create our own temporary table to hold the
123960         -          ** intermediate results.
123961         -          */
123962         -          unionTab = pParse->nTab++;
123963         -          assert( p->pOrderBy==0 );
123964         -          addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
123965         -          assert( p->addrOpenEphm[0] == -1 );
123966         -          p->addrOpenEphm[0] = addr;
123967         -          findRightmost(p)->selFlags |= SF_UsesEphemeral;
123968         -          assert( p->pEList );
123969         -        }
123970         -  
123971         -        /* Code the SELECT statements to our left
123972         -        */
123973         -        assert( !pPrior->pOrderBy );
123974         -        sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
123975         -        rc = sqlite3Select(pParse, pPrior, &uniondest);
123976         -        if( rc ){
123977         -          goto multi_select_end;
123978         -        }
123979         -  
123980         -        /* Code the current SELECT statement
123981         -        */
123982         -        if( p->op==TK_EXCEPT ){
123983         -          op = SRT_Except;
123984         -        }else{
123985         -          assert( p->op==TK_UNION );
123986         -          op = SRT_Union;
123987         -        }
123988         -        p->pPrior = 0;
123989         -        pLimit = p->pLimit;
123990         -        p->pLimit = 0;
123991         -        uniondest.eDest = op;
123992         -        ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",
123993         -                          selectOpName(p->op)));
123994         -        rc = sqlite3Select(pParse, p, &uniondest);
123995         -        testcase( rc!=SQLITE_OK );
123996         -        /* Query flattening in sqlite3Select() might refill p->pOrderBy.
123997         -        ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
123998         -        sqlite3ExprListDelete(db, p->pOrderBy);
123999         -        pDelete = p->pPrior;
124000         -        p->pPrior = pPrior;
124001         -        p->pOrderBy = 0;
124002         -        if( p->op==TK_UNION ){
124003         -          p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
124004         -        }
124005         -        sqlite3ExprDelete(db, p->pLimit);
124006         -        p->pLimit = pLimit;
124007         -        p->iLimit = 0;
124008         -        p->iOffset = 0;
124009         -  
124010         -        /* Convert the data in the temporary table into whatever form
124011         -        ** it is that we currently need.
124012         -        */
124013         -        assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
124014         -        if( dest.eDest!=priorOp ){
124015         -          int iCont, iBreak, iStart;
124016         -          assert( p->pEList );
124017         -          iBreak = sqlite3VdbeMakeLabel(v);
124018         -          iCont = sqlite3VdbeMakeLabel(v);
124019         -          computeLimitRegisters(pParse, p, iBreak);
124020         -          sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
124021         -          iStart = sqlite3VdbeCurrentAddr(v);
124022         -          selectInnerLoop(pParse, p, unionTab,
124023         -                          0, 0, &dest, iCont, iBreak);
124024         -          sqlite3VdbeResolveLabel(v, iCont);
124025         -          sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
124026         -          sqlite3VdbeResolveLabel(v, iBreak);
124027         -          sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
124028         -        }
124029         -        break;
124030         -      }
124031         -      default: assert( p->op==TK_INTERSECT ); {
124032         -        int tab1, tab2;
124033         -        int iCont, iBreak, iStart;
124034         -        Expr *pLimit;
124035         -        int addr;
124036         -        SelectDest intersectdest;
124037         -        int r1;
124038         -  
124039         -        /* INTERSECT is different from the others since it requires
124040         -        ** two temporary tables.  Hence it has its own case.  Begin
124041         -        ** by allocating the tables we will need.
124042         -        */
124043         -        tab1 = pParse->nTab++;
124044         -        tab2 = pParse->nTab++;
       123226  +  }else
       123227  +
       123228  +  /* Generate code for the left and right SELECT statements.
       123229  +  */
       123230  +  switch( p->op ){
       123231  +    case TK_ALL: {
       123232  +      int addr = 0;
       123233  +      int nLimit;
       123234  +      assert( !pPrior->pLimit );
       123235  +      pPrior->iLimit = p->iLimit;
       123236  +      pPrior->iOffset = p->iOffset;
       123237  +      pPrior->pLimit = p->pLimit;
       123238  +      explainSetInteger(iSub1, pParse->iNextSelectId);
       123239  +      rc = sqlite3Select(pParse, pPrior, &dest);
       123240  +      p->pLimit = 0;
       123241  +      if( rc ){
       123242  +        goto multi_select_end;
       123243  +      }
       123244  +      p->pPrior = 0;
       123245  +      p->iLimit = pPrior->iLimit;
       123246  +      p->iOffset = pPrior->iOffset;
       123247  +      if( p->iLimit ){
       123248  +        addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
       123249  +        VdbeComment((v, "Jump ahead if LIMIT reached"));
       123250  +        if( p->iOffset ){
       123251  +          sqlite3VdbeAddOp3(v, OP_OffsetLimit,
       123252  +                            p->iLimit, p->iOffset+1, p->iOffset);
       123253  +        }
       123254  +      }
       123255  +      explainSetInteger(iSub2, pParse->iNextSelectId);
       123256  +      rc = sqlite3Select(pParse, p, &dest);
       123257  +      testcase( rc!=SQLITE_OK );
       123258  +      pDelete = p->pPrior;
       123259  +      p->pPrior = pPrior;
       123260  +      p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
       123261  +      if( pPrior->pLimit
       123262  +       && sqlite3ExprIsInteger(pPrior->pLimit->pLeft, &nLimit)
       123263  +       && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit) 
       123264  +      ){
       123265  +        p->nSelectRow = sqlite3LogEst((u64)nLimit);
       123266  +      }
       123267  +      if( addr ){
       123268  +        sqlite3VdbeJumpHere(v, addr);
       123269  +      }
       123270  +      break;
       123271  +    }
       123272  +    case TK_EXCEPT:
       123273  +    case TK_UNION: {
       123274  +      int unionTab;    /* Cursor number of the temporary table holding result */
       123275  +      u8 op = 0;       /* One of the SRT_ operations to apply to self */
       123276  +      int priorOp;     /* The SRT_ operation to apply to prior selects */
       123277  +      Expr *pLimit;    /* Saved values of p->nLimit  */
       123278  +      int addr;
       123279  +      SelectDest uniondest;
       123280  +
       123281  +      testcase( p->op==TK_EXCEPT );
       123282  +      testcase( p->op==TK_UNION );
       123283  +      priorOp = SRT_Union;
       123284  +      if( dest.eDest==priorOp ){
       123285  +        /* We can reuse a temporary table generated by a SELECT to our
       123286  +        ** right.
       123287  +        */
       123288  +        assert( p->pLimit==0 );      /* Not allowed on leftward elements */
       123289  +        unionTab = dest.iSDParm;
       123290  +      }else{
       123291  +        /* We will need to create our own temporary table to hold the
       123292  +        ** intermediate results.
       123293  +        */
       123294  +        unionTab = pParse->nTab++;
124045 123295           assert( p->pOrderBy==0 );
124046         -  
124047         -        addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
       123296  +        addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
124048 123297           assert( p->addrOpenEphm[0] == -1 );
124049 123298           p->addrOpenEphm[0] = addr;
124050 123299           findRightmost(p)->selFlags |= SF_UsesEphemeral;
124051 123300           assert( p->pEList );
124052         -  
124053         -        /* Code the SELECTs to our left into temporary table "tab1".
124054         -        */
124055         -        sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
124056         -        rc = sqlite3Select(pParse, pPrior, &intersectdest);
124057         -        if( rc ){
124058         -          goto multi_select_end;
124059         -        }
124060         -  
124061         -        /* Code the current SELECT into temporary table "tab2"
124062         -        */
124063         -        addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
124064         -        assert( p->addrOpenEphm[1] == -1 );
124065         -        p->addrOpenEphm[1] = addr;
124066         -        p->pPrior = 0;
124067         -        pLimit = p->pLimit;
124068         -        p->pLimit = 0;
124069         -        intersectdest.iSDParm = tab2;
124070         -        ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",
124071         -                          selectOpName(p->op)));
124072         -        rc = sqlite3Select(pParse, p, &intersectdest);
124073         -        testcase( rc!=SQLITE_OK );
124074         -        pDelete = p->pPrior;
124075         -        p->pPrior = pPrior;
124076         -        if( p->nSelectRow>pPrior->nSelectRow ){
124077         -          p->nSelectRow = pPrior->nSelectRow;
124078         -        }
124079         -        sqlite3ExprDelete(db, p->pLimit);
124080         -        p->pLimit = pLimit;
124081         -  
124082         -        /* Generate code to take the intersection of the two temporary
124083         -        ** tables.
124084         -        */
       123301  +      }
       123302  +
       123303  +      /* Code the SELECT statements to our left
       123304  +      */
       123305  +      assert( !pPrior->pOrderBy );
       123306  +      sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
       123307  +      explainSetInteger(iSub1, pParse->iNextSelectId);
       123308  +      rc = sqlite3Select(pParse, pPrior, &uniondest);
       123309  +      if( rc ){
       123310  +        goto multi_select_end;
       123311  +      }
       123312  +
       123313  +      /* Code the current SELECT statement
       123314  +      */
       123315  +      if( p->op==TK_EXCEPT ){
       123316  +        op = SRT_Except;
       123317  +      }else{
       123318  +        assert( p->op==TK_UNION );
       123319  +        op = SRT_Union;
       123320  +      }
       123321  +      p->pPrior = 0;
       123322  +      pLimit = p->pLimit;
       123323  +      p->pLimit = 0;
       123324  +      uniondest.eDest = op;
       123325  +      explainSetInteger(iSub2, pParse->iNextSelectId);
       123326  +      rc = sqlite3Select(pParse, p, &uniondest);
       123327  +      testcase( rc!=SQLITE_OK );
       123328  +      /* Query flattening in sqlite3Select() might refill p->pOrderBy.
       123329  +      ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
       123330  +      sqlite3ExprListDelete(db, p->pOrderBy);
       123331  +      pDelete = p->pPrior;
       123332  +      p->pPrior = pPrior;
       123333  +      p->pOrderBy = 0;
       123334  +      if( p->op==TK_UNION ){
       123335  +        p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
       123336  +      }
       123337  +      sqlite3ExprDelete(db, p->pLimit);
       123338  +      p->pLimit = pLimit;
       123339  +      p->iLimit = 0;
       123340  +      p->iOffset = 0;
       123341  +
       123342  +      /* Convert the data in the temporary table into whatever form
       123343  +      ** it is that we currently need.
       123344  +      */
       123345  +      assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
       123346  +      if( dest.eDest!=priorOp ){
       123347  +        int iCont, iBreak, iStart;
124085 123348           assert( p->pEList );
124086 123349           iBreak = sqlite3VdbeMakeLabel(v);
124087 123350           iCont = sqlite3VdbeMakeLabel(v);
124088 123351           computeLimitRegisters(pParse, p, iBreak);
124089         -        sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
124090         -        r1 = sqlite3GetTempReg(pParse);
124091         -        iStart = sqlite3VdbeAddOp2(v, OP_RowData, tab1, r1);
124092         -        sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
124093         -        VdbeCoverage(v);
124094         -        sqlite3ReleaseTempReg(pParse, r1);
124095         -        selectInnerLoop(pParse, p, tab1,
       123352  +        sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
       123353  +        iStart = sqlite3VdbeCurrentAddr(v);
       123354  +        selectInnerLoop(pParse, p, unionTab,
124096 123355                           0, 0, &dest, iCont, iBreak);
124097 123356           sqlite3VdbeResolveLabel(v, iCont);
124098         -        sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
       123357  +        sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
124099 123358           sqlite3VdbeResolveLabel(v, iBreak);
124100         -        sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
124101         -        sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
124102         -        break;
124103         -      }
124104         -    }
124105         -  
124106         -  #ifndef SQLITE_OMIT_EXPLAIN
124107         -    if( p->pNext==0 ){
124108         -      ExplainQueryPlanPop(pParse);
124109         -    }
124110         -  #endif
124111         -  }
124112         -  
       123359  +        sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
       123360  +      }
       123361  +      break;
       123362  +    }
       123363  +    default: assert( p->op==TK_INTERSECT ); {
       123364  +      int tab1, tab2;
       123365  +      int iCont, iBreak, iStart;
       123366  +      Expr *pLimit;
       123367  +      int addr;
       123368  +      SelectDest intersectdest;
       123369  +      int r1;
       123370  +
       123371  +      /* INTERSECT is different from the others since it requires
       123372  +      ** two temporary tables.  Hence it has its own case.  Begin
       123373  +      ** by allocating the tables we will need.
       123374  +      */
       123375  +      tab1 = pParse->nTab++;
       123376  +      tab2 = pParse->nTab++;
       123377  +      assert( p->pOrderBy==0 );
       123378  +
       123379  +      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
       123380  +      assert( p->addrOpenEphm[0] == -1 );
       123381  +      p->addrOpenEphm[0] = addr;
       123382  +      findRightmost(p)->selFlags |= SF_UsesEphemeral;
       123383  +      assert( p->pEList );
       123384  +
       123385  +      /* Code the SELECTs to our left into temporary table "tab1".
       123386  +      */
       123387  +      sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
       123388  +      explainSetInteger(iSub1, pParse->iNextSelectId);
       123389  +      rc = sqlite3Select(pParse, pPrior, &intersectdest);
       123390  +      if( rc ){
       123391  +        goto multi_select_end;
       123392  +      }
       123393  +
       123394  +      /* Code the current SELECT into temporary table "tab2"
       123395  +      */
       123396  +      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
       123397  +      assert( p->addrOpenEphm[1] == -1 );
       123398  +      p->addrOpenEphm[1] = addr;
       123399  +      p->pPrior = 0;
       123400  +      pLimit = p->pLimit;
       123401  +      p->pLimit = 0;
       123402  +      intersectdest.iSDParm = tab2;
       123403  +      explainSetInteger(iSub2, pParse->iNextSelectId);
       123404  +      rc = sqlite3Select(pParse, p, &intersectdest);
       123405  +      testcase( rc!=SQLITE_OK );
       123406  +      pDelete = p->pPrior;
       123407  +      p->pPrior = pPrior;
       123408  +      if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
       123409  +      sqlite3ExprDelete(db, p->pLimit);
       123410  +      p->pLimit = pLimit;
       123411  +
       123412  +      /* Generate code to take the intersection of the two temporary
       123413  +      ** tables.
       123414  +      */
       123415  +      assert( p->pEList );
       123416  +      iBreak = sqlite3VdbeMakeLabel(v);
       123417  +      iCont = sqlite3VdbeMakeLabel(v);
       123418  +      computeLimitRegisters(pParse, p, iBreak);
       123419  +      sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
       123420  +      r1 = sqlite3GetTempReg(pParse);
       123421  +      iStart = sqlite3VdbeAddOp2(v, OP_RowData, tab1, r1);
       123422  +      sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v);
       123423  +      sqlite3ReleaseTempReg(pParse, r1);
       123424  +      selectInnerLoop(pParse, p, tab1,
       123425  +                      0, 0, &dest, iCont, iBreak);
       123426  +      sqlite3VdbeResolveLabel(v, iCont);
       123427  +      sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
       123428  +      sqlite3VdbeResolveLabel(v, iBreak);
       123429  +      sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
       123430  +      sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
       123431  +      break;
       123432  +    }
       123433  +  }
       123434  +
       123435  +  explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
       123436  +
124113 123437     /* Compute collating sequences used by 
124114 123438     ** temporary tables needed to implement the compound select.
124115 123439     ** Attach the KeyInfo structure to all temporary tables.
124116 123440     **
124117 123441     ** This section is run by the right-most SELECT statement only.
124118 123442     ** SELECT statements to the left always skip this part.  The right-most
124119 123443     ** SELECT might also skip this part if it has no ORDER BY clause and
................................................................................
124443 123767     int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
124444 123768     KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
124445 123769     KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
124446 123770     sqlite3 *db;          /* Database connection */
124447 123771     ExprList *pOrderBy;   /* The ORDER BY clause */
124448 123772     int nOrderBy;         /* Number of terms in the ORDER BY clause */
124449 123773     int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
       123774  +#ifndef SQLITE_OMIT_EXPLAIN
       123775  +  int iSub1;            /* EQP id of left-hand query */
       123776  +  int iSub2;            /* EQP id of right-hand query */
       123777  +#endif
124450 123778   
124451 123779     assert( p->pOrderBy!=0 );
124452 123780     assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
124453 123781     db = pParse->db;
124454 123782     v = pParse->pVdbe;
124455 123783     assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
124456 123784     labelEnd = sqlite3VdbeMakeLabel(v);
................................................................................
124562 123890     regAddrA = ++pParse->nMem;
124563 123891     regAddrB = ++pParse->nMem;
124564 123892     regOutA = ++pParse->nMem;
124565 123893     regOutB = ++pParse->nMem;
124566 123894     sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
124567 123895     sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
124568 123896   
124569         -  ExplainQueryPlan((pParse, 1, "MERGE (%s)", selectOpName(p->op)));
124570         -
124571 123897     /* Generate a coroutine to evaluate the SELECT statement to the
124572 123898     ** left of the compound operator - the "A" select.
124573 123899     */
124574 123900     addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
124575 123901     addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
124576 123902     VdbeComment((v, "left SELECT"));
124577 123903     pPrior->iLimit = regLimitA;
124578         -  ExplainQueryPlan((pParse, 1, "LEFT"));
       123904  +  explainSetInteger(iSub1, pParse->iNextSelectId);
124579 123905     sqlite3Select(pParse, pPrior, &destA);
124580 123906     sqlite3VdbeEndCoroutine(v, regAddrA);
124581 123907     sqlite3VdbeJumpHere(v, addr1);
124582 123908   
124583 123909     /* Generate a coroutine to evaluate the SELECT statement on 
124584 123910     ** the right - the "B" select
124585 123911     */
................................................................................
124586 123912     addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
124587 123913     addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
124588 123914     VdbeComment((v, "right SELECT"));
124589 123915     savedLimit = p->iLimit;
124590 123916     savedOffset = p->iOffset;
124591 123917     p->iLimit = regLimitB;
124592 123918     p->iOffset = 0;  
124593         -  ExplainQueryPlan((pParse, 1, "RIGHT"));
       123919  +  explainSetInteger(iSub2, pParse->iNextSelectId);
124594 123920     sqlite3Select(pParse, p, &destB);
124595 123921     p->iLimit = savedLimit;
124596 123922     p->iOffset = savedOffset;
124597 123923     sqlite3VdbeEndCoroutine(v, regAddrB);
124598 123924   
124599 123925     /* Generate a subroutine that outputs the current row of the A
124600 123926     ** select as the next output row of the compound select.
................................................................................
124698 124024       sqlite3SelectDelete(db, p->pPrior);
124699 124025     }
124700 124026     p->pPrior = pPrior;
124701 124027     pPrior->pNext = p;
124702 124028   
124703 124029     /*** TBD:  Insert subroutine calls to close cursors on incomplete
124704 124030     **** subqueries ****/
124705         -  ExplainQueryPlanPop(pParse);
       124031  +  explainComposite(pParse, p->op, iSub1, iSub2, 0);
124706 124032     return pParse->nErr!=0;
124707 124033   }
124708 124034   #endif
124709 124035   
124710 124036   #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
124711 124037   
124712 124038   /* An instance of the SubstContext object describes an substitution edit
................................................................................
126486 125812   static void explainSimpleCount(
126487 125813     Parse *pParse,                  /* Parse context */
126488 125814     Table *pTab,                    /* Table being queried */
126489 125815     Index *pIdx                     /* Index used to optimize scan, or NULL */
126490 125816   ){
126491 125817     if( pParse->explain==2 ){
126492 125818       int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
126493         -    sqlite3VdbeExplain(pParse, 0, "SCAN TABLE %s%s%s",
       125819  +    char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
126494 125820           pTab->zName,
126495 125821           bCover ? " USING COVERING INDEX " : "",
126496 125822           bCover ? pIdx->zName : ""
126497 125823       );
       125824  +    sqlite3VdbeAddOp4(
       125825  +        pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
       125826  +    );
126498 125827     }
126499 125828   }
126500 125829   #else
126501 125830   # define explainSimpleCount(a,b,c)
126502 125831   #endif
126503 125832   
126504 125833   /*
................................................................................
126702 126031     DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
126703 126032     SortCtx sSort;         /* Info on how to code the ORDER BY clause */
126704 126033     AggInfo sAggInfo;      /* Information used by aggregate queries */
126705 126034     int iEnd;              /* Address of the end of the query */
126706 126035     sqlite3 *db;           /* The database connection */
126707 126036     ExprList *pMinMaxOrderBy = 0;  /* Added ORDER BY for min/max queries */
126708 126037     u8 minMaxFlag;                 /* Flag for min/max queries */
       126038  +
       126039  +#ifndef SQLITE_OMIT_EXPLAIN
       126040  +  int iRestoreSelectId = pParse->iSelectId;
       126041  +  pParse->iSelectId = pParse->iNextSelectId++;
       126042  +#endif
126709 126043   
126710 126044     db = pParse->db;
126711         -  v = sqlite3GetVdbe(pParse);
126712 126045     if( p==0 || db->mallocFailed || pParse->nErr ){
126713 126046       return 1;
126714 126047     }
126715 126048     if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
126716 126049     memset(&sAggInfo, 0, sizeof(sAggInfo));
126717 126050   #if SELECTTRACE_ENABLED
126718         -  SELECTTRACE(1,pParse,p, ("begin processing:\n", pParse->addrExplain));
       126051  +#ifndef SQLITE_OMIT_EXPLAIN
       126052  +  p->iSelectId = pParse->iSelectId;
       126053  +#endif
       126054  +  SELECTTRACE(1,pParse,p, ("begin processing:\n", pParse->iSelectId));
126719 126055     if( sqlite3SelectTrace & 0x100 ){
126720 126056       sqlite3TreeViewSelect(0, p, 0);
126721 126057     }
126722 126058   #endif
126723 126059   
126724 126060     assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
126725 126061     assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
................................................................................
126748 126084   #if SELECTTRACE_ENABLED
126749 126085     if( sqlite3SelectTrace & 0x104 ){
126750 126086       SELECTTRACE(0x104,pParse,p, ("after name resolution:\n"));
126751 126087       sqlite3TreeViewSelect(0, p, 0);
126752 126088     }
126753 126089   #endif
126754 126090   
       126091  +  /* Get a pointer the VDBE under construction, allocating a new VDBE if one
       126092  +  ** does not already exist */
       126093  +  v = sqlite3GetVdbe(pParse);
       126094  +  if( v==0 ) goto select_end;
126755 126095     if( pDest->eDest==SRT_Output ){
126756 126096       generateColumnNames(pParse, p);
126757 126097     }
126758 126098   
126759 126099     /* Try to various optimizations (flattening subqueries, and strength
126760 126100     ** reduction of join operators) in the FROM clause up into the main query
126761 126101     */
................................................................................
126842 126182     /* Handle compound SELECT statements using the separate multiSelect()
126843 126183     ** procedure.
126844 126184     */
126845 126185     if( p->pPrior ){
126846 126186       rc = multiSelect(pParse, p, pDest);
126847 126187   #if SELECTTRACE_ENABLED
126848 126188       SELECTTRACE(0x1,pParse,p,("end compound-select processing\n"));
126849         -    if( (sqlite3SelectTrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){
       126189  +    if( pParse->iSelectId==0 && (sqlite3SelectTrace & 0x2000)!=0 ){
126850 126190         sqlite3TreeViewSelect(0, p, 0);
126851 126191       }
126852 126192   #endif
126853         -    if( p->pNext==0 ) ExplainQueryPlanPop(pParse);
       126193  +    explainSetInteger(pParse->iSelectId, iRestoreSelectId);
126854 126194       return rc;
126855 126195     }
126856 126196   #endif
126857 126197   
126858 126198     /* For each term in the FROM clause, do two things:
126859 126199     ** (1) Authorized unreferenced tables
126860 126200     ** (2) Generate code for all sub-queries
................................................................................
126958 126298         int addrTop = sqlite3VdbeCurrentAddr(v)+1;
126959 126299        
126960 126300         pItem->regReturn = ++pParse->nMem;
126961 126301         sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
126962 126302         VdbeComment((v, "%s", pItem->pTab->zName));
126963 126303         pItem->addrFillSub = addrTop;
126964 126304         sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
126965         -      ExplainQueryPlan((pParse, 1, "CO-ROUTINE 0x%p", pSub));
       126305  +      explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
126966 126306         sqlite3Select(pParse, pSub, &dest);
126967 126307         pItem->pTab->nRowLogEst = pSub->nSelectRow;
126968 126308         pItem->fg.viaCoroutine = 1;
126969 126309         pItem->regResult = dest.iSdst;
126970 126310         sqlite3VdbeEndCoroutine(v, pItem->regReturn);
126971 126311         sqlite3VdbeJumpHere(v, addrTop-1);
126972 126312         sqlite3ClearTempRegCache(pParse);
................................................................................
126993 126333           VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
126994 126334         }else{
126995 126335           VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
126996 126336         }
126997 126337         pPrior = isSelfJoinView(pTabList, pItem);
126998 126338         if( pPrior ){
126999 126339           sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pPrior->iCursor);
       126340  +        explainSetInteger(pItem->iSelectId, pPrior->iSelectId);
127000 126341           assert( pPrior->pSelect!=0 );
127001 126342           pSub->nSelectRow = pPrior->pSelect->nSelectRow;
127002 126343         }else{
127003 126344           sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
127004         -        ExplainQueryPlan((pParse, 1, "MATERIALIZE 0x%p", pSub));
       126345  +        explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
127005 126346           sqlite3Select(pParse, pSub, &dest);
127006 126347         }
127007 126348         pItem->pTab->nRowLogEst = pSub->nSelectRow;
127008 126349         if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
127009 126350         retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
127010 126351         VdbeComment((v, "end %s", pItem->pTab->zName));
127011 126352         sqlite3VdbeChangeP1(v, topAddr, retAddr);
................................................................................
127635 126976     */
127636 126977   select_end:
127637 126978     sqlite3ExprListDelete(db, pMinMaxOrderBy);
127638 126979     sqlite3DbFree(db, sAggInfo.aCol);
127639 126980     sqlite3DbFree(db, sAggInfo.aFunc);
127640 126981   #if SELECTTRACE_ENABLED
127641 126982     SELECTTRACE(0x1,pParse,p,("end processing\n"));
127642         -  if( (sqlite3SelectTrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){
       126983  +  if( pParse->iSelectId==0 && (sqlite3SelectTrace & 0x2000)!=0 ){
127643 126984       sqlite3TreeViewSelect(0, p, 0);
127644 126985     }
127645 126986   #endif
127646         -  ExplainQueryPlanPop(pParse);
       126987  +  explainSetInteger(pParse->iSelectId, iRestoreSelectId);
127647 126988     return rc;
127648 126989   }
127649 126990   
127650 126991   /************** End of select.c **********************************************/
127651 126992   /************** Begin file table.c *******************************************/
127652 126993   /*
127653 126994   ** 2001 September 15
................................................................................
129840 129181     WhereInfo *pWInfo;
129841 129182     int nArg = 2 + pTab->nCol;      /* Number of arguments to VUpdate */
129842 129183     int regArg;                     /* First register in VUpdate arg array */
129843 129184     int regRec;                     /* Register in which to assemble record */
129844 129185     int regRowid;                   /* Register for ephem table rowid */
129845 129186     int iCsr = pSrc->a[0].iCursor;  /* Cursor used for virtual table scan */
129846 129187     int aDummy[2];                  /* Unused arg for sqlite3WhereOkOnePass() */
129847         -  int eOnePass;                   /* True to use onepass strategy */
       129188  +  int bOnePass;                   /* True to use onepass strategy */
129848 129189     int addr;                       /* Address of OP_OpenEphemeral */
129849 129190   
129850 129191     /* Allocate nArg registers in which to gather the arguments for VUpdate. Then
129851 129192     ** create and open the ephemeral table in which the records created from
129852 129193     ** these arguments will be temporarily stored. */
129853 129194     assert( v );
129854 129195     ephemTab = pParse->nTab++;
................................................................................
129885 129226       assert( pPk!=0 );
129886 129227       assert( pPk->nKeyCol==1 );
129887 129228       iPk = pPk->aiColumn[0];
129888 129229       sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, iPk, regArg);
129889 129230       sqlite3VdbeAddOp2(v, OP_SCopy, regArg+2+iPk, regArg+1);
129890 129231     }
129891 129232   
129892         -  eOnePass = sqlite3WhereOkOnePass(pWInfo, aDummy);
       129233  +  bOnePass = sqlite3WhereOkOnePass(pWInfo, aDummy);
129893 129234   
129894         -  /* There is no ONEPASS_MULTI on virtual tables */
129895         -  assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
129896         -
129897         -  if( eOnePass ){
       129235  +  if( bOnePass ){
129898 129236       /* If using the onepass strategy, no-op out the OP_OpenEphemeral coded
129899 129237       ** above. */
129900 129238       sqlite3VdbeChangeToNoop(v, addr);
129901         -    sqlite3VdbeAddOp1(v, OP_Close, iCsr);
129902 129239     }else{
129903 129240       /* Create a record from the argument register contents and insert it into
129904 129241       ** the ephemeral table. */
129905 129242       sqlite3MultiWrite(pParse);
129906 129243       sqlite3VdbeAddOp3(v, OP_MakeRecord, regArg, nArg, regRec);
129907 129244   #ifdef SQLITE_DEBUG
129908 129245       /* Signal an assert() within OP_MakeRecord that it is allowed to
................................................................................
129910 129247       sqlite3VdbeChangeP5(v, OPFLAG_NOCHNG_MAGIC);
129911 129248   #endif
129912 129249       sqlite3VdbeAddOp2(v, OP_NewRowid, ephemTab, regRowid);
129913 129250       sqlite3VdbeAddOp3(v, OP_Insert, ephemTab, regRec, regRowid);
129914 129251     }
129915 129252   
129916 129253   
129917         -  if( eOnePass==ONEPASS_OFF ){
       129254  +  if( bOnePass==0 ){
129918 129255       /* End the virtual table scan */
129919 129256       sqlite3WhereEnd(pWInfo);
129920 129257   
129921 129258       /* Begin scannning through the ephemeral table. */
129922 129259       addr = sqlite3VdbeAddOp1(v, OP_Rewind, ephemTab); VdbeCoverage(v);
129923 129260   
129924 129261       /* Extract arguments from the current row of the ephemeral table and 
................................................................................
129930 129267     sqlite3VtabMakeWritable(pParse, pTab);
129931 129268     sqlite3VdbeAddOp4(v, OP_VUpdate, 0, nArg, regArg, pVTab, P4_VTAB);
129932 129269     sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
129933 129270     sqlite3MayAbort(pParse);
129934 129271   
129935 129272     /* End of the ephemeral table scan. Or, if using the onepass strategy,
129936 129273     ** jump to here if the scan visited zero rows. */
129937         -  if( eOnePass==ONEPASS_OFF ){
       129274  +  if( bOnePass==0 ){
129938 129275       sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
129939 129276       sqlite3VdbeJumpHere(v, addr);
129940 129277       sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
129941 129278     }else{
129942 129279       sqlite3WhereEnd(pWInfo);
129943 129280     }
129944 129281   }
................................................................................
130173 129510           int k;
130174 129511           assert( pPk->aiColumn[i]>=0 );
130175 129512           k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
130176 129513           sqlite3VdbeAddOp3(v, OP_Column, iCur, k, iPk+i);
130177 129514           VdbeComment((v, "%s.%s", pIdx->zName,
130178 129515                       pTab->aCol[pPk->aiColumn[i]].zName));
130179 129516         }
130180         -      sqlite3VdbeVerifyAbortable(v, OE_Abort);
130181 129517         i = sqlite3VdbeAddOp4Int(v, OP_Found, iDataCur, 0, iPk, nPk);
130182 129518         VdbeCoverage(v);
130183 129519         sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CORRUPT, OE_Abort, 0, 
130184 129520               "corrupt database", P4_STATIC);
130185 129521         sqlite3VdbeJumpHere(v, i);
130186 129522       }
130187 129523     }
................................................................................
130236 129572   
130237 129573     /* printf("SQL: [%s]\n", zSql); fflush(stdout); */
130238 129574     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
130239 129575     if( rc!=SQLITE_OK ) return rc;
130240 129576     while( SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
130241 129577       const char *zSubSql = (const char*)sqlite3_column_text(pStmt,0);
130242 129578       assert( sqlite3_strnicmp(zSql,"SELECT",6)==0 );
130243         -    /* The secondary SQL must be one of CREATE TABLE, CREATE INDEX,
130244         -    ** or INSERT.  Historically there have been attacks that first
130245         -    ** corrupt the sqlite_master.sql field with other kinds of statements
130246         -    ** then run VACUUM to get those statements to execute at inappropriate
130247         -    ** times. */
130248         -    if( zSubSql
130249         -     && (strncmp(zSubSql,"CRE",3)==0 || strncmp(zSubSql,"INS",3)==0)
130250         -    ){
       129579  +    assert( sqlite3_strnicmp(zSubSql,"SELECT",6)!=0 || CORRUPT_DB );
       129580  +    if( zSubSql && zSubSql[0]!='S' ){
130251 129581         rc = execSql(db, pzErrMsg, zSubSql);
130252 129582         if( rc!=SQLITE_OK ) break;
130253 129583       }
130254 129584     }
130255 129585     assert( rc!=SQLITE_ROW );
130256 129586     if( rc==SQLITE_DONE ) rc = SQLITE_OK;
130257 129587     if( rc ){
................................................................................
130456 129786         " WHERE type='table'AND name<>'sqlite_sequence'"
130457 129787         " AND coalesce(rootpage,1)>0",
130458 129788         zDbMain
130459 129789     );
130460 129790     if( rc!=SQLITE_OK ) goto end_of_vacuum;
130461 129791     rc = execSqlF(db, pzErrMsg,
130462 129792         "SELECT sql FROM \"%w\".sqlite_master"
130463         -      " WHERE type='index'",
       129793  +      " WHERE type='index' AND length(sql)>10",
130464 129794         zDbMain
130465 129795     );
130466 129796     if( rc!=SQLITE_OK ) goto end_of_vacuum;
130467 129797     db->init.iDb = 0;
130468 129798   
130469 129799     /* Loop through the tables in the main database. For each, do
130470 129800     ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
................................................................................
131626 130956     Table *pTab;
131627 130957     sqlite3_vtab *pVtab;
131628 130958     sqlite3_module *pMod;
131629 130959     void (*xSFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
131630 130960     void *pArg = 0;
131631 130961     FuncDef *pNew;
131632 130962     int rc = 0;
       130963  +  char *zLowerName;
       130964  +  unsigned char *z;
       130965  +
131633 130966   
131634 130967     /* Check to see the left operand is a column in a virtual table */
131635 130968     if( NEVER(pExpr==0) ) return pDef;
131636 130969     if( pExpr->op!=TK_COLUMN ) return pDef;
131637 130970     pTab = pExpr->pTab;
131638 130971     if( pTab==0 ) return pDef;
131639 130972     if( !IsVirtual(pTab) ) return pDef;
................................................................................
131640 130973     pVtab = sqlite3GetVTable(db, pTab)->pVtab;
131641 130974     assert( pVtab!=0 );
131642 130975     assert( pVtab->pModule!=0 );
131643 130976     pMod = (sqlite3_module *)pVtab->pModule;
131644 130977     if( pMod->xFindFunction==0 ) return pDef;
131645 130978    
131646 130979     /* Call the xFindFunction method on the virtual table implementation
131647         -  ** to see if the implementation wants to overload this function.
131648         -  **
131649         -  ** Though undocumented, we have historically always invoked xFindFunction
131650         -  ** with an all lower-case function name.  Continue in this tradition to
131651         -  ** avoid any chance of an incompatibility.
       130980  +  ** to see if the implementation wants to overload this function 
131652 130981     */
131653         -#ifdef SQLITE_DEBUG
131654         -  {
131655         -    int i;
131656         -    for(i=0; pDef->zName[i]; i++){
131657         -      unsigned char x = (unsigned char)pDef->zName[i];
131658         -      assert( x==sqlite3UpperToLower[x] );
       130982  +  zLowerName = sqlite3DbStrDup(db, pDef->zName);
       130983  +  if( zLowerName ){
       130984  +    for(z=(unsigned char*)zLowerName; *z; z++){
       130985  +      *z = sqlite3UpperToLower[*z];
131659 130986       }
       130987  +    rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xSFunc, &pArg);
       130988  +    sqlite3DbFree(db, zLowerName);
131660 130989     }
131661         -#endif
131662         -  rc = pMod->xFindFunction(pVtab, nArg, pDef->zName, &xSFunc, &pArg);
131663 130990     if( rc==0 ){
131664 130991       return pDef;
131665 130992     }
131666 130993   
131667 130994     /* Create a new ephemeral function definition for the overloaded
131668 130995     ** function */
131669 130996     pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
................................................................................
132315 131642   
132316 131643   /* wherecode.c: */
132317 131644   #ifndef SQLITE_OMIT_EXPLAIN
132318 131645   SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
132319 131646     Parse *pParse,                  /* Parse context */
132320 131647     SrcList *pTabList,              /* Table list this loop refers to */
132321 131648     WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
       131649  +  int iLevel,                     /* Value for "level" column of output */
       131650  +  int iFrom,                      /* Value for "from" column of output */
132322 131651     u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
132323 131652   );
132324 131653   #else
132325         -# define sqlite3WhereExplainOneScan(u,v,w,x) 0
       131654  +# define sqlite3WhereExplainOneScan(u,v,w,x,y,z) 0
132326 131655   #endif /* SQLITE_OMIT_EXPLAIN */
132327 131656   #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
132328 131657   SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
132329 131658     Vdbe *v,                        /* Vdbe to add scanstatus entry to */
132330 131659     SrcList *pSrclist,              /* FROM clause pLvl reads data from */
132331 131660     WhereLevel *pLvl,               /* Level to add scanstatus() entry for */
132332 131661     int addrExplain                 /* Address of OP_Explain (or 0) */
................................................................................
132438 131767     int iTerm,                  /* Zero-based index of first term. */
132439 131768     int bAnd,                   /* Non-zero to append " AND " */
132440 131769     const char *zOp             /* Name of the operator */
132441 131770   ){
132442 131771     int i;
132443 131772   
132444 131773     assert( nTerm>=1 );
132445         -  if( bAnd ) sqlite3_str_append(pStr, " AND ", 5);
       131774  +  if( bAnd ) sqlite3StrAccumAppend(pStr, " AND ", 5);
132446 131775   
132447         -  if( nTerm>1 ) sqlite3_str_append(pStr, "(", 1);
       131776  +  if( nTerm>1 ) sqlite3StrAccumAppend(pStr, "(", 1);
132448 131777     for(i=0; i<nTerm; i++){
132449         -    if( i ) sqlite3_str_append(pStr, ",", 1);
132450         -    sqlite3_str_appendall(pStr, explainIndexColumnName(pIdx, iTerm+i));
       131778  +    if( i ) sqlite3StrAccumAppend(pStr, ",", 1);
       131779  +    sqlite3StrAccumAppendAll(pStr, explainIndexColumnName(pIdx, iTerm+i));
132451 131780     }
132452         -  if( nTerm>1 ) sqlite3_str_append(pStr, ")", 1);
       131781  +  if( nTerm>1 ) sqlite3StrAccumAppend(pStr, ")", 1);
132453 131782   
132454         -  sqlite3_str_append(pStr, zOp, 1);
       131783  +  sqlite3StrAccumAppend(pStr, zOp, 1);
132455 131784   
132456         -  if( nTerm>1 ) sqlite3_str_append(pStr, "(", 1);
       131785  +  if( nTerm>1 ) sqlite3StrAccumAppend(pStr, "(", 1);
132457 131786     for(i=0; i<nTerm; i++){
132458         -    if( i ) sqlite3_str_append(pStr, ",", 1);
132459         -    sqlite3_str_append(pStr, "?", 1);
       131787  +    if( i ) sqlite3StrAccumAppend(pStr, ",", 1);
       131788  +    sqlite3StrAccumAppend(pStr, "?", 1);
132460 131789     }
132461         -  if( nTerm>1 ) sqlite3_str_append(pStr, ")", 1);
       131790  +  if( nTerm>1 ) sqlite3StrAccumAppend(pStr, ")", 1);
132462 131791   }
132463 131792   
132464 131793   /*
132465 131794   ** Argument pLevel describes a strategy for scanning table pTab. This 
132466 131795   ** function appends text to pStr that describes the subset of table
132467 131796   ** rows scanned by the strategy in the form of an SQL expression.
132468 131797   **
................................................................................
132478 131807   static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop){
132479 131808     Index *pIndex = pLoop->u.btree.pIndex;
132480 131809     u16 nEq = pLoop->u.btree.nEq;
132481 131810     u16 nSkip = pLoop->nSkip;
132482 131811     int i, j;
132483 131812   
132484 131813     if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
132485         -  sqlite3_str_append(pStr, " (", 2);
       131814  +  sqlite3StrAccumAppend(pStr, " (", 2);
132486 131815     for(i=0; i<nEq; i++){
132487 131816       const char *z = explainIndexColumnName(pIndex, i);
132488         -    if( i ) sqlite3_str_append(pStr, " AND ", 5);
132489         -    sqlite3_str_appendf(pStr, i>=nSkip ? "%s=?" : "ANY(%s)", z);
       131817  +    if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5);
       131818  +    sqlite3XPrintf(pStr, i>=nSkip ? "%s=?" : "ANY(%s)", z);
132490 131819     }
132491 131820   
132492 131821     j = i;
132493 131822     if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
132494 131823       explainAppendTerm(pStr, pIndex, pLoop->u.btree.nBtm, j, i, ">");
132495 131824       i = 1;
132496 131825     }
132497 131826     if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
132498 131827       explainAppendTerm(pStr, pIndex, pLoop->u.btree.nTop, j, i, "<");
132499 131828     }
132500         -  sqlite3_str_append(pStr, ")", 1);
       131829  +  sqlite3StrAccumAppend(pStr, ")", 1);
132501 131830   }
132502 131831   
132503 131832   /*
132504 131833   ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
132505 131834   ** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was
132506 131835   ** defined at compile-time. If it is not a no-op, a single OP_Explain opcode 
132507 131836   ** is added to the output to describe the table scan strategy in pLevel.
................................................................................
132509 131838   ** If an OP_Explain opcode is added to the VM, its address is returned.
132510 131839   ** Otherwise, if no OP_Explain is coded, zero is returned.
132511 131840   */
132512 131841   SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
132513 131842     Parse *pParse,                  /* Parse context */
132514 131843     SrcList *pTabList,              /* Table list this loop refers to */
132515 131844     WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
       131845  +  int iLevel,                     /* Value for "level" column of output */
       131846  +  int iFrom,                      /* Value for "from" column of output */
132516 131847     u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
132517 131848   ){
132518 131849     int ret = 0;
132519 131850   #if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
132520 131851     if( sqlite3ParseToplevel(pParse)->explain==2 )
132521 131852   #endif
132522 131853     {
132523 131854       struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
132524 131855       Vdbe *v = pParse->pVdbe;      /* VM being constructed */
132525 131856       sqlite3 *db = pParse->db;     /* Database handle */
       131857  +    int iId = pParse->iSelectId;  /* Select id (left-most output column) */
132526 131858       int isSearch;                 /* True for a SEARCH. False for SCAN. */
132527 131859       WhereLoop *pLoop;             /* The controlling WhereLoop object */
132528 131860       u32 flags;                    /* Flags that describe this loop */
132529 131861       char *zMsg;                   /* Text to add to EQP output */
132530 131862       StrAccum str;                 /* EQP output string */
132531 131863       char zBuf[100];               /* Initial space for EQP output string */
132532 131864   
................................................................................
132535 131867       if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_OR_SUBCLAUSE) ) return 0;
132536 131868   
132537 131869       isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
132538 131870               || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
132539 131871               || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
132540 131872   
132541 131873       sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
132542         -    sqlite3_str_appendall(&str, isSearch ? "SEARCH" : "SCAN");
       131874  +    sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN");
132543 131875       if( pItem->pSelect ){
132544         -      sqlite3_str_appendf(&str, " SUBQUERY 0x%p", pItem->pSelect);
       131876  +      sqlite3XPrintf(&str, " SUBQUERY %d", pItem->iSelectId);
132545 131877       }else{
132546         -      sqlite3_str_appendf(&str, " TABLE %s", pItem->zName);
       131878  +      sqlite3XPrintf(&str, " TABLE %s", pItem->zName);
132547 131879       }
132548 131880   
132549 131881       if( pItem->zAlias ){
132550         -      sqlite3_str_appendf(&str, " AS %s", pItem->zAlias);
       131882  +      sqlite3XPrintf(&str, " AS %s", pItem->zAlias);
132551 131883       }
132552 131884       if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
132553 131885         const char *zFmt = 0;
132554 131886         Index *pIdx;
132555 131887   
132556 131888         assert( pLoop->u.btree.pIndex!=0 );
132557 131889         pIdx = pLoop->u.btree.pIndex;
................................................................................
132566 131898           zFmt = "AUTOMATIC COVERING INDEX";
132567 131899         }else if( flags & WHERE_IDX_ONLY ){
132568 131900           zFmt = "COVERING INDEX %s";
132569 131901         }else{
132570 131902           zFmt = "INDEX %s";
132571 131903         }
132572 131904         if( zFmt ){
132573         -        sqlite3_str_append(&str, " USING ", 7);
132574         -        sqlite3_str_appendf(&str, zFmt, pIdx->zName);
       131905  +        sqlite3StrAccumAppend(&str, " USING ", 7);
       131906  +        sqlite3XPrintf(&str, zFmt, pIdx->zName);
132575 131907           explainIndexRange(&str, pLoop);
132576 131908         }
132577 131909       }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
132578 131910         const char *zRangeOp;
132579 131911         if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
132580 131912           zRangeOp = "=";
132581 131913         }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
................................................................................
132582 131914           zRangeOp = ">? AND rowid<";
132583 131915         }else if( flags&WHERE_BTM_LIMIT ){
132584 131916           zRangeOp = ">";
132585 131917         }else{
132586 131918           assert( flags&WHERE_TOP_LIMIT);
132587 131919           zRangeOp = "<";
132588 131920         }
132589         -      sqlite3_str_appendf(&str, 
132590         -          " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp);
       131921  +      sqlite3XPrintf(&str, " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp);
132591 131922       }
132592 131923   #ifndef SQLITE_OMIT_VIRTUALTABLE
132593 131924       else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
132594         -      sqlite3_str_appendf(&str, " VIRTUAL TABLE INDEX %d:%s",
       131925  +      sqlite3XPrintf(&str, " VIRTUAL TABLE INDEX %d:%s",
132595 131926                     pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
132596 131927       }
132597 131928   #endif
132598 131929   #ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
132599 131930       if( pLoop->nOut>=10 ){
132600         -      sqlite3_str_appendf(&str, " (~%llu rows)",
132601         -             sqlite3LogEstToInt(pLoop->nOut));
       131931  +      sqlite3XPrintf(&str, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut));
132602 131932       }else{
132603         -      sqlite3_str_append(&str, " (~1 row)", 9);
       131933  +      sqlite3StrAccumAppend(&str, " (~1 row)", 9);
132604 131934       }
132605 131935   #endif
132606 131936       zMsg = sqlite3StrAccumFinish(&str);
132607         -    ret = sqlite3VdbeAddOp4(v, OP_Explain, sqlite3VdbeCurrentAddr(v),
132608         -                            pParse->addrExplain, 0, zMsg,P4_DYNAMIC);
       131937  +    ret = sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg,P4_DYNAMIC);
132609 131938     }
132610 131939     return ret;
132611 131940   }
132612 131941   #endif /* SQLITE_OMIT_EXPLAIN */
132613 131942   
132614 131943   #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
132615 131944   /*
................................................................................
134321 133650       }
134322 133651   
134323 133652       /* Run a separate WHERE clause for each term of the OR clause.  After
134324 133653       ** eliminating duplicates from other WHERE clauses, the action for each
134325 133654       ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
134326 133655       */
134327 133656       wctrlFlags =  WHERE_OR_SUBCLAUSE | (pWInfo->wctrlFlags & WHERE_SEEK_TABLE);
134328         -    ExplainQueryPlan((pParse, 1, "MULTI-INDEX OR"));
134329 133657       for(ii=0; ii<pOrWc->nTerm; ii++){
134330 133658         WhereTerm *pOrTerm = &pOrWc->a[ii];
134331 133659         if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
134332 133660           WhereInfo *pSubWInfo;           /* Info for single OR-term scan */
134333 133661           Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
134334 133662           int jmp1 = 0;                   /* Address of jump operation */
134335 133663           assert( (pTabItem[0].fg.jointype & JT_LEFT)==0 
................................................................................
134343 133671           WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
134344 133672           pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
134345 133673                                         wctrlFlags, iCovCur);
134346 133674           assert( pSubWInfo || pParse->nErr || db->mallocFailed );
134347 133675           if( pSubWInfo ){
134348 133676             WhereLoop *pSubLoop;
134349 133677             int addrExplain = sqlite3WhereExplainOneScan(
134350         -              pParse, pOrTab, &pSubWInfo->a[0], 0
       133678  +              pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
134351 133679             );
134352 133680             sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain);
134353 133681   
134354 133682             /* This is the sub-WHERE clause body.  First skip over
134355 133683             ** duplicate rows from prior sub-WHERE clauses, and record the
134356 133684             ** rowid (or PRIMARY KEY) for the current row so that the same
134357 133685             ** row will be skipped in subsequent sub-WHERE clauses.
................................................................................
134442 133770             }
134443 133771   
134444 133772             /* Finish the loop through table entries that match term pOrTerm. */
134445 133773             sqlite3WhereEnd(pSubWInfo);
134446 133774           }
134447 133775         }
134448 133776       }
134449         -    ExplainQueryPlanPop(pParse);
134450 133777       pLevel->u.pCovidx = pCov;
134451 133778       if( pCov ) pLevel->iIdxCur = iCovCur;
134452 133779       if( pAndExpr ){
134453 133780         pAndExpr->pLeft = 0;
134454 133781         sqlite3ExprDelete(db, pAndExpr);
134455 133782       }
134456 133783       sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
................................................................................
139020 138347           pNew->nSkip = 0;
139021 138348           pNew->u.btree.pIndex = 0;
139022 138349           pNew->nLTerm = 1;
139023 138350           pNew->aLTerm[0] = pTerm;
139024 138351           /* TUNING: One-time cost for computing the automatic index is
139025 138352           ** estimated to be X*N*log2(N) where N is the number of rows in
139026 138353           ** the table being indexed and where X is 7 (LogEst=28) for normal
139027         -        ** tables or 0.5 (LogEst=-10) for views and subqueries.  The value
       138354  +        ** tables or 1.375 (LogEst=4) for views and subqueries.  The value
139028 138355           ** of X is smaller for views and subqueries so that the query planner
139029 138356           ** will be more aggressive about generating automatic indexes for
139030 138357           ** those objects, since there is no opportunity to add schema
139031 138358           ** indexes on subqueries and views. */
139032         -        pNew->rSetup = rLogSize + rSize;
       138359  +        pNew->rSetup = rLogSize + rSize + 4;
139033 138360           if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){
139034         -          pNew->rSetup += 28;
139035         -        }else{
139036         -          pNew->rSetup -= 10;
       138361  +          pNew->rSetup += 24;
139037 138362           }
139038 138363           ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
139039 138364           if( pNew->rSetup<0 ) pNew->rSetup = 0;
139040 138365           /* TUNING: Each index lookup yields 20 rows in the table.  This
139041 138366           ** is more than the usual guess of 10 rows, since we have no way
139042 138367           ** of knowing how selective the index will ultimately be.  It would
139043 138368           ** not be unreasonable to make this value much larger. */
................................................................................
140165 139490           LogEst rUnsorted;                 /* Unsorted cost of (pFrom+pWLoop) */
140166 139491           i8 isOrdered = pFrom->isOrdered;  /* isOrdered for (pFrom+pWLoop) */
140167 139492           Bitmask maskNew;                  /* Mask of src visited by (..) */
140168 139493           Bitmask revMask = 0;              /* Mask of rev-order loops for (..) */
140169 139494   
140170 139495           if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
140171 139496           if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
140172         -        if( (pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 && pFrom->nRow<3 ){
       139497  +        if( (pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 && pFrom->nRow<10 ){
140173 139498             /* Do not use an automatic index if the this loop is expected
140174         -          ** to run less than 1.25 times.  It is tempting to also exclude
140175         -          ** automatic index usage on an outer loop, but sometimes an automatic
140176         -          ** index is useful in the outer loop of a correlated subquery. */
       139499  +          ** to run less than 2 times. */
140177 139500             assert( 10==sqlite3LogEst(2) );
140178 139501             continue;
140179 139502           }
140180         -
140181 139503           /* At this point, pWLoop is a candidate to be the next loop. 
140182 139504           ** Compute its cost */
140183 139505           rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
140184 139506           rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
140185 139507           nOut = pFrom->nRow + pWLoop->nOut;
140186 139508           maskNew = pFrom->maskLoop | pWLoop->maskSelf;
140187 139509           if( isOrdered<0 ){
................................................................................
140755 140077     /* Special case: No FROM clause
140756 140078     */
140757 140079     if( nTabList==0 ){
140758 140080       if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
140759 140081       if( wctrlFlags & WHERE_WANT_DISTINCT ){
140760 140082         pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
140761 140083       }
140762         -    ExplainQueryPlan((pParse, 0, "SCAN CONSTANT ROW"));
140763 140084     }else{
140764 140085       /* Assign a bit from the bitmask to every term in the FROM clause.
140765 140086       **
140766 140087       ** The N-th term of the FROM clause is assigned a bitmask of 1<<N.
140767 140088       **
140768 140089       ** The rule of the previous sentence ensures thta if X is the bitmask for
140769 140090       ** a table T, then X-1 is the bitmask for all other tables to the left of T.
................................................................................
141151 140472       if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
141152 140473         constructAutomaticIndex(pParse, &pWInfo->sWC,
141153 140474                   &pTabList->a[pLevel->iFrom], notReady, pLevel);
141154 140475         if( db->mallocFailed ) goto whereBeginError;
141155 140476       }
141156 140477   #endif
141157 140478       addrExplain = sqlite3WhereExplainOneScan(
141158         -        pParse, pTabList, pLevel, wctrlFlags
       140479  +        pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags
141159 140480       );
141160 140481       pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
141161 140482       notReady = sqlite3WhereCodeOneLoopStart(pWInfo, ii, notReady);
141162 140483       pWInfo->iContinue = pLevel->addrCont;
141163 140484       if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_OR_SUBCLAUSE)==0 ){
141164 140485         sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain);
141165 140486       }
................................................................................
147616 146937           { SQLITE_DBCONFIG_ENABLE_FKEY,           SQLITE_ForeignKeys    },
147617 146938           { SQLITE_DBCONFIG_ENABLE_TRIGGER,        SQLITE_EnableTrigger  },
147618 146939           { SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, SQLITE_Fts3Tokenizer  },
147619 146940           { SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, SQLITE_LoadExtension  },
147620 146941           { SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE,      SQLITE_NoCkptOnClose  },
147621 146942           { SQLITE_DBCONFIG_ENABLE_QPSG,           SQLITE_EnableQPSG     },
147622 146943           { SQLITE_DBCONFIG_TRIGGER_EQP,           SQLITE_TriggerEQP     },
147623         -        { SQLITE_DBCONFIG_RESET_DATABASE,        SQLITE_ResetDatabase  },
147624 146944         };
147625 146945         unsigned int i;
147626 146946         rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
147627 146947         for(i=0; i<ArraySize(aFlagOp); i++){
147628 146948           if( aFlagOp[i].op==op ){
147629 146949             int onoff = va_arg(ap, int);
147630 146950             int *pRes = va_arg(ap, int*);
................................................................................
148590 147910   #ifdef SQLITE_ENABLE_API_ARMOR
148591 147911     if( !sqlite3SafetyCheckOk(db) ){
148592 147912       return SQLITE_MISUSE_BKPT;
148593 147913     }
148594 147914   #endif
148595 147915     sqlite3_mutex_enter(db->mutex);
148596 147916     if( xDestroy ){
148597         -    pArg = (FuncDestructor *)sqlite3Malloc(sizeof(FuncDestructor));
       147917  +    pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
148598 147918       if( !pArg ){
148599         -      sqlite3OomFault(db);
148600 147919         xDestroy(p);
148601 147920         goto out;
148602 147921       }
148603         -    pArg->nRef = 0;
148604 147922       pArg->xDestroy = xDestroy;
148605 147923       pArg->pUserData = p;
148606 147924     }
148607 147925     rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xSFunc, xStep, xFinal, pArg);
148608 147926     if( pArg && pArg->nRef==0 ){
148609 147927       assert( rc!=SQLITE_OK );
148610 147928       xDestroy(p);
148611         -    sqlite3_free(pArg);
       147929  +    sqlite3DbFree(db, pArg);
148612 147930     }
148613 147931   
148614 147932    out:
148615 147933     rc = sqlite3ApiExit(db, rc);
148616 147934     sqlite3_mutex_leave(db->mutex);
148617 147935     return rc;
148618 147936   }
................................................................................
148642 147960     rc = sqlite3ApiExit(db, rc);
148643 147961     sqlite3_mutex_leave(db->mutex);
148644 147962     return rc;
148645 147963   }
148646 147964   #endif
148647 147965   
148648 147966   
148649         -/*
148650         -** The following is the implementation of an SQL function that always
148651         -** fails with an error message stating that the function is used in the
148652         -** wrong context.  The sqlite3_overload_function() API might construct
148653         -** SQL function that use this routine so that the functions will exist
148654         -** for name resolution but are actually overloaded by the xFindFunction
148655         -** method of virtual tables.
148656         -*/
148657         -static void sqlite3InvalidFunction(
148658         -  sqlite3_context *context,  /* The function calling context */
148659         -  int NotUsed,               /* Number of arguments to the function */
148660         -  sqlite3_value **NotUsed2   /* Value of each argument */
148661         -){
148662         -  const char *zName = (const char*)sqlite3_user_data(context);
148663         -  char *zErr;
148664         -  UNUSED_PARAMETER2(NotUsed, NotUsed2);
148665         -  zErr = sqlite3_mprintf(
148666         -      "unable to use function %s in the requested context", zName);
148667         -  sqlite3_result_error(context, zErr, -1);
148668         -  sqlite3_free(zErr);
148669         -}
148670         -
148671 147967   /*
148672 147968   ** Declare that a function has been overloaded by a virtual table.
148673 147969   **
148674 147970   ** If the function already exists as a regular global function, then
148675 147971   ** this routine is a no-op.  If the function does not exist, then create
148676 147972   ** a new one that always throws a run-time error.  
148677 147973   **
................................................................................
148681 147977   ** properly.
148682 147978   */
148683 147979   SQLITE_API int sqlite3_overload_function(
148684 147980     sqlite3 *db,
148685 147981     const char *zName,
148686 147982     int nArg
148687 147983   ){
148688         -  int rc;
148689         -  char *zCopy;
       147984  +  int rc = SQLITE_OK;
148690 147985   
148691 147986   #ifdef SQLITE_ENABLE_API_ARMOR
148692 147987     if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
148693 147988       return SQLITE_MISUSE_BKPT;
148694 147989     }
148695 147990   #endif
148696 147991     sqlite3_mutex_enter(db->mutex);
148697         -  rc = sqlite3FindFunction(db, zName, nArg, SQLITE_UTF8, 0)!=0;
       147992  +  if( sqlite3FindFunction(db, zName, nArg, SQLITE_UTF8, 0)==0 ){
       147993  +    rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
       147994  +                           0, sqlite3InvalidFunction, 0, 0, 0);
       147995  +  }
       147996  +  rc = sqlite3ApiExit(db, rc);
148698 147997     sqlite3_mutex_leave(db->mutex);
148699         -  if( rc ) return SQLITE_OK;
148700         -  zCopy = sqlite3_mprintf(zName);
148701         -  if( zCopy==0 ) return SQLITE_NOMEM;
148702         -  return sqlite3_create_function_v2(db, zName, nArg, SQLITE_UTF8,
148703         -                           zCopy, sqlite3InvalidFunction, 0, 0, sqlite3_free);
       147998  +  return rc;
148704 147999   }
148705 148000   
148706 148001   #ifndef SQLITE_OMIT_TRACE
148707 148002   /*
148708 148003   ** Register a trace function.  The pArg from the previously registered trace
148709 148004   ** is returned.  
148710 148005   **
................................................................................
152535 151830   
152536 151831   /* fts3_expr.c */
152537 151832   SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
152538 151833     char **, int, int, int, const char *, int, Fts3Expr **, char **
152539 151834   );
152540 151835   SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
152541 151836   #ifdef SQLITE_TEST
152542         -SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db, Fts3Hash*);
       151837  +SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
152543 151838   SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
152544 151839   #endif
152545 151840   
152546 151841   SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
152547 151842     sqlite3_tokenizer_cursor **
152548 151843   );
152549 151844   
................................................................................
156245 155540       ){
156246 155541         rc = SQLITE_NOMEM;
156247 155542       }
156248 155543     }
156249 155544   
156250 155545   #ifdef SQLITE_TEST
156251 155546     if( rc==SQLITE_OK ){
156252         -    rc = sqlite3Fts3ExprInitTestInterface(db, pHash);
       155547  +    rc = sqlite3Fts3ExprInitTestInterface(db);
156253 155548     }
156254 155549   #endif
156255 155550   
156256 155551     /* Create the virtual table wrapper around the hash-table and overload 
156257 155552     ** the four scalar functions. If this is successful, register the
156258 155553     ** module with sqlite.
156259 155554     */
................................................................................
159904 159199   *****************************************************************************
159905 159200   ** Everything after this point is just test code.
159906 159201   */
159907 159202   
159908 159203   #ifdef SQLITE_TEST
159909 159204   
159910 159205   /* #include <stdio.h> */
       159206  +
       159207  +/*
       159208  +** Function to query the hash-table of tokenizers (see README.tokenizers).
       159209  +*/
       159210  +static int queryTestTokenizer(
       159211  +  sqlite3 *db, 
       159212  +  const char *zName,  
       159213  +  const sqlite3_tokenizer_module **pp
       159214  +){
       159215  +  int rc;
       159216  +  sqlite3_stmt *pStmt;
       159217  +  const char zSql[] = "SELECT fts3_tokenizer(?)";
       159218  +
       159219  +  *pp = 0;
       159220  +  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
       159221  +  if( rc!=SQLITE_OK ){
       159222  +    return rc;
       159223  +  }
       159224  +
       159225  +  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
       159226  +  if( SQLITE_ROW==sqlite3_step(pStmt) ){
       159227  +    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
       159228  +      memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
       159229  +    }
       159230  +  }
       159231  +
       159232  +  return sqlite3_finalize(pStmt);
       159233  +}
159911 159234   
159912 159235   /*
159913 159236   ** Return a pointer to a buffer containing a text representation of the
159914 159237   ** expression passed as the first argument. The buffer is obtained from
159915 159238   ** sqlite3_malloc(). It is the responsibility of the caller to use 
159916 159239   ** sqlite3_free() to release the memory. If an OOM condition is encountered,
159917 159240   ** NULL is returned.
................................................................................
159972 159295   ** to parse the query expression (see README.tokenizers). The second argument
159973 159296   ** is the query expression to parse. Each subsequent argument is the name
159974 159297   ** of a column of the fts3 table that the query expression may refer to.
159975 159298   ** For example:
159976 159299   **
159977 159300   **   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
159978 159301   */
159979         -static void fts3ExprTestCommon(
159980         -  int bRebalance,
       159302  +static void fts3ExprTest(
159981 159303     sqlite3_context *context,
159982 159304     int argc,
159983 159305     sqlite3_value **argv
159984 159306   ){
       159307  +  sqlite3_tokenizer_module const *pModule = 0;
159985 159308     sqlite3_tokenizer *pTokenizer = 0;
159986 159309     int rc;
159987 159310     char **azCol = 0;
159988 159311     const char *zExpr;
159989 159312     int nExpr;
159990 159313     int nCol;
159991 159314     int ii;
159992 159315     Fts3Expr *pExpr;
159993 159316     char *zBuf = 0;
159994         -  Fts3Hash *pHash = (Fts3Hash*)sqlite3_user_data(context);
159995         -  const char *zTokenizer = 0;
159996         -  char *zErr = 0;
       159317  +  sqlite3 *db = sqlite3_context_db_handle(context);
159997 159318   
159998 159319     if( argc<3 ){
159999 159320       sqlite3_result_error(context, 
160000 159321           "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
160001 159322       );
160002 159323       return;
160003 159324     }
160004 159325   
160005         -  zTokenizer = (const char*)sqlite3_value_text(argv[0]);
160006         -  rc = sqlite3Fts3InitTokenizer(pHash, zTokenizer, &pTokenizer, &zErr);
160007         -  if( rc!=SQLITE_OK ){
160008         -    if( rc==SQLITE_NOMEM ){
160009         -      sqlite3_result_error_nomem(context);
160010         -    }else{
160011         -      sqlite3_result_error(context, zErr, -1);
160012         -    }
160013         -    sqlite3_free(zErr);
160014         -    return;
       159326  +  rc = queryTestTokenizer(db,
       159327  +                          (const char *)sqlite3_value_text(argv[0]), &pModule);
       159328  +  if( rc==SQLITE_NOMEM ){
       159329  +    sqlite3_result_error_nomem(context);
       159330  +    goto exprtest_out;
       159331  +  }else if( !pModule ){
       159332  +    sqlite3_result_error(context, "No such tokenizer module", -1);
       159333  +    goto exprtest_out;
160015 159334     }
       159335  +
       159336  +  rc = pModule->xCreate(0, 0, &pTokenizer);
       159337  +  assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
       159338  +  if( rc==SQLITE_NOMEM ){
       159339  +    sqlite3_result_error_nomem(context);
       159340  +    goto exprtest_out;
       159341  +  }
       159342  +  pTokenizer->pModule = pModule;
160016 159343   
160017 159344     zExpr = (const char *)sqlite3_value_text(argv[1]);
160018 159345     nExpr = sqlite3_value_bytes(argv[1]);
160019 159346     nCol = argc-2;
160020 159347     azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
160021 159348     if( !azCol ){
160022 159349       sqlite3_result_error_nomem(context);
160023 159350       goto exprtest_out;
160024 159351     }
160025 159352     for(ii=0; ii<nCol; ii++){
160026 159353       azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
160027 159354     }
160028 159355   
160029         -  if( bRebalance ){
       159356  +  if( sqlite3_user_data(context) ){
160030 159357       char *zDummy = 0;
160031 159358       rc = sqlite3Fts3ExprParse(
160032 159359           pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
160033 159360       );
160034 159361       assert( rc==SQLITE_OK || pExpr==0 );
160035 159362       sqlite3_free(zDummy);
160036 159363     }else{
................................................................................
160048 159375       sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
160049 159376       sqlite3_free(zBuf);
160050 159377     }
160051 159378   
160052 159379     sqlite3Fts3ExprFree(pExpr);
160053 159380   
160054 159381   exprtest_out:
160055         -  if( pTokenizer ){
160056         -    rc = pTokenizer->pModule->xDestroy(pTokenizer);
       159382  +  if( pModule && pTokenizer ){
       159383  +    rc = pModule->xDestroy(pTokenizer);
160057 159384     }
160058 159385     sqlite3_free(azCol);
160059 159386   }
160060 159387   
160061         -static void fts3ExprTest(
160062         -  sqlite3_context *context,
160063         -  int argc,
160064         -  sqlite3_value **argv
160065         -){
160066         -  fts3ExprTestCommon(0, context, argc, argv);
160067         -}
160068         -static void fts3ExprTestRebalance(
160069         -  sqlite3_context *context,
160070         -  int argc,
160071         -  sqlite3_value **argv
160072         -){
160073         -  fts3ExprTestCommon(1, context, argc, argv);
160074         -}
160075         -
160076 159388   /*
160077 159389   ** Register the query expression parser test function fts3_exprtest() 
160078 159390   ** with database connection db. 
160079 159391   */
160080         -SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db, Fts3Hash *pHash){
       159392  +SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
160081 159393     int rc = sqlite3_create_function(
160082         -      db, "fts3_exprtest", -1, SQLITE_UTF8, (void*)pHash, fts3ExprTest, 0, 0
       159394  +      db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
160083 159395     );
160084 159396     if( rc==SQLITE_OK ){
160085 159397       rc = sqlite3_create_function(db, "fts3_exprtest_rebalance", 
160086         -        -1, SQLITE_UTF8, (void*)pHash, fts3ExprTestRebalance, 0, 0
       159398  +        -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0
160087 159399       );
160088 159400     }
160089 159401     return rc;
160090 159402   }
160091 159403   
160092 159404   #endif
160093 159405   #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
................................................................................
170540 169852   ** The data structure for a single virtual r-tree table is stored in three 
170541 169853   ** native SQLite tables declared as follows. In each case, the '%' character
170542 169854   ** in the table name is replaced with the user-supplied name of the r-tree
170543 169855   ** table.
170544 169856   **
170545 169857   **   CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
170546 169858   **   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
170547         -**   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER, ...)
       169859  +**   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
170548 169860   **
170549 169861   ** The data for each node of the r-tree structure is stored in the %_node
170550 169862   ** table. For each node that is not the root node of the r-tree, there is
170551 169863   ** an entry in the %_parent table associating the node with its parent.
170552 169864   ** And for each row of data in the table, there is an entry in the %_rowid
170553 169865   ** table that maps from the entries rowid to the id of the node that it
170554         -** is stored on.  If the r-tree contains auxiliary columns, those are stored
170555         -** on the end of the %_rowid table.
       169866  +** is stored on.
170556 169867   **
170557 169868   ** The root node of an r-tree always exists, even if the r-tree table is
170558 169869   ** empty. The nodeno of the root node is always 1. All other nodes in the
170559 169870   ** table must be the same size as the root node. The content of each node
170560 169871   ** is formatted as follows:
170561 169872   **
170562 169873   **   1. If the node is the root node (node 1), then the first 2 bytes
................................................................................
170611 169922   typedef struct RtreeGeomCallback RtreeGeomCallback;
170612 169923   typedef union RtreeCoord RtreeCoord;
170613 169924   typedef struct RtreeSearchPoint RtreeSearchPoint;
170614 169925   
170615 169926   /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
170616 169927   #define RTREE_MAX_DIMENSIONS 5
170617 169928   
170618         -/* Maximum number of auxiliary columns */
170619         -#define RTREE_MAX_AUX_COLUMN 100
170620         -
170621 169929   /* Size of hash table Rtree.aHash. This hash table is not expected to
170622 169930   ** ever contain very many entries, so a fixed number of buckets is 
170623 169931   ** used.
170624 169932   */
170625 169933   #define HASHSIZE 97
170626 169934   
170627 169935   /* The xBestIndex method of this virtual table requires an estimate of
................................................................................
170642 169950     sqlite3 *db;                /* Host database connection */
170643 169951     int iNodeSize;              /* Size in bytes of each node in the node table */
170644 169952     u8 nDim;                    /* Number of dimensions */
170645 169953     u8 nDim2;                   /* Twice the number of dimensions */
170646 169954     u8 eCoordType;              /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */
170647 169955     u8 nBytesPerCell;           /* Bytes consumed per cell */
170648 169956     u8 inWrTrans;               /* True if inside write transaction */
170649         -  u8 nAux;                    /* # of auxiliary columns in %_rowid */
170650 169957     int iDepth;                 /* Current depth of the r-tree structure */
170651 169958     char *zDb;                  /* Name of database containing r-tree table */
170652 169959     char *zName;                /* Name of r-tree table */ 
170653 169960     u32 nBusy;                  /* Current number of users of this structure */
170654 169961     i64 nRowEst;                /* Estimated number of rows in this table */
170655 169962     u32 nCursor;                /* Number of open cursors */
170656         -  u32 nNodeRef;               /* Number RtreeNodes with positive nRef */
170657         -  char *zReadAuxSql;          /* SQL for statement to read aux data */
170658 169963   
170659 169964     /* List of nodes removed during a CondenseTree operation. List is
170660 169965     ** linked together via the pointer normally used for hash chains -
170661 169966     ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree 
170662 169967     ** headed by the node (leaf nodes have RtreeNode.iNode==0).
170663 169968     */
170664 169969     RtreeNode *pDeleted;
................................................................................
170677 169982     sqlite3_stmt *pDeleteRowid;
170678 169983   
170679 169984     /* Statements to read/write/delete a record from xxx_parent */
170680 169985     sqlite3_stmt *pReadParent;
170681 169986     sqlite3_stmt *pWriteParent;
170682 169987     sqlite3_stmt *pDeleteParent;
170683 169988   
170684         -  /* Statement for writing to the "aux:" fields, if there are any */
170685         -  sqlite3_stmt *pWriteAux;
170686         -
170687 169989     RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */ 
170688 169990   };
170689 169991   
170690 169992   /* Possible values for Rtree.eCoordType: */
170691 169993   #define RTREE_COORD_REAL32 0
170692 169994   #define RTREE_COORD_INT32  1
170693 169995   
................................................................................
170756 170058   /* 
170757 170059   ** An rtree cursor object.
170758 170060   */
170759 170061   struct RtreeCursor {
170760 170062     sqlite3_vtab_cursor base;         /* Base class.  Must be first */
170761 170063     u8 atEOF;                         /* True if at end of search */
170762 170064     u8 bPoint;                        /* True if sPoint is valid */
170763         -  u8 bAuxValid;                     /* True if pReadAux is valid */
170764 170065     int iStrategy;                    /* Copy of idxNum search parameter */
170765 170066     int nConstraint;                  /* Number of entries in aConstraint */
170766 170067     RtreeConstraint *aConstraint;     /* Search constraints. */
170767 170068     int nPointAlloc;                  /* Number of slots allocated for aPoint[] */
170768 170069     int nPoint;                       /* Number of slots used in aPoint[] */
170769 170070     int mxLevel;                      /* iLevel value for root of the tree */
170770 170071     RtreeSearchPoint *aPoint;         /* Priority queue for search points */
170771         -  sqlite3_stmt *pReadAux;           /* Statement to read aux-data */
170772 170072     RtreeSearchPoint sPoint;          /* Cached next search point */
170773 170073     RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
170774 170074     u32 anQueue[RTREE_MAX_DEPTH+1];   /* Number of queued entries by iLevel */
170775 170075   };
170776 170076   
170777 170077   /* Return the Rtree of a RtreeCursor */
170778 170078   #define RTREE_OF_CURSOR(X)   ((Rtree*)((X)->base.pVtab))
................................................................................
171051 170351   }
171052 170352   
171053 170353   /*
171054 170354   ** Increment the reference count of node p.
171055 170355   */
171056 170356   static void nodeReference(RtreeNode *p){
171057 170357     if( p ){
171058         -    assert( p->nRef>0 );
171059 170358       p->nRef++;
171060 170359     }
171061 170360   }
171062 170361   
171063 170362   /*
171064 170363   ** Clear the content of node p (set all bytes to 0x00).
171065 170364   */
................................................................................
171119 170418   static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
171120 170419     RtreeNode *pNode;
171121 170420     pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
171122 170421     if( pNode ){
171123 170422       memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
171124 170423       pNode->zData = (u8 *)&pNode[1];
171125 170424       pNode->nRef = 1;
171126         -    pRtree->nNodeRef++;
171127 170425       pNode->pParent = pParent;
171128 170426       pNode->isDirty = 1;
171129 170427       nodeReference(pParent);
171130 170428     }
171131 170429     return pNode;
171132 170430   }
171133 170431   
................................................................................
171153 170451   ){
171154 170452     int rc = SQLITE_OK;
171155 170453     RtreeNode *pNode = 0;
171156 170454   
171157 170455     /* Check if the requested node is already in the hash table. If so,
171158 170456     ** increase its reference count and return it.
171159 170457     */
171160         -  if( (pNode = nodeHashLookup(pRtree, iNode))!=0 ){
       170458  +  if( (pNode = nodeHashLookup(pRtree, iNode)) ){
171161 170459       assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
171162 170460       if( pParent && !pNode->pParent ){
171163         -      pParent->nRef++;
       170461  +      nodeReference(pParent);
171164 170462         pNode->pParent = pParent;
171165 170463       }
171166 170464       pNode->nRef++;
171167 170465       *ppNode = pNode;
171168 170466       return SQLITE_OK;
171169 170467     }
171170 170468   
................................................................................
171195 170493       pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
171196 170494       if( !pNode ){
171197 170495         rc = SQLITE_NOMEM;
171198 170496       }else{
171199 170497         pNode->pParent = pParent;
171200 170498         pNode->zData = (u8 *)&pNode[1];
171201 170499         pNode->nRef = 1;
171202         -      pRtree->nNodeRef++;
171203 170500         pNode->iNode = iNode;
171204 170501         pNode->isDirty = 0;
171205 170502         pNode->pNext = 0;
171206 170503         rc = sqlite3_blob_read(pRtree->pNodeBlob, pNode->zData,
171207 170504                                pRtree->iNodeSize, 0);
171208 170505         nodeReference(pParent);
171209 170506       }
................................................................................
171236 170533       if( pNode!=0 ){
171237 170534         nodeHashInsert(pRtree, pNode);
171238 170535       }else{
171239 170536         rc = SQLITE_CORRUPT_VTAB;
171240 170537       }
171241 170538       *ppNode = pNode;
171242 170539     }else{
171243         -    if( pNode ){
171244         -      pRtree->nNodeRef--;
171245         -      sqlite3_free(pNode);
171246         -    }
       170540  +    sqlite3_free(pNode);
171247 170541       *ppNode = 0;
171248 170542     }
171249 170543   
171250 170544     return rc;
171251 170545   }
171252 170546   
171253 170547   /*
................................................................................
171336 170630   ** Release a reference to a node. If the node is dirty and the reference
171337 170631   ** count drops to zero, the node data is written to the database.
171338 170632   */
171339 170633   static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){
171340 170634     int rc = SQLITE_OK;
171341 170635     if( pNode ){
171342 170636       assert( pNode->nRef>0 );
171343         -    assert( pRtree->nNodeRef>0 );
171344 170637       pNode->nRef--;
171345 170638       if( pNode->nRef==0 ){
171346         -      pRtree->nNodeRef--;
171347 170639         if( pNode->iNode==1 ){
171348 170640           pRtree->iDepth = -1;
171349 170641         }
171350 170642         if( pNode->pParent ){
171351 170643           rc = nodeRelease(pRtree, pNode->pParent);
171352 170644         }
171353 170645         if( rc==SQLITE_OK ){
................................................................................
171456 170748   ** Decrement the r-tree reference count. When the reference count reaches
171457 170749   ** zero the structure is deleted.
171458 170750   */
171459 170751   static void rtreeRelease(Rtree *pRtree){
171460 170752     pRtree->nBusy--;
171461 170753     if( pRtree->nBusy==0 ){
171462 170754       pRtree->inWrTrans = 0;
171463         -    assert( pRtree->nCursor==0 );
       170755  +    pRtree->nCursor = 0;
171464 170756       nodeBlobReset(pRtree);
171465         -    assert( pRtree->nNodeRef==0 );
171466 170757       sqlite3_finalize(pRtree->pWriteNode);
171467 170758       sqlite3_finalize(pRtree->pDeleteNode);
171468 170759       sqlite3_finalize(pRtree->pReadRowid);
171469 170760       sqlite3_finalize(pRtree->pWriteRowid);
171470 170761       sqlite3_finalize(pRtree->pDeleteRowid);
171471 170762       sqlite3_finalize(pRtree->pReadParent);
171472 170763       sqlite3_finalize(pRtree->pWriteParent);
171473 170764       sqlite3_finalize(pRtree->pDeleteParent);
171474         -    sqlite3_finalize(pRtree->pWriteAux);
171475         -    sqlite3_free(pRtree->zReadAuxSql);
171476 170765       sqlite3_free(pRtree);
171477 170766     }
171478 170767   }
171479 170768   
171480 170769   /* 
171481 170770   ** Rtree virtual table module xDisconnect method.
171482 170771   */
................................................................................
171557 170846   */
171558 170847   static int rtreeClose(sqlite3_vtab_cursor *cur){
171559 170848     Rtree *pRtree = (Rtree *)(cur->pVtab);
171560 170849     int ii;
171561 170850     RtreeCursor *pCsr = (RtreeCursor *)cur;
171562 170851     assert( pRtree->nCursor>0 );
171563 170852     freeCursorConstraints(pCsr);
171564         -  sqlite3_finalize(pCsr->pReadAux);
171565 170853     sqlite3_free(pCsr->aPoint);
171566 170854     for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
171567 170855     sqlite3_free(pCsr);
171568 170856     pRtree->nCursor--;
171569 170857     nodeBlobReset(pRtree);
171570 170858     return SQLITE_OK;
171571 170859   }
................................................................................
171929 171217         int ii;
171930 171218         pNew = rtreeEnqueue(pCur, rScore, iLevel);
171931 171219         if( pNew==0 ) return 0;
171932 171220         ii = (int)(pNew - pCur->aPoint) + 1;
171933 171221         if( ii<RTREE_CACHE_SZ ){
171934 171222           assert( pCur->aNode[ii]==0 );
171935 171223           pCur->aNode[ii] = pCur->aNode[0];
171936         -      }else{
       171224  +       }else{
171937 171225           nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);
171938 171226         }
171939 171227         pCur->aNode[0] = 0;
171940 171228         *pNew = pCur->sPoint;
171941 171229       }
171942 171230       pCur->sPoint.rScore = rScore;
171943 171231       pCur->sPoint.iLevel = iLevel;
................................................................................
172100 171388   */
172101 171389   static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
172102 171390     RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
172103 171391     int rc = SQLITE_OK;
172104 171392   
172105 171393     /* Move to the next entry that matches the configured constraints. */
172106 171394     RTREE_QUEUE_TRACE(pCsr, "POP-Nx:");
172107         -  if( pCsr->bAuxValid ){
172108         -    pCsr->bAuxValid = 0;
172109         -    sqlite3_reset(pCsr->pReadAux);
172110         -  }
172111 171395     rtreeSearchPointPop(pCsr);
172112 171396     rc = rtreeStepToLeaf(pCsr);
172113 171397     return rc;
172114 171398   }
172115 171399   
172116 171400   /* 
172117 171401   ** Rtree virtual table module xRowid method.
................................................................................
172138 171422     int rc = SQLITE_OK;
172139 171423     RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
172140 171424   
172141 171425     if( rc ) return rc;
172142 171426     if( p==0 ) return SQLITE_OK;
172143 171427     if( i==0 ){
172144 171428       sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
172145         -  }else if( i<=pRtree->nDim2 ){
       171429  +  }else{
172146 171430       nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);
172147 171431   #ifndef SQLITE_RTREE_INT_ONLY
172148 171432       if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
172149 171433         sqlite3_result_double(ctx, c.f);
172150 171434       }else
172151 171435   #endif
172152 171436       {
172153 171437         assert( pRtree->eCoordType==RTREE_COORD_INT32 );
172154 171438         sqlite3_result_int(ctx, c.i);
172155 171439       }
172156         -  }else{
172157         -    if( !pCsr->bAuxValid ){
172158         -      if( pCsr->pReadAux==0 ){
172159         -        rc = sqlite3_prepare_v3(pRtree->db, pRtree->zReadAuxSql, -1, 0,
172160         -                                &pCsr->pReadAux, 0);
172161         -        if( rc ) return rc;
172162         -      }
172163         -      sqlite3_bind_int64(pCsr->pReadAux, 1, 
172164         -          nodeGetRowid(pRtree, pNode, p->iCell));
172165         -      rc = sqlite3_step(pCsr->pReadAux);
172166         -      if( rc==SQLITE_ROW ){
172167         -        pCsr->bAuxValid = 1;
172168         -      }else{
172169         -        sqlite3_reset(pCsr->pReadAux);
172170         -        if( rc==SQLITE_DONE ) rc = SQLITE_OK;
172171         -        return rc;
172172         -      }
172173         -    }
172174         -    sqlite3_result_value(ctx,
172175         -         sqlite3_column_value(pCsr->pReadAux, i - pRtree->nDim2 + 1));
172176         -  }  
       171440  +  }
172177 171441     return SQLITE_OK;
172178 171442   }
172179 171443   
172180 171444   /* 
172181 171445   ** Use nodeAcquire() to obtain the leaf node containing the record with 
172182 171446   ** rowid iRowid. If successful, set *ppLeaf to point to the node and
172183 171447   ** return SQLITE_OK. If there is no such record in the table, set
................................................................................
172247 171511   ){
172248 171512     Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
172249 171513     RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
172250 171514     RtreeNode *pRoot = 0;
172251 171515     int ii;
172252 171516     int rc = SQLITE_OK;
172253 171517     int iCell = 0;
172254         -  sqlite3_stmt *pStmt;
172255 171518   
172256 171519     rtreeReference(pRtree);
172257 171520   
172258 171521     /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
172259 171522     freeCursorConstraints(pCsr);
172260 171523     sqlite3_free(pCsr->aPoint);
172261         -  pStmt = pCsr->pReadAux;
172262 171524     memset(pCsr, 0, sizeof(RtreeCursor));
172263 171525     pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
172264         -  pCsr->pReadAux = pStmt;
172265 171526   
172266 171527     pCsr->iStrategy = idxNum;
172267 171528     if( idxNum==1 ){
172268 171529       /* Special case - lookup by rowid. */
172269 171530       RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
172270 171531       RtreeSearchPoint *p;     /* Search point for the leaf */
172271 171532       i64 iRowid = sqlite3_value_int64(argv[0]);
................................................................................
172420 171681         ** and then a linear search of an R-Tree node. This should be 
172421 171682         ** considered almost as quick as a direct rowid lookup (for which 
172422 171683         ** sqlite uses an internal cost of 0.0). It is expected to return
172423 171684         ** a single row.
172424 171685         */ 
172425 171686         pIdxInfo->estimatedCost = 30.0;
172426 171687         pIdxInfo->estimatedRows = 1;
172427         -      pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_UNIQUE;
172428 171688         return SQLITE_OK;
172429 171689       }
172430 171690   
172431         -    if( p->usable
172432         -    && ((p->iColumn>0 && p->iColumn<=pRtree->nDim2)
172433         -        || p->op==SQLITE_INDEX_CONSTRAINT_MATCH)
172434         -    ){
       171691  +    if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
172435 171692         u8 op;
172436 171693         switch( p->op ){
172437 171694           case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
172438 171695           case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
172439 171696           case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
172440 171697           case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
172441 171698           case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
................................................................................
173000 172257       pLeft = nodeNew(pRtree, pNode);
173001 172258       pRtree->iDepth++;
173002 172259       pNode->isDirty = 1;
173003 172260       writeInt16(pNode->zData, pRtree->iDepth);
173004 172261     }else{
173005 172262       pLeft = pNode;
173006 172263       pRight = nodeNew(pRtree, pLeft->pParent);
173007         -    pLeft->nRef++;
       172264  +    nodeReference(pLeft);
173008 172265     }
173009 172266   
173010 172267     if( !pLeft || !pRight ){
173011 172268       rc = SQLITE_NOMEM;
173012 172269       goto splitnode_out;
173013 172270     }
173014 172271   
................................................................................
173490 172747   
173491 172748     /* Re-insert the contents of any underfull nodes removed from the tree. */
173492 172749     for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
173493 172750       if( rc==SQLITE_OK ){
173494 172751         rc = reinsertNodeContent(pRtree, pLeaf);
173495 172752       }
173496 172753       pRtree->pDeleted = pLeaf->pNext;
173497         -    pRtree->nNodeRef--;
173498 172754       sqlite3_free(pLeaf);
173499 172755     }
173500 172756   
173501 172757     /* Release the reference to the root node. */
173502 172758     if( rc==SQLITE_OK ){
173503 172759       rc = nodeRelease(pRtree, pRoot);
173504 172760     }else{
................................................................................
173587 172843   
173588 172844   /*
173589 172845   ** The xUpdate method for rtree module virtual tables.
173590 172846   */
173591 172847   static int rtreeUpdate(
173592 172848     sqlite3_vtab *pVtab, 
173593 172849     int nData, 
173594         -  sqlite3_value **aData, 
       172850  +  sqlite3_value **azData, 
173595 172851     sqlite_int64 *pRowid
173596 172852   ){
173597 172853     Rtree *pRtree = (Rtree *)pVtab;
173598 172854     int rc = SQLITE_OK;
173599 172855     RtreeCell cell;                 /* New cell to insert if nData>1 */
173600 172856     int bHaveRowid = 0;             /* Set to 1 after new rowid is determined */
173601 172857   
173602         -  if( pRtree->nNodeRef ){
173603         -    /* Unable to write to the btree while another cursor is reading from it,
173604         -    ** since the write might do a rebalance which would disrupt the read
173605         -    ** cursor. */
173606         -    return SQLITE_LOCKED_VTAB;
173607         -  }
173608 172858     rtreeReference(pRtree);
173609 172859     assert(nData>=1);
173610 172860   
173611 172861     cell.iRowid = 0;  /* Used only to suppress a compiler warning */
173612 172862   
173613 172863     /* Constraint handling. A write operation on an r-tree table may return
173614 172864     ** SQLITE_CONSTRAINT for two reasons:
................................................................................
173619 172869     ** In the first case, if the conflict-handling mode is REPLACE, then
173620 172870     ** the conflicting row can be removed before proceeding. In the second
173621 172871     ** case, SQLITE_CONSTRAINT must be returned regardless of the
173622 172872     ** conflict-handling mode specified by the user.
173623 172873     */
173624 172874     if( nData>1 ){
173625 172875       int ii;
173626         -    int nn = nData - 4;
173627 172876   
173628         -    if( nn > pRtree->nDim2 ) nn = pRtree->nDim2;
173629         -    /* Populate the cell.aCoord[] array. The first coordinate is aData[3].
       172877  +    /* Populate the cell.aCoord[] array. The first coordinate is azData[3].
173630 172878       **
173631 172879       ** NB: nData can only be less than nDim*2+3 if the rtree is mis-declared
173632 172880       ** with "column" that are interpreted as table constraints.
173633 172881       ** Example:  CREATE VIRTUAL TABLE bad USING rtree(x,y,CHECK(y>5));
173634 172882       ** This problem was discovered after years of use, so we silently ignore
173635 172883       ** these kinds of misdeclared tables to avoid breaking any legacy.
173636 172884       */
       172885  +    assert( nData<=(pRtree->nDim2 + 3) );
173637 172886   
173638 172887   #ifndef SQLITE_RTREE_INT_ONLY
173639 172888       if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
173640         -      for(ii=0; ii<nn; ii+=2){
173641         -        cell.aCoord[ii].f = rtreeValueDown(aData[ii+3]);
173642         -        cell.aCoord[ii+1].f = rtreeValueUp(aData[ii+4]);
       172889  +      for(ii=0; ii<nData-4; ii+=2){
       172890  +        cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
       172891  +        cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
173643 172892           if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
173644 172893             rc = rtreeConstraintError(pRtree, ii+1);
173645 172894             goto constraint;
173646 172895           }
173647 172896         }
173648 172897       }else
173649 172898   #endif
173650 172899       {
173651         -      for(ii=0; ii<nn; ii+=2){
173652         -        cell.aCoord[ii].i = sqlite3_value_int(aData[ii+3]);
173653         -        cell.aCoord[ii+1].i = sqlite3_value_int(aData[ii+4]);
       172900  +      for(ii=0; ii<nData-4; ii+=2){
       172901  +        cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
       172902  +        cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
173654 172903           if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
173655 172904             rc = rtreeConstraintError(pRtree, ii+1);
173656 172905             goto constraint;
173657 172906           }
173658 172907         }
173659 172908       }
173660 172909   
173661 172910       /* If a rowid value was supplied, check if it is already present in 
173662 172911       ** the table. If so, the constraint has failed. */
173663         -    if( sqlite3_value_type(aData[2])!=SQLITE_NULL ){
173664         -      cell.iRowid = sqlite3_value_int64(aData[2]);
173665         -      if( sqlite3_value_type(aData[0])==SQLITE_NULL
173666         -       || sqlite3_value_int64(aData[0])!=cell.iRowid
       172912  +    if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
       172913  +      cell.iRowid = sqlite3_value_int64(azData[2]);
       172914  +      if( sqlite3_value_type(azData[0])==SQLITE_NULL
       172915  +       || sqlite3_value_int64(azData[0])!=cell.iRowid
173667 172916         ){
173668 172917           int steprc;
173669 172918           sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
173670 172919           steprc = sqlite3_step(pRtree->pReadRowid);
173671 172920           rc = sqlite3_reset(pRtree->pReadRowid);
173672 172921           if( SQLITE_ROW==steprc ){
173673 172922             if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
................................................................................
173678 172927             }
173679 172928           }
173680 172929         }
173681 172930         bHaveRowid = 1;
173682 172931       }
173683 172932     }
173684 172933   
173685         -  /* If aData[0] is not an SQL NULL value, it is the rowid of a
       172934  +  /* If azData[0] is not an SQL NULL value, it is the rowid of a
173686 172935     ** record to delete from the r-tree table. The following block does
173687 172936     ** just that.
173688 172937     */
173689         -  if( sqlite3_value_type(aData[0])!=SQLITE_NULL ){
173690         -    rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(aData[0]));
       172938  +  if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
       172939  +    rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
173691 172940     }
173692 172941   
173693         -  /* If the aData[] array contains more than one element, elements
173694         -  ** (aData[2]..aData[argc-1]) contain a new record to insert into
       172942  +  /* If the azData[] array contains more than one element, elements
       172943  +  ** (azData[2]..azData[argc-1]) contain a new record to insert into
173695 172944     ** the r-tree structure.
173696 172945     */
173697 172946     if( rc==SQLITE_OK && nData>1 ){
173698 172947       /* Insert the new record into the r-tree */
173699 172948       RtreeNode *pLeaf = 0;
173700 172949   
173701 172950       /* Figure out the rowid of the new row. */
................................................................................
173712 172961         pRtree->iReinsertHeight = -1;
173713 172962         rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
173714 172963         rc2 = nodeRelease(pRtree, pLeaf);
173715 172964         if( rc==SQLITE_OK ){
173716 172965           rc = rc2;
173717 172966         }
173718 172967       }
173719         -    if( pRtree->nAux ){
173720         -      sqlite3_stmt *pUp = pRtree->pWriteAux;
173721         -      int jj;
173722         -      sqlite3_bind_int64(pUp, 1, *pRowid);
173723         -      for(jj=0; jj<pRtree->nAux; jj++){
173724         -        sqlite3_bind_value(pUp, jj+2, aData[pRtree->nDim2+3+jj]);
173725         -      }
173726         -      sqlite3_step(pUp);
173727         -      rc = sqlite3_reset(pUp);
173728         -    }
173729 172968     }
173730 172969   
173731 172970   constraint:
173732 172971     rtreeRelease(pRtree);
173733 172972     return rc;
173734 172973   }
173735 172974   
................................................................................
173878 173117     int isCreate
173879 173118   ){
173880 173119     int rc = SQLITE_OK;
173881 173120   
173882 173121     #define N_STATEMENT 8
173883 173122     static const char *azSql[N_STATEMENT] = {
173884 173123       /* Write the xxx_node table */
173885         -    "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(?1, ?2)",
173886         -    "DELETE FROM '%q'.'%q_node' WHERE nodeno = ?1",
       173124  +    "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
       173125  +    "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
173887 173126   
173888 173127       /* Read and write the xxx_rowid table */
173889         -    "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = ?1",
173890         -    "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(?1, ?2)",
173891         -    "DELETE FROM '%q'.'%q_rowid' WHERE rowid = ?1",
       173128  +    "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
       173129  +    "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
       173130  +    "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
173892 173131   
173893 173132       /* Read and write the xxx_parent table */
173894         -    "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = ?1",
173895         -    "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(?1, ?2)",
173896         -    "DELETE FROM '%q'.'%q_parent' WHERE nodeno = ?1"
       173133  +    "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
       173134  +    "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
       173135  +    "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
173897 173136     };
173898 173137     sqlite3_stmt **appStmt[N_STATEMENT];
173899 173138     int i;
173900 173139   
173901 173140     pRtree->db = db;
173902 173141   
173903 173142     if( isCreate ){
173904         -    char *zCreate;
173905         -    sqlite3_str *p = sqlite3_str_new(db);
173906         -    int ii;
173907         -    sqlite3_str_appendf(p,
173908         -       "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY,nodeno",
173909         -       zDb, zPrefix);
173910         -    for(ii=0; ii<pRtree->nAux; ii++){
173911         -      sqlite3_str_appendf(p,",a%d",ii);
173912         -    }
173913         -    sqlite3_str_appendf(p,
173914         -      ");CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY,data);",
173915         -      zDb, zPrefix);
173916         -    sqlite3_str_appendf(p,
173917         -    "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,parentnode);",
173918         -      zDb, zPrefix);
173919         -    sqlite3_str_appendf(p,
173920         -       "INSERT INTO \"%w\".\"%w_node\"VALUES(1,zeroblob(%d))",
173921         -       zDb, zPrefix, pRtree->iNodeSize);
173922         -    zCreate = sqlite3_str_finish(p);
       173143  +    char *zCreate = sqlite3_mprintf(
       173144  +"CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
       173145  +"CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
       173146  +"CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,"
       173147  +                                  " parentnode INTEGER);"
       173148  +"INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
       173149  +      zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
       173150  +    );
173923 173151       if( !zCreate ){
173924 173152         return SQLITE_NOMEM;
173925 173153       }
173926 173154       rc = sqlite3_exec(db, zCreate, 0, 0, 0);
173927 173155       sqlite3_free(zCreate);
173928 173156       if( rc!=SQLITE_OK ){
173929 173157         return rc;
................................................................................
173937 173165     appStmt[4] = &pRtree->pDeleteRowid;
173938 173166     appStmt[5] = &pRtree->pReadParent;
173939 173167     appStmt[6] = &pRtree->pWriteParent;
173940 173168     appStmt[7] = &pRtree->pDeleteParent;
173941 173169   
173942 173170     rc = rtreeQueryStat1(db, pRtree);
173943 173171     for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
173944         -    char *zSql;
173945         -    const char *zFormat;
173946         -    if( i!=3 || pRtree->nAux==0 ){
173947         -       zFormat = azSql[i];
173948         -    }else {
173949         -       /* An UPSERT is very slightly slower than REPLACE, but it is needed
173950         -       ** if there are auxiliary columns */
173951         -       zFormat = "INSERT INTO\"%w\".\"%w_rowid\"(rowid,nodeno)VALUES(?1,?2)"
173952         -                  "ON CONFLICT(rowid)DO UPDATE SET nodeno=excluded.nodeno";
173953         -    }
173954         -    zSql = sqlite3_mprintf(zFormat, zDb, zPrefix);
       173172  +    char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
173955 173173       if( zSql ){
173956 173174         rc = sqlite3_prepare_v3(db, zSql, -1, SQLITE_PREPARE_PERSISTENT,
173957 173175                                 appStmt[i], 0); 
173958 173176       }else{
173959 173177         rc = SQLITE_NOMEM;
173960 173178       }
173961 173179       sqlite3_free(zSql);
173962 173180     }
173963         -  if( pRtree->nAux ){
173964         -    pRtree->zReadAuxSql = sqlite3_mprintf(
173965         -       "SELECT * FROM \"%w\".\"%w_rowid\" WHERE rowid=?1",
173966         -       zDb, zPrefix);
173967         -    if( pRtree->zReadAuxSql==0 ){
173968         -      rc = SQLITE_NOMEM;
173969         -    }else{
173970         -      sqlite3_str *p = sqlite3_str_new(db);
173971         -      int ii;
173972         -      char *zSql;
173973         -      sqlite3_str_appendf(p, "UPDATE \"%w\".\"%w_rowid\"SET ", zDb, zPrefix);
173974         -      for(ii=0; ii<pRtree->nAux; ii++){
173975         -        if( ii ) sqlite3_str_append(p, ",", 1);
173976         -        sqlite3_str_appendf(p,"a%d=?%d",ii,ii+2);
173977         -      }
173978         -      sqlite3_str_appendf(p, " WHERE rowid=?1");
173979         -      zSql = sqlite3_str_finish(p);
173980         -      if( zSql==0 ){
173981         -        rc = SQLITE_NOMEM;
173982         -      }else{
173983         -        rc = sqlite3_prepare_v3(db, zSql, -1, SQLITE_PREPARE_PERSISTENT,
173984         -                                &pRtree->pWriteAux, 0); 
173985         -        sqlite3_free(zSql);
173986         -      }
173987         -    }
173988         -  }
173989 173181   
173990 173182     return rc;
173991 173183   }
173992 173184   
173993 173185   /*
173994 173186   ** The second argument to this function contains the text of an SQL statement
173995 173187   ** that returns a single integer value. The statement is compiled and executed
................................................................................
174084 173276     int isCreate                        /* True for xCreate, false for xConnect */
174085 173277   ){
174086 173278     int rc = SQLITE_OK;
174087 173279     Rtree *pRtree;
174088 173280     int nDb;              /* Length of string argv[1] */
174089 173281     int nName;            /* Length of string argv[2] */
174090 173282     int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
174091         -  sqlite3_str *pSql;
174092         -  char *zSql;
174093         -  int ii = 4;
174094         -  int iErr;
174095 173283   
174096 173284     const char *aErrMsg[] = {
174097 173285       0,                                                    /* 0 */
174098 173286       "Wrong number of columns for an rtree table",         /* 1 */
174099 173287       "Too few columns for an rtree table",                 /* 2 */
174100         -    "Too many columns for an rtree table",                /* 3 */
174101         -    "Auxiliary rtree columns must be last"                /* 4 */
       173288  +    "Too many columns for an rtree table"                 /* 3 */
174102 173289     };
174103 173290   
174104         -  assert( RTREE_MAX_AUX_COLUMN<256 ); /* Aux columns counted by a u8 */
174105         -  if( argc>RTREE_MAX_AUX_COLUMN+3 ){
174106         -    *pzErr = sqlite3_mprintf("%s", aErrMsg[3]);
       173291  +  int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
       173292  +  if( aErrMsg[iErr] ){
       173293  +    *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
174107 173294       return SQLITE_ERROR;
174108 173295     }
174109 173296   
174110 173297     sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
174111 173298   
174112 173299     /* Allocate the sqlite3_vtab structure */
174113 173300     nDb = (int)strlen(argv[1]);
................................................................................
174117 173304       return SQLITE_NOMEM;
174118 173305     }
174119 173306     memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
174120 173307     pRtree->nBusy = 1;
174121 173308     pRtree->base.pModule = &rtreeModule;
174122 173309     pRtree->zDb = (char *)&pRtree[1];
174123 173310     pRtree->zName = &pRtree->zDb[nDb+1];
       173311  +  pRtree->nDim = (u8)((argc-4)/2);
       173312  +  pRtree->nDim2 = pRtree->nDim*2;
       173313  +  pRtree->nBytesPerCell = 8 + pRtree->nDim2*4;
174124 173314     pRtree->eCoordType = (u8)eCoordType;
174125 173315     memcpy(pRtree->zDb, argv[1], nDb);
174126 173316     memcpy(pRtree->zName, argv[2], nName);
174127 173317   
       173318  +  /* Figure out the node size to use. */
       173319  +  rc = getNodeSize(db, pRtree, isCreate, pzErr);
174128 173320   
174129 173321     /* Create/Connect to the underlying relational database schema. If
174130 173322     ** that is successful, call sqlite3_declare_vtab() to configure
174131 173323     ** the r-tree table schema.
174132 173324     */
174133         -  pSql = sqlite3_str_new(db);
174134         -  sqlite3_str_appendf(pSql, "CREATE TABLE x(%s", argv[3]);
174135         -  for(ii=4; ii<argc; ii++){
174136         -    if( argv[ii][0]=='+' ){
174137         -      pRtree->nAux++;
174138         -      sqlite3_str_appendf(pSql, ",%s", argv[ii]+1);
174139         -    }else if( pRtree->nAux>0 ){
174140         -      break;
174141         -    }else{
174142         -      pRtree->nDim2++;
174143         -      sqlite3_str_appendf(pSql, ",%s", argv[ii]);
174144         -    }
174145         -  }
174146         -  sqlite3_str_appendf(pSql, ");");
174147         -  zSql = sqlite3_str_finish(pSql);
174148         -  if( !zSql ){
174149         -    rc = SQLITE_NOMEM;
174150         -  }else if( ii<argc ){
174151         -    *pzErr = sqlite3_mprintf("%s", aErrMsg[4]);
174152         -    rc = SQLITE_ERROR;
174153         -  }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
174154         -    *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
174155         -  }
174156         -  sqlite3_free(zSql);
174157         -  if( rc ) goto rtreeInit_fail;
174158         -  pRtree->nDim = pRtree->nDim2/2;
174159         -  if( pRtree->nDim<1 ){
174160         -    iErr = 2;
174161         -  }else if( pRtree->nDim2>RTREE_MAX_DIMENSIONS*2 ){
174162         -    iErr = 3;
174163         -  }else if( pRtree->nDim2 % 2 ){
174164         -    iErr = 1;
174165         -  }else{
174166         -    iErr = 0;
174167         -  }
174168         -  if( iErr ){
174169         -    *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
174170         -    goto rtreeInit_fail;
174171         -  }
174172         -  pRtree->nBytesPerCell = 8 + pRtree->nDim2*4;
174173         -
174174         -  /* Figure out the node size to use. */
174175         -  rc = getNodeSize(db, pRtree, isCreate, pzErr);
174176         -  if( rc ) goto rtreeInit_fail;
174177         -  rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate);
174178         -  if( rc ){
174179         -    *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
174180         -    goto rtreeInit_fail;
174181         -  }
174182         -
174183         -  *ppVtab = (sqlite3_vtab *)pRtree;
174184         -  return SQLITE_OK;
174185         -
174186         -rtreeInit_fail:
174187         -  if( rc==SQLITE_OK ) rc = SQLITE_ERROR;
174188         -  assert( *ppVtab==0 );
174189         -  assert( pRtree->nBusy==1 );
174190         -  rtreeRelease(pRtree);
       173325  +  if( rc==SQLITE_OK ){
       173326  +    if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
       173327  +      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
       173328  +    }else{
       173329  +      char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
       173330  +      char *zTmp;
       173331  +      int ii;
       173332  +      for(ii=4; zSql && ii<argc; ii++){
       173333  +        zTmp = zSql;
       173334  +        zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
       173335  +        sqlite3_free(zTmp);
       173336  +      }
       173337  +      if( zSql ){
       173338  +        zTmp = zSql;
       173339  +        zSql = sqlite3_mprintf("%s);", zTmp);
       173340  +        sqlite3_free(zTmp);
       173341  +      }
       173342  +      if( !zSql ){
       173343  +        rc = SQLITE_NOMEM;
       173344  +      }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
       173345  +        *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
       173346  +      }
       173347  +      sqlite3_free(zSql);
       173348  +    }
       173349  +  }
       173350  +
       173351  +  if( rc==SQLITE_OK ){
       173352  +    *ppVtab = (sqlite3_vtab *)pRtree;
       173353  +  }else{
       173354  +    assert( *ppVtab==0 );
       173355  +    assert( pRtree->nBusy==1 );
       173356  +    rtreeRelease(pRtree);
       173357  +  }
174191 173358     return rc;
174192 173359   }
174193 173360   
174194 173361   
174195 173362   /*
174196 173363   ** Implementation of a scalar function that decodes r-tree nodes to
174197 173364   ** human readable strings. This can be used for debugging and analysis.
................................................................................
174412 173579   
174413 173580   /*
174414 173581   ** This function is used to check that the %_parent (if bLeaf==0) or %_rowid
174415 173582   ** (if bLeaf==1) table contains a specified entry. The schemas of the
174416 173583   ** two tables are:
174417 173584   **
174418 173585   **   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
174419         -**   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER, ...)
       173586  +**   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
174420 173587   **
174421 173588   ** In both cases, this function checks that there exists an entry with
174422 173589   ** IPK value iKey and the second column set to iVal.
174423 173590   **
174424 173591   */
174425 173592   static void rtreeCheckMapping(
174426 173593     RtreeCheck *pCheck,             /* RtreeCheck object */
................................................................................
174427 173594     int bLeaf,                      /* True for a leaf cell, false for interior */
174428 173595     i64 iKey,                       /* Key for mapping */
174429 173596     i64 iVal                        /* Expected value for mapping */
174430 173597   ){
174431 173598     int rc;
174432 173599     sqlite3_stmt *pStmt;
174433 173600     const char *azSql[2] = {
174434         -    "SELECT parentnode FROM %Q.'%q_parent' WHERE nodeno=?1",
174435         -    "SELECT nodeno FROM %Q.'%q_rowid' WHERE rowid=?1"
       173601  +    "SELECT parentnode FROM %Q.'%q_parent' WHERE nodeno=?",
       173602  +    "SELECT nodeno FROM %Q.'%q_rowid' WHERE rowid=?"
174436 173603     };
174437 173604   
174438 173605     assert( bLeaf==0 || bLeaf==1 );
174439 173606     if( pCheck->aCheckMapping[bLeaf]==0 ){
174440 173607       pCheck->aCheckMapping[bLeaf] = rtreeCheckPrepare(pCheck,
174441 173608           azSql[bLeaf], pCheck->zDb, pCheck->zTab
174442 173609       );
................................................................................
174612 173779     const char *zDb,                /* Name of db ("main", "temp" etc.) */
174613 173780     const char *zTab,               /* Name of rtree table to check */
174614 173781     char **pzReport                 /* OUT: sqlite3_malloc'd report text */
174615 173782   ){
174616 173783     RtreeCheck check;               /* Common context for various routines */
174617 173784     sqlite3_stmt *pStmt = 0;        /* Used to find column count of rtree table */
174618 173785     int bEnd = 0;                   /* True if transaction should be closed */
174619         -  int nAux = 0;                   /* Number of extra columns. */
174620 173786   
174621 173787     /* Initialize the context object */
174622 173788     memset(&check, 0, sizeof(check));
174623 173789     check.db = db;
174624 173790     check.zDb = zDb;
174625 173791     check.zTab = zTab;
174626 173792   
................................................................................
174628 173794     ** to ensure that the queries run as part of this integrity-check operate
174629 173795     ** on a consistent snapshot.  */
174630 173796     if( sqlite3_get_autocommit(db) ){
174631 173797       check.rc = sqlite3_exec(db, "BEGIN", 0, 0, 0);
174632 173798       bEnd = 1;
174633 173799     }
174634 173800   
174635         -  /* Find the number of auxiliary columns */
174636         -  if( check.rc==SQLITE_OK ){
174637         -    pStmt = rtreeCheckPrepare(&check, "SELECT * FROM %Q.'%q_rowid'", zDb, zTab);
174638         -    if( pStmt ){
174639         -      nAux = sqlite3_column_count(pStmt) - 2;
174640         -      sqlite3_finalize(pStmt);
174641         -    }
174642         -    check.rc = SQLITE_OK;
174643         -  }
174644         -
174645 173801     /* Find number of dimensions in the rtree table. */
174646 173802     pStmt = rtreeCheckPrepare(&check, "SELECT * FROM %Q.%Q", zDb, zTab);
174647 173803     if( pStmt ){
174648 173804       int rc;
174649         -    check.nDim = (sqlite3_column_count(pStmt) - 1 - nAux) / 2;
       173805  +    check.nDim = (sqlite3_column_count(pStmt) - 1) / 2;
174650 173806       if( check.nDim<1 ){
174651 173807         rtreeCheckAppendMsg(&check, "Schema corrupt or not an rtree");
174652 173808       }else if( SQLITE_ROW==sqlite3_step(pStmt) ){
174653 173809         check.bInt = (sqlite3_column_type(pStmt, 1)==SQLITE_INTEGER);
174654 173810       }
174655 173811       rc = sqlite3_finalize(pStmt);
174656 173812       if( rc!=SQLITE_CORRUPT ) check.rc = rc;
................................................................................
176492 175648   **
176493 175649   ** RBU_STATE_COOKIE:
176494 175650   **   Valid if STAGE==1. The current change-counter cookie value in the 
176495 175651   **   target db file.
176496 175652   **
176497 175653   ** RBU_STATE_OALSZ:
176498 175654   **   Valid if STAGE==1. The size in bytes of the *-oal file.
176499         -**
176500         -** RBU_STATE_DATATBL:
176501         -**   Only valid if STAGE==1. The RBU database name of the table 
176502         -**   currently being read.
176503 175655   */
176504 175656   #define RBU_STATE_STAGE        1
176505 175657   #define RBU_STATE_TBL          2
176506 175658   #define RBU_STATE_IDX          3
176507 175659   #define RBU_STATE_ROW          4
176508 175660   #define RBU_STATE_PROGRESS     5
176509 175661   #define RBU_STATE_CKPT         6
176510 175662   #define RBU_STATE_COOKIE       7
176511 175663   #define RBU_STATE_OALSZ        8
176512 175664   #define RBU_STATE_PHASEONESTEP 9
176513         -#define RBU_STATE_DATATBL     10
176514 175665   
176515 175666   #define RBU_STAGE_OAL         1
176516 175667   #define RBU_STAGE_MOVE        2
176517 175668   #define RBU_STAGE_CAPTURE     3
176518 175669   #define RBU_STAGE_CKPT        4
176519 175670   #define RBU_STAGE_DONE        5
176520 175671   
................................................................................
176549 175700   
176550 175701   /*
176551 175702   ** A structure to store values read from the rbu_state table in memory.
176552 175703   */
176553 175704   struct RbuState {
176554 175705     int eStage;
176555 175706     char *zTbl;
176556         -  char *zDataTbl;
176557 175707     char *zIdx;
176558 175708     i64 iWalCksum;
176559 175709     int nRow;
176560 175710     i64 nProgress;
176561 175711     u32 iCookie;
176562 175712     i64 iOalSz;
176563 175713     i64 nPhaseOneStep;
................................................................................
178613 177763   
178614 177764   /*
178615 177765   ** Free an RbuState object allocated by rbuLoadState().
178616 177766   */
178617 177767   static void rbuFreeState(RbuState *p){
178618 177768     if( p ){
178619 177769       sqlite3_free(p->zTbl);
178620         -    sqlite3_free(p->zDataTbl);
178621 177770       sqlite3_free(p->zIdx);
178622 177771       sqlite3_free(p);
178623 177772     }
178624 177773   }
178625 177774   
178626 177775   /*
178627 177776   ** Allocate an RbuState object and load the contents of the rbu_state 
................................................................................
178684 177833           pRet->iOalSz = (u32)sqlite3_column_int64(pStmt, 1);
178685 177834           break;
178686 177835   
178687 177836         case RBU_STATE_PHASEONESTEP:
178688 177837           pRet->nPhaseOneStep = sqlite3_column_int64(pStmt, 1);
178689 177838           break;
178690 177839   
178691         -      case RBU_STATE_DATATBL:
178692         -        pRet->zDataTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
178693         -        break;
178694         -
178695 177840         default:
178696 177841           rc = SQLITE_CORRUPT;
178697 177842           break;
178698 177843       }
178699 177844     }
178700 177845     rc2 = sqlite3_finalize(pStmt);
178701 177846     if( rc==SQLITE_OK ) rc = rc2;
................................................................................
179462 178607             "(%d, %Q), "
179463 178608             "(%d, %Q), "
179464 178609             "(%d, %d), "
179465 178610             "(%d, %d), "
179466 178611             "(%d, %lld), "
179467 178612             "(%d, %lld), "
179468 178613             "(%d, %lld), "
179469         -          "(%d, %lld), "
179470         -          "(%d, %Q)  ",
       178614  +          "(%d, %lld) ",
179471 178615             p->zStateDb,
179472 178616             RBU_STATE_STAGE, eStage,
179473 178617             RBU_STATE_TBL, p->objiter.zTbl, 
179474 178618             RBU_STATE_IDX, p->objiter.zIdx, 
179475 178619             RBU_STATE_ROW, p->nStep, 
179476 178620             RBU_STATE_PROGRESS, p->nProgress,
179477 178621             RBU_STATE_CKPT, p->iWalCksum,
179478 178622             RBU_STATE_COOKIE, (i64)pFd->iCookie,
179479 178623             RBU_STATE_OALSZ, p->iOalSz,
179480         -          RBU_STATE_PHASEONESTEP, p->nPhaseOneStep,
179481         -          RBU_STATE_DATATBL, p->objiter.zDataTbl
       178624  +          RBU_STATE_PHASEONESTEP, p->nPhaseOneStep
179482 178625         )
179483 178626       );
179484 178627       assert( pInsert==0 || rc==SQLITE_OK );
179485 178628   
179486 178629       if( rc==SQLITE_OK ){
179487 178630         sqlite3_step(pInsert);
179488 178631         rc = sqlite3_finalize(pInsert);
................................................................................
179730 178873     assert( p->rc==SQLITE_OK );
179731 178874     if( pState->zTbl ){
179732 178875       RbuObjIter *pIter = &p->objiter;
179733 178876       int rc = SQLITE_OK;
179734 178877   
179735 178878       while( rc==SQLITE_OK && pIter->zTbl && (pIter->bCleanup 
179736 178879          || rbuStrCompare(pIter->zIdx, pState->zIdx)
179737         -       || (pState->zDataTbl==0 && rbuStrCompare(pIter->zTbl, pState->zTbl))
179738         -       || (pState->zDataTbl && rbuStrCompare(pIter->zDataTbl, pState->zDataTbl))
       178880  +       || rbuStrCompare(pIter->zTbl, pState->zTbl) 
179739 178881       )){
179740 178882         rc = rbuObjIterNext(p, pIter);
179741 178883       }
179742 178884   
179743 178885       if( rc==SQLITE_OK && !pIter->zTbl ){
179744 178886         rc = SQLITE_ERROR;
179745 178887         p->zErrmsg = sqlite3_mprintf("rbu_state mismatch error");
................................................................................
189850 188992           if( p->zRoot ){
189851 188993             jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
189852 188994           }else{
189853 188995             jsonAppendChar(&x, '$');
189854 188996           }
189855 188997           if( p->eType==JSON_ARRAY ){
189856 188998             jsonPrintf(30, &x, "[%d]", p->iRowid);
189857         -        }else if( p->eType==JSON_OBJECT ){
       188999  +        }else{
189858 189000             jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
189859 189001           }
189860 189002         }
189861 189003         jsonResult(&x);
189862 189004         break;
189863 189005       }
189864 189006       case JEACH_PATH: {
................................................................................
207581 206723   static void fts5SourceIdFunc(
207582 206724     sqlite3_context *pCtx,          /* Function call context */
207583 206725     int nArg,                       /* Number of args */
207584 206726     sqlite3_value **apUnused        /* Function arguments */
207585 206727   ){
207586 206728     assert( nArg==0 );
207587 206729     UNUSED_PARAM2(nArg, apUnused);
207588         -  sqlite3_result_text(pCtx, "fts5: 2018-06-04 19:24:41 c7ee0833225bfd8c5ec2f9bf62b97c4e04d03bd9566366d5221ac8fb199a87ca", -1, SQLITE_TRANSIENT);
       206730  +  sqlite3_result_text(pCtx, "fts5: 2018-04-26 12:27:03 368c14da868a843767344f6cc17c499fddd83244c0510337ed9a918e64ee2413", -1, SQLITE_TRANSIENT);
207589 206731   }
207590 206732   
207591 206733   static int fts5Init(sqlite3 *db){
207592 206734     static const sqlite3_module fts5Mod = {
207593 206735       /* iVersion      */ 2,
207594 206736       /* xCreate       */ fts5CreateMethod,
207595 206737       /* xConnect      */ fts5ConnectMethod,
................................................................................
211851 210993   #endif
211852 210994     return rc;
211853 210995   }
211854 210996   #endif /* SQLITE_CORE */
211855 210997   #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_STMTVTAB) */
211856 210998   
211857 210999   /************** End of stmt.c ************************************************/
211858         -#if __LINE__!=211858
       211000  +#if __LINE__!=211000
211859 211001   #undef SQLITE_SOURCE_ID
211860         -#define SQLITE_SOURCE_ID      "2018-06-04 19:24:41 c7ee0833225bfd8c5ec2f9bf62b97c4e04d03bd9566366d5221ac8fb199aalt2"
       211002  +#define SQLITE_SOURCE_ID      "2018-04-26 18:34:26 9fd0faf517993587d2f54212638545fc85fbbc84a031bcfae8c1e5894825alt2"
211861 211003   #endif
211862 211004   /* Return the source-id for this library */
211863 211005   SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
211864 211006   /************************** End of sqlite3.c ******************************/

Changes to src/sqlite3.h.

   121    121   **
   122    122   ** See also: [sqlite3_libversion()],
   123    123   ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
   124    124   ** [sqlite_version()] and [sqlite_source_id()].
   125    125   */
   126    126   #define SQLITE_VERSION        "3.24.0"
   127    127   #define SQLITE_VERSION_NUMBER 3024000
   128         -#define SQLITE_SOURCE_ID      "2018-06-04 19:24:41 c7ee0833225bfd8c5ec2f9bf62b97c4e04d03bd9566366d5221ac8fb199a87ca"
          128  +#define SQLITE_SOURCE_ID      "2018-04-26 18:34:26 9fd0faf517993587d2f54212638545fc85fbbc84a031bcfae8c1e5894825d83b"
   129    129   
   130    130   /*
   131    131   ** CAPI3REF: Run-Time Library Version Numbers
   132    132   ** KEYWORDS: sqlite3_version sqlite3_sourceid
   133    133   **
   134    134   ** These interfaces provide the same information as the [SQLITE_VERSION],
   135    135   ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
................................................................................
   500    500   #define SQLITE_IOERR_CONVPATH          (SQLITE_IOERR | (26<<8))
   501    501   #define SQLITE_IOERR_VNODE             (SQLITE_IOERR | (27<<8))
   502    502   #define SQLITE_IOERR_AUTH              (SQLITE_IOERR | (28<<8))
   503    503   #define SQLITE_IOERR_BEGIN_ATOMIC      (SQLITE_IOERR | (29<<8))
   504    504   #define SQLITE_IOERR_COMMIT_ATOMIC     (SQLITE_IOERR | (30<<8))
   505    505   #define SQLITE_IOERR_ROLLBACK_ATOMIC   (SQLITE_IOERR | (31<<8))
   506    506   #define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))
   507         -#define SQLITE_LOCKED_VTAB             (SQLITE_LOCKED |  (2<<8))
   508    507   #define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))
   509    508   #define SQLITE_BUSY_SNAPSHOT           (SQLITE_BUSY   |  (2<<8))
   510    509   #define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
   511    510   #define SQLITE_CANTOPEN_ISDIR          (SQLITE_CANTOPEN | (2<<8))
   512    511   #define SQLITE_CANTOPEN_FULLPATH       (SQLITE_CANTOPEN | (3<<8))
   513    512   #define SQLITE_CANTOPEN_CONVPATH       (SQLITE_CANTOPEN | (4<<8))
   514    513   #define SQLITE_CORRUPT_VTAB            (SQLITE_CORRUPT | (1<<8))
   515         -#define SQLITE_CORRUPT_SEQUENCE        (SQLITE_CORRUPT | (2<<8))
   516    514   #define SQLITE_READONLY_RECOVERY       (SQLITE_READONLY | (1<<8))
   517    515   #define SQLITE_READONLY_CANTLOCK       (SQLITE_READONLY | (2<<8))
   518    516   #define SQLITE_READONLY_ROLLBACK       (SQLITE_READONLY | (3<<8))
   519    517   #define SQLITE_READONLY_DBMOVED        (SQLITE_READONLY | (4<<8))
   520    518   #define SQLITE_READONLY_CANTINIT       (SQLITE_READONLY | (5<<8))
   521    519   #define SQLITE_READONLY_DIRECTORY      (SQLITE_READONLY | (6<<8))
   522    520   #define SQLITE_ABORT_ROLLBACK          (SQLITE_ABORT | (2<<8))
................................................................................
  2110   2108   ** behavior. The first parameter passed to this operation is an integer -
  2111   2109   ** positive to enable output for trigger programs, or zero to disable it,
  2112   2110   ** or negative to leave the setting unchanged.
  2113   2111   ** The second parameter is a pointer to an integer into which is written 
  2114   2112   ** 0 or 1 to indicate whether output-for-triggers has been disabled - 0 if 
  2115   2113   ** it is not disabled, 1 if it is.  
  2116   2114   ** </dd>
  2117         -**
  2118         -** <dt>SQLITE_DBCONFIG_RESET_DATABASE</dt>
  2119         -** <dd> Set the SQLITE_DBCONFIG_RESET_DATABASE flag and then run
  2120         -** [VACUUM] in order to reset a database back to an empty database
  2121         -** with no schema and no content. The following process works even for
  2122         -** a badly corrupted database file:
  2123         -** <ol>
  2124         -** <li> sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0);
  2125         -** <li> [sqlite3_exec](db, "[VACUUM]", 0, 0, 0);
  2126         -** <li> sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0);
  2127         -** </ol>
  2128         -** Because resetting a database is destructive and irreversible, the
  2129         -** process requires the use of this obscure API and multiple steps to help
  2130         -** ensure that it does not happen by accident.
  2131         -** </dd>
  2132   2115   ** </dl>
  2133   2116   */
  2134   2117   #define SQLITE_DBCONFIG_MAINDBNAME            1000 /* const char* */
  2135   2118   #define SQLITE_DBCONFIG_LOOKASIDE             1001 /* void* int int */
  2136   2119   #define SQLITE_DBCONFIG_ENABLE_FKEY           1002 /* int int* */
  2137   2120   #define SQLITE_DBCONFIG_ENABLE_TRIGGER        1003 /* int int* */
  2138   2121   #define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */
  2139   2122   #define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */
  2140   2123   #define SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      1006 /* int int* */
  2141   2124   #define SQLITE_DBCONFIG_ENABLE_QPSG           1007 /* int int* */
  2142   2125   #define SQLITE_DBCONFIG_TRIGGER_EQP           1008 /* int int* */
  2143         -#define SQLITE_DBCONFIG_RESET_DATABASE        1009 /* int int* */
  2144         -#define SQLITE_DBCONFIG_MAX                   1009 /* Largest DBCONFIG */
         2126  +#define SQLITE_DBCONFIG_MAX                   1008 /* Largest DBCONFIG */
  2145   2127   
  2146   2128   /*
  2147   2129   ** CAPI3REF: Enable Or Disable Extended Result Codes
  2148   2130   ** METHOD: sqlite3
  2149   2131   **
  2150   2132   ** ^The sqlite3_extended_result_codes() routine enables or disables the
  2151   2133   ** [extended result codes] feature of SQLite. ^The extended result
................................................................................
  5523   5505   ** using [sqlite3_free].
  5524   5506   ** Hence, if this variable is modified directly, either it should be
  5525   5507   ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  5526   5508   ** or else the use of the [data_store_directory pragma] should be avoided.
  5527   5509   */
  5528   5510   SQLITE_API SQLITE_EXTERN char *sqlite3_data_directory;
  5529   5511   
  5530         -/*
  5531         -** CAPI3REF: Win32 Specific Interface
  5532         -**
  5533         -** These interfaces are available only on Windows.  The
  5534         -** [sqlite3_win32_set_directory] interface is used to set the value associated
  5535         -** with the [sqlite3_temp_directory] or [sqlite3_data_directory] variable, to
  5536         -** zValue, depending on the value of the type parameter.  The zValue parameter
  5537         -** should be NULL to cause the previous value to be freed via [sqlite3_free];
  5538         -** a non-NULL value will be copied into memory obtained from [sqlite3_malloc]
  5539         -** prior to being used.  The [sqlite3_win32_set_directory] interface returns
  5540         -** [SQLITE_OK] to indicate success, [SQLITE_ERROR] if the type is unsupported,
  5541         -** or [SQLITE_NOMEM] if memory could not be allocated.  The value of the
  5542         -** [sqlite3_data_directory] variable is intended to act as a replacement for
  5543         -** the current directory on the sub-platforms of Win32 where that concept is
  5544         -** not present, e.g. WinRT and UWP.  The [sqlite3_win32_set_directory8] and
  5545         -** [sqlite3_win32_set_directory16] interfaces behave exactly the same as the
  5546         -** sqlite3_win32_set_directory interface except the string parameter must be
  5547         -** UTF-8 or UTF-16, respectively.
  5548         -*/
  5549         -SQLITE_API int sqlite3_win32_set_directory(
  5550         -  unsigned long type, /* Identifier for directory being set or reset */
  5551         -  void *zValue        /* New value for directory being set or reset */
  5552         -);
  5553         -SQLITE_API int sqlite3_win32_set_directory8(unsigned long type, const char *zValue);
  5554         -SQLITE_API int sqlite3_win32_set_directory16(unsigned long type, const void *zValue);
  5555         -
  5556         -/*
  5557         -** CAPI3REF: Win32 Directory Types
  5558         -**
  5559         -** These macros are only available on Windows.  They define the allowed values
  5560         -** for the type argument to the [sqlite3_win32_set_directory] interface.
  5561         -*/
  5562         -#define SQLITE_WIN32_DATA_DIRECTORY_TYPE  1
  5563         -#define SQLITE_WIN32_TEMP_DIRECTORY_TYPE  2
  5564         -
  5565   5512   /*
  5566   5513   ** CAPI3REF: Test For Auto-Commit Mode
  5567   5514   ** KEYWORDS: {autocommit mode}
  5568   5515   ** METHOD: sqlite3
  5569   5516   **
  5570   5517   ** ^The sqlite3_get_autocommit() interface returns non-zero or
  5571   5518   ** zero if the given database connection is or is not in autocommit mode,
................................................................................
  6290   6237     int idxFlags;              /* Mask of SQLITE_INDEX_SCAN_* flags */
  6291   6238     /* Fields below are only available in SQLite 3.10.0 and later */
  6292   6239     sqlite3_uint64 colUsed;    /* Input: Mask of columns used by statement */
  6293   6240   };
  6294   6241   
  6295   6242   /*
  6296   6243   ** CAPI3REF: Virtual Table Scan Flags
  6297         -**
  6298         -** Virtual table implementations are allowed to set the 
  6299         -** [sqlite3_index_info].idxFlags field to some combination of
  6300         -** these bits.
  6301   6244   */
  6302   6245   #define SQLITE_INDEX_SCAN_UNIQUE      1     /* Scan visits at most 1 row */
  6303   6246   
  6304   6247   /*
  6305   6248   ** CAPI3REF: Virtual Table Constraint Operator Codes
  6306   6249   **
  6307   6250   ** These macros defined the allowed values for the
................................................................................
  7115   7058   ** parsing ambiguity.  For example, the statement
  7116   7059   ** "CREATE TABLE BEGIN(REPLACE,PRAGMA,END);" is accepted by SQLite, and
  7117   7060   ** creates a new table named "BEGIN" with three columns named
  7118   7061   ** "REPLACE", "PRAGMA", and "END".  Nevertheless, best practice is to avoid
  7119   7062   ** using keywords as identifiers.  Common techniques used to avoid keyword
  7120   7063   ** name collisions include:
  7121   7064   ** <ul>
  7122         -** <li> Put all identifier names inside double-quotes.  This is the official
         7065  +** <li> Put all indentifier names inside double-quotes.  This is the official
  7123   7066   **      SQL way to escape identifier names.
  7124   7067   ** <li> Put identifier names inside &#91;...&#93;.  This is not standard SQL,
  7125   7068   **      but it is what SQL Server does and so lots of programmers use this
  7126   7069   **      technique.
  7127   7070   ** <li> Begin every identifier with the letter "Z" as no SQL keywords start
  7128   7071   **      with "Z".
  7129   7072   ** <li> Include a digit somewhere in every identifier name.
................................................................................
  7134   7077   ** SQLite is compiled with the [-DSQLITE_OMIT_VACUUM] option.  Also,
  7135   7078   ** new keywords may be added to future releases of SQLite.
  7136   7079   */
  7137   7080   SQLITE_API int sqlite3_keyword_count(void);
  7138   7081   SQLITE_API int sqlite3_keyword_name(int,const char**,int*);
  7139   7082   SQLITE_API int sqlite3_keyword_check(const char*,int);
  7140   7083   
  7141         -/*
  7142         -** CAPI3REF: Dynamic String Object
  7143         -** KEYWORDS: {dynamic string}
  7144         -**
  7145         -** An instance of the sqlite3_str object contains a dynamically-sized
  7146         -** string under construction.
  7147         -**
  7148         -** The lifecycle of an sqlite3_str object is as follows:
  7149         -** <ol>
  7150         -** <li> ^The sqlite3_str object is created using [sqlite3_str_new()].
  7151         -** <li> ^Text is appended to the sqlite3_str object using various
  7152         -** methods, such as [sqlite3_str_appendf()].
  7153         -** <li> ^The sqlite3_str object is destroyed and the string it created
  7154         -** is returned using the [sqlite3_str_finish()] interface.
  7155         -** </ol>
  7156         -*/
  7157         -typedef struct sqlite3_str sqlite3_str;
  7158         -
  7159         -/*
  7160         -** CAPI3REF: Create A New Dynamic String Object
  7161         -** CONSTRUCTOR: sqlite3_str
  7162         -**
  7163         -** ^The [sqlite3_str_new(D)] interface allocates and initializes
  7164         -** a new [sqlite3_str] object.  To avoid memory leaks, the object returned by
  7165         -** [sqlite3_str_new()] must be freed by a subsequent call to 
  7166         -** [sqlite3_str_finish(X)].
  7167         -**
  7168         -** ^The [sqlite3_str_new(D)] interface always returns a pointer to a
  7169         -** valid [sqlite3_str] object, though in the event of an out-of-memory
  7170         -** error the returned object might be a special singleton that will
  7171         -** silently reject new text, always return SQLITE_NOMEM from 
  7172         -** [sqlite3_str_errcode()], always return 0 for 
  7173         -** [sqlite3_str_length()], and always return NULL from
  7174         -** [sqlite3_str_finish(X)].  It is always safe to use the value
  7175         -** returned by [sqlite3_str_new(D)] as the sqlite3_str parameter
  7176         -** to any of the other [sqlite3_str] methods.
  7177         -**
  7178         -** The D parameter to [sqlite3_str_new(D)] may be NULL.  If the
  7179         -** D parameter in [sqlite3_str_new(D)] is not NULL, then the maximum
  7180         -** length of the string contained in the [sqlite3_str] object will be
  7181         -** the value set for [sqlite3_limit](D,[SQLITE_LIMIT_LENGTH]) instead
  7182         -** of [SQLITE_MAX_LENGTH].
  7183         -*/
  7184         -SQLITE_API sqlite3_str *sqlite3_str_new(sqlite3*);
  7185         -
  7186         -/*
  7187         -** CAPI3REF: Finalize A Dynamic String
  7188         -** DESTRUCTOR: sqlite3_str
  7189         -**
  7190         -** ^The [sqlite3_str_finish(X)] interface destroys the sqlite3_str object X
  7191         -** and returns a pointer to a memory buffer obtained from [sqlite3_malloc64()]
  7192         -** that contains the constructed string.  The calling application should
  7193         -** pass the returned value to [sqlite3_free()] to avoid a memory leak.
  7194         -** ^The [sqlite3_str_finish(X)] interface may return a NULL pointer if any
  7195         -** errors were encountered during construction of the string.  ^The
  7196         -** [sqlite3_str_finish(X)] interface will also return a NULL pointer if the
  7197         -** string in [sqlite3_str] object X is zero bytes long.
  7198         -*/
  7199         -SQLITE_API char *sqlite3_str_finish(sqlite3_str*);
  7200         -
  7201         -/*
  7202         -** CAPI3REF: Add Content To A Dynamic String
  7203         -** METHOD: sqlite3_str
  7204         -**
  7205         -** These interfaces add content to an sqlite3_str object previously obtained
  7206         -** from [sqlite3_str_new()].
  7207         -**
  7208         -** ^The [sqlite3_str_appendf(X,F,...)] and 
  7209         -** [sqlite3_str_vappendf(X,F,V)] interfaces uses the [built-in printf]
  7210         -** functionality of SQLite to append formatted text onto the end of 
  7211         -** [sqlite3_str] object X.
  7212         -**
  7213         -** ^The [sqlite3_str_append(X,S,N)] method appends exactly N bytes from string S
  7214         -** onto the end of the [sqlite3_str] object X.  N must be non-negative.
  7215         -** S must contain at least N non-zero bytes of content.  To append a
  7216         -** zero-terminated string in its entirety, use the [sqlite3_str_appendall()]
  7217         -** method instead.
  7218         -**
  7219         -** ^The [sqlite3_str_appendall(X,S)] method appends the complete content of
  7220         -** zero-terminated string S onto the end of [sqlite3_str] object X.
  7221         -**
  7222         -** ^The [sqlite3_str_appendchar(X,N,C)] method appends N copies of the
  7223         -** single-byte character C onto the end of [sqlite3_str] object X.
  7224         -** ^This method can be used, for example, to add whitespace indentation.
  7225         -**
  7226         -** ^The [sqlite3_str_reset(X)] method resets the string under construction
  7227         -** inside [sqlite3_str] object X back to zero bytes in length.  
  7228         -**
  7229         -** These methods do not return a result code.  ^If an error occurs, that fact
  7230         -** is recorded in the [sqlite3_str] object and can be recovered by a
  7231         -** subsequent call to [sqlite3_str_errcode(X)].
  7232         -*/
  7233         -SQLITE_API void sqlite3_str_appendf(sqlite3_str*, const char *zFormat, ...);
  7234         -SQLITE_API void sqlite3_str_vappendf(sqlite3_str*, const char *zFormat, va_list);
  7235         -SQLITE_API void sqlite3_str_append(sqlite3_str*, const char *zIn, int N);
  7236         -SQLITE_API void sqlite3_str_appendall(sqlite3_str*, const char *zIn);
  7237         -SQLITE_API void sqlite3_str_appendchar(sqlite3_str*, int N, char C);
  7238         -SQLITE_API void sqlite3_str_reset(sqlite3_str*);
  7239         -
  7240         -/*
  7241         -** CAPI3REF: Status Of A Dynamic String
  7242         -** METHOD: sqlite3_str
  7243         -**
  7244         -** These interfaces return the current status of an [sqlite3_str] object.
  7245         -**
  7246         -** ^If any prior errors have occurred while constructing the dynamic string
  7247         -** in sqlite3_str X, then the [sqlite3_str_errcode(X)] method will return
  7248         -** an appropriate error code.  ^The [sqlite3_str_errcode(X)] method returns
  7249         -** [SQLITE_NOMEM] following any out-of-memory error, or
  7250         -** [SQLITE_TOOBIG] if the size of the dynamic string exceeds
  7251         -** [SQLITE_MAX_LENGTH], or [SQLITE_OK] if there have been no errors.
  7252         -**
  7253         -** ^The [sqlite3_str_length(X)] method returns the current length, in bytes,
  7254         -** of the dynamic string under construction in [sqlite3_str] object X.
  7255         -** ^The length returned by [sqlite3_str_length(X)] does not include the
  7256         -** zero-termination byte.
  7257         -**
  7258         -** ^The [sqlite3_str_value(X)] method returns a pointer to the current
  7259         -** content of the dynamic string under construction in X.  The value
  7260         -** returned by [sqlite3_str_value(X)] is managed by the sqlite3_str object X
  7261         -** and might be freed or altered by any subsequent method on the same
  7262         -** [sqlite3_str] object.  Applications must not used the pointer returned
  7263         -** [sqlite3_str_value(X)] after any subsequent method call on the same
  7264         -** object.  ^Applications may change the content of the string returned
  7265         -** by [sqlite3_str_value(X)] as long as they do not write into any bytes
  7266         -** outside the range of 0 to [sqlite3_str_length(X)] and do not read or
  7267         -** write any byte after any subsequent sqlite3_str method call.
  7268         -*/
  7269         -SQLITE_API int sqlite3_str_errcode(sqlite3_str*);
  7270         -SQLITE_API int sqlite3_str_length(sqlite3_str*);
  7271         -SQLITE_API char *sqlite3_str_value(sqlite3_str*);
  7272         -
  7273   7084   /*
  7274   7085   ** CAPI3REF: SQLite Runtime Status
  7275   7086   **
  7276   7087   ** ^These interfaces are used to retrieve runtime status information
  7277   7088   ** about the performance of SQLite, and optionally to reset various
  7278   7089   ** highwater marks.  ^The first argument is an integer code for
  7279   7090   ** the specific parameter to measure.  ^(Recognized integer codes
................................................................................
  8535   8346   /*
  8536   8347   ** CAPI3REF: Determine If Virtual Table Column Access Is For UPDATE
  8537   8348   **
  8538   8349   ** If the sqlite3_vtab_nochange(X) routine is called within the [xColumn]
  8539   8350   ** method of a [virtual table], then it returns true if and only if the
  8540   8351   ** column is being fetched as part of an UPDATE operation during which the
  8541   8352   ** column value will not change.  Applications might use this to substitute
  8542         -** a return value that is less expensive to compute and that the corresponding
  8543         -** [xUpdate] method understands as a "no-change" value.
         8353  +** a lighter-weight value to return that the corresponding [xUpdate] method
         8354  +** understands as a "no-change" value.
  8544   8355   **
  8545   8356   ** If the [xColumn] method calls sqlite3_vtab_nochange() and finds that
  8546         -** the column is not changed by the UPDATE statement, then the xColumn
         8357  +** the column is not changed by the UPDATE statement, they the xColumn
  8547   8358   ** method can optionally return without setting a result, without calling
  8548   8359   ** any of the [sqlite3_result_int|sqlite3_result_xxxxx() interfaces].
  8549   8360   ** In that case, [sqlite3_value_nochange(X)] will return true for the
  8550   8361   ** same column in the [xUpdate] method.
  8551   8362   */
  8552   8363   SQLITE_API int sqlite3_vtab_nochange(sqlite3_context*);
  8553   8364   
................................................................................
  9034   8845   ** to the contiguous memory representation of the database that SQLite
  9035   8846   ** is currently using for that database, or NULL if the no such contiguous
  9036   8847   ** memory representation of the database exists.  A contiguous memory
  9037   8848   ** representation of the database will usually only exist if there has
  9038   8849   ** been a prior call to [sqlite3_deserialize(D,S,...)] with the same
  9039   8850   ** values of D and S.
  9040   8851   ** The size of the database is written into *P even if the 
  9041         -** SQLITE_SERIALIZE_NOCOPY bit is set but no contiguous copy
         8852  +** SQLITE_SERIALIZE_NOCOPY bit is set but no contigious copy
  9042   8853   ** of the database exists.
  9043   8854   **
  9044   8855   ** A call to sqlite3_serialize(D,S,P,F) might return NULL even if the
  9045   8856   ** SQLITE_SERIALIZE_NOCOPY bit is omitted from argument F if a memory
  9046   8857   ** allocation error occurs.
  9047   8858   **
  9048   8859   ** This interface is only available if SQLite is compiled with the

Changes to src/timeline.c.

   770    770     if( whiteFg ){
   771    771       /* Make the color lighter */
   772    772       static const unsigned int t = 215;
   773    773       if( mx<t ) for(i=0; i<3; i++) x[i] += t - mx;
   774    774     }else{
   775    775       /* Make the color darker */
   776    776       static const unsigned int t = 128;
   777         -    if( mx>t ){
   778         -      for(i=0; i<3; i++){
   779         -        x[i] = x[i]>=mx-t ? x[i] - (mx-t) : 0;
   780         -      }
   781         -    }
          777  +    if( mx>t ) for(i=0; i<3; i++) x[i] -= mx - t;
   782    778     }
   783    779     sqlite3_snprintf(sizeof(zRes),zRes,"#%02x%02x%02x",x[0],x[1],x[2]);
   784    780     return zRes;
   785    781   }
   786    782   
   787    783   /*
   788    784   ** Generate all of the necessary javascript to generate a timeline
................................................................................
  1116   1112         glob_expr("filename.name", zChng));
  1117   1113   }
  1118   1114   static void addFileGlobDescription(
  1119   1115     const char *zChng,        /* The filename GLOB list */
  1120   1116     Blob *pDescription        /* Result description */
  1121   1117   ){
  1122   1118     if( zChng==0 || zChng[0]==0 ) return;
  1123         -  blob_appendf(pDescription, " that include changes to files matching '%h'",
         1119  +  blob_appendf(pDescription, " that include changes to files matching %Q",
  1124   1120                  zChng);
  1125   1121   }
  1126   1122   
  1127   1123   /*
  1128   1124   ** Tag match expression type code.
  1129   1125   */
  1130   1126   typedef enum {
................................................................................
  1419   1415     const char *zSearch = P("s");      /* Search string */
  1420   1416     const char *zUses = P("uf");       /* Only show check-ins hold this file */
  1421   1417     const char *zYearMonth = P("ym");  /* Show check-ins for the given YYYY-MM */
  1422   1418     const char *zYearWeek = P("yw");   /* Check-ins for YYYY-WW (week-of-year) */
  1423   1419     char *zYearWeekStart = 0;          /* YYYY-MM-DD for start of YYYY-WW */
  1424   1420     const char *zDay = P("ymd");       /* Check-ins for the day YYYY-MM-DD */
  1425   1421     const char *zNDays = P("days");    /* Show events over the previous N days */
  1426         -  int nDays = 0;                     /* Numeric value for zNDays */
         1422  +  int nDays;                         /* Numeric value for zNDays */
  1427   1423     const char *zChng = P("chng");     /* List of GLOBs for files that changed */
  1428   1424     int useDividers = P("nd")==0;      /* Show dividers if "nd" is missing */
  1429   1425     int renameOnly = P("namechng")!=0; /* Show only check-ins that rename files */
  1430   1426     int forkOnly = PB("forks");        /* Show only forks and their children */
  1431   1427     int bisectOnly = PB("bisect");     /* Show the check-ins of the bisect */
  1432   1428     int tmFlags = 0;                   /* Timeline flags */
  1433   1429     const char *zThisTag = 0;          /* Suppress links to this tag */

Changes to win/include/dirent.h.

   295    295   static int _wclosedir (_WDIR *dirp);
   296    296   
   297    297   static void rewinddir (DIR* dirp);
   298    298   static void _wrewinddir (_WDIR* dirp);
   299    299   
   300    300   static int scandir (const char *dirname, struct dirent ***namelist,
   301    301       int (*filter)(const struct dirent*),
   302         -    int (*compare)(const struct dirent**, const struct dirent**));
          302  +    int (*compare)(const void *, const void *));
   303    303   
   304    304   static int alphasort (const struct dirent **a, const struct dirent **b);
   305    305   
   306    306   static int versionsort (const struct dirent **a, const struct dirent **b);
   307    307   
   308    308   
   309    309   /* For compatibility with Symbian */
................................................................................
   363    363           dirp->handle = INVALID_HANDLE_VALUE;
   364    364           dirp->patt = NULL;
   365    365           dirp->cached = 0;
   366    366   
   367    367           /* Compute the length of full path plus zero terminator
   368    368            *
   369    369            * Note that on WinRT there's no way to convert relative paths
   370         -         * into absolute paths, so just assume it is an absolute path.
          370  +         * into absolute paths, so just assume its an absolute path.
   371    371            */
   372    372   #       if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP)
   373    373               n = wcslen(dirname);
   374    374   #       else
   375    375               n = GetFullPathNameW (dirname, 0, NULL, NULL);
   376    376   #       endif
   377    377   
................................................................................
   381    381   
   382    382               /*
   383    383                * Convert relative directory name to an absolute one.  This
   384    384                * allows rewinddir() to function correctly even when current
   385    385                * working directory is changed between opendir() and rewinddir().
   386    386                *
   387    387                * Note that on WinRT there's no way to convert relative paths
   388         -             * into absolute paths, so just assume it is an absolute path.
          388  +             * into absolute paths, so just assume its an absolute path.
   389    389                */
   390    390   #           if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP)
   391    391                   wcsncpy_s(dirp->patt, n+1, dirname, n);
   392    392   #           else
   393    393                   n = GetFullPathNameW (dirname, n, dirp->patt, NULL);
   394    394   #           endif
   395    395               if (n > 0) {
................................................................................
   448    448   
   449    449       return dirp;
   450    450   }
   451    451   
   452    452   /*
   453    453    * Read next directory entry.
   454    454    *
   455         - * Returns pointer to static directory entry which may be overwritten by
          455  + * Returns pointer to static directory entry which may be overwritted by
   456    456    * subsequent calls to _wreaddir().
   457    457    */
   458    458   static struct _wdirent*
   459    459   _wreaddir(
   460    460       _WDIR *dirp)
   461    461   {
   462    462       struct _wdirent *entry;
................................................................................
   639    639       } else if (dirp->handle != INVALID_HANDLE_VALUE) {
   640    640   
   641    641           /* Get the next directory entry from stream */
   642    642           if (FindNextFileW (dirp->handle, &dirp->data) != FALSE) {
   643    643               /* Got a file */
   644    644               p = &dirp->data;
   645    645           } else {
   646         -            /* The very last entry has been processed or an error occurred */
          646  +            /* The very last entry has been processed or an error occured */
   647    647               FindClose (dirp->handle);
   648    648               dirp->handle = INVALID_HANDLE_VALUE;
   649    649               p = NULL;
   650    650           }
   651    651   
   652    652       } else {
   653    653   
................................................................................
   738    738       /* Return pointer to statically allocated directory entry */
   739    739       return entry;
   740    740   }
   741    741   
   742    742   /*
   743    743    * Read next directory entry into called-allocated buffer.
   744    744    *
   745         - * Returns zero on success.  If the end of directory stream is reached, then
          745  + * Returns zero on sucess.  If the end of directory stream is reached, then
   746    746    * sets result to NULL and returns zero.
   747    747    */
   748    748   static int
   749    749   readdir_r(
   750    750       DIR *dirp,
   751    751       struct dirent *entry,
   752    752       struct dirent **result)
................................................................................
   800    800               entry->d_off = 0;
   801    801               entry->d_reclen = sizeof (struct dirent);
   802    802   
   803    803           } else {
   804    804   
   805    805               /*
   806    806                * Cannot convert file name to multi-byte string so construct
   807         -             * an erroneous directory entry and return that.  Note that
          807  +             * an errornous directory entry and return that.  Note that
   808    808                * we cannot return NULL as that would stop the processing
   809    809                * of directory entries completely.
   810    810                */
   811    811               entry->d_name[0] = '?';
   812    812               entry->d_name[1] = '\0';
   813    813               entry->d_namlen = 1;
   814    814               entry->d_type = DT_UNKNOWN;
................................................................................
   873    873    * Scan directory for entries.
   874    874    */
   875    875   static int
   876    876   scandir(
   877    877       const char *dirname,
   878    878       struct dirent ***namelist,
   879    879       int (*filter)(const struct dirent*),
   880         -    int (*compare)(const struct dirent**, const struct dirent**))
          880  +    int (*compare)(const void*, const void*))
   881    881   {
   882    882       struct dirent **files = NULL;
   883    883       size_t size = 0;
   884    884       size_t allocated = 0;
   885    885       const size_t init_size = 1;
   886    886       DIR *dir = NULL;
   887    887       struct dirent *entry;
................................................................................
   933    933                       break;
   934    934                   }
   935    935               }
   936    936   
   937    937               /* Read directory entry to temporary area */
   938    938               if (readdir_r (dir, tmp, &entry) == /*OK*/0) {
   939    939   
   940         -                /* Did we get an entry? */
          940  +                /* Did we got an entry? */
   941    941                   if (entry != NULL) {
   942    942                       int pass;
   943    943   
   944    944                       /* Determine whether to include the entry in result */
   945    945                       if (filter) {
   946    946                           /* Let the filter function decide */
   947    947                           pass = filter (tmp);
................................................................................
   961    961   
   962    962                   } else {
   963    963   
   964    964                       /*
   965    965                        * End of directory stream reached => sort entries and
   966    966                        * exit.
   967    967                        */
   968         -                    qsort (files, size, sizeof (void*),
   969         -                        (int (*) (const void*, const void*)) compare);
          968  +                    qsort (files, size, sizeof (void*), compare);
   970    969                       break;
   971    970   
   972    971                   }
   973    972   
   974    973               } else {
   975    974                   /* Error reading directory entry */
   976    975                   result = /*Error*/ -1;
................................................................................
  1057   1056           if (wcstr  &&  sizeInWords) {
  1058   1057               if (n >= sizeInWords) {
  1059   1058                   n = sizeInWords - 1;
  1060   1059               }
  1061   1060               wcstr[n] = 0;
  1062   1061           }
  1063   1062   
  1064         -        /* Length of resulting multi-byte string WITH zero terminator */
         1063  +        /* Length of resuting multi-byte string WITH zero terminator */
  1065   1064           if (pReturnValue) {
  1066   1065               *pReturnValue = n + 1;
  1067   1066           }
  1068   1067   
  1069   1068           /* Success */
  1070   1069           error = 0;
  1071   1070   

Changes to www/fossil-v-git.wiki.

     6      6   you can easily [./inout.wiki | move your content]&#185;.
     7      7   
     8      8   Fossil and [http://git-scm.com | Git] are very similar in many respects,
     9      9   but they also have important differences.
    10     10   See the table below for
    11     11   a high-level summary and the text that follows for more details.
    12     12   
    13         -Keep in mind that you are reading this on a Fossil website, and though
    14         -we try to be fair, the information here
    15         -might be biased in favor of Fossil.  Ask around for second opinions from
    16         -people who have used <em>both</em> Fossil and Git.
           13  +Keep in mind that you are reading this on a Fossil website,
           14  +so the information here
           15  +might be biased in favor of Fossil.  Ask around with people who have
           16  +used both Fossil and Git for other opinions.
    17     17   
    18     18   &#185;<small><i>Git does not support
    19     19   wiki, tickets, or tech-notes, so those elements will not transfer when
    20     20   exporting from Fossil to Git.</i></small>
    21     21   
    22         -<h2>2.0 Differences Between Fossil And Git</h2>
    23         -
    24         -Differences between Fossil and Git are summarized by the following table,
    25         -with further description in the text that follows.
           22  +<h2>2.0 Executive Summary:</h2>
    26     23   
    27     24   <blockquote><table border=1 cellpadding=5 align=center>
    28     25   <tr><th width="50%">GIT</th><th width="50%">FOSSIL</th></tr>
    29     26   <tr><td>File versioning only</td>
    30     27       <td>Versioning, Tickets, Wiki, and Technotes</td></tr>
    31     28   <tr><td>Ad-hoc, pile-of-files key/value database</td>
    32     29       <td>Relational SQL database</td></tr>
................................................................................
    37     34   <tr><td>One check-out per repository</td>
    38     35       <td>Many check-outs per repository</td></tr>
    39     36   <tr><td>Remembers what you should have done</td>
    40     37       <td>Remembers what you actually did</td></tr>
    41     38   <tr><td>GPL</td><td>BSD</td></tr>
    42     39   </table></blockquote>
    43     40   
    44         -<h3>2.1 Feature Set</h3>
           41  +<h2>3.0 Discussion</h2>
           42  +
           43  +<h3>3.1 Feature Set</h3>
    45     44   
    46     45   Git provides file versioning services only, whereas Fossil adds
    47     46   integrated [./wikitheory.wiki | wiki],
    48     47   [./bugtheory.wiki | ticketing &amp; bug tracking],
    49     48   [./embeddeddoc.wiki | embedded documentation], and
    50     49   [./event.wiki | Technical notes].
    51     50   These additional capabilities are available for Git as 3rd-party and/or
................................................................................
    62     61   the stand-alone Fossil executable together with a 2-line CGI script
    63     62   suffice to instantiate a full-featured developer website.  To accomplish
    64     63   the same using Git requires locating, installing, configuring, integrating,
    65     64   and managing a wide assortment of separate tools.  Standing up a developer
    66     65   website using Fossil can be done in minutes, whereas doing the same using
    67     66   Git requires hours or days.
    68     67   
    69         -<h3>2.2 Database</h3>
           68  +<h3>3.2 Database</h3>
    70     69   
    71     70   The baseline data structures for Fossil and Git are the same (modulo
    72     71   formatting details).  Both systems store check-ins as immutable
    73     72   objects referencing their immediate ancestors and named by a
    74     73   cryptographic hash of the check-in content.
    75     74   
    76     75   The difference is that Git stores its objects as individual files
................................................................................
   106    105   The ease with which check-ins can be located and queried in Fossil
   107    106   has resulted in a huge variety of reports and status screens
   108    107   ([./webpage-ex.md|examples]) that show project state
   109    108   in ways that help developers
   110    109   maintain enhanced awareness and comprehension
   111    110   and avoid errors.
   112    111   
   113         -<h3>2.3 Cathedral vs. Bazaar</h3>
          112  +<h3>3.3 Cathedral vs. Bazaar</h3>
   114    113   
   115    114   Fossil and Git promote different development styles.  Git promotes a
   116    115   "bazaar" development style in which numerous anonymous developers make
   117    116   small and sometimes haphazard contributions.  Fossil
   118    117   promotes a "cathedral" development model in which the project is
   119    118   closely supervised by an highly engaged architect and implemented by
   120    119   a clique of developers.
................................................................................
   136    135   Work in progress from one developer is readily visible to all other
   137    136   developers and to the project leader, well before the code is ready
   138    137   to integrate.  Fossil places a lot of emphasis on reporting the state
   139    138   of the project, and the changes underway by all developers, so that
   140    139   all developers and especially the project leader can maintain a better
   141    140   mental picture of what is happening, and better situational awareness.
   142    141   
   143         -<h3>2.4 Linux vs. SQLite</h3>
          142  +<h3>3.4 Linux vs. SQLite</h3>
   144    143   
   145    144   Git was specifically designed to support the development of Linux.
   146    145   Fossil was specifically designed to support the development of SQLite.
   147    146   
   148    147   Both SQLite and Linux are important pieces of software.
   149    148   SQLite is found on far more systems than Linux.  (Almost every Linux
   150    149   system uses SQLite, but there are many non-Linux systems such as
................................................................................
   157    156   Git is designed for this scenario.
   158    157   
   159    158   SQLite uses cathedral-style development.  95% of the code in SQLite
   160    159   comes from just three programmers, 64% from just the lead developer.
   161    160   And all SQLite developers know each other well and interact daily.
   162    161   Fossil is designed for this development model.
   163    162   
   164         -<h3>2.5 Lots of little tools vs. Self-contained system</h3>
          163  +<h3>3.5 Lots of little tools vs. Self-contained system</h3>
   165    164   
   166    165   Git consists of many small tools, each doing one small part of the job,
   167    166   which can be recombined (by experts) to perform powerful operations.
   168    167   Git has a lot of complexity and many dependencies and requires an "installer"
   169    168   script or program to get it running.
   170    169   
   171    170   Fossil is a single self-contained stand-alone executable with hardly
................................................................................
   175    174   
   176    175   The designer of Git says that the unix philosophy is to have lots of
   177    176   small tools that collaborate to get the job done.  The designer of
   178    177   Fossil says that the unix philosophy is "it just works".  Both
   179    178   individuals have written their DVCSes to reflect their own view
   180    179   of the "unix philosophy".
   181    180   
   182         -<h3>2.6 One vs. Many Check-outs per Repository</h3>
          181  +<h3>3.6 One vs. Many Check-outs per Repository</h3>
   183    182   
   184    183   A "repository" in Git is a pile-of-files in the ".git" subdirectory
   185    184   of a single check-out.  The check-out and the repository are inseperable.
   186    185   
   187    186   With Fossil, a "repository" is a single SQLite database file
   188    187   that can be stored anywhere.  There
   189    188   can be multiple active check-outs from the same repository, perhaps
   190    189   open on different branches or on different snapshots of the same branch.
   191    190   Long-running tests or builds can be running in one check-out while
   192    191   changes are being committed in another.
   193    192   
   194         -<h3>2.7 What you should have done vs. What you actually did</h3>
          193  +<h3>3.7 What you should have done vs. What you actually did</h3>
   195    194   
   196    195   Git puts a lot of emphasis on maintaining
   197    196   a "clean" check-in history.  Extraneous and experimental branches by
   198    197   individual developers often never make it into the main repository.  And
   199    198   branches are often rebased before being pushed, to make
   200    199   it appear as if development had been linear.  Git strives to record what
   201    200   the development of a project should have looked like had there been no
................................................................................
   208    207   is that this makes the history "accurate".  In actual practice, the
   209    208   superior reporting tools available in Fossil mean that the added "mess"
   210    209   is not a factor.
   211    210   
   212    211   One commentator has mused that Git records history according to
   213    212   the victors, whereas Fossil records history as it actually happened.
   214    213   
   215         -<h3>2.8 GPL vs. BSD</h3>
          214  +<h3>3.8 GPL vs. BSD</h3>
   216    215   
   217    216   Git is covered by the GPL license whereas Fossil is covered by
   218    217   a two-clause BSD license.
   219    218   
   220    219   Consider the difference between GPL and BSD licenses:  GPL is designed
   221    220   to make writing easier at the expense of making reading harder.  BSD is
   222    221   designed to make reading easier at the expense of making writing harder.
................................................................................
   244    243   implementations themselves, not to the projects which the systems store.
   245    244   Nevertheless, one can see a more GPL-oriented world-view in Git and a
   246    245   more BSD-oriented world-view in Fossil.  Git encourages anonymous contributions
   247    246   and siloed development, which are hallmarks of the GPL/bazaar approach to
   248    247   software, whereas Fossil encourages a more tightly collaborative,
   249    248   cliquish, cathedral-style approach more typical of BSD-licensed projects.
   250    249   
   251         -<h2>3.0 Missing Features</h2>
          250  +<h2>4.0 Missing Features</h2>
   252    251   
   253    252   Most of the capabilities found in Git are also available in Fossil and
   254    253   the other way around. For example, both systems have local check-outs,
   255    254   remote repositories, push/pull/sync, bisect capabilities, and a "stash".
   256    255   Both systems store project history as a directed acyclic graph (DAG)
   257    256   of immutable check-in objects.
   258    257   
   259    258   But there are a few capabilities in one system that are missing from the
   260    259   other.
   261    260   
   262         -<h3>3.1 Features found in Fossil but missing from Git</h3>
          261  +<h3>4.1 Features found in Fossil but missing from Git</h3>
   263    262   
   264    263     *  <b>The ability to show descendents of a check-in.</b>
   265    264   
   266    265      Both Git and Fossil can easily find the ancestors of a check-in.  But
   267    266      only Fossil shows the descendents.  (It is possible to find the
   268    267      descendents of a check-in in Git using the log, but that is sufficiently
   269    268      difficult that nobody ever actually does it.)
................................................................................
   294    293     *  <b>The [/help?cmd=ui|fossil ui] command</b>
   295    294   
   296    295      Fossil supports an integrated web interface.  Some of the same features
   297    296      are available using third-party add-ons for Git, but they do not provide
   298    297      nearly as many features and they are not nearly as convenient to use.
   299    298   
   300    299   
   301         -<h3>3.2 Features found in Git but missing from Fossil</h3>
          300  +<h2>4.2 Features found in Git but missing from Fossil</h2>
   302    301   
   303    302     *  <b>Rebase</b>
   304    303   
   305    304      Because of its emphasis on recording history exactly as it happened,
   306    305      rather than as we would have liked it to happen, Fossil deliberately
   307    306      does not provide a "rebase" command.  One can rebase manually in Fossil,
   308         -   with sufficient perserverence, but it is not something that can be done with
          307  +   with sufficient perserverence, but it not something that can be done with
   309    308      a single command.
   310    309   
   311    310     *  <b>Push or pull a single branch</b>
   312    311   
   313    312      The [/help?cmd=push|fossil push], [/help?cmd=pull|fossil pull], and
   314    313      [/help?cmd=sync|fossil sync] commands do not provide the capability to
   315    314      push or pull individual branches.  Pushing and pulling in Fossil is
   316    315      all or nothing.  This is in keeping with Fossil's emphasis on maintaining
   317    316      a complete record and on sharing everything between all developers.

Changes to www/index.wiki.

     7      7   <li> [/uv/download.html | Download]
     8      8   <li> [./quickstart.wiki | Quick Start]
     9      9   <li> [./build.wiki | Install]
    10     10   <li> [../COPYRIGHT-BSD2.txt | License]
    11     11   <li> [./faq.wiki | FAQ]
    12     12   <li> [./changes.wiki | Change Log]
    13     13   <li> [./hacker-howto.wiki | Hacker How-To]
    14         -<li> [./fossil-v-git.wiki | Fossil vs. Git]
    15     14   <li> [./hints.wiki | Tip &amp; Hints]
    16     15   <li> [./permutedindex.html | Documentation Index]
    17     16   <li> [http://www.fossil-scm.org/schimpf-book/home | Jim Schimpf's book]
    18     17   <li> Mailing list
    19     18        <ul>
    20     19        <li> [http://mailinglists.sqlite.org/cgi-bin/mailman/listinfo/fossil-users | sign-up]
    21     20        <li> [http://www.mail-archive.com/fossil-users@lists.fossil-scm.org | archives]
................................................................................
    30     29     1.  <b>Integrated Bug Tracking, Wiki, and Technotes</b> -
    31     30         In addition to doing [./concepts.wiki | distributed version control]
    32     31         like Git and Mercurial,
    33     32         Fossil also supports [./bugtheory.wiki | bug tracking],
    34     33         [./wikitheory.wiki | wiki], and [./event.wiki | technotes].
    35     34   
    36     35     2.  <b>Built-in Web Interface</b> -
    37         -      Fossil has a built-in,
    38         -      [https://fossil-scm.org/skins/index.html | themeable],
    39         -      and intuitive [./webui.wiki | web interface]
           36  +      Fossil has a built-in and intuitive [./webui.wiki | web interface]
    40     37         with a rich variety of information pages
    41     38         ([./webpage-ex.md|examples]) promoting situational awareness.
    42     39   
    43     40         This entire website is just a running instance of Fossil.
    44     41         The pages you see here are all [./wikitheory.wiki | wiki] or
    45     42         [./embeddeddoc.wiki | embedded documentation] or (in the case of
    46     43         the [/uv/download.html|download] page)
................................................................................
    94     91        [./quotes.wiki | Quotes] about Fossil and other DVCSes.
    95     92     *  [./faq.wiki | Frequently Asked Questions]
    96     93     *  The [./concepts.wiki | concepts] behind Fossil.
    97     94        [./whyusefossil.wiki#definitions | Another viewpoint].
    98     95     *  [./quickstart.wiki | Quick Start] guide to using Fossil.
    99     96     *  [./qandc.wiki | Questions &amp; Criticisms] directed at Fossil.
   100     97     *  [./build.wiki | Compiling and Installing]
           98  +  *  "Fuel" is cross-platform GUI front-end for Fossil
           99  +     written in Qt.  [http://fuelscm.org/].
          100  +     Fuel is an independent project run by a different group of
          101  +     developers.
   101    102     *  Fossil supports [./embeddeddoc.wiki | embedded documentation]
   102    103        that is versioned along with project source code.
   103    104     *  Fossil uses an [./fileformat.wiki | enduring file format] that is
   104    105        designed to be readable, searchable, and extensible by people
   105    106        not yet born.
   106    107     *  A tutorial on [./branching.wiki | branching], what it means and how
   107    108        to do it using Fossil.

Changes to www/stats.wiki.

     3      3   
     4      4   The questions will inevitably arise:  How does Fossil perform?
     5      5   Does it use a lot of disk space or bandwidth?  Is it scalable?
     6      6   
     7      7   In an attempt to answers these questions, this report looks at several
     8      8   projects that use fossil for configuration management and examines how
     9      9   well they are working.  The following table is a summary of the results.
    10         -(Last updated on 2018-06-04.)
           10  +(Last updated on 2015-02-28.)
    11     11   Explanation and analysis follows the table.
    12     12   
    13     13   <table border=1>
    14     14   <tr>
    15     15   <th>Project</th>
    16     16   <th>Number Of Artifacts</th>
    17     17   <th>Number Of Check-ins</th>
    18         -<th>Project&nbsp;Duration<br>(as of 2018-06-04)</th>
           18  +<th>Project&nbsp;Duration<br>(as of 2015-02-28)</th>
    19     19   <th>Uncompressed Size</th>
    20     20   <th>Repository Size</th>
    21     21   <th>Compression Ratio</th>
    22     22   <th>Clone Bandwidth</th>
    23     23   </tr>
    24     24   
    25     25   <tr align="center">
    26     26   <td>[http://www.sqlite.org/src/timeline | SQLite]
    27         -<td>77492
    28         -<td>20686
    29         -<td>6580&nbsp;days<br>18.02&nbsp;years
    30         -<td>5.6&nbsp;GB
    31         -<td>70.0&nbsp;MB
    32         -<td>80:1
    33         -<td>51.1&nbsp;MB
           27  +<td>56089
           28  +<td>14357
           29  +<td>5388&nbsp;days<br>14.75&nbsp;years
           30  +<td>3.4&nbsp;GB
           31  +<td>45.5&nbsp;MB
           32  +<td>73:1
           33  +<td>29.9&nbsp;MB
    34     34   </tr>
    35     35   
    36     36   <tr align="center">
    37         -<td>[http://core.tcl.tk/tcl/timeline | TCL]
    38         -<td>161991
    39         -<td>23146
    40         -<td>7375&nbsp;days<br>20.19&nbsp;years
    41         -<td>8.0&nbsp;GB
    42         -<td>222.0&nbsp;MB
    43         -<td>36:1
    44         -<td>150.5&nbsp;MB
           37  +<td>[http://core.tcl-lang.org/tcl/timeline | TCL]
           38  +<td>139662
           39  +<td>18125
           40  +<td>6183&nbsp;days<br>16.93&nbsp;years
           41  +<td>6.6&nbsp;GB
           42  +<td>192.6&nbsp;MB
           43  +<td>34:1
           44  +<td>117.1&nbsp;MB
    45     45   </tr>
    46     46   
    47     47   <tr align="center">
    48     48   <td>[/timeline | Fossil]
    49         -<td>39148
    50         -<td>11266
    51         -<td>3971&nbsp;days<br>10.87&nbsp;years
    52         -<td>3.8&nbsp;GB
    53         -<td>42.0&nbsp;MB
    54         -<td>90:1
    55         -<td>27.4&nbsp;MB
           49  +<td>29937
           50  +<td>8238
           51  +<td>2779&nbsp;days<br>7.61&nbsp;years
           52  +<td>2.3&nbsp;GB
           53  +<td>34.0&nbsp;MB
           54  +<td>67:1
           55  +<td>21.5&nbsp;MB
    56     56   </tr>
    57     57   
    58     58   <tr align="center">
    59     59   <td>[http://www.sqlite.org/slt/timeline | SLT]
    60         -<td>2384
    61         -<td>169
    62         -<td>3474&nbsp;days<br>9.51&nbsp;years
    63         -<td>2.1&nbsp;GB
    64         -<td>145.9&nbsp;MB
    65         -<td>14:1
    66         -<td>143.4&nbsp;MB
           60  +<td>2278
           61  +<td>136
           62  +<td>2282&nbsp;days<br>6.25&nbsp;years
           63  +<td>2.0&nbsp;GB
           64  +<td>144.7&nbsp;MB
           65  +<td>13:1
           66  +<td>142.1&nbsp;MB
    67     67   </tr>
    68     68   
    69     69   <tr align="center">
    70     70   <td>[http://www.sqlite.org/th3.html | TH3]
    71         -<td>12406
    72         -<td>3718
    73         -<td>3539&nbsp;days<br>9.69&nbsp;years
    74         -<td>544&nbsp;MB
    75         -<td>18.0&nbsp;MB
    76         -<td>30:1
    77         -<td>14.7&nbsp;MB
           71  +<td>8729
           72  +<td>2406
           73  +<td>2347&nbsp;days<br>6.43&nbsp;years
           74  +<td>386&nbsp;MB
           75  +<td>15.2&nbsp;MB
           76  +<td>25:1
           77  +<td>12.6&nbsp;MB
    78     78   </tr>
    79     79   
    80     80   <tr align="center">
    81     81   <td>[http://www.sqlite.org/docsrc/timeline | SQLite Docs]
    82         -<td>8752
    83         -<td>2783
    84         -<td>3857&nbsp;days<br>10.56&nbsp;years
    85         -<td>349.9&nbsp;MB
    86         -<td>16.3&nbsp;MB
    87         -<td>21:1
    88         -<td>13.57&nbsp;MB
           82  +<td>5503
           83  +<td>1631
           84  +<td>2666&nbsp;days<br>7.30&nbsp;years
           85  +<td>194&nbsp;MB
           86  +<td>10.9&nbsp;MB
           87  +<td>17:1
           88  +<td>8.37&nbsp;MB
    89     89   </tr>
    90     90   
    91     91   </table>
    92     92   
    93     93   <h2>Measured Attributes</h2>
    94     94   
    95     95   In Fossil, every version of every file, every wiki page, every change to
................................................................................
   127    127   
   128    128   <h2>Analysis And Supplemental Data</h2>
   129    129   
   130    130   Perhaps the two most interesting datapoints in the above table are SQLite
   131    131   and SLT.  SQLite is a long-running project with long revision chains.
   132    132   Some of the files in SQLite have been edited over a thousand times.
   133    133   Each of these edits is stored as a delta, and hence the SQLite project
   134         -gets excellent 80:1 compression.  SLT, on the other hand, consists of
          134  +gets excellent 73:1 compression.  SLT, on the other hand, consists of
   135    135   many large (megabyte-sized) SQL scripts that have one or maybe two
   136    136   edits each.  There is very little delta compression occurring and so the
   137    137   overall repository compression ratio is much lower.  Note also that
   138    138   quite a bit more bandwidth is required to clone SLT than SQLite.
   139    139   
   140    140   For the first nine years of its development, SQLite was versioned by CVS.
   141    141   The resulting CVS repository measured over 320MB in size.  So, the

Changes to www/sync.wiki.

   496    496   <p>The reqconfig card is normally sent in response to the
   497    497   "fossil configuration pull" command.  The format is as follows:
   498    498   
   499    499   <blockquote>
   500    500   <b>reqconfig</b> <i>configuration-name</i>
   501    501   </blockquote>
   502    502   
   503         -<p>As of 2018-06-04, the configuration-name must be one of the
          503  +<p>As of [/timeline?r=trunk&c=2015-03-19+03%3A57%3A46&n=20|2015-03-19], the configuration-name must be one of the
   504    504   following values:
   505    505   
   506    506   <table border=0 align="center">
   507    507   <tr><td valign="top">
   508    508   <ul>
   509    509   <li> css
   510    510   <li> header
   511    511   <li> footer
   512         -<li> details
   513    512   <li> logo-mimetype
   514    513   <li> logo-image
   515    514   <li> background-mimetype
   516    515   <li> background-image
   517    516   <li> index-page
   518    517   <li> timeline-block-markup
   519    518   <li> timeline-max-comment
   520    519   <li> timeline-plaintext
          520  +<ul></td><td valign="top"><ul>
   521    521   <li> adunit
   522    522   <li> adunit-omit-if-admin
   523    523   <li> adunit-omit-if-user
   524         -<ul></td><td valign="top"><ul>
   525         -<li> th1-docs
   526         -<li> th1-hooks
   527         -<li> th1-setup
   528         -<li> tcl
   529         -<li> tcl-setup
          524  +<li> white-foreground
   530    525   <li> project-name
   531    526   <li> short-project-name
   532    527   <li> project-description
   533    528   <li> index-page
   534    529   <li> manifest
   535    530   <li> binary-glob
   536    531   <li> clean-glob
          532  +<ul></td><td valign="top"><ul>
   537    533   <li> ignore-glob
   538    534   <li> keep-glob
   539    535   <li> crlf-glob
   540         -<ul></td><td valign="top"><ul>
   541    536   <li> crnl-glob
   542    537   <li> encoding-glob
   543    538   <li> empty-dirs
   544    539   <li> allow-symlinks
   545    540   <li> dotfiles
   546         -<li> parent-project-code
   547         -<li> parent-projet-name
   548         -<li> hash-policy
   549         -<li> mv-rm-files
   550    541   <li> ticket-table
   551    542   <li> ticket-common
   552    543   <li> ticket-change
   553    544   <li> ticket-newpage
          545  +<ul></td><td valign="top"><ul>
   554    546   <li> ticket-viewpage
   555    547   <li> ticket-editpage
   556         -<ul></td><td valign="top"><ul>
   557    548   <li> ticket-reportlist
   558    549   <li> ticket-report-template
   559    550   <li> ticket-key-template
   560    551   <li> ticket-title-expr
   561    552   <li> ticket-closed-expr
   562         -<li> xfer-common-script
   563         -<li> xfer-push-script
   564         -<li> xfer-commit-script
   565         -<li> xfer-ticket-script
   566    553   <li> @reportfmt
   567    554   <li> @user
   568    555   <li> @concealed
   569    556   <li> @shun
   570    557   </ul></td></tr>
   571    558   </table>
   572    559   
................................................................................
   683    670   </ol>
   684    671   
   685    672   <h3>3.12 Comment Cards</h3>
   686    673   
   687    674   <p>Any card that begins with "#" (ASCII 0x23) is a comment card and
   688    675   is silently ignored.</p>
   689    676   
   690         -<h3>3.13 Message and Error Cards</h3>
          677  +<h3>3.13 Error Cards</h3>
   691    678   
   692    679   <p>If the server discovers anything wrong with a request, it generates
   693    680   an error card in its reply.  When the client sees the error card,
   694    681   it displays an error message to the user and aborts the sync
   695    682   operation.  An error card looks like this:</p>
   696    683   
   697    684   <blockquote>
................................................................................
   703    690   A space (ASCII 0x20) is represented as "\s" (ASCII 0x5C, 0x73).  A
   704    691   newline (ASCII 0x0a) is "\n" (ASCII 0x6C, x6E).  A backslash
   705    692   (ASCII 0x5C) is represented as two backslashes "\\".  Apart from
   706    693   space and newline, no other whitespace characters nor any
   707    694   unprintable characters are allowed in
   708    695   the error message.</p>
   709    696   
   710         -<p>The server can also send a message card that also prints a
   711         -message on the client console, but which is not an error:
   712         -
   713         -<blockquote>
   714         -<b>message</b> <i>message-text</i>
   715         -</blockquote>
   716         -
   717         -<p>The message-text uses the same format as an error message.
   718         -
   719    697   <h3>3.14 Unknown Cards</h3>
   720    698   
   721    699   <p>If either the client or the server sees a card that is not
   722    700   described above, then it generates an error and aborts.</p>
   723    701   
   724    702   <h2>4.0 Phantoms And Clusters</h2>
   725    703   
................................................................................
   933    911       <li> <b>gimme</b> <i>artifact-id</i>
   934    912       <li> <b>uvgimme</b> <i>name</i>
   935    913       <li> <b>cookie</b>  <i>cookie-text</i>
   936    914       <li> <b>reqconfig</b> <i>parameter-name</i>
   937    915       <li> <b>config</b> <i>parameter-name size</i> <b>\n</b> <i>content</i>
   938    916       <li> <b>pragma</b> <i>name</i> <i>value...</i>
   939    917       <li> <b>error</b> <i>error-message</i>
   940         -    <li> <b>message</b> <i>text-messate</i>
   941    918       <li> <b>#</b> <i>arbitrary-text...</i>
   942    919       </ul>
   943    920   <li>Phantoms are artifacts that a repository knows exist but does not possess.
   944    921   <li>Clusters are artifacts that contain IDs of other artifacts.
   945    922   <li>Clusters are created automatically on the server during a pull.
   946    923   <li>Repositories keep track of all artifacts that are not named in any
   947    924   cluster and send igot messages for those artifacts.
   948    925   <li>Repositories keep track of all the phantoms they hold and send
   949    926   gimme messages for those artifacts.
   950    927   </ol>