Fossil

Check-in Differences
Login

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

Difference From:

[565c2173] Reworded 2 references to 40-character artifact IDs, since those particular IDs may now be longer than 40 characters. (user: stephan tags: trunk, date: 2018-12-07 19:36:09)

To:

[9aa9ba8b] Version 2.7 (user: drh tags: trunk, release, version-2.7, date: 2018-09-22 17:40:11)

Changes to Makefile.classic.

    51     51   #### We sometimes add the -static option here so that we can build a
    52     52   #    static executable that will run in a chroot jail.
    53     53   #LIB = -static
    54     54   TCC += -DFOSSIL_DYNAMIC_BUILD=1
    55     55   
    56     56   TCCFLAGS = $(CFLAGS)
    57     57   
    58         -# We don't attempt to use libedit or libreadline in this simplified
    59         -# build system (contrast auto.def and Makefile.in) so use the included
    60         -# copy of linenoise.  MinGW can't make use of this, but linenoise is
    61         -# ifdef'd out elsewhere for that platform.  Note that this is a make
    62         -# flag handled in src/main.mk, not a C preprocessor flag.
    63         -USE_LINENOISE := 1
    64         -
    65     58   #### Extra arguments for linking the finished binary.  Fossil needs
    66     59   #    to link against the Z-Lib compression library unless the miniz
    67     60   #    library in the source tree is being used.  There are no other
    68     61   #    required dependencies.
    69     62   ZLIB_LIB.0 = -lz
    70     63   ZLIB_LIB.1 =
    71     64   ZLIB_LIB.  = $(ZLIB_LIB.0)
................................................................................
    72     65   
    73     66   # If using zlib:
    74     67   LIB += $(ZLIB_LIB.$(FOSSIL_ENABLE_MINIZ)) $(LDFLAGS)
    75     68   
    76     69   # If using HTTPS:
    77     70   LIB += -lcrypto -lssl
    78     71   
    79         -# Many platforms put cos() needed by src/piechart.c in libm, rather than
    80         -# in libc.  We cannot enable this by default because libm doesn't exist
    81         -# everywhere.
    82         -#LIB += -lm
    83         -
    84     72   #### Tcl shell for use in running the fossil testsuite.  If you do not
    85     73   #    care about testing the end result, this can be blank.
    86     74   #
    87     75   TCLSH = tclsh
    88     76   
    89     77   # You should not need to change anything below this line
    90     78   ###############################################################################

Changes to auto.def.

   511    511   cc-check-function-in-lib gethostbyname nsl
   512    512   if {![cc-check-function-in-lib socket {socket network}]} {
   513    513       # Last resort, may be Windows
   514    514       if {[is_mingw]} {
   515    515           define-append LIBS -lwsock32
   516    516       }
   517    517   }
   518         -
   519         -# The SMTP module requires special libraries and headers for MX DNS
   520         -# record lookups and such.
   521         -cc-check-includes arpa/nameser.h
   522         -cc-include-needs bind/resolv.h netinet/in.h
   523         -cc-check-includes bind/resolv.h
   524         -cc-check-includes resolv.h
   525         -if {    !(([cc-check-function-in-lib dn_expand resolv] ||
   526         -           [cc-check-function-in-lib   ns_name_uncompress {bind resolv}] ||
   527         -           [cc-check-function-in-lib __ns_name_uncompress {bind resolv}]) &&
   528         -          ([cc-check-function-in-lib   ns_parserr {bind resolv}] ||
   529         -           [cc-check-function-in-lib __ns_parserr {bind resolv}]) &&
   530         -          ([cc-check-function-in-lib   res_query {bind resolv}] ||
   531         -           [cc-check-function-in-lib __res_query {bind resolv}]))} {
   532         -    msg-result "WARNING: SMTP feature will not be able to look up local MX."
   533         -}
   534         -cc-check-function-in-lib res_9_ns_initparse resolv
   535         -
   536         -# Other nonstandard function checks
          518  +cc-check-function-in-lib ns_name_uncompress resolv
   537    519   cc-check-functions utime
   538    520   cc-check-functions usleep
   539    521   cc-check-functions strchrnul
   540    522   cc-check-functions pledge
   541    523   cc-check-functions backtrace
   542    524   
   543    525   # Check for getloadavg(), and if it doesn't exist, define FOSSIL_OMIT_LOAD_AVERAGE

Changes to fossil.1.

     1         -.TH FOSSIL "1" "September 2018" "http://fossil-scm.org" "User Commands"
            1  +.TH FOSSIL "1" "February 2015" "http://fossil-scm.org" "User Commands"
     2      2   .SH NAME
     3      3   fossil \- Distributed Version Control System
     4      4   .SH SYNOPSIS
     5      5   .B fossil
     6      6   \fIhelp\fR
     7      7   .br
     8      8   .B fossil
     9      9   \fIhelp COMMAND\fR
    10     10   .br
    11     11   .B fossil
    12     12   \fICOMMAND [OPTIONS]\fR
    13     13   .SH DESCRIPTION
    14     14   Fossil is a distributed version control system (DVCS) with built-in
    15         -forum, wiki, ticket tracker, CGI/HTTP interface, and HTTP server.
           15  +wiki, ticket tracker, CGI/http interface, and http server.
    16     16   
    17     17   .SH Common COMMANDs:
    18     18   
    19         -add            clean          help           push           timeline
           19  +add            changes        gdiff          publish        status
           20  +.br
           21  +addremove      clean          help           pull           sync
           22  +.br
           23  +all            clone          import         push           tag
           24  +.br
           25  +amend          commit         info           rebuild        timeline
           26  +.br
           27  +annotate       delete         init           remote-url     ui
           28  +.br
           29  +bisect         diff           ls             revert         undo
    20     30   .br
    21         -addremove      clone          import         rebuild        ui
           31  +blame          export         merge          rm             unpublished
    22     32   .br
    23         -all            commit         info           remote-url     undo
           33  +branch         extras         mv             settings       unversioned
    24     34   .br
    25         -amend          delete         init           revert         unpublished
    26         -.br
    27         -annotate       diff           ls             rm             unversioned
    28         -.br
    29         -bisect         export         merge          settings       update
           35  +bundle         finfo          open           sqlite3        update
    30     36   .br
    31         -blame          extras         mv             sql            version
    32         -.br
    33         -branch         finfo          open           stash
    34         -.br
    35         -bundle         fusefs         praise         status
    36         -.br
    37         -cat            gdiff          publish        sync
    38         -.br
    39         -changes        grep           pull           tag
           37  +cat            fusefs         praise         stash          version
    40     38   
    41     39   .SH FEATURES
    42     40   
    43     41   Features as described on the fossil home page.
    44     42   
    45     43   .HP
    46     44   1.
    47         -.B Integrated Bug Tracking, Wiki, Forum, and Technotes
           45  +.B Integrated Bug Tracking, Wiki, & Technotes
    48     46   - In addition to doing distributed version control like Git and
    49         -Mercurial, Fossil also supports bug tracking, wiki, forum, and
    50         -technotes.
           47  +Mercurial, Fossil also supports bug tracking, wiki, and technotes.
    51     48   
    52     49   .HP
    53     50   2.
    54     51   .B Built-in Web Interface
    55     52   - Fossil has a built-in and intuitive web interface that promotes
    56     53   project situational awareness. Type "fossil ui" and Fossil automatically
    57     54   opens a web browser to a page that shows detailed graphical history and
................................................................................
    67     64   
    68     65   .HP
    69     66   4.
    70     67   .B Simple Networking
    71     68   - No custom protocols or TCP ports. Fossil uses plain old HTTP (or HTTPS
    72     69   or SSH) for all network communications, so it works fine from behind
    73     70   restrictive firewalls, including proxies. The protocol is bandwidth
    74         -efficient to the point that Fossil can be used comfortably over dial-up
    75         -or over the exceedingly slow Wifi on airliners.
           71  +efficient to the point that Fossil can be used comfortably over dial-up.
    76     72   
    77     73   .HP
    78     74   5.
    79     75   .B CGI/SCGI Enabled
    80     76   - No server is required, but if you want to set one up, Fossil supports
    81         -four easy server configurations.
           77  +four simple server configurations.
    82     78   
    83     79   .HP
    84     80   6.
    85     81   .B Autosync
    86     82   - Fossil supports "autosync" mode which helps to keep projects moving
    87     83   forward by reducing the amount of needless forking and merging often
    88     84   associated with distributed projects.
................................................................................
    89     85   
    90     86   .HP
    91     87   7.
    92     88   .B Robust & Reliable
    93     89   - Fossil stores content using an enduring file format in an SQLite
    94     90   database so that transactions are atomic even if interrupted by a
    95     91   power loss or system crash. Automatic self-checks verify that all
    96         -aspects of the repository are consistent prior to each commit.
    97         -
    98         -.HP
    99         -8.
   100         -.B Free and Open-Source
   101         -- Uses the 2-clause BSD license.
           92  +aspects of the repository are consistent prior to each commit. In
           93  +over seven years of operation, no work has ever been lost after
           94  +having been committed to a Fossil repository.
   102     95   
   103     96   .SH DOCUMENTATION
   104     97   http://www.fossil-scm.org/
   105     98   .br
   106     99   .B fossil
   107    100   \fIui\fR

Changes to skins/bootstrap/header.txt.

     1      1   <html lang="en">
     2      2   <head>
     3      3     <meta charset="utf-8">
     4      4     <base href="$baseurl/$current_page" />
     5      5     <title>$<project_name>: $<title></title>
     6      6       <meta name="viewport" content="width=device-width, initial-scale=1.0">
     7         -    <meta http-equiv="Content-Security-Policy" content="default-src 'self' data:; script-src 'self' 'nonce-$<nonce>'; style-src 'self' 'unsafe-inline'"/>
     8      7       <link rel="alternate" type="application/rss+xml" title="RSS Feed" href="$home/timeline.rss" />
     9      8       <link rel="stylesheet" href="$home/style.css?default" type="text/css" media="screen" />
    10      9       <script>
    11     10       function gebi(x){
    12     11         if(/^#/.test(x)) x = x.substr(1);
    13     12         var e = document.getElementById(x);
    14     13         if(!e) throw new Error("Expecting element with ID "+x);
................................................................................
   113    112             </div><!--/.nav-collapse -->
   114    113           </div>
   115    114         </div>
   116    115         <div class="content">
   117    116           <th1>
   118    117             html "<div class='container'>"
   119    118               html "<ul class='breadcrumb'>"
   120         -              html "<li><a href='$home$index_page'>Home</a></li>"
   121         -              html "<li><a href='$home/$current_page'>[htmlize $title]</a></li>"
          119  +              html "<li><a href='$index_page'>Home</a></li>"
          120  +              html "<li><a href='$home/$current_page'>$title</a></li>"
   122    121                 html "</ul>"
   123    122               </th1>

Changes to skins/default/css.txt.

   143    143       overflow: auto;
   144    144       border: 1px solid #ccc;
   145    145       border-radius: 5px;
   146    146   }
   147    147   .content blockquote {
   148    148       padding: 0 15px;
   149    149   }
   150         -div.forumHierRoot blockquote, div.forumHier blockquote, div.forumEdit blockquote {
          150  +div.forumHierRoot blockquote, div.forumHier blockquote {
   151    151       background-color: rgba(65, 131, 196, 0.1);
   152    152       border-left: 3px solid #254769;
   153    153       padding: .1em 1em;
   154    154   }
   155    155   
   156    156   table.report {
   157    157       cursor: auto;

Changes to src/alerts.c.

   844    844         emailerError(p, "Failed to insert email message into output queue.\n"
   845    845                         "%s", sqlite3_errmsg(p->db));
   846    846       }
   847    847     }else if( p->zCmd ){
   848    848       FILE *out = popen(p->zCmd, "w");
   849    849       if( out ){
   850    850         fwrite(blob_buffer(&all), 1, blob_size(&all), out);
   851         -      pclose(out);
          851  +      fclose(out);
   852    852       }else{
   853    853         emailerError(p, "Could not open output pipe \"%s\"", p->zCmd);
   854    854       }
   855    855     }else if( p->zDir ){
   856    856       char *zFile = file_time_tempname(p->zDir, ".email");
   857    857       blob_write_to_file(&all, zFile);
   858    858       fossil_free(zFile);
................................................................................
   920    920   ** are sent when email-send-method is "relay".  There should be an
   921    921   ** SMTP server configured as a Mail Submission Agent listening on the
   922    922   ** designated host and port and all times.
   923    923   */
   924    924   
   925    925   
   926    926   /*
   927         -** COMMAND: alerts*
          927  +** COMMAND: alerts
   928    928   ** 
   929    929   ** Usage: %fossil alerts SUBCOMMAND ARGS...
   930    930   **
   931    931   ** Subcommands:
   932    932   **
   933    933   **    pending                 Show all pending alerts.  Useful for debugging.
   934    934   **
................................................................................
  2033   2033       p->type = db_column_text(&q, 3)[0];
  2034   2034       p->needMod = db_column_int(&q, 4);
  2035   2035       p->zFromName = 0;
  2036   2036       p->pNext = 0;
  2037   2037       switch( p->type ){
  2038   2038         case 'c':  zType = "Check-In";        break;
  2039   2039         case 'f':  zType = "Forum post";      break;
  2040         -      case 't':  zType = "Ticket Change";   break;
  2041         -      case 'w':  zType = "Wiki Edit";       break;
         2040  +      case 't':  zType = "Wiki Edit";       break;
         2041  +      case 'w':  zType = "Ticket Change";   break;
  2042   2042       }
  2043   2043       blob_init(&p->hdr, 0, 0);
  2044   2044       blob_init(&p->txt, 0, 0);
  2045   2045       blob_appendf(&p->txt,"== %s %s ==\n%s\n%s/info/%.20s\n",
  2046   2046         db_column_text(&q,1),
  2047   2047         zType,
  2048   2048         db_column_text(&q,2),
................................................................................
  2424   2424       const char *zEmail = db_column_text(&q, 1);
  2425   2425       const char *zCap = db_column_text(&q, 3);
  2426   2426       int nHit = 0;
  2427   2427       for(p=pEvents; p; p=p->pNext){
  2428   2428         if( strchr(zSub,p->type)==0 ) continue;
  2429   2429         if( p->needMod ){
  2430   2430           /* For events that require moderator approval, only send an alert
  2431         -        ** if the recipient is a moderator for that type of event.  Setup
  2432         -        ** and Admin users always get notified. */
         2431  +        ** if the recipient is a moderator for that type of event */
  2433   2432           char xType = '*';
  2434         -        if( strpbrk(zCap,"as")==0 ){
  2435         -          switch( p->type ){
  2436         -            case 'f':  xType = '5';  break;
  2437         -            case 't':  xType = 'q';  break;
  2438         -            case 'w':  xType = 'l';  break;
  2439         -          }
  2440         -          if( strchr(zCap,xType)==0 ) continue;
         2433  +        switch( p->type ){
         2434  +          case 'f':  xType = '5';  break;
         2435  +          case 't':  xType = 'q';  break;
         2436  +          case 'w':  xType = 'l';  break;
  2441   2437           }
         2438  +        if( strchr(zCap,xType)==0 ) continue;
  2442   2439         }else if( strchr(zCap,'s')!=0 || strchr(zCap,'a')!=0 ){
  2443   2440           /* Setup and admin users can get any notification that does not
  2444   2441           ** require moderation */
  2445   2442         }else{
  2446   2443           /* Other users only see the alert if they have sufficient
  2447   2444           ** privilege to view the event itself */
  2448   2445           char xType = '*';
................................................................................
  2699   2696       return;
  2700   2697     }
  2701   2698     if( fossil_strcmp(P("name"),"test1")==0 ){
  2702   2699       /* Visit the /announce/test1 page to see the CGI variables */
  2703   2700       @ <p style='border: 1px solid black; padding: 1ex;'>
  2704   2701       cgi_print_all(0, 0);
  2705   2702       @ </p>
  2706         -  }else if( P("submit")!=0 && cgi_csrf_safe(1) ){
         2703  +  }else
         2704  +  if( P("submit")!=0 && cgi_csrf_safe(1) ){
  2707   2705       char *zErr = alert_send_announcement();
  2708   2706       style_header("Announcement Sent");
  2709   2707       if( zErr ){
  2710   2708         @ <h1>Internal Error</h1>
  2711   2709         @ <p>The following error was reported by the system:
  2712   2710         @ <blockquote><pre>
  2713   2711         @ %h(zErr)
  2714   2712         @ </pre></blockquote>
  2715   2713       }else{
  2716   2714         @ <p>The announcement has been sent.</p>
  2717   2715       }
  2718   2716       style_footer();    
  2719   2717       return;
  2720         -  } else if( !alert_enabled() ){
  2721         -    style_header("Cannot Send Announcement");
  2722         -    @ <p>Either you have no subscribers yet, or email alerts are not yet
  2723         -    @ <a href="https://fossil-scm.org/fossil/doc/trunk/www/alerts.md">set up</a>
  2724         -    @ for this repository.</p>
  2725         -    return;
  2726   2718     }
  2727         -
  2728   2719     style_header("Send Announcement");
  2729   2720     @ <form method="POST">
  2730   2721     @ <table class="subscribe">
  2731   2722     if( g.perm.Admin ){
  2732   2723       int aa = PB("aa");
  2733   2724       int all = PB("all");
  2734   2725       const char *aack = aa ? "checked" : "";

Changes to src/backoffice.c.

   380    380     Lease x;
   381    381     sqlite3_uint64 tmNow;
   382    382   
   383    383     if( backofficeDb ) return;
   384    384     if( g.zRepositoryName==0 ) return;
   385    385     if( g.db==0 ) return;
   386    386     if( !db_table_exists("repository","config") ) return;
   387         -  if( db_get_boolean("backoffice-disable",0) ) return;
   388    387     tmNow = time(0);
   389    388     backofficeReadLease(&x);
   390    389     if( x.tmNext>=tmNow && backofficeProcessExists(x.idNext) ){
   391    390       /* Another backoffice process is already queued up to run.  This
   392    391       ** process does not need to do any backoffice work. */
   393    392       return;
   394    393     }else{
   395    394       /* We need to run backup to be (at a minimum) on-deck */
   396    395       backofficeDb = fossil_strdup(g.zRepositoryName);
   397    396     }
   398    397   }
   399    398   
   400         -/*
   401         -** Call this routine to disable backoffice
   402         -*/
   403         -void backoffice_disable(void){
   404         -  backofficeDb = "x";
   405         -}
   406         -
   407    399   /*
   408    400   ** Check for errors prior to running backoffice_thread() or backoffice_run().
   409    401   */
   410    402   static void backoffice_error_check_one(int *pOnce){
   411    403     if( *pOnce ){
   412    404       fossil_panic("multiple calls to backoffice()");
   413    405     }
................................................................................
   437    429     Lease x;
   438    430     sqlite3_uint64 tmNow;
   439    431     sqlite3_uint64 idSelf;
   440    432     int lastWarning = 0;
   441    433     int warningDelay = 30;
   442    434     static int once = 0;
   443    435   
   444         -  if( sqlite3_db_readonly(g.db, 0) ) return;
   445    436     backoffice_error_check_one(&once);
   446    437     idSelf = backofficeProcessId();
   447    438     while(1){
   448    439       tmNow = time(0);
   449    440       db_begin_write();
   450    441       backofficeReadLease(&x);
   451    442       if( x.tmNext>=tmNow
................................................................................
   531    522   
   532    523     /* Here is where the actual work of the backoffice happens */
   533    524     alert_backoffice(0);
   534    525     smtp_cleanup();
   535    526   }
   536    527   
   537    528   /*
   538         -** COMMAND: backoffice*
          529  +** COMMAND: backoffice
   539    530   **
   540    531   ** Usage: backoffice [-R repository]
   541    532   **
   542    533   ** Run backoffice processing.  This might be done by a cron job or
   543    534   ** similar to make sure backoffice processing happens periodically.
   544    535   */
   545    536   void backoffice_command(void){

Changes to src/bisect.c.

   383    383       char *zDisplay = db_lget("bisect-display","chart");
   384    384       int m = (int)strlen(zDisplay);
   385    385       bisect_path();
   386    386       pMid = path_midpoint();
   387    387       if( pMid==0 ){
   388    388         fossil_print("bisect complete\n");
   389    389       }else{
   390         -      int nSpan = path_length();
   391         -      int nStep = path_search_depth();
   392    390         g.argv[1] = "update";
   393    391         g.argv[2] = db_text(0, "SELECT uuid FROM blob WHERE rid=%d", pMid->rid);
   394    392         g.argc = 3;
   395    393         g.fNoSync = 1;
   396    394         update_cmd();
   397         -      fossil_print("span: %d  steps-remaining: %d\n", nSpan, nStep);
   398    395       }
   399    396   
   400    397       if( strncmp(zDisplay,"chart",m)==0 ){
   401    398         bisect_chart(1);
   402    399       }else if( strncmp(zDisplay, "log", m)==0 ){
   403    400         bisect_chart(0);
   404    401       }else if( strncmp(zDisplay, "status", m)==0 ){

Changes to src/branch.c.

   176    176   
   177    177     /* Commit */
   178    178     db_end_transaction(0);
   179    179   
   180    180     /* Do an autosync push, if requested */
   181    181     if( !isPrivate ) autosync_loop(SYNC_PUSH, db_get_int("autosync-tries",1),0);
   182    182   }
   183         -
   184         -/*
   185         -** Create a TEMP table named "tmp_brlist" with 7 columns:
   186         -**
   187         -**      name           Name of the branch
   188         -**      mtime          Time of last checkin on this branch
   189         -**      isclosed       True if the branch is closed
   190         -**      mergeto        Another branch this branch was merged into
   191         -**      nckin          Number of checkins on this branch
   192         -**      ckin           Hash of the last checkin on this branch
   193         -**      bgclr          Background color for this branch
   194         -*/
   195         -static const char createBrlistQuery[] =
   196         -@ CREATE TEMP TABLE IF NOT EXISTS tmp_brlist AS
   197         -@ SELECT
   198         -@   tagxref.value AS name,
   199         -@   max(event.mtime) AS mtime,
   200         -@   EXISTS(SELECT 1 FROM tagxref AS tx
   201         -@           WHERE tx.rid=tagxref.rid
   202         -@             AND tx.tagid=(SELECT tagid FROM tag WHERE tagname='closed')
   203         -@             AND tx.tagtype>0) AS isclosed,
   204         -@   (SELECT tagxref.value
   205         -@      FROM plink CROSS JOIN tagxref
   206         -@    WHERE plink.pid=event.objid
   207         -@       AND tagxref.rid=plink.cid
   208         -@      AND tagxref.tagid=(SELECT tagid FROM tag WHERE tagname='branch')
   209         -@      AND tagtype>0) AS mergeto,
   210         -@   count(*) AS nckin,
   211         -@   (SELECT uuid FROM blob WHERE rid=tagxref.rid) AS ckin,
   212         -@   event.bgcolor AS bgclr
   213         -@  FROM tagxref, tag, event
   214         -@ WHERE tagxref.tagid=tag.tagid
   215         -@   AND tagxref.tagtype>0
   216         -@   AND tag.tagname='branch'
   217         -@   AND event.objid=tagxref.rid
   218         -@ GROUP BY 1;
   219         -;
   220         -
   221         -/* Call this routine to create the TEMP table */
   222         -static void brlist_create_temp_table(void){
   223         -  db_multi_exec(createBrlistQuery/*works-like:""*/);
   224         -}
   225         -
   226    183   
   227    184   #if INTERFACE
   228    185   /*
   229    186   ** Allows bits in the mBplqFlags parameter to branch_prepare_list_query().
   230    187   */
   231    188   #define BRL_CLOSED_ONLY      0x001 /* Show only closed branches */
   232    189   #define BRL_OPEN_ONLY        0x002 /* Show only open branches */
   233    190   #define BRL_BOTH             0x003 /* Show both open and closed branches */
   234    191   #define BRL_OPEN_CLOSED_MASK 0x003
   235         -#define BRL_ORDERBY_MTIME    0x004 /* Sort by MTIME. (otherwise sort by name)*/
   236         -#define BRL_REVERSE          0x008 /* Reverse the sort order */
          192  +#define BRL_MTIME            0x004 /* Include lastest check-in time */
          193  +#define BRL_ORDERBY_MTIME    0x008 /* Sort by MTIME. (otherwise sort by name)*/
   237    194   
   238    195   #endif /* INTERFACE */
   239    196   
   240    197   /*
   241    198   ** Prepare a query that will list branches.
   242    199   **
   243    200   ** If (which<0) then the query pulls only closed branches. If
   244    201   ** (which>0) then the query pulls all (closed and opened)
   245    202   ** branches. Else the query pulls currently-opened branches.
   246    203   */
   247    204   void branch_prepare_list_query(Stmt *pQuery, int brFlags){
   248         -  Blob sql;
   249         -  blob_init(&sql, 0, 0);
   250         -  brlist_create_temp_table();
   251    205     switch( brFlags & BRL_OPEN_CLOSED_MASK ){
   252    206       case BRL_CLOSED_ONLY: {
   253         -      blob_append_sql(&sql,
   254         -        "SELECT name FROM tmp_brlist WHERE isclosed"
          207  +      db_prepare(pQuery,
          208  +        "SELECT value FROM tagxref"
          209  +        " WHERE tagid=%d AND value NOT NULL "
          210  +        "EXCEPT "
          211  +        "SELECT value FROM tagxref"
          212  +        " WHERE tagid=%d"
          213  +        "   AND rid IN leaf"
          214  +        "   AND NOT %z"
          215  +        " ORDER BY value COLLATE nocase /*sort*/",
          216  +        TAG_BRANCH, TAG_BRANCH, leaf_is_closed_sql("tagxref.rid")
   255    217         );
   256    218         break;
   257    219       }
   258    220       case BRL_BOTH: {
   259         -      blob_append_sql(&sql,
   260         -        "SELECT name FROM tmp_brlist"
          221  +      db_prepare(pQuery,
          222  +        "SELECT DISTINCT value FROM tagxref"
          223  +        " WHERE tagid=%d AND value NOT NULL"
          224  +        "   AND rid IN leaf"
          225  +        " ORDER BY value COLLATE nocase /*sort*/",
          226  +        TAG_BRANCH
   261    227         );
   262    228         break;
   263    229       }
   264    230       case BRL_OPEN_ONLY: {
   265         -      blob_append_sql(&sql,
   266         -        "SELECT name FROM tmp_brlist WHERE NOT isclosed"
          231  +      db_prepare(pQuery,
          232  +        "SELECT DISTINCT value FROM tagxref"
          233  +        " WHERE tagid=%d AND value NOT NULL"
          234  +        "   AND rid IN leaf"
          235  +        "   AND NOT %z"
          236  +        " ORDER BY value COLLATE nocase /*sort*/",
          237  +        TAG_BRANCH, leaf_is_closed_sql("tagxref.rid")
   267    238         );
   268    239         break;
   269    240       }
   270    241     }
   271         -  if( brFlags & BRL_ORDERBY_MTIME ){
   272         -    blob_append_sql(&sql, " ORDER BY -mtime");
   273         -  }else{
   274         -    blob_append_sql(&sql, " ORDER BY name COLLATE nocase");
   275         -  }
   276         -  if( brFlags & BRL_REVERSE ){
   277         -    blob_append_sql(&sql," DESC");
   278         -  }
   279         -  db_prepare_blob(pQuery, &sql);
   280         -  blob_reset(&sql);
   281    242   }
   282    243   
   283    244   /*
   284    245   ** If the branch named in the argument is open, return a RID for one of
   285    246   ** the open leaves of that branch.  If the branch does not exists or is
   286    247   ** closed, return 0.
   287    248   */
................................................................................
   313    274   **
   314    275   **        Print the name of the branch for the current check-out
   315    276   **
   316    277   **    fossil branch info BRANCH-NAME
   317    278   **
   318    279   **        Print information about a branch
   319    280   **
   320         -**    fossil branch list|ls ?OPTIONS?
          281  +**    fossil branch list|ls ?-a|--all|-c|--closed?
   321    282   **
   322         -**        List all branches. Options:
   323         -**          -a|--all      List all branches.  Default show only open branches
   324         -**          -c|--closed   List closed branches.
   325         -**          -r            Reverse the sort order
   326         -**          -t            Show recently changed branches first
          283  +**        List all branches.  Use -a or --all to list all branches and
          284  +**        -c or --closed to list all closed branches.  The default is to
          285  +**        show only open branches.
   327    286   **
   328    287   **    fossil branch new BRANCH-NAME BASIS ?OPTIONS?
   329    288   **
   330    289   **        Create a new branch BRANCH-NAME off of check-in BASIS.
   331    290   **        Supported options for this subcommand include:
   332    291   **        --private             branch is private (i.e., remains local)
   333    292   **        --bgcolor COLOR       use COLOR instead of automatic background
................................................................................
   384    343     }else if( (strncmp(zCmd,"list",n)==0)||(strncmp(zCmd, "ls", n)==0) ){
   385    344       Stmt q;
   386    345       int vid;
   387    346       char *zCurrent = 0;
   388    347       int brFlags = BRL_OPEN_ONLY;
   389    348       if( find_option("all","a",0)!=0 ) brFlags = BRL_BOTH;
   390    349       if( find_option("closed","c",0)!=0 ) brFlags = BRL_CLOSED_ONLY;
   391         -    if( find_option("t",0,0)!=0 ) brFlags |= BRL_ORDERBY_MTIME;
   392         -    if( find_option("r",0,0)!=0 ) brFlags |= BRL_REVERSE;
   393    350   
   394    351       if( g.localOpen ){
   395    352         vid = db_lget_int("checkout", 0);
   396    353         zCurrent = db_text(0, "SELECT value FROM tagxref"
   397    354                               " WHERE rid=%d AND tagid=%d", vid, TAG_BRANCH);
   398    355       }
   399    356       branch_prepare_list_query(&q, brFlags);
................................................................................
   406    363     }else if( strncmp(zCmd,"new",n)==0 ){
   407    364       branch_new();
   408    365     }else{
   409    366       fossil_fatal("branch subcommand should be one of: "
   410    367                    "current info list ls new");
   411    368     }
   412    369   }
          370  +
          371  +static const char brlistQuery[] =
          372  +@ SELECT
          373  +@   tagxref.value,
          374  +@   max(event.mtime),
          375  +@   EXISTS(SELECT 1 FROM tagxref AS tx
          376  +@           WHERE tx.rid=tagxref.rid
          377  +@             AND tx.tagid=(SELECT tagid FROM tag WHERE tagname='closed')
          378  +@             AND tx.tagtype>0),
          379  +@   (SELECT tagxref.value
          380  +@      FROM plink CROSS JOIN tagxref
          381  +@    WHERE plink.pid=event.objid
          382  +@       AND tagxref.rid=plink.cid
          383  +@      AND tagxref.tagid=(SELECT tagid FROM tag WHERE tagname='branch')
          384  +@      AND tagtype>0),
          385  +@   count(*),
          386  +@   (SELECT uuid FROM blob WHERE rid=tagxref.rid),
          387  +@   event.bgcolor
          388  +@  FROM tagxref, tag, event
          389  +@ WHERE tagxref.tagid=tag.tagid
          390  +@   AND tagxref.tagtype>0
          391  +@   AND tag.tagname='branch'
          392  +@   AND event.objid=tagxref.rid
          393  +@ GROUP BY 1
          394  +@ ORDER BY 2 DESC;
          395  +;
   413    396   
   414    397   /*
   415    398   ** This is the new-style branch-list page that shows the branch names
   416    399   ** together with their ages (time of last check-in) and whether or not
   417    400   ** they are closed or merged to another branch.
   418    401   **
   419    402   ** Control jumps to this routine from brlist_page() (the /brlist handler)
................................................................................
   426    409     login_check_credentials();
   427    410     if( !g.perm.Read ){ login_needed(g.anon.Read); return; }
   428    411     style_header("Branches");
   429    412     style_adunit_config(ADUNIT_RIGHT_OK);
   430    413     style_submenu_checkbox("colors", "Use Branch Colors", 0, 0);
   431    414     login_anonymous_available();
   432    415   
   433         -  brlist_create_temp_table();
   434         -  db_prepare(&q, "SELECT * FROM tmp_brlist ORDER BY mtime DESC");
          416  +  db_prepare(&q, brlistQuery/*works-like:""*/);
   435    417     rNow = db_double(0.0, "SELECT julianday('now')");
   436    418     @ <div class="brlist">
   437    419     @ <table class='sortable' data-column-types='tkNtt' data-init-sort='2'>
   438    420     @ <thead><tr>
   439    421     @ <th>Branch Name</th>
   440    422     @ <th>Age</th>
   441    423     @ <th>Check-ins</th>
................................................................................
   462    444       }
   463    445       if( zBgClr && zBgClr[0] && show_colors ){
   464    446         @ <tr style="background-color:%s(zBgClr)">
   465    447       }else{
   466    448         @ <tr>
   467    449       }
   468    450       @ <td>%z(href("%R/timeline?n=100&r=%T",zBranch))%h(zBranch)</a></td>
   469         -    @ <td data-sortkey="%016llx(iMtime)">%s(zAge)</td>
          451  +    @ <td data-sortkey="%016llx(-iMtime)">%s(zAge)</td>
   470    452       @ <td>%d(nCkin)</td>
   471    453       fossil_free(zAge);
   472    454       @ <td>%s(isClosed?"closed":"")</td>
   473    455       if( zMergeTo ){
   474    456         @ <td>merged into
   475    457         @ %z(href("%R/timeline?f=%!S",zLastCkin))%h(zMergeTo)</a></td>
   476    458       }else{

Changes to src/browse.c.

   940    940     }else if( rAge*1440.0<90 ){
   941    941       return mprintf("%.1f minutes", rAge*1440.0);
   942    942     }else if( rAge*24.0<36 ){
   943    943       return mprintf("%.1f hours", rAge*24.0);
   944    944     }else if( rAge<365.0 ){
   945    945       return mprintf("%.1f days", rAge);
   946    946     }else{
   947         -    return mprintf("%.2f years", rAge/365.2425);
          947  +    return mprintf("%.2f years", rAge/365.0);
   948    948     }
   949    949   }
   950    950   
   951    951   /*
   952    952   ** COMMAND: test-fileage
   953    953   **
   954    954   ** Usage: %fossil test-fileage CHECKIN

Changes to src/cache.c.

   342    342                    " Should be one of: clear init list status", zCmd);
   343    343     }
   344    344   }
   345    345   
   346    346   /*
   347    347   ** WEBPAGE: cachestat
   348    348   **
   349         -** Show information about the webpage cache.  Requires Setup privilege.
          349  +** Show information about the webpage cache.  Requires Admin privilege.
   350    350   */
   351    351   void cache_page(void){
   352    352     sqlite3 *db;
   353    353     sqlite3_stmt *pStmt;
   354    354     char zBuf[100];
   355    355   
   356    356     login_check_credentials();

Changes to src/capabilities.c.

   226    226   
   227    227   /*
   228    228   ** The following structure holds descriptions of the various capabilities.
   229    229   */
   230    230   static struct Caps {
   231    231     char cCap;              /* The capability letter */
   232    232     unsigned short eClass;  /* The "class" for this capability */
   233         -  unsigned nUser;         /* Number of users with this capability */
   234    233     char *zAbbrev;          /* Abbreviated mnemonic name */
   235    234     char *zOneLiner;        /* One-line summary */
   236    235   } aCap[] = {
   237         -  { 'a', CAPCLASS_SUPER, 0,
          236  +  { 'a', CAPCLASS_SUPER,
   238    237       "Admin", "Create and delete users" },
   239         -  { 'b', CAPCLASS_WIKI|CAPCLASS_TKT, 0,
          238  +  { 'b', CAPCLASS_WIKI|CAPCLASS_TKT,
   240    239       "Attach", "Add attchments to wiki or tickets" },
   241         -  { 'c', CAPCLASS_TKT, 0,
          240  +  { 'c', CAPCLASS_TKT,
   242    241       "Append-Tkt", "Append to existing tickets" },
   243         -  { 'd', CAPCLASS_WIKI|CAPCLASS_TKT, 0,
          242  +  { 'd', CAPCLASS_WIKI|CAPCLASS_TKT,
   244    243       "Delete", "Delete wiki or tickets" },
   245         -  { 'e', CAPCLASS_DATA, 0,
          244  +  { 'e', CAPCLASS_DATA,
   246    245       "View-PII", "View sensitive info such as email addresses" },
   247         -  { 'f', CAPCLASS_WIKI, 0,
          246  +  { 'f', CAPCLASS_WIKI,
   248    247       "New-Wiki", "Create new wiki pages" },
   249         -  { 'g', CAPCLASS_DATA, 0,
          248  +  { 'g', CAPCLASS_DATA,
   250    249       "Clone", "Clone the repository" },
   251         -  { 'h', CAPCLASS_OTHER, 0,
          250  +  { 'h', CAPCLASS_OTHER,
   252    251       "Hyperlinks", "Show hyperlinks to detailed repository history" },
   253         -  { 'i', CAPCLASS_CODE, 0,
          252  +  { 'i', CAPCLASS_CODE,
   254    253       "Check-In", "Check-in code changes" },
   255         -  { 'j', CAPCLASS_WIKI, 0,
          254  +  { 'j', CAPCLASS_WIKI,
   256    255       "Read-Wiki", "View wiki pages" },
   257         -  { 'k', CAPCLASS_WIKI, 0,
          256  +  { 'k', CAPCLASS_WIKI,
   258    257       "Write-Wiki", "Edit wiki pages" },
   259         -  { 'l', CAPCLASS_WIKI|CAPCLASS_SUPER, 0,
          258  +  { 'l', CAPCLASS_WIKI|CAPCLASS_SUPER,
   260    259       "Mod-Wiki", "Moderator for wiki pages" },
   261         -  { 'm', CAPCLASS_WIKI, 0,
          260  +  { 'm', CAPCLASS_WIKI,
   262    261       "Append-Wiki", "Append to wiki pages" },
   263         -  { 'n', CAPCLASS_TKT, 0,
          262  +  { 'n', CAPCLASS_TKT,
   264    263       "New-Tkt", "Create new tickets" },
   265         -  { 'o', CAPCLASS_CODE, 0,
          264  +  { 'o', CAPCLASS_CODE,
   266    265       "Check-Out", "Check out code" },
   267         -  { 'p', CAPCLASS_OTHER, 0,
          266  +  { 'p', CAPCLASS_OTHER,
   268    267       "Password", "Change your own password" },
   269         -  { 'q', CAPCLASS_TKT|CAPCLASS_SUPER, 0,
          268  +  { 'q', CAPCLASS_TKT|CAPCLASS_SUPER,
   270    269       "Mod-Tkt", "Moderate tickets" },
   271         -  { 'r', CAPCLASS_TKT, 0,
          270  +  { 'r', CAPCLASS_TKT,
   272    271       "Read-Tkt", "View tickets" },
   273         -  { 's', CAPCLASS_SUPER, 0,
          272  +  { 's', CAPCLASS_SUPER,
   274    273       "Superuser", "Setup and configure the respository" },
   275         -  { 't', CAPCLASS_TKT, 0,
          274  +  { 't', CAPCLASS_TKT,
   276    275       "Reports", "Create new ticket report formats" },
   277         -  { 'u', CAPCLASS_OTHER, 0,
          276  +  { 'u', CAPCLASS_OTHER,
   278    277       "Reader", "Inherit all the capabilities of the \"reader\" user" },
   279         -  { 'v', CAPCLASS_OTHER, 0,
          278  +  { 'v', CAPCLASS_OTHER,
   280    279       "Developer", "Inherit all capabilities of the \"developer\" user" },
   281         -  { 'w', CAPCLASS_TKT, 0,
          280  +  { 'w', CAPCLASS_TKT,
   282    281       "Write-Tkt", "Edit tickets" },
   283         -  { 'x', CAPCLASS_DATA, 0,
          282  +  { 'x', CAPCLASS_DATA,
   284    283       "Private", "Push and/or pull private branches" },
   285         -  { 'y', CAPCLASS_SUPER, 0,
          284  +  { 'y', CAPCLASS_SUPER,
   286    285       "Write-UV", "Push unversioned content" },
   287         -  { 'z', CAPCLASS_CODE, 0,
          286  +  { 'z', CAPCLASS_CODE,
   288    287       "Zip-Download", "Download a ZIP archive, tarball, or SQL archive" },
   289         -  { '2', CAPCLASS_FORUM, 0,
          288  +  { '2', CAPCLASS_FORUM,
   290    289       "Forum-Read", "Read forum posts by others" },
   291         -  { '3', CAPCLASS_FORUM, 0,
          290  +  { '3', CAPCLASS_FORUM,
   292    291       "Forum-Write", "Create new forum messages" },
   293         -  { '4', CAPCLASS_FORUM, 0,
          292  +  { '4', CAPCLASS_FORUM,
   294    293       "Forum-Trusted", "Create forum messages that bypass moderation" },
   295         -  { '5', CAPCLASS_FORUM|CAPCLASS_SUPER, 0,
          294  +  { '5', CAPCLASS_FORUM|CAPCLASS_SUPER,
   296    295       "Forum-Mod", "Moderator for forum messages" },
   297         -  { '6', CAPCLASS_FORUM|CAPCLASS_SUPER, 0,
          296  +  { '6', CAPCLASS_FORUM|CAPCLASS_SUPER,
   298    297       "Forum-Admin", "Set or remove capability '4' from other users" },
   299         -  { '7', CAPCLASS_ALERT, 0,
          298  +  { '7', CAPCLASS_ALERT,
   300    299       "Alerts", "Sign up for email alerts" },
   301         -  { 'A', CAPCLASS_ALERT|CAPCLASS_SUPER, 0,
          300  +  { 'A', CAPCLASS_ALERT|CAPCLASS_SUPER,
   302    301       "Announce", "Send announcements to all subscribers" },
   303         -  { 'D', CAPCLASS_OTHER, 0,
          302  +  { 'D', CAPCLASS_OTHER,
   304    303       "Debug", "Enable debugging features" },
   305    304   };
   306    305   
   307         -/*
   308         -** Populate the aCap[].nUser values based on the current content
   309         -** of the USER table.
   310         -*/
   311         -void capabilities_count(void){
   312         -  int i;
   313         -  static int done = 0;
   314         -  Stmt q;
   315         -  if( done ) return;
   316         -  db_prepare(&q, "SELECT fullcap(cap) FROM user");
   317         -  while( db_step(&q)==SQLITE_ROW ){
   318         -    const char *zCap = db_column_text(&q, 0);
   319         -    if( zCap==0 || zCap[0]==0 ) continue;
   320         -    for(i=0; i<sizeof(aCap)/sizeof(aCap[0]); i++){
   321         -      if( strchr(zCap, aCap[i].cCap) ) aCap[i].nUser++;
   322         -    }
   323         -  }
   324         -  db_finalize(&q);
   325         -  done = 1;
   326         -}
   327         -
   328    306   
   329    307   /*
   330    308   ** Generate HTML that lists all of the capability letters together with
   331    309   ** a brief summary of what each letter means.
   332    310   */
   333    311   void capabilities_table(unsigned mClass){
   334    312     int i;
   335         -  if( g.perm.Admin ) capabilities_count();
   336    313     @ <table>
   337         -  @ <tbody>
   338    314     for(i=0; i<sizeof(aCap)/sizeof(aCap[0]); i++){
   339         -    int n;
   340    315       if( (aCap[i].eClass & mClass)==0 ) continue;
   341    316       @ <tr><th valign="top">%c(aCap[i].cCap)</th>
   342         -    @  <td>%h(aCap[i].zAbbrev)</td><td>%h(aCap[i].zOneLiner)</td>\
   343         -    n = aCap[i].nUser;
   344         -    if( n && g.perm.Admin ){
   345         -      @ <td><a href="%R/setup_ulist?with=%c(aCap[i].cCap)">\
   346         -      @ %d(n) user%s(n>1?"s":"")</a></td>\
   347         -    }
   348         -    @ </tr>
          317  +    @  <td><i>%h(aCap[i].zAbbrev):</i> %h(aCap[i].zOneLiner)</td></tr>
   349    318     }
   350         -  @ </tbody>
   351    319     @ </table>
   352    320   }
   353    321   
   354    322   /*
   355    323   ** Generate a "capability summary table" that shows the major capabilities
   356    324   ** against the various user categories.
   357    325   */

Changes to src/cgi.c.

  2065   2065   ** Return true if information is coming from the loopback network.
  2066   2066   */
  2067   2067   int cgi_is_loopback(const char *zIpAddr){
  2068   2068     return fossil_strcmp(zIpAddr, "127.0.0.1")==0 ||
  2069   2069            fossil_strcmp(zIpAddr, "::ffff:127.0.0.1")==0 ||
  2070   2070            fossil_strcmp(zIpAddr, "::1")==0;
  2071   2071   }
  2072         -
  2073         -/*
  2074         -** Return true if the HTTP request is likely to be from a small-screen
  2075         -** mobile device.
  2076         -**
  2077         -** The returned value is a guess.  Use it only for setting up defaults.
  2078         -*/
  2079         -int cgi_from_mobile(void){
  2080         -  const char *zAgent = P("HTTP_USER_AGENT");
  2081         -  if( zAgent==0 ) return 0;
  2082         -  if( sqlite3_strglob("*iPad*", zAgent)==0 ) return 0;
  2083         -  return sqlite3_strlike("%mobile%", zAgent, 0)==0;
  2084         -}

Changes to src/comformat.c.

     1      1   /*
     2      2   ** Copyright (c) 2007 D. Richard Hipp
     3      3   **
     4      4   ** This program is free software; you can redistribute it and/or
     5      5   ** modify it under the terms of the Simplified BSD License (also
     6      6   ** known as the "2-Clause License" or "FreeBSD License".)
     7         -**
            7  +
     8      8   ** This program is distributed in the hope that it will be useful,
     9      9   ** but without any warranty; without even the implied warranty of
    10     10   ** merchantability or fitness for a particular purpose.
    11     11   **
    12     12   ** Author contact information:
    13     13   **   drh@hwaci.com
    14     14   **   http://www.hwaci.com/drh/
................................................................................
    93     93     *pMaxChars = COMMENT_LEGACY_LINE_LENGTH - indent;
    94     94     return -1;
    95     95   #endif
    96     96   }
    97     97   
    98     98   /*
    99     99   ** This function checks the current line being printed against the original
   100         -** comment text.  Upon matching, it updates the provided character and line
   101         -** counts, if applicable.  The caller needs to emit a new line, if desired.
          100  +** comment text.  Upon matching, it emits a new line and updates the provided
          101  +** character and line counts, if applicable.
   102    102   */
   103    103   static int comment_check_orig(
   104    104     const char *zOrigText, /* [in] Original comment text ONLY, may be NULL. */
   105    105     const char *zLine,     /* [in] The comment line to print. */
   106    106     int *pCharCnt,         /* [in/out] Pointer to the line character count. */
   107    107     int *pLineCnt          /* [in/out] Pointer to the total line count. */
   108    108   ){
   109    109     if( zOrigText && fossil_strcmp(zLine, zOrigText)==0 ){
          110  +    fossil_print("\n");
   110    111       if( pCharCnt ) *pCharCnt = 0;
   111    112       if( pLineCnt ) (*pLineCnt)++;
   112    113       return 1;
   113    114     }
   114    115     return 0;
   115    116   }
   116    117   
................................................................................
   118    119   ** This function scans the specified comment line starting just after the
   119    120   ** initial index and returns the index of the next spacing character -OR-
   120    121   ** zero if such a character cannot be found.  For the purposes of this
   121    122   ** algorithm, the NUL character is treated the same as a spacing character.
   122    123   */
   123    124   static int comment_next_space(
   124    125     const char *zLine, /* [in] The comment line being printed. */
   125         -  int index,         /* [in] The current character index being handled. */
   126         -  int *distUTF8      /* [out] Distance to next space in UTF-8 sequences. */
          126  +  int index          /* [in] The current character index being handled. */
   127    127   ){
   128    128     int nextIndex = index + 1;
   129         -  int fNonASCII=0;
   130    129     for(;;){
   131    130       char c = zLine[nextIndex];
   132         -    if( (c&0x80)==0x80 ) fNonASCII=1;
   133    131       if( c==0 || fossil_isspace(c) ){
   134         -      if( distUTF8 ){
   135         -        if( fNonASCII!=0 ){
   136         -          *distUTF8 = strlen_utf8(&zLine[index], nextIndex-index);
   137         -        }else{
   138         -          *distUTF8 = nextIndex-index;
   139         -        }
   140         -      }
   141    132         return nextIndex;
   142    133       }
   143    134       nextIndex++;
   144    135     }
   145    136     return 0; /* NOT REACHED */
   146    137   }
   147    138   
   148    139   /*
   149         -** Count the number of UTF-8 sequences in a string. Incomplete, ill-formed and
   150         -** overlong sequences are counted as one sequence. The invalid lead bytes 0xC0
   151         -** to 0xC1 and 0xF5 to 0xF7 are allowed to initiate (ill-formed) 2- and 4-byte
   152         -** sequences, respectively, the other invalid lead bytes 0xF8 to 0xFF are
   153         -** treated as invalid 1-byte sequences (as lone trail bytes).
   154         -** Combining characters and East Asian Wide and Fullwidth characters are counted
   155         -** as one, so this function does not calculate the effective "display width".
          140  +** This function is called when printing a logical comment line to perform
          141  +** the necessary indenting.
   156    142   */
   157         -int strlen_utf8(const char *zString, int lengthBytes){
   158         -  int i;          /* Counted bytes. */
   159         -  int lengthUTF8; /* Counted UTF-8 sequences. */
   160         -#if 0
   161         -  assert( lengthBytes>=0 );
   162         -#endif
   163         -  for(i=0, lengthUTF8=0; i<lengthBytes; i++, lengthUTF8++){
   164         -    char c = zString[i];
   165         -    int cchUTF8=1; /* Code units consumed. */
   166         -    int maxUTF8=1; /* Expected sequence length. */
   167         -    if( (c&0xe0)==0xc0 )maxUTF8=2;          /* UTF-8 lead byte 110vvvvv */
   168         -    else if( (c&0xf0)==0xe0 )maxUTF8=3;     /* UTF-8 lead byte 1110vvvv */
   169         -    else if( (c&0xf8)==0xf0 )maxUTF8=4;     /* UTF-8 lead byte 11110vvv */
   170         -    while( cchUTF8<maxUTF8 &&
   171         -            i<lengthBytes-1 &&
   172         -            (zString[i+1]&0xc0)==0x80 ){    /* UTF-8 trail byte 10vvvvvv */
   173         -      cchUTF8++;
   174         -      i++;
   175         -    }
   176         -  }
   177         -  return lengthUTF8;
   178         -}
   179         -
   180         -/*
   181         -** This function is called when printing a logical comment line to calculate
   182         -** the necessary indenting.  The caller needs to emit the indenting spaces.
   183         -*/
   184         -static void comment_calc_indent(
          143  +static void comment_print_indent(
   185    144     const char *zLine, /* [in] The comment line being printed. */
   186    145     int indent,        /* [in] Number of spaces to indent, zero for none. */
   187    146     int trimCrLf,      /* [in] Non-zero to trim leading/trailing CR/LF. */
   188    147     int trimSpace,     /* [in] Non-zero to trim leading/trailing spaces. */
   189    148     int *piIndex       /* [in/out] Pointer to first non-space character. */
   190    149   ){
          150  +  if( indent>0 ){
          151  +    fossil_print("%*s", indent, "");
          152  +  }
   191    153     if( zLine && piIndex ){
   192    154       int index = *piIndex;
   193    155       if( trimCrLf ){
   194    156         while( zLine[index]=='\r' || zLine[index]=='\n' ){ index++; }
   195    157       }
   196    158       if( trimSpace ){
   197    159         while( fossil_isspace(zLine[index]) ){ index++; }
................................................................................
   215    177     int trimCrLf,          /* [in] Non-zero to trim leading/trailing CR/LF. */
   216    178     int trimSpace,         /* [in] Non-zero to trim leading/trailing spaces. */
   217    179     int wordBreak,         /* [in] Non-zero to try breaking on word boundaries. */
   218    180     int origBreak,         /* [in] Non-zero to break before original comment. */
   219    181     int *pLineCnt,         /* [in/out] Pointer to the total line count. */
   220    182     const char **pzLine    /* [out] Pointer to the end of the logical line. */
   221    183   ){
   222         -  int index = 0, charCnt = 0, lineCnt = 0, maxChars, i;
   223         -  char zBuf[400]; int iBuf=0; /* Output buffer and counter. */
   224         -  int cchUTF8, maxUTF8;       /* Helper variables to count UTF-8 sequences. */
          184  +  int index = 0, charCnt = 0, lineCnt = 0, maxChars;
   225    185     if( !zLine ) return;
   226    186     if( lineChars<=0 ) return;
   227         -#if 0
   228         -  assert( indent<sizeof(zBuf)-5 );       /* See following comments to explain */
   229         -  assert( origIndent<sizeof(zBuf)-5 );   /* these limits. */
   230         -#endif
   231         -  if( indent>sizeof(zBuf)-6 ){
   232         -    /* Limit initial indent to fit output buffer. */
   233         -    indent = sizeof(zBuf)-6;
   234         -  }
   235         -  comment_calc_indent(zLine, indent, trimCrLf, trimSpace, &index);
   236         -  if( indent>0 ){
   237         -    for(i=0; i<indent; i++){
   238         -      zBuf[iBuf++] = ' ';
   239         -    }
   240         -  }
   241         -  if( origIndent>sizeof(zBuf)-6 ){
   242         -    /* Limit line indent to fit output buffer. */
   243         -    origIndent = sizeof(zBuf)-6;
   244         -  }
          187  +  comment_print_indent(zLine, indent, trimCrLf, trimSpace, &index);
   245    188     maxChars = lineChars;
   246    189     for(;;){
   247    190       int useChars = 1;
   248    191       char c = zLine[index];
   249         -    /* Flush the output buffer if there's no space left for at least one more
   250         -    ** (potentially 4-byte) UTF-8 sequence, one level of indentation spaces,
   251         -    ** a new line, and a terminating NULL. */
   252         -    if( iBuf>sizeof(zBuf)-origIndent-6 ){
   253         -      zBuf[iBuf]=0;
   254         -      iBuf=0;
   255         -      fossil_print("%s", zBuf);
   256         -    }
   257    192       if( c==0 ){
   258    193         break;
   259    194       }else{
   260    195         if( origBreak && index>0 ){
   261    196           const char *zCurrent = &zLine[index];
   262    197           if( comment_check_orig(zOrigText, zCurrent, &charCnt, &lineCnt) ){
   263         -          zBuf[iBuf++] = '\n';
   264         -          comment_calc_indent(zLine, origIndent, trimCrLf, trimSpace, &index);
   265         -          for( i=0; i<origIndent; i++ ){
   266         -            zBuf[iBuf++] = ' ';
   267         -          }
          198  +          comment_print_indent(zCurrent, origIndent, trimCrLf, trimSpace,
          199  +                               &index);
   268    200             maxChars = lineChars;
   269    201           }
   270    202         }
   271    203         index++;
   272    204       }
   273    205       if( c=='\n' ){
   274    206         lineCnt++;
   275    207         charCnt = 0;
   276    208         useChars = 0;
   277    209       }else if( c=='\t' ){
   278         -      int distUTF8;
   279         -      int nextIndex = comment_next_space(zLine, index, &distUTF8);
   280         -      if( nextIndex<=0 || distUTF8>maxChars ){
          210  +      int nextIndex = comment_next_space(zLine, index);
          211  +      if( nextIndex<=0 || (nextIndex-index)>maxChars ){
   281    212           break;
   282    213         }
   283    214         charCnt++;
   284    215         useChars = COMMENT_TAB_WIDTH;
   285    216         if( maxChars<useChars ){
   286         -        zBuf[iBuf++] = ' ';
          217  +        fossil_print(" ");
   287    218           break;
   288    219         }
   289    220       }else if( wordBreak && fossil_isspace(c) ){
   290         -      int distUTF8;
   291         -      int nextIndex = comment_next_space(zLine, index, &distUTF8);
   292         -      if( nextIndex<=0 || distUTF8>maxChars ){
          221  +      int nextIndex = comment_next_space(zLine, index);
          222  +      if( nextIndex<=0 || (nextIndex-index)>maxChars ){
   293    223           break;
   294    224         }
   295    225         charCnt++;
   296    226       }else{
   297    227         charCnt++;
   298    228       }
   299    229       assert( c!='\n' || charCnt==0 );
   300         -    zBuf[iBuf++] = c;
   301         -    /* Skip over UTF-8 sequences, see comment on strlen_utf8() for details. */
   302         -    cchUTF8=1; /* Code units consumed. */
   303         -    maxUTF8=1; /* Expected sequence length. */
   304         -    if( (c&0xe0)==0xc0 )maxUTF8=2;          /* UTF-8 lead byte 110vvvvv */
   305         -    else if( (c&0xf0)==0xe0 )maxUTF8=3;     /* UTF-8 lead byte 1110vvvv */
   306         -    else if( (c&0xf8)==0xf0 )maxUTF8=4;     /* UTF-8 lead byte 11110vvv */
   307         -    while( cchUTF8<maxUTF8 &&
   308         -            (zLine[index]&0xc0)==0x80 ){    /* UTF-8 trail byte 10vvvvvv */
   309         -      cchUTF8++;
   310         -      zBuf[iBuf++] = zLine[index++];
   311         -    }
   312         -    maxChars -= useChars;
          230  +    fossil_print("%c", c);
          231  +    if( (c&0x80)==0 || (zLine[index+1]&0xc0)!=0xc0 ) maxChars -= useChars;
   313    232       if( maxChars<=0 ) break;
   314    233       if( c=='\n' ) break;
   315    234     }
   316    235     if( charCnt>0 ){
   317         -    zBuf[iBuf++] = '\n';
          236  +    fossil_print("\n");
   318    237       lineCnt++;
   319    238     }
   320         -  /* Flush the remaining output buffer. */
   321         -  if( iBuf>0 ){
   322         -    zBuf[iBuf]=0;
   323         -    iBuf=0;
   324         -    fossil_print("%s", zBuf);
   325         -  }
   326    239     if( pLineCnt ){
   327    240       *pLineCnt += lineCnt;
   328    241     }
   329    242     if( pzLine ){
   330    243       *pzLine = zLine + index;
   331    244     }
   332    245   }
................................................................................
   344    257   */
   345    258   static int comment_print_legacy(
   346    259     const char *zText, /* The comment text to be printed. */
   347    260     int indent,        /* Number of spaces to indent each non-initial line. */
   348    261     int width          /* Maximum number of characters per line. */
   349    262   ){
   350    263     int maxChars = width - indent;
   351         -  int si, sk, i, k, kc;
          264  +  int si, sk, i, k;
   352    265     int doIndent = 0;
   353    266     char *zBuf;
   354    267     char zBuffer[400];
   355    268     int lineCnt = 0;
   356         -  int cchUTF8, maxUTF8; /* Helper variables to count UTF-8 sequences. */
   357    269   
   358    270     if( width<0 ){
   359    271       comment_set_maxchars(indent, &maxChars);
   360    272     }
   361    273     if( zText==0 ) zText = "(NULL)";
   362    274     if( maxChars<=0 ){
   363    275       maxChars = strlen(zText);
   364    276     }
   365         -  /* Ensure the buffer can hold the longest-possible UTF-8 sequences. */
   366         -  if( maxChars >= (sizeof(zBuffer)/4-1) ){
   367         -    zBuf = fossil_malloc(maxChars*4+1);
          277  +  if( maxChars >= (sizeof(zBuffer)) ){
          278  +    zBuf = fossil_malloc(maxChars+1);
   368    279     }else{
   369    280       zBuf = zBuffer;
   370    281     }
   371    282     for(;;){
   372    283       while( fossil_isspace(zText[0]) ){ zText++; }
   373    284       if( zText[0]==0 ){
   374    285         if( doIndent==0 ){
   375    286           fossil_print("\n");
   376    287           lineCnt = 1;
   377    288         }
   378    289         if( zBuf!=zBuffer) fossil_free(zBuf);
   379    290         return lineCnt;
   380    291       }
   381         -    for(sk=si=i=k=kc=0; zText[i] && kc<maxChars; i++){
          292  +    for(sk=si=i=k=0; zText[i] && k<maxChars; i++){
   382    293         char c = zText[i];
   383         -      kc++; /* Count complete UTF-8 sequences. */
   384         -      /* Skip over UTF-8 sequences, see comment on strlen_utf8() for details. */
   385         -      cchUTF8=1; /* Code units consumed. */
   386         -      maxUTF8=1; /* Expected sequence length. */
   387         -      if( (c&0xe0)==0xc0 )maxUTF8=2;        /* UTF-8 lead byte 110vvvvv */
   388         -      else if( (c&0xf0)==0xe0 )maxUTF8=3;   /* UTF-8 lead byte 1110vvvv */
   389         -      else if( (c&0xf8)==0xf0 )maxUTF8=4;   /* UTF-8 lead byte 11110vvv */
   390         -      if( maxUTF8>1 ){
   391         -        zBuf[k++] = c;
   392         -        while( cchUTF8<maxUTF8 &&
   393         -                (zText[i+1]&0xc0)==0x80 ){  /* UTF-8 trail byte 10vvvvvv */
   394         -          cchUTF8++;
   395         -          zBuf[k++] = zText[++i];
   396         -        }
   397         -      }
   398         -      else if( fossil_isspace(c) ){
          294  +      if( fossil_isspace(c) ){
   399    295           si = i;
   400    296           sk = k;
   401    297           if( k==0 || zBuf[k-1]!=' ' ){
   402    298             zBuf[k++] = ' ';
   403    299           }
   404    300         }else{
   405    301           zBuf[k] = c;

Changes to src/db.c.

  3028   3028   */
  3029   3029   /*
  3030   3030   ** SETTING: backoffice-nodelay boolean default=off
  3031   3031   ** If backoffice-nodelay is true, then the backoffice processing
  3032   3032   ** will never invoke sleep().  If it has nothing useful to do,
  3033   3033   ** it simply exits.
  3034   3034   */
  3035         -/*
  3036         -** SETTING: backoffice-disable boolean default=off
  3037         -** If backoffice-disable is true, then the automatic backoffice
  3038         -** processing is disabled.  Automatic backoffice processing is the
  3039         -** backoffice work that normally runs after each web page is
  3040         -** rendered.  Backoffice processing that is triggered by the
  3041         -** "fossil backoffice" command is unaffected by this setting.
  3042         -**
  3043         -** Backoffice processing does things such as delivering
  3044         -** email notifications.  So if this setting is true, and if
  3045         -** there is no cron job periodically running "fossil backoffice",
  3046         -** email notifications and other work normally done by the
  3047         -** backoffice will not occur.
  3048         -*/
  3049   3035   /*
  3050   3036   ** SETTING: backoffice-logfile width=40
  3051   3037   ** If backoffice-logfile is not an empty string and is a valid
  3052   3038   ** filename, then a one-line message is appended to that file
  3053   3039   ** every time the backoffice runs.  This can be used for debugging,
  3054   3040   ** to ensure that backoffice is running appropriately.
  3055   3041   */
................................................................................
  3200   3186   /*
  3201   3187   ** SETTING: keep-glob        width=40 versionable block-text
  3202   3188   ** The value is a comma or newline-separated list of GLOB
  3203   3189   ** patterns specifying files that the "clean" command will keep.
  3204   3190   */
  3205   3191   /*
  3206   3192   ** SETTING: localauth        boolean default=off
  3207         -** If enabled, require that HTTP connections from the loopback
  3208         -** address (127.0.0.1) be authenticated by password.  If false,
  3209         -** some HTTP requests might be granted full "Setup" user
  3210         -** privileges without having to present login credentials.
  3211         -** This mechanism allows the "fossil ui" command to provide
  3212         -** full access to the repository without requiring the user to
  3213         -** log in first.
  3214         -**
  3215         -** In order for full "Setup" privilege to be granted without a
  3216         -** login, the following conditions must be met:
  3217         -**
  3218         -**   (1)  This setting ("localauth") must be off
  3219         -**   (2)  The HTTP request arrive over the loopback TCP/IP
  3220         -**        address (127.0.01) or else via SSH.
  3221         -**   (3)  The request must be HTTP, not HTTPS. (This
  3222         -**        restriction is designed to help prevent accidentally
  3223         -**        providing "Setup" privileges to requests arriving
  3224         -**        over a reverse proxy.)
  3225         -**   (4)  The command that launched the fossil server must be
  3226         -**        one of the following:
  3227         -**        (a) "fossil ui"
  3228         -**        (b) "fossil server" with the --localauth option
  3229         -**        (c) "fossil http" with the --localauth option
  3230         -**        (d) CGI with the "localauth" setting in the cgi script.
  3231         -**
  3232         -** For maximum security, set "localauth" to 1.  However, because
  3233         -** of the other restrictions (2) through (4), it should be safe
  3234         -** to leave "localauth" set to 0 in most installations, and 
  3235         -** especially on cloned repositories on workstations. Leaving
  3236         -** "localauth" at 0 makes the "fossil ui" command more convenient
  3237         -** to use.
         3193  +** If enabled, require that HTTP connections from
         3194  +** 127.0.0.1 be authenticated by password.  If
         3195  +** false, all HTTP requests from localhost have
         3196  +** unrestricted access to the repository.
  3238   3197   */
  3239   3198   /*
  3240   3199   ** SETTING: main-branch      width=40 default=trunk
  3241   3200   ** The value is the primary branch for the project.
  3242   3201   */
  3243   3202   /*
  3244   3203   ** SETTING: manifest         width=5 versionable

Changes to src/dispatch.c.

   363    363         const char *z = aCommand[i].zName;
   364    364         const char *zBoldOn  = aCommand[i].eCmdFlags&CMDFLAG_1ST_TIER?"<b>" :"";
   365    365         const char *zBoldOff = aCommand[i].eCmdFlags&CMDFLAG_1ST_TIER?"</b>":"";
   366    366         if( '/'==*z || strncmp(z,"test",4)==0 ) continue;
   367    367         if( (aCommand[i].eCmdFlags & CMDFLAG_SETTING)!=0 ) continue;
   368    368         @ <li><a href="%R/help?cmd=%s(z)">%s(zBoldOn)%s(z)%s(zBoldOff)</a></li>
   369    369       }
   370         -    @ </ul></div>
          370  +    @ </ui></div>
   371    371   
   372    372       @ <a name='webpages'></a>
   373    373       @ <h1>Available web UI pages:</h1>
   374    374       @ <div class="columns" style="column-width: 18ex;">
   375    375       @ <ul>
   376    376       for(i=0; i<MX_COMMAND; i++){
   377    377         const char *z = aCommand[i].zName;
................................................................................
   488    488       if( (aCommand[i].eCmdFlags & cmdMask)==0 ) continue;
   489    489       if( zPrefix && memcmp(zPrefix, z, nPrefix)!=0 ) continue;
   490    490       aCmd[nCmd++] = aCommand[i].zName;
   491    491     }
   492    492     multi_column_list(aCmd, nCmd);
   493    493   }
   494    494   
   495         -/*
   496         -** Documentation on universal command-line options.
   497         -*/
   498         -/* @-comment: # */
   499         -static const char zOptions[] =
   500         -@ Command-line options common to all commands:
   501         -@ 
   502         -@   --args FILENAME         Read additional arguments and options from FILENAME
   503         -@   --cgitrace              Active CGI tracing
   504         -@   --comfmtflags VALUE     Set comment formatting flags to VALUE
   505         -@   --errorlog FILENAME     Log errors to FILENAME 
   506         -@   --help                  Show help on the command rather than running it
   507         -@   --httptrace             Trace outbound HTTP requests
   508         -@   --localtime             Display times using the local timezone
   509         -@   --no-th-hook            Do not run TH1 hooks
   510         -@   --quiet                 Reduce the amount of output
   511         -@   --sqlstats              Show SQL usage statistics when done
   512         -@   --sqltrace              Trace all SQL commands
   513         -@   --sshtrace              Trace SSH activity
   514         -@   --ssl-identity NAME     Set the SSL identity to NAME
   515         -@   --systemtrace           Trace calls to system()
   516         -@   --user|-U USER          Make the default user be USER
   517         -@   --utc                   Display times using UTC
   518         -@   --vfs NAME              Cause SQLite to use the NAME VFS
   519         -;
   520         -
   521    495   /*
   522    496   ** COMMAND: help
   523    497   **
   524    498   ** Usage: %fossil help TOPIC
   525    499   **    or: %fossil TOPIC --help
   526    500   **
   527    501   ** Display information on how to use TOPIC, which may be a command, webpage, or
   528    502   ** setting.  Webpage names begin with "/".  To display a list of available
   529    503   ** topics, use one of:
   530    504   **
   531    505   **    %fossil help                Show common commands
   532    506   **    %fossil help -a|--all       Show both common and auxiliary commands
   533         -**    %fossil help -o|--options   Show command-line options common to all cmds
   534    507   **    %fossil help -s|--setting   Show setting names
   535    508   **    %fossil help -t|--test      Show test commands only
   536    509   **    %fossil help -x|--aux       Show auxiliary commands only
   537    510   **    %fossil help -w|--www       Show list of webpages
   538    511   */
   539    512   void help_cmd(void){
   540    513     int rc;
................................................................................
   543    516     const char *zCmdOrPage;
   544    517     const char *zCmdOrPagePlural;
   545    518     const CmdOrPage *pCmd = 0;
   546    519     if( g.argc<3 ){
   547    520       z = g.argv[0];
   548    521       fossil_print(
   549    522         "Usage: %s help TOPIC\n"
   550         -      "Common commands:  (use \"%s help help\" for more options)\n",
          523  +      "Common commands:  (use \"%s help -a|--all\" for a complete list)\n",
   551    524         z, z);
   552    525       command_list(0, CMDFLAG_1ST_TIER);
   553    526       version_cmd();
   554    527       return;
   555    528     }
   556         -  if( find_option("options","o",0) ){
   557         -    fossil_print("%s", zOptions);
   558         -    return;
   559         -  }
   560    529     if( find_option("all","a",0) ){
   561    530       command_list(0, CMDFLAG_1ST_TIER | CMDFLAG_2ND_TIER);
   562    531       return;
   563    532     }
   564    533     else if( find_option("www","w",0) ){
   565    534       command_list(0, CMDFLAG_WEBPAGE);
   566    535       return;

Changes to src/forum.c.

   264    264       @ <i>Deleted</i>
   265    265     }
   266    266     if( zClass ){
   267    267       @ </div>
   268    268     }
   269    269   }
   270    270   
   271         -/*
   272         -** Generate the buttons in the display that allow a forum supervisor to
   273         -** mark a user as trusted.  Only do this if:
   274         -**
   275         -**   (1)  The poster is an individual, not a special user like "anonymous"
   276         -**   (2)  The current user has Forum Supervisor privilege
   277         -*/
   278         -static void generateTrustControls(Manifest *pPost){
   279         -  if( !g.perm.AdminForum ) return;
   280         -  if( login_is_special(pPost->zUser) ) return;
   281         -  @ <br>
   282         -  @ <label><input type="checkbox" name="trust">
   283         -  @ Trust user "%h(pPost->zUser)"
   284         -  @ so that future posts by "%h(pPost->zUser)" do not require moderation.
   285         -  @ </label>
   286         -  @ <input type="hidden" name="trustuser" value="%h(pPost->zUser)">
   287         -}
   288         -
   289    271   /*
   290    272   ** Display all posts in a forum thread in chronological order
   291    273   */
   292    274   static void forum_display_chronological(int froot, int target){
   293    275     ForumThread *pThread = forumthread_create(froot, 0);
   294    276     ForumEntry *p;
   295    277     int notAnon = login_is_individual();
................................................................................
   311    293       if( pPost->zThreadTitle ){
   312    294         @ <h1>%h(pPost->zThreadTitle)</h1>
   313    295       }
   314    296       zDate = db_text(0, "SELECT datetime(%.17g)", pPost->rDate);
   315    297       @ <p>By %h(pPost->zUser) on %h(zDate) (%d(p->fpid))
   316    298       fossil_free(zDate);
   317    299       if( p->pEdit ){
   318         -      @ edit of %z(href("%R/forumpost/%S?t=c",p->pEdit->zUuid))%d(p->fprev)</a>
          300  +      @ edit of %z(href("%R/forumpost/%S?t",p->pEdit->zUuid))%d(p->fprev)</a>
   319    301       }
   320    302       if( p->firt ){
   321    303         ForumEntry *pIrt = p->pPrev;
   322    304         while( pIrt && pIrt->fpid!=p->firt ) pIrt = pIrt->pPrev;
   323    305         if( pIrt ){
   324         -        @ reply to %z(href("%R/forumpost/%S?t=c",pIrt->zUuid))%d(p->firt)</a>
          306  +        @ reply to %z(href("%R/forumpost/%S?t",pIrt->zUuid))%d(p->firt)</a>
   325    307         }
   326    308       }
   327    309       if( p->pLeaf ){
   328         -      @ updated by %z(href("%R/forumpost/%S?t=c",p->pLeaf->zUuid))\
          310  +      @ updated by %z(href("%R/forumpost/%S?t",p->pLeaf->zUuid))\
   329    311         @ %d(p->pLeaf->fpid)</a>
   330    312       }
   331    313       if( g.perm.Debug ){
   332    314         @ <span class="debug">\
   333    315         @ <a href="%R/artifact/%h(p->zUuid)">artifact</a></span>
   334    316       }
   335    317       if( p->fpid!=target ){
   336         -      @ %z(href("%R/forumpost/%S?t=c",p->zUuid))[link]</a>
          318  +      @ %z(href("%R/forumpost/%S?t",p->zUuid))[link]</a>
   337    319       }
   338    320       isPrivate = content_is_private(p->fpid);
   339    321       sameUser = notAnon && fossil_strcmp(pPost->zUser, g.zLogin)==0;
   340    322       if( isPrivate && !g.perm.ModForum && !sameUser ){
   341    323         @ <p><span class="modpending">Awaiting Moderator Approval</span></p>
   342    324       }else{
   343    325         forum_render(0, pPost->zMimetype, pPost->zWiki, 0);
................................................................................
   356    338             @ <input type="submit" name="nullout" value="Delete">
   357    339           }
   358    340         }else if( g.perm.ModForum ){
   359    341           /* Provide moderators with moderation buttons for posts that
   360    342           ** are pending moderation */
   361    343           @ <input type="submit" name="approve" value="Approve">
   362    344           @ <input type="submit" name="reject" value="Reject">
   363         -        generateTrustControls(pPost);
   364    345         }else if( sameUser ){
   365    346           /* A post that is pending moderation can be deleted by the
   366    347           ** person who originally submitted the post */
   367    348           @ <input type="submit" name="reject" value="Delete">
   368    349         }
   369    350         @ </form></p>
   370    351       }
................................................................................
   463    444             @ <input type="submit" name="nullout" value="Delete">
   464    445           }
   465    446         }else if( g.perm.ModForum ){
   466    447           /* Provide moderators with moderation buttons for posts that
   467    448           ** are pending moderation */
   468    449           @ <input type="submit" name="approve" value="Approve">
   469    450           @ <input type="submit" name="reject" value="Reject">
   470         -        generateTrustControls(pPost);
   471    451         }else if( sameUser ){
   472    452           /* A post that is pending moderation can be deleted by the
   473    453           ** person who originally submitted the post */
   474    454           @ <input type="submit" name="reject" value="Delete">
   475    455         }
   476    456         @ </form></p>
   477    457       }
................................................................................
   489    469   ** it's entire thread.  The selected posting is enclosed within
   490    470   ** <div class='forumSel'>...</div>.  Javascript is used to move the
   491    471   ** selected posting into view after the page loads.
   492    472   **
   493    473   ** Query parameters:
   494    474   **
   495    475   **   name=X        REQUIRED.  The hash of the post to display
   496         -**   t=MODE        Display mode. MODE is 'c' for chronological or
   497         -**                   'h' for hierarchical, or 'a' for automatic.
          476  +**   t             Show a chronologic listing instead of hierarchical
   498    477   */
   499    478   void forumpost_page(void){
   500    479     forumthread_page();
   501    480   }
   502    481   
   503    482   /*
   504    483   ** WEBPAGE: forumthread
................................................................................
   506    485   ** Show all forum messages associated with a particular message thread.
   507    486   ** The result is basically the same as /forumpost except that none of
   508    487   ** the postings in the thread are selected.
   509    488   **
   510    489   ** Query parameters:
   511    490   **
   512    491   **   name=X        REQUIRED.  The hash of any post of the thread.
   513         -**   t=MODE        Display mode. MODE is 'c' for chronological or
   514         -**                   'h' for hierarchical, or 'a' for automatic.
          492  +**   t             Show a chronologic listing instead of hierarchical
   515    493   */
   516    494   void forumthread_page(void){
   517    495     int fpid;
   518    496     int froot;
   519    497     const char *zName = P("name");
   520         -  const char *zMode = PD("t","a");
   521    498     login_check_credentials();
   522    499     if( !g.perm.RdForum ){
   523    500       login_needed(g.anon.RdForum);
   524    501       return;
   525    502     }
   526    503     if( zName==0 ){
   527    504       webpage_error("Missing \"name=\" query parameter");
................................................................................
   532    509     }
   533    510     style_header("Forum");
   534    511     froot = db_int(0, "SELECT froot FROM forumpost WHERE fpid=%d", fpid);
   535    512     if( froot==0 ){
   536    513       webpage_error("Not a forum post: \"%s\"", zName);
   537    514     }
   538    515     if( fossil_strcmp(g.zPath,"forumthread")==0 ) fpid = 0;
   539         -  if( zMode[0]=='a' ){
   540         -    if( cgi_from_mobile() ){
   541         -      zMode = "c";  /* Default to chronological on mobile */
   542         -    }else{
   543         -      zMode = "h";
   544         -    }
   545         -  }
   546         -  if( zMode[0]=='c' ){
   547         -    style_submenu_element("Hierarchical", "%R/%s/%s?t=h", g.zPath, zName);
          516  +  if( P("t") ){
          517  +    if( g.perm.Debug ){
          518  +      style_submenu_element("Hierarchical", "%R/%s/%s", g.zPath, zName);
          519  +    }                          
   548    520       forum_display_chronological(froot, fpid);
   549    521     }else{
   550         -    style_submenu_element("Chronological", "%R/%s/%s?t=c", g.zPath, zName);
          522  +    if( g.perm.Debug ){
          523  +      style_submenu_element("Chronological", "%R/%s/%s?t", g.zPath, zName);
          524  +    }                          
   551    525       forum_display_hierarchical(froot, fpid);
   552    526     }
   553    527     style_load_js("forum.js");
   554    528     style_footer();
   555    529   }
   556    530   
   557    531   /*
................................................................................
   764    738     }
   765    739     if( P("preview") ){
   766    740       @ <h1>Preview:</h1>
   767    741       forum_render(zTitle, zMimetype, zContent, "forumEdit");
   768    742     }
   769    743     style_header("New Forum Thread");
   770    744     @ <form action="%R/forume1" method="POST">
   771         -  @ <h1>New Thread:</h1>
          745  +  @ <h1>New Message:</h1>
   772    746     forum_from_line();
   773    747     forum_entry_widget(zTitle, zMimetype, zContent);
   774    748     @ <input type="submit" name="preview" value="Preview">
   775    749     if( P("preview") ){
   776    750       @ <input type="submit" name="submit" value="Submit">
   777    751     }else{
   778    752       @ <input type="submit" name="submit" value="Submit" disabled>
................................................................................
   821    795     if( P("cancel") ){
   822    796       cgi_redirectf("%R/forumpost/%S",P("fpid"));
   823    797       return;
   824    798     }
   825    799     isCsrfSafe = cgi_csrf_safe(1);
   826    800     if( g.perm.ModForum && isCsrfSafe ){
   827    801       if( P("approve") ){
   828         -      const char *zUserToTrust;
   829    802         moderation_approve(fpid);
   830         -      if( g.perm.AdminForum
   831         -       && PB("trust")
   832         -       && (zUserToTrust = P("trustuser"))!=0
   833         -      ){
   834         -        db_multi_exec("UPDATE user SET cap=cap||'4' "
   835         -                      "WHERE login=%Q AND cap NOT GLOB '*4*'",
   836         -                      zUserToTrust);
   837         -      }
   838    803         cgi_redirectf("%R/forumpost/%S",P("fpid"));
   839    804         return;
   840    805       }
   841    806       if( P("reject") ){
   842    807         char *zParent = 
   843    808           db_text(0,
   844    809             "SELECT uuid FROM forumpost, blob"
................................................................................
   970    935     srchFlags = search_restrict(SRCH_FORUM);
   971    936     if( !g.perm.RdForum ){
   972    937       login_needed(g.anon.RdForum);
   973    938       return;
   974    939     }
   975    940     style_header("Forum");
   976    941     if( g.perm.WrForum ){
   977         -    style_submenu_element("New Thread","%R/forumnew");
   978         -  }else{
   979         -    /* Can't combine this with previous case using the ternary operator
   980         -     * because that causes an error yelling about "non-constant format"
   981         -     * with some compilers.  I can't see it, since both expressions have
   982         -     * the same format, but I'm no C spec lawyer. */
   983         -    style_submenu_element("New Thread","%R/login");
          942  +    style_submenu_element("New Message","%R/forumnew");
   984    943     }
   985    944     if( g.perm.ModForum && moderation_needed() ){
   986    945       style_submenu_element("Moderation Requests", "%R/modreq");
   987    946     }
   988    947     if( (srchFlags & SRCH_FORUM)!=0 ){
   989    948       if( search_screen(SRCH_FORUM, 0) ){
   990    949         style_submenu_element("Recent Threads","%R/forum");

Changes to src/http_socket.c.

   194    194     return rc;
   195    195   }
   196    196   
   197    197   /*
   198    198   ** Send content out over the open socket connection.
   199    199   */
   200    200   size_t socket_send(void *NotUsed, const void *pContent, size_t N){
   201         -  ssize_t sent;
          201  +  size_t sent;
   202    202     size_t total = 0;
   203    203     while( N>0 ){
   204    204       sent = send(iSocket, pContent, N, 0);
   205    205       if( sent<=0 ) break;
   206         -    total += (size_t)sent;
   207         -    N -= (size_t)sent;
          206  +    total += sent;
          207  +    N -= sent;
   208    208       pContent = (void*)&((char*)pContent)[sent];
   209    209     }
   210    210     return total;
   211    211   }
   212    212   
   213    213   /*
   214    214   ** Receive content back from the open socket connection.

Changes to src/info.c.

  2127   2127       @ <hr />
  2128   2128       content_get(rid, &content);
  2129   2129       if( renderAsWiki ){
  2130   2130         wiki_render_by_mimetype(&content, zMime);
  2131   2131       }else if( renderAsHtml ){
  2132   2132         @ <iframe src="%R/raw/%T(blob_str(&downloadName))?name=%s(zUuid)"
  2133   2133         @ width="100%%" frameborder="0" marginwidth="0" marginheight="0"
  2134         -      @ sandbox="allow-same-origin" id="ifm1">
         2134  +      @ sandbox="allow-same-origin"
         2135  +      @ onload="this.height=this.contentDocument.documentElement.scrollHeight;">
  2135   2136         @ </iframe>
  2136         -      @ <script nonce="%h(style_nonce())">
  2137         -      @ document.getElementById("ifm1").addEventListener("load",
  2138         -      @   function(){
  2139         -      @     this.height=this.contentDocument.documentElement.scrollHeight + 75;
  2140         -      @   }
  2141         -      @ );
  2142         -      @ </script>
  2143   2137       }else{
  2144   2138         style_submenu_element("Hex", "%s/hexdump?name=%s", g.zTop, zUuid);
  2145   2139         blob_to_utf8_no_bom(&content, 0);
  2146   2140         zMime = mimetype_from_content(&content);
  2147   2141         @ <blockquote>
  2148   2142         if( zMime==0 ){
  2149   2143           const char *z;

Changes to src/main.c.

   970    970         fossil_fatal(
   971    971           "unrecognized command-line option, or missing argument: %s",
   972    972           g.argv[i]);
   973    973       }
   974    974     }
   975    975   }
   976    976   
          977  +/*
          978  +** Print a list of words in multiple columns.
          979  +*/
          980  +
   977    981   
   978    982   /*
   979    983   ** This function returns a human readable version string.
   980    984   */
   981    985   const char *get_version(){
   982    986     static const char version[] = RELEASE_VERSION " " MANIFEST_VERSION " "
   983    987                                   MANIFEST_DATE " UTC";
................................................................................
  1294   1298       if( g.db==0 && file_isfile(zRepo, ExtFILE) ){
  1295   1299         db_open_repository(zRepo);
  1296   1300       }
  1297   1301     }
  1298   1302   #endif
  1299   1303     return zRepo;
  1300   1304   }
         1305  +
         1306  +/*
         1307  +** Generate a web-page that lists all repositories located under the
         1308  +** g.zRepositoryName directory and return non-zero.
         1309  +**
         1310  +** For the special case when g.zRepositoryName a non-chroot-jail "/",
         1311  +** compose the list using the "repo:" entries in the global_config
         1312  +** table of the configuration database.  These entries comprise all
         1313  +** of the repositories known to the "all" command.  The special case
         1314  +** processing is disallowed for chroot jails because g.zRepositoryName
         1315  +** is always "/" inside a chroot jail and so it cannot be used as a flag
         1316  +** to signal the special processing in that case.  The special case
         1317  +** processing is intended for the "fossil all ui" command which never
         1318  +** runs in a chroot jail anyhow.
         1319  +**
         1320  +** Or, if no repositories can be located beneath g.zRepositoryName,
         1321  +** return 0.
         1322  +*/
         1323  +static int repo_list_page(void){
         1324  +  Blob base;
         1325  +  int n = 0;
         1326  +  int allRepo;
         1327  +
         1328  +  assert( g.db==0 );
         1329  +  if( fossil_strcmp(g.zRepositoryName,"/")==0 && !g.fJail ){
         1330  +    /* For the special case of the "repository directory" being "/",
         1331  +    ** show all of the repositories named in the ~/.fossil database.
         1332  +    **
         1333  +    ** On unix systems, then entries are of the form "repo:/home/..."
         1334  +    ** and on Windows systems they are like on unix, starting with a "/"
         1335  +    ** or they can begin with a drive letter: "repo:C:/Users/...".  In either
         1336  +    ** case, we want returned path to omit any initial "/".
         1337  +    */
         1338  +    db_open_config(1, 0);
         1339  +    db_multi_exec(
         1340  +       "CREATE TEMP VIEW sfile AS"
         1341  +       "  SELECT ltrim(substr(name,6),'/') AS 'pathname' FROM global_config"
         1342  +       "   WHERE name GLOB 'repo:*'"
         1343  +    );
         1344  +    allRepo = 1;
         1345  +  }else{
         1346  +    /* The default case:  All repositories under the g.zRepositoryName
         1347  +    ** directory.
         1348  +    */
         1349  +    blob_init(&base, g.zRepositoryName, -1);
         1350  +    sqlite3_open(":memory:", &g.db);
         1351  +    db_multi_exec("CREATE TABLE sfile(pathname TEXT);");
         1352  +    db_multi_exec("CREATE TABLE vfile(pathname);");
         1353  +    vfile_scan(&base, blob_size(&base), 0, 0, 0);
         1354  +    db_multi_exec("DELETE FROM sfile WHERE pathname NOT GLOB '*[^/].fossil'");
         1355  +    allRepo = 0;
         1356  +  }
         1357  +  @ <html>
         1358  +  @ <head>
         1359  +  @ <base href="%s(g.zBaseURL)/" />
         1360  +  @ <meta name="viewport" content="width=device-width, initial-scale=1.0">
         1361  +  @ <title>Repository List</title>
         1362  +  @ </head>
         1363  +  @ <body>
         1364  +  n = db_int(0, "SELECT count(*) FROM sfile");
         1365  +  if( n>0 ){
         1366  +    Stmt q;
         1367  +    sqlite3_int64 iNow, iMTime;
         1368  +    @ <h1 align="center">Fossil Repositories</h1>
         1369  +    @ <table border="0" class="sortable" data-init-sort="1" \
         1370  +    @ data-column-types="tnk"><thead>
         1371  +    @ <tr><th>Filename<th width="20"><th>Last Modified</tr>
         1372  +    @ </thead><tbody>
         1373  +    db_prepare(&q, "SELECT pathname"
         1374  +                   " FROM sfile ORDER BY pathname COLLATE nocase;");
         1375  +    iNow = db_int64(0, "SELECT strftime('%%s','now')");
         1376  +    while( db_step(&q)==SQLITE_ROW ){
         1377  +      const char *zName = db_column_text(&q, 0);
         1378  +      int nName = (int)strlen(zName);
         1379  +      char *zUrl;
         1380  +      char *zAge;
         1381  +      char *zFull;
         1382  +      if( nName<7 ) continue;
         1383  +      zUrl = sqlite3_mprintf("%.*s", nName-7, zName);
         1384  +      if( zName[0]=='/'
         1385  +#ifdef _WIN32
         1386  +          || sqlite3_strglob("[a-zA-Z]:/*", zName)==0
         1387  +#endif
         1388  +      ){
         1389  +        zFull = mprintf("%s", zName);
         1390  +      }else if ( allRepo ){
         1391  +        zFull = mprintf("/%s", zName);
         1392  +      }else{
         1393  +        zFull = mprintf("%s/%s", g.zRepositoryName, zName);
         1394  +      }
         1395  +      iMTime = file_mtime(zFull, ExtFILE);
         1396  +      fossil_free(zFull);
         1397  +      if( iMTime<=0 ){
         1398  +        zAge = mprintf("...");
         1399  +      }else{
         1400  +        zAge = human_readable_age((iNow - iMTime)/86400.0);
         1401  +      }
         1402  +      if( sqlite3_strglob("*.fossil", zName)!=0 ){
         1403  +        /* The "fossil server DIRECTORY" and "fossil ui DIRECTORY" commands
         1404  +        ** do not work for repositories whose names do not end in ".fossil".
         1405  +        ** So do not hyperlink those cases. */
         1406  +        @ <tr><td>%h(zName)
         1407  +      } else if( sqlite3_strglob("*/.*", zName)==0 ){
         1408  +        /* Do not show hidden repos */
         1409  +        @ <tr><td>%h(zName) (hidden)
         1410  +      } else if( allRepo && sqlite3_strglob("[a-zA-Z]:/?*", zName)!=0 ){
         1411  +        @ <tr><td><a href="%R/%T(zUrl)/home" target="_blank">/%h(zName)</a>
         1412  +      }else{
         1413  +        @ <tr><td><a href="%R/%T(zUrl)/home" target="_blank">%h(zName)</a>
         1414  +      }
         1415  +      @ <td></td><td data-sortkey='%010llx(iNow - iMTime)'>%h(zAge)</tr>
         1416  +      fossil_free(zAge);
         1417  +      sqlite3_free(zUrl);
         1418  +    }
         1419  +    @ </tbody></table>
         1420  +  }else{
         1421  +    @ <h1>No Repositories Found</h1>
         1422  +  }
         1423  +  @ <script>%s(builtin_text("sorttable.js"))</script>
         1424  +  @ </body>
         1425  +  @ </html>
         1426  +  cgi_reply();
         1427  +  sqlite3_close(g.db);
         1428  +  g.db = 0;
         1429  +  return n;
         1430  +}
         1431  +
         1432  +/*
         1433  +** COMMAND: test-list-page
         1434  +**
         1435  +** Usage: %fossil test-list-page DIRECTORY
         1436  +**
         1437  +** Show all repositories underneath DIRECTORY.  Or if DIRECTORY is "/"
         1438  +** show all repositories in the ~/.fossil file.
         1439  +*/
         1440  +void test_list_page(void){
         1441  +  if( g.argc<3 ){
         1442  +    g.zRepositoryName = "/";
         1443  +  }else{
         1444  +    g.zRepositoryName = g.argv[2];
         1445  +  }
         1446  +  g.httpOut = stdout;
         1447  +  repo_list_page();
         1448  +}
  1301   1449   
  1302   1450   /*
  1303   1451   ** Called whenever a crash is encountered while processing a webpage.
  1304   1452   */
  1305   1453   void sigsegv_handler(int x){
  1306   1454   #if HAVE_BACKTRACE
  1307   1455     void *array[20];
................................................................................
  2231   2379     noJail = find_option("nojail",0,0)!=0;
  2232   2380     allowRepoList = find_option("repolist",0,0)!=0;
  2233   2381     g.useLocalauth = find_option("localauth", 0, 0)!=0;
  2234   2382     g.sslNotAvailable = find_option("nossl", 0, 0)!=0;
  2235   2383     g.fNoHttpCompress = find_option("nocompress",0,0)!=0;
  2236   2384     zInFile = find_option("in",0,1);
  2237   2385     if( zInFile ){
  2238         -    backoffice_disable();
  2239   2386       g.httpIn = fossil_fopen(zInFile, "rb");
  2240   2387       if( g.httpIn==0 ) fossil_fatal("cannot open \"%s\" for reading", zInFile);
  2241   2388     }else{
  2242   2389       g.httpIn = stdin;
  2243   2390     }
  2244   2391     zOutFile = find_option("out",0,1);
  2245   2392     if( zOutFile ){
................................................................................
  2696   2843   **     case=6           Call webpage_assert()
  2697   2844   **     case=7           Call webpage_error()
  2698   2845   */
  2699   2846   void test_warning_page(void){
  2700   2847     int iCase = atoi(PD("case","0"));
  2701   2848     int i;
  2702   2849     login_check_credentials();
  2703         -  if( !g.perm.Admin ){
         2850  +  if( !g.perm.Setup && !g.perm.Admin ){
  2704   2851       login_needed(0);
  2705   2852       return;
  2706   2853     }
  2707   2854     style_header("Warning Test Page");
  2708   2855     style_submenu_element("Error Log","%R/errorlog");
  2709   2856     if( iCase<1 || iCase>4 ){
  2710   2857       @ <p>Generate a message to the <a href="%R/errorlog">error log</a>

Changes to src/main.mk.

   102    102     $(SRCDIR)/popen.c \
   103    103     $(SRCDIR)/pqueue.c \
   104    104     $(SRCDIR)/printf.c \
   105    105     $(SRCDIR)/publish.c \
   106    106     $(SRCDIR)/purge.c \
   107    107     $(SRCDIR)/rebuild.c \
   108    108     $(SRCDIR)/regexp.c \
   109         -  $(SRCDIR)/repolist.c \
   110    109     $(SRCDIR)/report.c \
   111    110     $(SRCDIR)/rss.c \
   112    111     $(SRCDIR)/schema.c \
   113    112     $(SRCDIR)/search.c \
   114    113     $(SRCDIR)/security_audit.c \
   115    114     $(SRCDIR)/setup.c \
   116    115     $(SRCDIR)/setupuser.c \
................................................................................
   313    312     $(OBJDIR)/popen_.c \
   314    313     $(OBJDIR)/pqueue_.c \
   315    314     $(OBJDIR)/printf_.c \
   316    315     $(OBJDIR)/publish_.c \
   317    316     $(OBJDIR)/purge_.c \
   318    317     $(OBJDIR)/rebuild_.c \
   319    318     $(OBJDIR)/regexp_.c \
   320         -  $(OBJDIR)/repolist_.c \
   321    319     $(OBJDIR)/report_.c \
   322    320     $(OBJDIR)/rss_.c \
   323    321     $(OBJDIR)/schema_.c \
   324    322     $(OBJDIR)/search_.c \
   325    323     $(OBJDIR)/security_audit_.c \
   326    324     $(OBJDIR)/setup_.c \
   327    325     $(OBJDIR)/setupuser_.c \
................................................................................
   451    449    $(OBJDIR)/popen.o \
   452    450    $(OBJDIR)/pqueue.o \
   453    451    $(OBJDIR)/printf.o \
   454    452    $(OBJDIR)/publish.o \
   455    453    $(OBJDIR)/purge.o \
   456    454    $(OBJDIR)/rebuild.o \
   457    455    $(OBJDIR)/regexp.o \
   458         - $(OBJDIR)/repolist.o \
   459    456    $(OBJDIR)/report.o \
   460    457    $(OBJDIR)/rss.o \
   461    458    $(OBJDIR)/schema.o \
   462    459    $(OBJDIR)/search.o \
   463    460    $(OBJDIR)/security_audit.o \
   464    461    $(OBJDIR)/setup.o \
   465    462    $(OBJDIR)/setupuser.o \
................................................................................
   575    572                    -DSQLITE_OMIT_LOAD_EXTENSION \
   576    573                    -DSQLITE_MAX_EXPR_DEPTH=0 \
   577    574                    -DSQLITE_USE_ALLOCA \
   578    575                    -DSQLITE_ENABLE_LOCKING_STYLE=0 \
   579    576                    -DSQLITE_DEFAULT_FILE_FORMAT=4 \
   580    577                    -DSQLITE_ENABLE_EXPLAIN_COMMENTS \
   581    578                    -DSQLITE_ENABLE_FTS4 \
          579  +                 -DSQLITE_ENABLE_FTS3_PARENTHESIS \
   582    580                    -DSQLITE_ENABLE_DBSTAT_VTAB \
   583    581                    -DSQLITE_ENABLE_JSON1 \
   584    582                    -DSQLITE_ENABLE_FTS5 \
   585    583                    -DSQLITE_ENABLE_STMTVTAB \
   586    584                    -DSQLITE_HAVE_ZLIB \
   587    585                    -DSQLITE_INTROSPECTION_PRAGMAS \
   588    586                    -DSQLITE_ENABLE_DBPAGE_VTAB
................................................................................
   601    599                   -DSQLITE_OMIT_LOAD_EXTENSION \
   602    600                   -DSQLITE_MAX_EXPR_DEPTH=0 \
   603    601                   -DSQLITE_USE_ALLOCA \
   604    602                   -DSQLITE_ENABLE_LOCKING_STYLE=0 \
   605    603                   -DSQLITE_DEFAULT_FILE_FORMAT=4 \
   606    604                   -DSQLITE_ENABLE_EXPLAIN_COMMENTS \
   607    605                   -DSQLITE_ENABLE_FTS4 \
          606  +                -DSQLITE_ENABLE_FTS3_PARENTHESIS \
   608    607                   -DSQLITE_ENABLE_DBSTAT_VTAB \
   609    608                   -DSQLITE_ENABLE_JSON1 \
   610    609                   -DSQLITE_ENABLE_FTS5 \
   611    610                   -DSQLITE_ENABLE_STMTVTAB \
   612    611                   -DSQLITE_HAVE_ZLIB \
   613    612                   -DSQLITE_INTROSPECTION_PRAGMAS \
   614    613                   -DSQLITE_ENABLE_DBPAGE_VTAB \
................................................................................
   785    784   	$(OBJDIR)/popen_.c:$(OBJDIR)/popen.h \
   786    785   	$(OBJDIR)/pqueue_.c:$(OBJDIR)/pqueue.h \
   787    786   	$(OBJDIR)/printf_.c:$(OBJDIR)/printf.h \
   788    787   	$(OBJDIR)/publish_.c:$(OBJDIR)/publish.h \
   789    788   	$(OBJDIR)/purge_.c:$(OBJDIR)/purge.h \
   790    789   	$(OBJDIR)/rebuild_.c:$(OBJDIR)/rebuild.h \
   791    790   	$(OBJDIR)/regexp_.c:$(OBJDIR)/regexp.h \
   792         -	$(OBJDIR)/repolist_.c:$(OBJDIR)/repolist.h \
   793    791   	$(OBJDIR)/report_.c:$(OBJDIR)/report.h \
   794    792   	$(OBJDIR)/rss_.c:$(OBJDIR)/rss.h \
   795    793   	$(OBJDIR)/schema_.c:$(OBJDIR)/schema.h \
   796    794   	$(OBJDIR)/search_.c:$(OBJDIR)/search.h \
   797    795   	$(OBJDIR)/security_audit_.c:$(OBJDIR)/security_audit.h \
   798    796   	$(OBJDIR)/setup_.c:$(OBJDIR)/setup.h \
   799    797   	$(OBJDIR)/setupuser_.c:$(OBJDIR)/setupuser.h \
................................................................................
  1558   1556   	$(OBJDIR)/translate $(SRCDIR)/regexp.c >$@
  1559   1557   
  1560   1558   $(OBJDIR)/regexp.o:	$(OBJDIR)/regexp_.c $(OBJDIR)/regexp.h $(SRCDIR)/config.h
  1561   1559   	$(XTCC) -o $(OBJDIR)/regexp.o -c $(OBJDIR)/regexp_.c
  1562   1560   
  1563   1561   $(OBJDIR)/regexp.h:	$(OBJDIR)/headers
  1564   1562   
  1565         -$(OBJDIR)/repolist_.c:	$(SRCDIR)/repolist.c $(OBJDIR)/translate
  1566         -	$(OBJDIR)/translate $(SRCDIR)/repolist.c >$@
  1567         -
  1568         -$(OBJDIR)/repolist.o:	$(OBJDIR)/repolist_.c $(OBJDIR)/repolist.h $(SRCDIR)/config.h
  1569         -	$(XTCC) -o $(OBJDIR)/repolist.o -c $(OBJDIR)/repolist_.c
  1570         -
  1571         -$(OBJDIR)/repolist.h:	$(OBJDIR)/headers
  1572         -
  1573   1563   $(OBJDIR)/report_.c:	$(SRCDIR)/report.c $(OBJDIR)/translate
  1574   1564   	$(OBJDIR)/translate $(SRCDIR)/report.c >$@
  1575   1565   
  1576   1566   $(OBJDIR)/report.o:	$(OBJDIR)/report_.c $(OBJDIR)/report.h $(SRCDIR)/config.h
  1577   1567   	$(XTCC) -o $(OBJDIR)/report.o -c $(OBJDIR)/report_.c
  1578   1568   
  1579   1569   $(OBJDIR)/report.h:	$(OBJDIR)/headers

Changes to src/makeheaders.c.

  1901   1901         return 0;
  1902   1902       }
  1903   1903       pFirst = pFirst->pNext;
  1904   1904     }
  1905   1905     return 1;
  1906   1906   }
  1907   1907   
  1908         -/*
  1909         -** Return TRUE if pFirst is the first token of a static assert.
  1910         -*/
  1911         -static int isStaticAssert(Token *pFirst){
  1912         -  if( (pFirst->nText==13 && strncmp(pFirst->zText, "static_assert", 13)==0)
  1913         -   || (pFirst->nText==14 && strncmp(pFirst->zText, "_Static_assert", 14)==0)
  1914         -  ){
  1915         -    return 1;
  1916         -  }else{
  1917         -    return 0;
  1918         -  }
  1919         -}
  1920   1908   
  1921   1909   /*
  1922   1910   ** This routine is called whenever we encounter a ";" or "=".  The stuff
  1923   1911   ** between pFirst and pLast constitutes either a typedef or a global
  1924   1912   ** variable definition.  Do the right thing.
  1925   1913   */
  1926   1914   static int ProcessDecl(Token *pFirst, Token *pEnd, int flags){
................................................................................
  1971   1959       }
  1972   1960       if( pFirst==0 || !isLocal ){
  1973   1961         return nErr;
  1974   1962       }
  1975   1963     }else if( flags & PS_Method ){
  1976   1964       /* Methods are declared by their class.  Don't declare separately. */
  1977   1965       return nErr;
  1978         -  }else if( isStaticAssert(pFirst) ){
  1979         -    return 0;
  1980   1966     }
  1981   1967     isVar =  (flags & (PS_Typedef|PS_Method))==0 && isVariableDef(pFirst,pEnd);
  1982   1968     if( isVar && (flags & (PS_Interface|PS_Export|PS_Local))!=0
  1983   1969     && (flags & PS_Extern)==0 ){
  1984   1970       fprintf(stderr,"%s:%d: Can't define a variable in this context\n",
  1985   1971         zFilename, pFirst->nLine);
  1986   1972       nErr++;

Changes to src/makemake.tcl.

   112    112     popen
   113    113     pqueue
   114    114     printf
   115    115     publish
   116    116     purge
   117    117     rebuild
   118    118     regexp
   119         -  repolist
   120    119     report
   121    120     rss
   122    121     schema
   123    122     search
   124    123     security_audit
   125    124     setup
   126    125     setupuser
................................................................................
   191    190     -DSQLITE_OMIT_LOAD_EXTENSION
   192    191     -DSQLITE_MAX_EXPR_DEPTH=0
   193    192     -DSQLITE_USE_ALLOCA
   194    193     -DSQLITE_ENABLE_LOCKING_STYLE=0
   195    194     -DSQLITE_DEFAULT_FILE_FORMAT=4
   196    195     -DSQLITE_ENABLE_EXPLAIN_COMMENTS
   197    196     -DSQLITE_ENABLE_FTS4
          197  +  -DSQLITE_ENABLE_FTS3_PARENTHESIS
   198    198     -DSQLITE_ENABLE_DBSTAT_VTAB
   199    199     -DSQLITE_ENABLE_JSON1
   200    200     -DSQLITE_ENABLE_FTS5
   201    201     -DSQLITE_ENABLE_STMTVTAB
   202    202     -DSQLITE_HAVE_ZLIB
   203    203     -DSQLITE_INTROSPECTION_PRAGMAS
   204    204     -DSQLITE_ENABLE_DBPAGE_VTAB
................................................................................
   708    708   endif
   709    709   
   710    710   #### The directories where the OpenSSL include and library files are located.
   711    711   #    The recommended usage here is to use the Sysinternals junction tool
   712    712   #    to create a hard link between an "openssl-1.x" sub-directory of the
   713    713   #    Fossil source code directory and the target OpenSSL source directory.
   714    714   #
   715         -OPENSSLDIR = $(SRCDIR)/../compat/openssl-1.0.2q
          715  +OPENSSLDIR = $(SRCDIR)/../compat/openssl-1.0.2p
   716    716   OPENSSLINCDIR = $(OPENSSLDIR)/include
   717    717   OPENSSLLIBDIR = $(OPENSSLDIR)
   718    718   
   719    719   #### Either the directory where the Tcl library is installed or the Tcl
   720    720   #    source code directory resides (depending on the value of the macro
   721    721   #    FOSSIL_TCL_SOURCE).  If this points to the Tcl install directory,
   722    722   #    this directory must have "include" and "lib" sub-directories.  If
................................................................................
  1564   1564   
  1565   1565   # Enable support for the SQLite Encryption Extension?
  1566   1566   !ifndef USE_SEE
  1567   1567   USE_SEE = 0
  1568   1568   !endif
  1569   1569   
  1570   1570   !if $(FOSSIL_ENABLE_SSL)!=0
  1571         -SSLDIR    = $(B)\compat\openssl-1.0.2q
         1571  +SSLDIR    = $(B)\compat\openssl-1.0.2p
  1572   1572   SSLINCDIR = $(SSLDIR)\inc32
  1573   1573   !if $(FOSSIL_DYNAMIC_BUILD)!=0
  1574   1574   SSLLIBDIR = $(SSLDIR)\out32dll
  1575   1575   !else
  1576   1576   SSLLIBDIR = $(SSLDIR)\out32
  1577   1577   !endif
  1578   1578   SSLLFLAGS = /nologo /opt:ref /debug

Changes to src/manifest.c.

  2527   2527       char *zFType;
  2528   2528       char *zTitle;
  2529   2529       schema_forum();
  2530   2530       froot = p->zThreadRoot ? uuid_to_rid(p->zThreadRoot, 1) : rid;
  2531   2531       fprev = p->nParent ? uuid_to_rid(p->azParent[0],1) : 0;
  2532   2532       firt = p->zInReplyTo ? uuid_to_rid(p->zInReplyTo,1) : 0;
  2533   2533       db_multi_exec(
  2534         -      "REPLACE INTO forumpost(fpid,froot,fprev,firt,fmtime)"
         2534  +      "INSERT INTO forumpost(fpid,froot,fprev,firt,fmtime)"
  2535   2535         "VALUES(%d,%d,nullif(%d,0),nullif(%d,0),%.17g)",
  2536   2536         p->rid, froot, fprev, firt, p->rDate
  2537   2537       );
  2538   2538       if( firt==0 ){
  2539   2539         /* This is the start of a new thread, either the initial entry
  2540   2540         ** or an edit of the initial entry. */
  2541   2541         zTitle = p->zThreadTitle;

Changes to src/markdown.md.

    23     23   
    24     24   > 1.  **\[display text\]\(URL\)**
    25     25   > 2.  **\[display text\]\(URL "Title"\)**
    26     26   > 3.  **\[display text\]\(URL 'Title'\)**
    27     27   > 4.  **\<URL\>**
    28     28   > 5.  **\[display text\]\[label\]**
    29     29   > 6.  **\[display text\]\[\]**
    30         -> 7.  **\[display text\]**
    31     30   
    32         -> **URL** may optionally be written **\<URL\>**.  With link formats 5, 6, and 7
           31  +> **URL** may optionally be written **\<URL\>**.  With link formats 5 and 6
    33     32   > ("reference links"), the URL is supplied elsewhere in the document, as shown
    34         -> below.  Link formats 6 and 7 reuse the display text as the label.  Labels are
           33  +> below.  Link format 6 reuses the display text as the label.  Labels are
    35     34   > case-insensitive.  The title may be split onto the next line with optional
    36     35   > indenting.
    37     36   
    38     37   > * **\[label\]:&nbsp;URL**
    39     38   > * **\[label\]:&nbsp;URL&nbsp;"Title"**
    40     39   > * **\[label\]:&nbsp;URL&nbsp;'Title'**
    41     40   > * **\[label\]:&nbsp;URL&nbsp;(Title)**

Changes to src/path.c.

   191    191     PathNode *p;
   192    192     int i;
   193    193     if( path.nStep<2 ) return 0;
   194    194     for(p=path.pEnd, i=0; p && i<path.nStep/2; p=p->pFrom, i++){}
   195    195     return p;
   196    196   }
   197    197   
   198         -/*
   199         -** Return an estimate of the number of comparisons remaining in order
   200         -** to bisect path.  This is based on the log2() of path.nStep.
   201         -*/
   202         -int path_search_depth(void){
   203         -  int i, j;
   204         -  for(i=0, j=1; j<path.nStep; i++, j+=j){}
   205         -  return i;
   206         -}
   207         -
   208    198   /*
   209    199   ** Compute the shortest path between two check-ins and then transfer
   210    200   ** that path into the "ancestor" table.  This is a utility used by
   211    201   ** both /annotate and /finfo.  See also: compute_direct_ancestors().
   212    202   */
   213    203   void path_shortest_stored_in_ancestor_table(
   214    204     int origid,     /* RID for check-in at start of the path */

Changes to src/printf.c.

  1000   1000     }else{
  1001   1001       out = fossil_fopen(g.zErrlog, "a");
  1002   1002       if( out==0 ) return;
  1003   1003     }
  1004   1004     now = time(0);
  1005   1005     pNow = gmtime(&now);
  1006   1006     fprintf(out, "------------- %04d-%02d-%02d %02d:%02d:%02d UTC ------------\n",
  1007         -          pNow->tm_year+1900, pNow->tm_mon+1, pNow->tm_mday,
         1007  +          pNow->tm_year+1900, pNow->tm_mon+1, pNow->tm_mday+1,
  1008   1008             pNow->tm_hour, pNow->tm_min, pNow->tm_sec);
  1009   1009     va_start(ap, zFormat);
  1010   1010     vfprintf(out, zFormat, ap);
  1011   1011     fprintf(out, "\n");
  1012   1012     va_end(ap);
  1013   1013     for(i=0; i<count(azEnv); i++){
  1014   1014       char *p;

Changes to src/regexp.c.

    14     14   **   http://www.hwaci.com/drh/
    15     15   **
    16     16   *******************************************************************************
    17     17   **
    18     18   ** This file was adapted from the test_regexp.c file in SQLite3.  That
    19     19   ** file is in the public domain.
    20     20   **
    21         -** See ../www/grep.md for details of the algorithm and RE dialect.
           21  +** The code in this file implements a compact but reasonably
           22  +** efficient regular-expression matcher for posix extended regular
           23  +** expressions against UTF8 text.  The following syntax is supported:
           24  +**
           25  +**     X*      zero or more occurrences of X
           26  +**     X+      one or more occurrences of X
           27  +**     X?      zero or one occurrences of X
           28  +**     X{p,q}  between p and q occurrences of X
           29  +**     (X)     match X
           30  +**     X|Y     X or Y
           31  +**     ^X      X occurring at the beginning of the string
           32  +**     X$      X occurring at the end of the string
           33  +**     .       Match any single character
           34  +**     \c      Character c where c is one of \{}()[]|*+?.
           35  +**     \c      C-language escapes for c in afnrtv.  ex: \t or \n
           36  +**     \uXXXX  Where XXXX is exactly 4 hex digits, unicode value XXXX
           37  +**     \xXX    Where XX is exactly 2 hex digits, unicode value XX
           38  +**     [abc]   Any single character from the set abc
           39  +**     [^abc]  Any single character not in the set abc
           40  +**     [a-z]   Any single character in the range a-z
           41  +**     [^a-z]  Any single character not in the range a-z
           42  +**     \b      Word boundary
           43  +**     \w      Word character.  [A-Za-z0-9_]
           44  +**     \W      Non-word character
           45  +**     \d      Digit
           46  +**     \D      Non-digit
           47  +**     \s      Whitespace character
           48  +**     \S      Non-whitespace character
           49  +**
           50  +** A nondeterministic finite automaton (NFA) is used for matching, so the
           51  +** performance is bounded by O(N*M) where N is the size of the regular
           52  +** expression and M is the size of the input string.  The matcher never
           53  +** exhibits exponential behavior.  Note that the X{p,q} operator expands
           54  +** to p copies of X following by q-p copies of X? and that the size of the
           55  +** regular expression in the O(N*M) performance bound is computed after
           56  +** this expansion.
    22     57   */
    23     58   #include "config.h"
    24     59   #include "regexp.h"
    25     60   
    26     61   /* The end-of-input character */
    27     62   #define RE_EOF            0    /* End of input */
    28     63   
................................................................................
   790    825   }
   791    826   
   792    827   /*
   793    828   ** COMMAND: grep
   794    829   **
   795    830   ** Usage: %fossil grep [OPTIONS] PATTERN FILENAME
   796    831   **
   797         -** Attempt to match the given POSIX extended regular expression PATTERN
   798         -** over all historic versions of FILENAME.  For details of the supported
   799         -** RE dialect, see https://fossil-scm.org/fossil/doc/trunk/www/grep.md
          832  +** Run grep over all historic version of FILENAME
   800    833   **
   801    834   ** Options:
   802    835   **
   803    836   **     -i|--ignore-case         Ignore case
   804         -**     -l|--files-with-matches  List only checkin ID for versions that match
          837  +**     -l|--files-with-matches  Print only filenames that match
   805    838   **     -v|--verbose             Show each file as it is analyzed
   806    839   */
   807    840   void re_grep_cmd(void){
   808    841     u32 flags = 0;
   809    842     int bVerbose = 0;
   810    843     ReCompiled *pRe;
   811    844     const char *zErr;
................................................................................
   813    846     Blob fullName;
   814    847   
   815    848     if( find_option("ignore-case","i",0)!=0 ) ignoreCase = 1;
   816    849     if( find_option("files-with-matches","l",0)!=0 ) flags |= GREP_EXISTS;
   817    850     if( find_option("verbose","v",0)!=0 ) bVerbose = 1;
   818    851     db_find_and_open_repository(0, 0);
   819    852     verify_all_options();
   820         -  if( g.argc<4 ){
          853  +  if( g.argc<3 ){
   821    854       usage("REGEXP FILENAME");
   822    855     }
   823    856     zErr = re_compile(&pRe, g.argv[2], ignoreCase);
   824    857     if( zErr ) fossil_fatal("%s", zErr);
   825    858   
   826    859     if( file_tree_name(g.argv[3], &fullName, 0, 0) ){
   827    860       int fnid = db_int(0, "SELECT fnid FROM filename WHERE name=%Q",

Deleted src/repolist.c.

     1         -/*
     2         -** Copyright (c) 2018 D. Richard Hipp
     3         -**
     4         -** This program is free software; you can redistribute it and/or
     5         -** modify it under the terms of the Simplified BSD License (also
     6         -** known as the "2-Clause License" or "FreeBSD License".)
     7         -**
     8         -** This program is distributed in the hope that it will be useful,
     9         -** but without any warranty; without even the implied warranty of
    10         -** merchantability or fitness for a particular purpose.
    11         -**
    12         -** Author contact information:
    13         -**   drh@hwaci.com
    14         -**   http://www.hwaci.com/drh/
    15         -**
    16         -*******************************************************************************
    17         -**
    18         -** This module contains code to implement the repository list page when
    19         -** "fossil server" or "fossil ui" is serving a directory full of repositories.
    20         -*/
    21         -#include "config.h"
    22         -#include "repolist.h"
    23         -
    24         -#if INTERFACE
    25         -/*
    26         -** Return value from the remote_repo_info() command.  zRepoName is the
    27         -** input.  All other fields are outputs.
    28         -*/
    29         -struct RepoInfo {
    30         -  char *zRepoName;      /* Name of the repository file */
    31         -  int isValid;          /* True if zRepoName is a valid Fossil repository */
    32         -  char *zProjName;      /* Project Name.  Memory from fossil_malloc() */
    33         -  double rMTime;        /* Last update.  Julian day number */
    34         -};
    35         -#endif
    36         -
    37         -/*
    38         -** Discover information about the repository given by
    39         -** pRepo->zRepoName.
    40         -*/
    41         -void remote_repo_info(RepoInfo *pRepo){
    42         -  sqlite3 *db;
    43         -  sqlite3_stmt *pStmt;
    44         -  int rc;
    45         -
    46         -  pRepo->isValid = 0;
    47         -  pRepo->zProjName = 0;
    48         -  pRepo->rMTime = 0.0;
    49         -
    50         -  rc = sqlite3_open(pRepo->zRepoName, &db);
    51         -  if( rc ) return;
    52         -  rc = sqlite3_prepare_v2(db, "SELECT value FROM config"
    53         -                              " WHERE name='project-name'",
    54         -                          -1, &pStmt, 0);
    55         -  if( rc ) return;
    56         -  if( sqlite3_step(pStmt)==SQLITE_ROW ){
    57         -    pRepo->zProjName = fossil_strdup((char*)sqlite3_column_text(pStmt,0));
    58         -  }
    59         -  sqlite3_finalize(pStmt);
    60         -  rc = sqlite3_prepare_v2(db, "SELECT max(mtime) FROM event", -1, &pStmt, 0);
    61         -  if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
    62         -    pRepo->rMTime = sqlite3_column_double(pStmt,0);
    63         -  }
    64         -  sqlite3_finalize(pStmt);
    65         -  sqlite3_close(db);
    66         -  pRepo->isValid = 1;
    67         -}
    68         -
    69         -/*
    70         -** Generate a web-page that lists all repositories located under the
    71         -** g.zRepositoryName directory and return non-zero.
    72         -**
    73         -** For the special case when g.zRepositoryName is a non-chroot-jail "/",
    74         -** compose the list using the "repo:" entries in the global_config
    75         -** table of the configuration database.  These entries comprise all
    76         -** of the repositories known to the "all" command.  The special case
    77         -** processing is disallowed for chroot jails because g.zRepositoryName
    78         -** is always "/" inside a chroot jail and so it cannot be used as a flag
    79         -** to signal the special processing in that case.  The special case
    80         -** processing is intended for the "fossil all ui" command which never
    81         -** runs in a chroot jail anyhow.
    82         -**
    83         -** Or, if no repositories can be located beneath g.zRepositoryName,
    84         -** return 0.
    85         -*/
    86         -int repo_list_page(void){
    87         -  Blob base;
    88         -  int n = 0;
    89         -  int allRepo;
    90         -
    91         -  assert( g.db==0 );
    92         -  if( fossil_strcmp(g.zRepositoryName,"/")==0 && !g.fJail ){
    93         -    /* For the special case of the "repository directory" being "/",
    94         -    ** show all of the repositories named in the ~/.fossil database.
    95         -    **
    96         -    ** On unix systems, then entries are of the form "repo:/home/..."
    97         -    ** and on Windows systems they are like on unix, starting with a "/"
    98         -    ** or they can begin with a drive letter: "repo:C:/Users/...".  In either
    99         -    ** case, we want returned path to omit any initial "/".
   100         -    */
   101         -    db_open_config(1, 0);
   102         -    db_multi_exec(
   103         -       "CREATE TEMP VIEW sfile AS"
   104         -       "  SELECT ltrim(substr(name,6),'/') AS 'pathname' FROM global_config"
   105         -       "   WHERE name GLOB 'repo:*'"
   106         -    );
   107         -    allRepo = 1;
   108         -  }else{
   109         -    /* The default case:  All repositories under the g.zRepositoryName
   110         -    ** directory.
   111         -    */
   112         -    blob_init(&base, g.zRepositoryName, -1);
   113         -    sqlite3_open(":memory:", &g.db);
   114         -    db_multi_exec("CREATE TABLE sfile(pathname TEXT);");
   115         -    db_multi_exec("CREATE TABLE vfile(pathname);");
   116         -    vfile_scan(&base, blob_size(&base), 0, 0, 0);
   117         -    db_multi_exec("DELETE FROM sfile WHERE pathname NOT GLOB '*[^/].fossil'");
   118         -    allRepo = 0;
   119         -  }
   120         -  @ <html>
   121         -  @ <head>
   122         -  @ <base href="%s(g.zBaseURL)/" />
   123         -  @ <meta name="viewport" content="width=device-width, initial-scale=1.0">
   124         -  @ <title>Repository List</title>
   125         -  @ </head>
   126         -  @ <body>
   127         -  n = db_int(0, "SELECT count(*) FROM sfile");
   128         -  if( n>0 ){
   129         -    Stmt q;
   130         -    double rNow;
   131         -    @ <h1 align="center">Fossil Repositories</h1>
   132         -    @ <table border="0" class="sortable" data-init-sort="1" \
   133         -    @ data-column-types="tntnk"><thead>
   134         -    @ <tr><th>Filename<th width="20">\
   135         -    @ <th>Project Name<th width="20">\
   136         -    @ <th>Last Modified</tr>
   137         -    @ </thead><tbody>
   138         -    db_prepare(&q, "SELECT pathname"
   139         -                   " FROM sfile ORDER BY pathname COLLATE nocase;");
   140         -    rNow = db_double(0, "SELECT julianday('now')");
   141         -    while( db_step(&q)==SQLITE_ROW ){
   142         -      const char *zName = db_column_text(&q, 0);
   143         -      int nName = (int)strlen(zName);
   144         -      char *zUrl;
   145         -      char *zAge;
   146         -      char *zFull;
   147         -      RepoInfo x;
   148         -      int iAge;
   149         -      if( nName<7 ) continue;
   150         -      zUrl = sqlite3_mprintf("%.*s", nName-7, zName);
   151         -      if( zName[0]=='/'
   152         -#ifdef _WIN32
   153         -          || sqlite3_strglob("[a-zA-Z]:/*", zName)==0
   154         -#endif
   155         -      ){
   156         -        zFull = mprintf("%s", zName);
   157         -      }else if ( allRepo ){
   158         -        zFull = mprintf("/%s", zName);
   159         -      }else{
   160         -        zFull = mprintf("%s/%s", g.zRepositoryName, zName);
   161         -      }
   162         -      x.zRepoName = zFull;
   163         -      remote_repo_info(&x);
   164         -      fossil_free(zFull);
   165         -      if( !x.isValid ){
   166         -        zAge = mprintf("...");
   167         -        iAge = 0;
   168         -      }else{
   169         -        iAge = (rNow - x.rMTime)*86400;
   170         -        if( iAge<0 ) x.rMTime = rNow;
   171         -        zAge = human_readable_age(rNow - x.rMTime);
   172         -      }
   173         -      @ <tr><td valign="top">\
   174         -      if( sqlite3_strglob("*.fossil", zName)!=0 ){
   175         -        /* The "fossil server DIRECTORY" and "fossil ui DIRECTORY" commands
   176         -        ** do not work for repositories whose names do not end in ".fossil".
   177         -        ** So do not hyperlink those cases. */
   178         -        @ %h(zName)
   179         -      } else if( sqlite3_strglob("*/.*", zName)==0 ){
   180         -        /* Do not show hidden repos */
   181         -        @ %h(zName) (hidden)
   182         -      } else if( allRepo && sqlite3_strglob("[a-zA-Z]:/?*", zName)!=0 ){
   183         -        @ <a href="%R/%T(zUrl)/home" target="_blank">/%h(zName)</a>
   184         -      }else{
   185         -        @ <a href="%R/%T(zUrl)/home" target="_blank">%h(zName)</a>
   186         -      }
   187         -      if( x.zProjName ){
   188         -        @ <td></td><td>%h(x.zProjName)</td>
   189         -        fossil_free(x.zProjName);
   190         -      }else{
   191         -        @ <td></td><td></td>
   192         -      }
   193         -      @ <td></td><td data-sortkey='%08x(iAge)'>%h(zAge)</tr>
   194         -      fossil_free(zAge);
   195         -      sqlite3_free(zUrl);
   196         -    }
   197         -    @ </tbody></table>
   198         -  }else{
   199         -    @ <h1>No Repositories Found</h1>
   200         -  }
   201         -  @ <script>%s(builtin_text("sorttable.js"))</script>
   202         -  @ </body>
   203         -  @ </html>
   204         -  cgi_reply();
   205         -  sqlite3_close(g.db);
   206         -  g.db = 0;
   207         -  return n;
   208         -}
   209         -
   210         -/*
   211         -** COMMAND: test-list-page
   212         -**
   213         -** Usage: %fossil test-list-page DIRECTORY
   214         -**
   215         -** Show all repositories underneath DIRECTORY.  Or if DIRECTORY is "/"
   216         -** show all repositories in the ~/.fossil file.
   217         -*/
   218         -void test_list_page(void){
   219         -  if( g.argc<3 ){
   220         -    g.zRepositoryName = "/";
   221         -  }else{
   222         -    g.zRepositoryName = g.argv[2];
   223         -  }
   224         -  g.httpOut = stdout;
   225         -  repo_list_page();
   226         -}

Changes to src/security_audit.c.

    40     40   **
    41     41   ** Run a security audit of the current Fossil setup.
    42     42   ** This page requires administrator access
    43     43   */
    44     44   void secaudit0_page(void){
    45     45     const char *zAnonCap;      /* Capabilities of user "anonymous" and "nobody" */
    46     46     const char *zPubPages;     /* GLOB pattern for public pages */
    47         -  const char *zSelfCap;      /* Capabilities of self-registered users */
    48     47     char *z;
    49     48     int n;
    50     49   
    51     50     login_check_credentials();
    52         -  if( !g.perm.Admin ){
           51  +  if( !g.perm.Setup && !g.perm.Admin ){
    53     52       login_needed(0);
    54     53       return;
    55     54     }
    56     55     style_header("Security Audit");
    57     56     @ <ol>
    58     57   
    59     58     /* Step 1:  Determine if the repository is public or private.  "Public"
    60     59     ** means that any anonymous user on the internet can access all content.
    61     60     ** "Private" repos require (non-anonymous) login to access all content,
    62     61     ** though some content may be accessible anonymously.
    63     62     */
    64     63     zAnonCap = db_text("", "SELECT fullcap(NULL)");
    65     64     zPubPages = db_get("public-pages",0);
    66         -  if( db_get_boolean("self-register",0) ){
    67         -    CapabilityString *pCap;
    68         -    pCap = capability_add(0, db_get("default-perms",""));
    69         -    capability_expand(pCap);
    70         -    zSelfCap = capability_string(pCap);
    71         -    capability_free(pCap);
    72         -  }else{
    73         -    zSelfCap = fossil_strdup("");
    74         -  }
    75     65     if( hasAnyCap(zAnonCap,"as") ){
    76     66       @ <li><p>This repository is <big><b>Wildly INSECURE</b></big> because
    77     67       @ it grants administrator privileges to anonymous users.  You
    78     68       @ should <a href="takeitprivate">take this repository private</a>
    79     69       @ immediately!  Or, at least remove the Setup and Admin privileges
    80     70       @ for users "anonymous" and "login" on the
    81     71       @ <a href="setup_ulist">User Configuration</a> page.
    82         -  }else if( hasAnyCap(zSelfCap,"as") ){
    83         -    @ <li><p>This repository is <big><b>Wildly INSECURE</b></big> because
    84         -    @ it grants administrator privileges to self-registered users.  You
    85         -    @ should <a href="takeitprivate">take this repository private</a>
    86         -    @ and/or disable self-registration
    87         -    @ immediately!  Or, at least remove the Setup and Admin privileges
    88         -    @ from the default permissions for new users.
    89     72     }else if( hasAnyCap(zAnonCap,"y") ){
    90     73       @ <li><p>This repository is <big><b>INSECURE</b></big> because
    91     74       @ it allows anonymous users to push unversioned files.
    92     75       @ <p>Fix this by <a href="takeitprivate">taking the repository private</a>
    93     76       @ or by removing the "y" permission from users "anonymous" and
    94     77       @ "nobody" on the <a href="setup_ulist">User Configuration</a> page.
    95         -  }else if( hasAnyCap(zSelfCap,"y") ){
    96         -    @ <li><p>This repository is <big><b>INSECURE</b></big> because
    97         -    @ it allows self-registered users to push unversioned files.
    98         -    @ <p>Fix this by <a href="takeitprivate">taking the repository private</a>
    99         -    @ or by removing the "y" permission from the default permissions or
   100         -    @ by disabling self-registration.
   101     78     }else if( hasAnyCap(zAnonCap,"goz") ){
   102     79       @ <li><p>This repository is <big><b>PUBLIC</b></big>. All
   103     80       @ checked-in content can be accessed by anonymous users.
   104     81       @ <a href="takeitprivate">Take it private</a>.<p>
   105         -  }else if( hasAnyCap(zSelfCap,"goz") ){
   106         -    @ <li><p>This repository is <big><b>PUBLIC</b></big> because all
   107         -    @ checked-in content can be accessed by self-registered users.
   108         -    @ This repostory would be private if you disabled self-registration.</p>
   109     82     }else if( !hasAnyCap(zAnonCap, "jrwy234567")
   110         -         && !hasAnyCap(zSelfCap, "jrwy234567")
   111     83            && (zPubPages==0 || zPubPages[0]==0) ){
   112     84       @ <li><p>This repository is <big><b>Completely PRIVATE</b></big>.
   113     85       @ A valid login and password is required to access any content.
   114     86     }else{
   115     87       @ <li><p>This repository is <big><b>Mostly PRIVATE</b></big>.
   116     88       @ A valid login and password is usually required, however some
   117         -    @ content can be accessed either anonymously or by self-registered
   118         -    @ users:
           89  +    @ content can be accessed anonymously:
   119     90       @ <ul>
   120         -    if( hasAnyCap(zAnonCap,"j") || hasAnyCap(zSelfCap,"j") ){
           91  +    if( hasAnyCap(zAnonCap,"j") ){
   121     92         @ <li> Wiki pages
   122     93       }
   123         -    if( hasAnyCap(zAnonCap,"r") || hasAnyCap(zSelfCap,"r") ){
           94  +    if( hasAnyCap(zAnonCap,"r") ){
   124     95         @ <li> Tickets
   125     96       }
   126         -    if( hasAnyCap(zAnonCap,"234567") || hasAnyCap(zSelfCap,"234567") ){
           97  +    if( hasAnyCap(zAnonCap,"234567") ){
   127     98         @ <li> Forum posts
   128     99       }
   129    100       if( zPubPages && zPubPages[0] ){
   130    101         Glob *pGlob = glob_create(zPubPages);
   131    102         int i;
   132    103         @ <li> URLs that match any of these GLOB patterns:
   133    104         @ <ul>
................................................................................
   437    408   /*
   438    409   ** WEBPAGE: takeitprivate
   439    410   **
   440    411   ** Disable anonymous access to this website
   441    412   */
   442    413   void takeitprivate_page(void){
   443    414     login_check_credentials();
   444         -  if( !g.perm.Admin ){
          415  +  if( !g.perm.Setup && !g.perm.Admin ){
   445    416       login_needed(0);
   446    417       return;
   447    418     }
   448    419     if( P("cancel") ){
   449    420       /* User pressed the cancel button.  Go back */
   450    421       cgi_redirect("secaudit0");
   451    422     }
   452    423     if( P("apply") ){
   453    424       db_multi_exec(
   454    425         "UPDATE user SET cap=''"
   455    426         " WHERE login IN ('nobody','anonymous');"
   456    427         "DELETE FROM config WHERE name='public-pages';"
   457    428       );
   458         -    db_set("self-register","0",0);
   459    429       cgi_redirect("secaudit0");
   460    430     }
   461    431     style_header("Make This Website Private");
   462    432     @ <p>Click the "Make It Private" button below to disable all
   463    433     @ anonymous access to this repository.  A valid login and password
   464    434     @ will be required to access this repository after clicking that
   465    435     @ button.</p>
................................................................................
   486    456   ** this page.
   487    457   */
   488    458   void errorlog_page(void){
   489    459     i64 szFile;
   490    460     FILE *in;
   491    461     char z[10000];
   492    462     login_check_credentials();
   493         -  if( !g.perm.Admin ){
          463  +  if( !g.perm.Setup && !g.perm.Admin ){
   494    464       login_needed(0);
   495    465       return;
   496    466     }
   497    467     style_header("Server Error Log");
   498    468     style_submenu_element("Test", "%R/test-warning");
   499    469     style_submenu_element("Refresh", "%R/errorlog");
   500    470     if( g.zErrlog==0 || fossil_strcmp(g.zErrlog,"-")==0 ){

Changes to src/setup.c.

    57     57   }
    58     58   
    59     59   
    60     60   
    61     61   /*
    62     62   ** WEBPAGE: setup
    63     63   **
    64         -** Main menu for the administrative pages.  Requires Admin or Setup
    65         -** privileges.  Links to sub-pages only usable by Setup users are
    66         -** shown only to Setup users.
           64  +** Main menu for the administrative pages.  Requires Admin privileges.
    67     65   */
    68     66   void setup_page(void){
    69         -  int setup_user = 0;
    70     67     login_check_credentials();
    71         -  if( !g.perm.Admin ){
           68  +  if( !g.perm.Setup ){
    72     69       login_needed(0);
    73     70     }
    74         -  setup_user = g.perm.Setup;
    75     71   
    76     72     style_header("Server Administration");
    77     73   
    78     74     /* Make sure the header contains <base href="...">.   Issue a warning
    79     75     ** if it does not. */
    80     76     if( !cgi_header_contains("<base href=") ){
    81     77       @ <p class="generalError"><b>Configuration Error:</b> Please add
................................................................................
    97     93       @ by SQLite will be poorly seeded.</p>
    98     94     }
    99     95   #endif
   100     96   
   101     97     @ <table border="0" cellspacing="3">
   102     98     setup_menu_entry("Users", "setup_ulist",
   103     99       "Grant privileges to individual users.");
   104         -  if( setup_user ){
   105         -    setup_menu_entry("Access", "setup_access",
   106         -      "Control access settings.");
   107         -    setup_menu_entry("Configuration", "setup_config",
   108         -      "Configure the WWW components of the repository");
   109         -  }
          100  +  setup_menu_entry("Access", "setup_access",
          101  +    "Control access settings.");
          102  +  setup_menu_entry("Configuration", "setup_config",
          103  +    "Configure the WWW components of the repository");
   110    104     setup_menu_entry("Security-Audit", "secaudit0",
   111    105       "Analyze the current configuration for security problems");
   112         -  if( setup_user ){
   113         -    setup_menu_entry("Settings", "setup_settings",
   114         -      "Web interface to the \"fossil settings\" command");
   115         -  }
          106  +  setup_menu_entry("Settings", "setup_settings",
          107  +    "Web interface to the \"fossil settings\" command");
   116    108     setup_menu_entry("Timeline", "setup_timeline",
   117    109       "Timeline display preferences");
   118         -  if( setup_user ){
   119         -    setup_menu_entry("Login-Group", "setup_login_group",
   120         -      "Manage single sign-on between this repository and others"
   121         -      " on the same server");
   122         -    setup_menu_entry("Tickets", "tktsetup",
   123         -      "Configure the trouble-ticketing system for this repository");
   124         -  }
          110  +  setup_menu_entry("Login-Group", "setup_login_group",
          111  +    "Manage single sign-on between this repository and others"
          112  +    " on the same server");
          113  +  setup_menu_entry("Tickets", "tktsetup",
          114  +    "Configure the trouble-ticketing system for this repository");
   125    115     setup_menu_entry("Search","srchsetup",
   126    116       "Configure the built-in search engine");
   127    117     setup_menu_entry("URL Aliases", "waliassetup",
   128    118       "Configure URL aliases");
   129         -  if( setup_user ){
   130         -    setup_menu_entry("Notification", "setup_notification",
   131         -      "Automatic notifications of changes via outbound email");
   132         -    setup_menu_entry("Email-Server", "setup_smtp",
   133         -      "Activate and configure the built-in email server");
   134         -    setup_menu_entry("Transfers", "xfersetup",
   135         -      "Configure the transfer system for this repository");
   136         -  }
          119  +  setup_menu_entry("Notification", "setup_notification",
          120  +    "Automatic notifications of changes via outbound email");
          121  +  setup_menu_entry("Email-Server", "setup_smtp",
          122  +    "Activate and configure the built-in email server");
          123  +  setup_menu_entry("Transfers", "xfersetup",
          124  +    "Configure the transfer system for this repository");
   137    125     setup_menu_entry("Skins", "setup_skin",
   138    126       "Select and/or modify the web interface \"skins\"");
   139    127     setup_menu_entry("Moderation", "setup_modreq",
   140    128       "Enable/Disable requiring moderator approval of Wiki and/or Ticket"
   141    129       " changes and attachments.");
   142    130     setup_menu_entry("Ad-Unit", "setup_adunit",
   143    131       "Edit HTML text for an ad unit inserted after the menu bar");
   144    132     setup_menu_entry("URLs & Checkouts", "urllist",
   145    133       "Show URLs used to access this repo and known check-outs");
   146         -  if( setup_user ){
   147         -    setup_menu_entry("Web-Cache", "cachestat",
   148         -      "View the status of the expensive-page cache");
   149         -  }
          134  +  setup_menu_entry("Web-Cache", "cachestat",
          135  +    "View the status of the expensive-page cache");
   150    136     setup_menu_entry("Logo", "setup_logo",
   151    137       "Change the logo and background images for the server");
   152    138     setup_menu_entry("Shunned", "shun",
   153    139       "Show artifacts that are shunned by this repository");
   154    140     setup_menu_entry("Artifact Receipts Log", "rcvfromlist",
   155    141       "A record of received artifacts and their sources");
   156    142     setup_menu_entry("User Log", "access_log",
................................................................................
   161    147       "View the Fossil server error log");
   162    148     setup_menu_entry("Unversioned Files", "uvlist?byage=1",
   163    149       "Show all unversioned files held");
   164    150     setup_menu_entry("Stats", "stat",
   165    151       "Repository Status Reports");
   166    152     setup_menu_entry("Sitemap", "sitemap",
   167    153       "Links to miscellaneous pages");
   168         -  if( setup_user ){
   169         -    setup_menu_entry("SQL", "admin_sql",
   170         -      "Enter raw SQL commands");
   171         -    setup_menu_entry("TH1", "admin_th1",
   172         -      "Enter raw TH1 commands");
   173         -  }
          154  +  setup_menu_entry("SQL", "admin_sql",
          155  +    "Enter raw SQL commands");
          156  +  setup_menu_entry("TH1", "admin_th1",
          157  +    "Enter raw TH1 commands");
   174    158     @ </table>
   175    159   
   176    160     style_footer();
   177    161   }
   178    162   
   179    163   /*
   180    164   ** Generate a checkbox for an attribute.
................................................................................
   305    289     @ </select> <b>%h(zLabel)</b>
   306    290   }
   307    291   
   308    292   
   309    293   /*
   310    294   ** WEBPAGE: setup_access
   311    295   **
   312         -** The access-control settings page.  Requires Setup privileges.
          296  +** The access-control settings page.  Requires Admin privileges.
   313    297   */
   314    298   void setup_access(void){
   315    299     login_check_credentials();
   316    300     if( !g.perm.Setup ){
   317    301       login_needed(0);
   318    302       return;
   319    303     }
................................................................................
   661    645         "0", "HH:MM",
   662    646         "1", "HH:MM:SS",
   663    647         "2", "YYYY-MM-DD HH:MM",
   664    648         "3", "YYMMDD HH:MM",
   665    649         "4", "(off)"
   666    650     };
   667    651     login_check_credentials();
   668         -  if( !g.perm.Admin ){
          652  +  if( !g.perm.Setup ){
   669    653       login_needed(0);
   670    654       return;
   671    655     }
   672    656   
   673    657     style_header("Timeline Display Preferences");
   674    658     db_begin_transaction();
   675    659     @ <form action="%s(g.zTop)/setup_timeline" method="post"><div>
................................................................................
   740    724     style_footer();
   741    725   }
   742    726   
   743    727   /*
   744    728   ** WEBPAGE: setup_settings
   745    729   **
   746    730   ** Change or view miscellaneous settings.  Part of the
   747         -** /setup pages requiring Setup privileges.
          731  +** Admin pages requiring Admin privileges.
   748    732   */
   749    733   void setup_settings(void){
   750    734     int nSetting;
   751    735     int i;
   752    736     Setting const *pSet;
   753    737     const Setting *aSetting = setting_info(&nSetting);
   754    738   
................................................................................
   827    811     db_end_transaction(0);
   828    812     style_footer();
   829    813   }
   830    814   
   831    815   /*
   832    816   ** WEBPAGE: setup_config
   833    817   **
   834         -** The "Admin/Configuration" page.  Requires Setup privilege.
          818  +** The "Admin/Configuration" page.  Requires Admin privilege.
   835    819   */
   836    820   void setup_config(void){
   837    821     login_check_credentials();
   838    822     if( !g.perm.Setup ){
   839    823       login_needed(0);
   840    824       return;
   841    825     }
................................................................................
   949    933   /*
   950    934   ** WEBPAGE: setup_modreq
   951    935   **
   952    936   ** Admin page for setting up moderation of tickets and wiki.
   953    937   */
   954    938   void setup_modreq(void){
   955    939     login_check_credentials();
   956         -  if( !g.perm.Admin ){
          940  +  if( !g.perm.Setup ){
   957    941       login_needed(0);
   958    942       return;
   959    943     }
   960    944   
   961    945     style_header("Moderator For Wiki And Tickets");
   962    946     db_begin_transaction();
   963    947     @ <form action="%R/setup_modreq" method="post"><div>
................................................................................
   997    981   ** WEBPAGE: setup_adunit
   998    982   **
   999    983   ** Administrative page for configuring and controlling ad units
  1000    984   ** and how they are displayed.
  1001    985   */
  1002    986   void setup_adunit(void){
  1003    987     login_check_credentials();
  1004         -  if( !g.perm.Admin ){
          988  +  if( !g.perm.Setup ){
  1005    989       login_needed(0);
  1006    990       return;
  1007    991     }
  1008    992     db_begin_transaction();
  1009    993     if( P("clear")!=0 && cgi_csrf_safe(1) ){
  1010    994       db_multi_exec("DELETE FROM config WHERE name GLOB 'adunit*'");
  1011    995       cgi_replace_parameter("adunit","");
................................................................................
  1087   1071     if( szLogoImg>0 ){
  1088   1072       zLogoMime = PD("logoim:mimetype","image/gif");
  1089   1073     }
  1090   1074     if( szBgImg>0 ){
  1091   1075       zBgMime = PD("bgim:mimetype","image/gif");
  1092   1076     }
  1093   1077     login_check_credentials();
  1094         -  if( !g.perm.Admin ){
         1078  +  if( !g.perm.Setup ){
  1095   1079       login_needed(0);
  1096   1080       return;
  1097   1081     }
  1098   1082     db_begin_transaction();
  1099   1083     if( !cgi_csrf_safe(1) ){
  1100   1084       /* Allow no state changes if not safe from CSRF */
  1101   1085     }else if( P("setlogo")!=0 && zLogoMime && zLogoMime[0] && szLogoImg>0 ){
................................................................................
  1228   1212   }
  1229   1213   
  1230   1214   
  1231   1215   /*
  1232   1216   ** WEBPAGE: admin_sql
  1233   1217   **
  1234   1218   ** Run raw SQL commands against the database file using the web interface.
  1235         -** Requires Setup privileges.
         1219  +** Requires Admin privileges.
  1236   1220   */
  1237   1221   void sql_page(void){
  1238   1222     const char *zQ;
  1239   1223     int go = P("go")!=0;
  1240   1224     login_check_credentials();
  1241   1225     if( !g.perm.Setup ){
  1242   1226       login_needed(0);
................................................................................
  1419   1403   void page_admin_log(){
  1420   1404     Stmt stLog;
  1421   1405     int limit;                 /* How many entries to show */
  1422   1406     int ofst;                  /* Offset to the first entry */
  1423   1407     int fLogEnabled;
  1424   1408     int counter = 0;
  1425   1409     login_check_credentials();
  1426         -  if( !g.perm.Admin ){
         1410  +  if( !g.perm.Setup && !g.perm.Admin ){
  1427   1411       login_needed(0);
  1428   1412       return;
  1429   1413     }
  1430   1414     style_header("Admin Log");
  1431   1415     create_admin_log_table();
  1432   1416     limit = atoi(PD("n","200"));
  1433   1417     ofst = atoi(PD("x","0"));
................................................................................
  1479   1463   /*
  1480   1464   ** WEBPAGE: srchsetup
  1481   1465   **
  1482   1466   ** Configure the search engine.  Requires Admin privilege.
  1483   1467   */
  1484   1468   void page_srchsetup(){
  1485   1469     login_check_credentials();
  1486         -  if( !g.perm.Admin ){
         1470  +  if( !g.perm.Setup && !g.perm.Admin ){
  1487   1471       login_needed(0);
  1488   1472       return;
  1489   1473     }
  1490   1474     style_header("Search Configuration");
  1491   1475     @ <form action="%s(g.zTop)/srchsetup" method="post"><div>
  1492   1476     login_insert_csrf_secret();
  1493   1477     @ <div style="text-align:center;font-weight:bold;">
................................................................................
  1603   1587   ** Configure the URL aliases
  1604   1588   */
  1605   1589   void page_waliassetup(){
  1606   1590     Stmt q;
  1607   1591     int cnt = 0;
  1608   1592     Blob namelist;
  1609   1593     login_check_credentials();
  1610         -  if( !g.perm.Admin ){
         1594  +  if( !g.perm.Setup && !g.perm.Admin ){
  1611   1595       login_needed(0);
  1612   1596       return;
  1613   1597     }
  1614   1598     style_header("URL Alias Configuration");
  1615   1599     if( P("submit")!=0 ){
  1616   1600       Blob token;
  1617   1601       Blob sql;

Changes to src/setupuser.c.

    40     40   
    41     41     login_check_credentials();
    42     42     if( !g.perm.Admin ){
    43     43       login_needed(0);
    44     44       return;
    45     45     }
    46     46   
    47         -  style_submenu_element("Add", "setup_uedit");
    48         -  style_submenu_element("Log", "access_log");
    49         -  style_submenu_element("Help", "setup_ulist_notes");
    50         -  style_header("User List");
    51     47     if( zWith==0 || zWith[0]==0 ){
           48  +    style_submenu_element("Add", "setup_uedit");
           49  +    style_submenu_element("Log", "access_log");
           50  +    style_submenu_element("Help", "setup_ulist_notes");
           51  +    style_header("User List");
    52     52       @ <table border=1 cellpadding=2 cellspacing=0 class='userTable'>
    53     53       @ <thead><tr>
    54     54       @   <th>Category
    55     55       @   <th>Capabilities (<a href='%R/setup_ucap_list'>key</a>)
    56     56       @   <th>Info <th>Last Change</tr></thead>
    57     57       @ <tbody>
    58     58       db_prepare(&s,
................................................................................
    85     85           @ <td>%h(zDate)
    86     86         }else{
    87     87           @ <td>
    88     88         }
    89     89         @ </tr>
    90     90       }
    91     91       db_finalize(&s);
    92         -    @ </tbody></table>
    93         -    @ <div class='section'>Users</div>
    94     92     }else{
    95         -    style_submenu_element("All Users", "setup_ulist");
    96         -    if( zWith[1]==0 ){
    97         -      @ <div class='section'>Users with capability "%h(zWith)"</div>
    98         -    }else{
    99         -      @ <div class='section'>Users with any capability in "%h(zWith)"</div>
   100         -    }
           93  +    style_header("Users With Capabilities \"%h\"", zWith);
   101     94     }
           95  +  @ </tbody></table>
           96  +  @ <div class='section'>Users</div>
   102     97     @ <table border=1 cellpadding=2 cellspacing=0 class='userTable sortable' \
   103     98     @  data-column-types='ktxTTK' data-init-sort='2'>
   104     99     @ <thead><tr>
   105    100     @ <th>Login Name<th>Caps<th>Info<th>Date<th>Expire<th>Last Login</tr></thead>
   106    101     @ <tbody>
   107    102     db_multi_exec(
   108    103       "CREATE TEMP TABLE lastAccess(uname TEXT PRIMARY KEY, atime REAL)"

Changes to src/shell.c.

  1313   1313   **
  1314   1314   **    May you do good and not evil.
  1315   1315   **    May you find forgiveness for yourself and forgive others.
  1316   1316   **    May you share freely, never taking more than you give.
  1317   1317   **
  1318   1318   ******************************************************************************
  1319   1319   **
  1320         -** This SQLite extension implements functions that compute SHA3 hashes.
         1320  +** This SQLite extension implements a functions that compute SHA1 hashes.
  1321   1321   ** Two SQL functions are implemented:
  1322   1322   **
  1323   1323   **     sha3(X,SIZE)
  1324   1324   **     sha3_query(Y,SIZE)
  1325   1325   **
  1326   1326   ** The sha3(X) function computes the SHA3 hash of the input X, or NULL if
  1327   1327   ** X is NULL.
................................................................................
  2124   2124   #  define mkdir(path,mode) _mkdir(path)
  2125   2125   #  define lstat(path,buf) stat(path,buf)
  2126   2126   #endif
  2127   2127   #include <time.h>
  2128   2128   #include <errno.h>
  2129   2129   
  2130   2130   
  2131         -/*
  2132         -** Structure of the fsdir() table-valued function
  2133         -*/
  2134         -                 /*    0    1    2     3    4           5             */
  2135   2131   #define FSDIR_SCHEMA "(name,mode,mtime,data,path HIDDEN,dir HIDDEN)"
  2136         -#define FSDIR_COLUMN_NAME     0     /* Name of the file */
  2137         -#define FSDIR_COLUMN_MODE     1     /* Access mode */
  2138         -#define FSDIR_COLUMN_MTIME    2     /* Last modification time */
  2139         -#define FSDIR_COLUMN_DATA     3     /* File content */
  2140         -#define FSDIR_COLUMN_PATH     4     /* Path to top of search */
  2141         -#define FSDIR_COLUMN_DIR      5     /* Path is relative to this directory */
  2142         -
  2143   2132   
  2144   2133   /*
  2145   2134   ** Set the result stored by context ctx to a blob containing the 
  2146   2135   ** contents of file zName.
  2147   2136   */
  2148   2137   static void readFileContents(sqlite3_context *ctx, const char *zName){
  2149   2138     FILE *in;
................................................................................
  2724   2713   static int fsdirColumn(
  2725   2714     sqlite3_vtab_cursor *cur,   /* The cursor */
  2726   2715     sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
  2727   2716     int i                       /* Which column to return */
  2728   2717   ){
  2729   2718     fsdir_cursor *pCur = (fsdir_cursor*)cur;
  2730   2719     switch( i ){
  2731         -    case FSDIR_COLUMN_NAME: {
         2720  +    case 0: { /* name */
  2732   2721         sqlite3_result_text(ctx, &pCur->zPath[pCur->nBase], -1, SQLITE_TRANSIENT);
  2733   2722         break;
  2734   2723       }
  2735   2724   
  2736         -    case FSDIR_COLUMN_MODE:
         2725  +    case 1: /* mode */
  2737   2726         sqlite3_result_int64(ctx, pCur->sStat.st_mode);
  2738   2727         break;
  2739   2728   
  2740         -    case FSDIR_COLUMN_MTIME:
         2729  +    case 2: /* mtime */
  2741   2730         sqlite3_result_int64(ctx, pCur->sStat.st_mtime);
  2742   2731         break;
  2743   2732   
  2744         -    case FSDIR_COLUMN_DATA: {
         2733  +    case 3: { /* data */
  2745   2734         mode_t m = pCur->sStat.st_mode;
  2746   2735         if( S_ISDIR(m) ){
  2747   2736           sqlite3_result_null(ctx);
  2748   2737   #if !defined(_WIN32) && !defined(WIN32)
  2749   2738         }else if( S_ISLNK(m) ){
  2750   2739           char aStatic[64];
  2751   2740           char *aBuf = aStatic;
................................................................................
  2767   2756           sqlite3_result_text(ctx, aBuf, n, SQLITE_TRANSIENT);
  2768   2757           if( aBuf!=aStatic ) sqlite3_free(aBuf);
  2769   2758   #endif
  2770   2759         }else{
  2771   2760           readFileContents(ctx, pCur->zPath);
  2772   2761         }
  2773   2762       }
  2774         -    case FSDIR_COLUMN_PATH:
  2775         -    default: {
  2776         -      /* The FSDIR_COLUMN_PATH and FSDIR_COLUMN_DIR are input parameters.
  2777         -      ** always return their values as NULL */
  2778         -      break;
  2779         -    }
  2780   2763     }
  2781   2764     return SQLITE_OK;
  2782   2765   }
  2783   2766   
  2784   2767   /*
  2785   2768   ** Return the rowid for the current row. In this implementation, the
  2786   2769   ** first row returned is assigned rowid value 1, and each subsequent
................................................................................
  2799   2782   static int fsdirEof(sqlite3_vtab_cursor *cur){
  2800   2783     fsdir_cursor *pCur = (fsdir_cursor*)cur;
  2801   2784     return (pCur->zPath==0);
  2802   2785   }
  2803   2786   
  2804   2787   /*
  2805   2788   ** xFilter callback.
  2806         -**
  2807         -** idxNum==1   PATH parameter only
  2808         -** idxNum==2   Both PATH and DIR supplied
  2809   2789   */
  2810   2790   static int fsdirFilter(
  2811   2791     sqlite3_vtab_cursor *cur, 
  2812   2792     int idxNum, const char *idxStr,
  2813   2793     int argc, sqlite3_value **argv
  2814   2794   ){
  2815   2795     const char *zDir = 0;
................................................................................
  2854   2834   ** that uses the generate_series virtual table.  This routine needs to create
  2855   2835   ** a query plan for each invocation and compute an estimated cost for that
  2856   2836   ** plan.
  2857   2837   **
  2858   2838   ** In this implementation idxNum is used to represent the
  2859   2839   ** query plan.  idxStr is unused.
  2860   2840   **
  2861         -** The query plan is represented by values of idxNum:
         2841  +** The query plan is represented by bits in idxNum:
  2862   2842   **
  2863         -**  (1)  The path value is supplied by argv[0]
  2864         -**  (2)  Path is in argv[0] and dir is in argv[1]
         2843  +**  (1)  start = $value  -- constraint exists
         2844  +**  (2)  stop = $value   -- constraint exists
         2845  +**  (4)  step = $value   -- constraint exists
         2846  +**  (8)  output in descending order
  2865   2847   */
  2866   2848   static int fsdirBestIndex(
  2867   2849     sqlite3_vtab *tab,
  2868   2850     sqlite3_index_info *pIdxInfo
  2869   2851   ){
  2870   2852     int i;                 /* Loop over constraints */
  2871         -  int idxPath = -1;      /* Index in pIdxInfo->aConstraint of PATH= */
  2872         -  int idxDir = -1;       /* Index in pIdxInfo->aConstraint of DIR= */
  2873         -  int seenPath = 0;      /* True if an unusable PATH= constraint is seen */
  2874         -  int seenDir = 0;       /* True if an unusable DIR= constraint is seen */
         2853  +  int idx4 = -1;
         2854  +  int idx5 = -1;
  2875   2855     const struct sqlite3_index_constraint *pConstraint;
  2876   2856   
  2877   2857     (void)tab;
  2878   2858     pConstraint = pIdxInfo->aConstraint;
  2879   2859     for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
         2860  +    if( pConstraint->usable==0 ) continue;
  2880   2861       if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  2881         -    switch( pConstraint->iColumn ){
  2882         -      case FSDIR_COLUMN_PATH: {
  2883         -        if( pConstraint->usable ){
  2884         -          idxPath = i;
  2885         -          seenPath = 0;
  2886         -        }else if( idxPath<0 ){
  2887         -          seenPath = 1;
  2888         -        }
  2889         -        break;
  2890         -      }
  2891         -      case FSDIR_COLUMN_DIR: {
  2892         -        if( pConstraint->usable ){
  2893         -          idxDir = i;
  2894         -          seenDir = 0;
  2895         -        }else if( idxDir<0 ){
  2896         -          seenDir = 1;
  2897         -        }
  2898         -        break;
  2899         -      }
  2900         -    } 
  2901         -  }
  2902         -  if( seenPath || seenDir ){
  2903         -    /* If input parameters are unusable, disallow this plan */
  2904         -    return SQLITE_CONSTRAINT;
         2862  +    if( pConstraint->iColumn==4 ) idx4 = i;
         2863  +    if( pConstraint->iColumn==5 ) idx5 = i;
  2905   2864     }
  2906   2865   
  2907         -  if( idxPath<0 ){
         2866  +  if( idx4<0 ){
  2908   2867       pIdxInfo->idxNum = 0;
  2909         -    /* The pIdxInfo->estimatedCost should have been initialized to a huge
  2910         -    ** number.  Leave it unchanged. */
  2911         -    pIdxInfo->estimatedRows = 0x7fffffff;
         2868  +    pIdxInfo->estimatedCost = (double)(((sqlite3_int64)1) << 50);
  2912   2869     }else{
  2913         -    pIdxInfo->aConstraintUsage[idxPath].omit = 1;
  2914         -    pIdxInfo->aConstraintUsage[idxPath].argvIndex = 1;
  2915         -    if( idxDir>=0 ){
  2916         -      pIdxInfo->aConstraintUsage[idxDir].omit = 1;
  2917         -      pIdxInfo->aConstraintUsage[idxDir].argvIndex = 2;
         2870  +    pIdxInfo->aConstraintUsage[idx4].omit = 1;
         2871  +    pIdxInfo->aConstraintUsage[idx4].argvIndex = 1;
         2872  +    if( idx5>=0 ){
         2873  +      pIdxInfo->aConstraintUsage[idx5].omit = 1;
         2874  +      pIdxInfo->aConstraintUsage[idx5].argvIndex = 2;
  2918   2875         pIdxInfo->idxNum = 2;
  2919   2876         pIdxInfo->estimatedCost = 10.0;
  2920   2877       }else{
  2921   2878         pIdxInfo->idxNum = 1;
  2922   2879         pIdxInfo->estimatedCost = 100.0;
  2923   2880       }
  2924   2881     }
................................................................................
  2949   2906       0,                         /* xSync */
  2950   2907       0,                         /* xCommit */
  2951   2908       0,                         /* xRollback */
  2952   2909       0,                         /* xFindMethod */
  2953   2910       0,                         /* xRename */
  2954   2911       0,                         /* xSavepoint */
  2955   2912       0,                         /* xRelease */
  2956         -    0,                         /* xRollbackTo */
  2957         -    0,                         /* xShadowName */
         2913  +    0                          /* xRollbackTo */
  2958   2914     };
  2959   2915   
  2960   2916     int rc = sqlite3_create_module(db, "fsdir", &fsdirModule, 0);
  2961   2917     return rc;
  2962   2918   }
  2963   2919   #else         /* SQLITE_OMIT_VIRTUALTABLE */
  2964   2920   # define fsdirRegister(x) SQLITE_OK
................................................................................
  3458   3414     0,                         /* xSync */
  3459   3415     0,                         /* xCommit */
  3460   3416     0,                         /* xRollback */
  3461   3417     0,                         /* xFindMethod */
  3462   3418     0,                         /* xRename */
  3463   3419     0,                         /* xSavepoint */
  3464   3420     0,                         /* xRelease */
  3465         -  0,                         /* xRollbackTo */
  3466         -  0                          /* xShadowName */
         3421  +  0                          /* xRollbackTo */
  3467   3422   };
  3468   3423   
  3469   3424   #endif /* SQLITE_OMIT_VIRTUALTABLE */
  3470   3425   
  3471   3426   int sqlite3CompletionVtabInit(sqlite3 *db){
  3472   3427     int rc = SQLITE_OK;
  3473   3428   #ifndef SQLITE_OMIT_VIRTUALTABLE
................................................................................
  5356   5311   ** xBestIndex callback.
  5357   5312   */
  5358   5313   static int zipfileBestIndex(
  5359   5314     sqlite3_vtab *tab,
  5360   5315     sqlite3_index_info *pIdxInfo
  5361   5316   ){
  5362   5317     int i;
  5363         -  int idx = -1;
  5364         -  int unusable = 0;
  5365   5318   
  5366   5319     for(i=0; i<pIdxInfo->nConstraint; i++){
  5367   5320       const struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
         5321  +    if( pCons->usable==0 ) continue;
         5322  +    if( pCons->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  5368   5323       if( pCons->iColumn!=ZIPFILE_F_COLUMN_IDX ) continue;
  5369         -    if( pCons->usable==0 ){
  5370         -      unusable = 1;
  5371         -    }else if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  5372         -      idx = i;
  5373         -    }
         5324  +    break;
  5374   5325     }
  5375         -  if( idx>=0 ){
  5376         -    pIdxInfo->aConstraintUsage[idx].argvIndex = 1;
  5377         -    pIdxInfo->aConstraintUsage[idx].omit = 1;
         5326  +
         5327  +  if( i<pIdxInfo->nConstraint ){
         5328  +    pIdxInfo->aConstraintUsage[i].argvIndex = 1;
         5329  +    pIdxInfo->aConstraintUsage[i].omit = 1;
  5378   5330       pIdxInfo->estimatedCost = 1000.0;
  5379   5331       pIdxInfo->idxNum = 1;
  5380         -  }else if( unusable ){
  5381         -    return SQLITE_CONSTRAINT;
         5332  +  }else{
         5333  +    pIdxInfo->estimatedCost = (double)(((sqlite3_int64)1) << 50);
         5334  +    pIdxInfo->idxNum = 0;
  5382   5335     }
         5336  +
  5383   5337     return SQLITE_OK;
  5384   5338   }
  5385   5339   
  5386   5340   static ZipfileEntry *zipfileNewEntry(const char *zPath){
  5387   5341     ZipfileEntry *pNew;
  5388   5342     pNew = sqlite3_malloc(sizeof(ZipfileEntry));
  5389   5343     if( pNew ){
................................................................................
  7178   7132       0,                            /* xCommit - commit transaction */
  7179   7133       0,                            /* xRollback - rollback transaction */
  7180   7134       0,                            /* xFindFunction - function overloading */
  7181   7135       0,                            /* xRename - rename the table */
  7182   7136       0,                            /* xSavepoint */
  7183   7137       0,                            /* xRelease */
  7184   7138       0,                            /* xRollbackTo */
  7185         -    0,                            /* xShadowName */
  7186   7139     };
  7187   7140   
  7188   7141     return sqlite3_create_module(p->dbv, "expert", &expertModule, (void*)p);
  7189   7142   }
  7190   7143   /*
  7191   7144   ** End of virtual table implementation.
  7192   7145   *************************************************************************/
................................................................................
  8603   8556   #define AUTOEQP_off      0           /* Automatic EXPLAIN QUERY PLAN is off */
  8604   8557   #define AUTOEQP_on       1           /* Automatic EQP is on */
  8605   8558   #define AUTOEQP_trigger  2           /* On and also show plans for triggers */
  8606   8559   #define AUTOEQP_full     3           /* Show full EXPLAIN */
  8607   8560   
  8608   8561   /* Allowed values for ShellState.openMode
  8609   8562   */
  8610         -#define SHELL_OPEN_UNSPEC      0      /* No open-mode specified */
  8611         -#define SHELL_OPEN_NORMAL      1      /* Normal database file */
  8612         -#define SHELL_OPEN_APPENDVFS   2      /* Use appendvfs */
  8613         -#define SHELL_OPEN_ZIPFILE     3      /* Use the zipfile virtual table */
  8614         -#define SHELL_OPEN_READONLY    4      /* Open a normal database read-only */
  8615         -#define SHELL_OPEN_DESERIALIZE 5      /* Open using sqlite3_deserialize() */
         8563  +#define SHELL_OPEN_UNSPEC     0      /* No open-mode specified */
         8564  +#define SHELL_OPEN_NORMAL     1      /* Normal database file */
         8565  +#define SHELL_OPEN_APPENDVFS  2      /* Use appendvfs */
         8566  +#define SHELL_OPEN_ZIPFILE    3      /* Use the zipfile virtual table */
         8567  +#define SHELL_OPEN_READONLY   4      /* Open a normal database read-only */
  8616   8568   
  8617   8569   /*
  8618   8570   ** These are the allowed shellFlgs values
  8619   8571   */
  8620   8572   #define SHFLG_Pagecache      0x00000001 /* The --pagecache option is used */
  8621   8573   #define SHFLG_Lookaside      0x00000002 /* Lookaside memory is used */
  8622   8574   #define SHFLG_Backslash      0x00000004 /* The --backslash option is used */
................................................................................
  8818   8770     if( x!=sz ){
  8819   8771       sqlite3_result_error(context, "could not read back the whole file", -1);
  8820   8772       goto edit_func_end;
  8821   8773     }
  8822   8774     if( bBin ){
  8823   8775       sqlite3_result_blob64(context, p, sz, sqlite3_free);
  8824   8776     }else{
  8825         -    sqlite3_int64 i, j;
         8777  +    int i, j;
  8826   8778       if( hasCRNL ){
  8827   8779         /* If the original contains \r\n then do no conversions back to \n */
  8828   8780         j = sz;
  8829   8781       }else{
  8830   8782         /* If the file did not originally contain \r\n then convert any new
  8831   8783         ** \r\n back into \n */
  8832   8784         for(i=j=0; i<sz; i++){
................................................................................
 10880  10832       sqlite3_free(zErr);
 10881  10833       free(zQ2);
 10882  10834     }
 10883  10835     return rc;
 10884  10836   }
 10885  10837   
 10886  10838   /*
 10887         -** Text of help messages.
 10888         -**
 10889         -** The help text for each individual command begins with a line that starts
 10890         -** with ".".  Subsequent lines are supplimental information.
 10891         -**
 10892         -** There must be two or more spaces between the end of the command and the
 10893         -** start of the description of what that command does.
        10839  +** Text of a help message
 10894  10840   */
 10895         -static const char *(azHelp[]) = {
        10841  +static char zHelp[] =
 10896  10842   #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
 10897         -  ".archive ...             Manage SQL archives",
 10898         -  "   Each command must have exactly one of the following options:",
 10899         -  "     -c, --create               Create a new archive",
 10900         -  "     -u, --update               Update or add files to an existing archive",
 10901         -  "     -t, --list                 List contents of archive",
 10902         -  "     -x, --extract              Extract files from archive",
 10903         -  "   Optional arguments:",
 10904         -  "     -v, --verbose              Print each filename as it is processed",
 10905         -  "     -f FILE, --file FILE       Operate on archive FILE (default is current db)",
 10906         -  "     -a FILE, --append FILE     Operate on FILE opened using the apndvfs VFS",
 10907         -  "     -C DIR, --directory DIR    Change to directory DIR to read/extract files",
 10908         -  "     -n, --dryrun               Show the SQL that would have occurred",
 10909         -  "   Examples:",
 10910         -  "     .ar -cf archive.sar foo bar  # Create archive.sar from files foo and bar",
 10911         -  "     .ar -tf archive.sar          # List members of archive.sar",
 10912         -  "     .ar -xvf archive.sar         # Verbosely extract files from archive.sar",
 10913         -  "   See also:",
 10914         -  "      http://sqlite.org/cli.html#sqlar_archive_support",
        10843  +  ".archive ...           Manage SQL archives: \".archive --help\" for details\n"
 10915  10844   #endif
 10916  10845   #ifndef SQLITE_OMIT_AUTHORIZATION
 10917         -  ".auth ON|OFF             Show authorizer callbacks",
 10918         -#endif
 10919         -  ".backup ?DB? FILE        Backup DB (default \"main\") to FILE",
 10920         -  "       --append            Use the appendvfs",
 10921         -  ".bail on|off             Stop after hitting an error.  Default OFF",
 10922         -  ".binary on|off           Turn binary output on or off.  Default OFF",
 10923         -  ".cd DIRECTORY            Change the working directory to DIRECTORY",
 10924         -  ".changes on|off          Show number of rows changed by SQL",
 10925         -  ".check GLOB              Fail if output since .testcase does not match",
 10926         -  ".clone NEWDB             Clone data into NEWDB from the existing database",
 10927         -  ".databases               List names and files of attached databases",
 10928         -  ".dbconfig ?op? ?val?     List or change sqlite3_db_config() options",
 10929         -  ".dbinfo ?DB?             Show status information about the database",
 10930         -  ".dump ?TABLE? ...        Render all database content as SQL",
 10931         -  "   Options:",
 10932         -  "     --preserve-rowids      Include ROWID values in the output",
 10933         -  "     --newlines             Allow unescaped newline characters in output",
 10934         -  "   TABLE is LIKE pattern for the tables to dump",
 10935         -  ".echo on|off             Turn command echo on or off",
 10936         -  ".eqp on|off|full         Enable or disable automatic EXPLAIN QUERY PLAN",
 10937         -  ".excel                   Display the output of next command in a spreadsheet",
 10938         -  ".exit ?CODE?             Exit this program with return-code CODE",
 10939         -  ".expert                  EXPERIMENTAL. Suggest indexes for specified queries",
        10846  +  ".auth ON|OFF           Show authorizer callbacks\n"
        10847  +#endif
        10848  +  ".backup ?DB? FILE      Backup DB (default \"main\") to FILE\n"
        10849  +  "                         Add \"--append\" to open using appendvfs.\n"
        10850  +  ".bail on|off           Stop after hitting an error.  Default OFF\n"
        10851  +  ".binary on|off         Turn binary output on or off.  Default OFF\n"
        10852  +  ".cd DIRECTORY          Change the working directory to DIRECTORY\n"
        10853  +  ".changes on|off        Show number of rows changed by SQL\n"
        10854  +  ".check GLOB            Fail if output since .testcase does not match\n"
        10855  +  ".clone NEWDB           Clone data into NEWDB from the existing database\n"
        10856  +  ".databases             List names and files of attached databases\n"
        10857  +  ".dbconfig ?op? ?val?   List or change sqlite3_db_config() options\n"
        10858  +  ".dbinfo ?DB?           Show status information about the database\n"
        10859  +  ".dump ?TABLE? ...      Dump the database in an SQL text format\n"
        10860  +  "                         If TABLE specified, only dump tables matching\n"
        10861  +  "                         LIKE pattern TABLE.\n"
        10862  +  ".echo on|off           Turn command echo on or off\n"
        10863  +  ".eqp on|off|full       Enable or disable automatic EXPLAIN QUERY PLAN\n"
        10864  +  ".excel                 Display the output of next command in a spreadsheet\n"
        10865  +  ".exit                  Exit this program\n"
        10866  +  ".expert                EXPERIMENTAL. Suggest indexes for specified queries\n"
 10940  10867   /* Because explain mode comes on automatically now, the ".explain" mode
 10941  10868   ** is removed from the help screen.  It is still supported for legacy, however */
 10942         -/*".explain ?on|off|auto?   Turn EXPLAIN output mode on or off or to automatic",*/
 10943         -  ".fullschema ?--indent?   Show schema and the content of sqlite_stat tables",
 10944         -  ".headers on|off          Turn display of headers on or off",
 10945         -  ".help ?-all? ?PATTERN?   Show help text for PATTERN",
 10946         -  ".import FILE TABLE       Import data from FILE into TABLE",
        10869  +/*".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic\n"*/
        10870  +  ".fullschema ?--indent? Show schema and the content of sqlite_stat tables\n"
        10871  +  ".headers on|off        Turn display of headers on or off\n"
        10872  +  ".help                  Show this message\n"
        10873  +  ".import FILE TABLE     Import data from FILE into TABLE\n"
 10947  10874   #ifndef SQLITE_OMIT_TEST_CONTROL
 10948         -  ".imposter INDEX TABLE    Create imposter table TABLE on index INDEX",
        10875  +  ".imposter INDEX TABLE  Create imposter table TABLE on index INDEX\n"
 10949  10876   #endif
 10950         -  ".indexes ?TABLE?         Show names of indexes",
 10951         -  "                           If TABLE is specified, only show indexes for",
 10952         -  "                           tables matching TABLE using the LIKE operator.",
        10877  +  ".indexes ?TABLE?       Show names of all indexes\n"
        10878  +  "                         If TABLE specified, only show indexes for tables\n"
        10879  +  "                         matching LIKE pattern TABLE.\n"
 10953  10880   #ifdef SQLITE_ENABLE_IOTRACE
 10954         -  ".iotrace FILE            Enable I/O diagnostic logging to FILE",
        10881  +  ".iotrace FILE          Enable I/O diagnostic logging to FILE\n"
 10955  10882   #endif
 10956         -  ".limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT",
 10957         -  ".lint OPTIONS            Report potential schema issues.",
 10958         -  "     Options:",
 10959         -  "        fkey-indexes     Find missing foreign key indexes",
        10883  +  ".limit ?LIMIT? ?VAL?   Display or change the value of an SQLITE_LIMIT\n"
        10884  +  ".lint OPTIONS          Report potential schema issues. Options:\n"
        10885  +  "                         fkey-indexes     Find missing foreign key indexes\n"
 10960  10886   #ifndef SQLITE_OMIT_LOAD_EXTENSION
 10961         -  ".load FILE ?ENTRY?       Load an extension library",
 10962         -#endif
 10963         -  ".log FILE|off            Turn logging on or off.  FILE can be stderr/stdout",
 10964         -  ".mode MODE ?TABLE?       Set output mode",
 10965         -  "   MODE is one of:",
 10966         -  "     ascii    Columns/rows delimited by 0x1F and 0x1E",
 10967         -  "     csv      Comma-separated values",
 10968         -  "     column   Left-aligned columns.  (See .width)",
 10969         -  "     html     HTML <table> code",
 10970         -  "     insert   SQL insert statements for TABLE",
 10971         -  "     line     One value per line",
 10972         -  "     list     Values delimited by \"|\"",
 10973         -  "     quote    Escape answers as for SQL",
 10974         -  "     tabs     Tab-separated values",
 10975         -  "     tcl      TCL list elements",
 10976         -  ".nullvalue STRING        Use STRING in place of NULL values",
 10977         -  ".once (-e|-x|FILE)       Output for the next SQL command only to FILE",
 10978         -  "     If FILE begins with '|' then open as a pipe",
 10979         -  "     Other options:",
 10980         -  "       -e    Invoke system text editor",
 10981         -  "       -x    Open in a spreadsheet",
 10982         -  ".open ?OPTIONS? ?FILE?   Close existing database and reopen FILE",
 10983         -  "     Options:",
 10984         -  "        --append        Use appendvfs to append database to the end of FILE",
 10985         -#ifdef SQLITE_ENABLE_DESERIALIZE
 10986         -  "        --deserialize   Load into memory useing sqlite3_deserialize()",
 10987         -#endif
 10988         -  "        --new           Initialize FILE to an empty database",
 10989         -  "        --readonly      Open FILE readonly",
 10990         -  "        --zip           FILE is a ZIP archive",
 10991         -  ".output ?FILE?           Send output to FILE or stdout if FILE is omitted",
 10992         -  "     If FILE begins with '|' then open it as a pipe.",
 10993         -  ".print STRING...         Print literal STRING",
 10994         -  ".prompt MAIN CONTINUE    Replace the standard prompts",
 10995         -  ".quit                    Exit this program",
 10996         -  ".read FILE               Read input from FILE",
 10997         -  ".restore ?DB? FILE       Restore content of DB (default \"main\") from FILE",
 10998         -  ".save FILE               Write in-memory database into FILE",
 10999         -  ".scanstats on|off        Turn sqlite3_stmt_scanstatus() metrics on or off",
 11000         -  ".schema ?PATTERN?        Show the CREATE statements matching PATTERN",
 11001         -  "     Options:",
 11002         -  "         --indent            Try to pretty-print the schema",
 11003         -  ".selftest ?OPTIONS?      Run tests defined in the SELFTEST table",
 11004         -  "    Options:",
 11005         -  "       --init               Create a new SELFTEST table",
 11006         -  "       -v                   Verbose output",
 11007         -  ".separator COL ?ROW?     Change the column and row separators",
        10887  +  ".load FILE ?ENTRY?     Load an extension library\n"
        10888  +#endif
        10889  +  ".log FILE|off          Turn logging on or off.  FILE can be stderr/stdout\n"
        10890  +  ".mode MODE ?TABLE?     Set output mode where MODE is one of:\n"
        10891  +  "                         ascii    Columns/rows delimited by 0x1F and 0x1E\n"
        10892  +  "                         csv      Comma-separated values\n"
        10893  +  "                         column   Left-aligned columns.  (See .width)\n"
        10894  +  "                         html     HTML <table> code\n"
        10895  +  "                         insert   SQL insert statements for TABLE\n"
        10896  +  "                         line     One value per line\n"
        10897  +  "                         list     Values delimited by \"|\"\n"
        10898  +  "                         quote    Escape answers as for SQL\n"
        10899  +  "                         tabs     Tab-separated values\n"
        10900  +  "                         tcl      TCL list elements\n"
        10901  +  ".nullvalue STRING      Use STRING in place of NULL values\n"
        10902  +  ".once (-e|-x|FILE)     Output for the next SQL command only to FILE\n"
        10903  +  "                         or invoke system text editor (-e) or spreadsheet (-x)\n"
        10904  +  "                         on the output.\n"
        10905  +  ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE\n"
        10906  +  "                         The --new option starts with an empty file\n"
        10907  +  "                         Other options: --readonly --append --zip\n"
        10908  +  ".output ?FILE?         Send output to FILE or stdout\n"
        10909  +  ".print STRING...       Print literal STRING\n"
        10910  +  ".prompt MAIN CONTINUE  Replace the standard prompts\n"
        10911  +  ".quit                  Exit this program\n"
        10912  +  ".read FILENAME         Execute SQL in FILENAME\n"
        10913  +  ".restore ?DB? FILE     Restore content of DB (default \"main\") from FILE\n"
        10914  +  ".save FILE             Write in-memory database into FILE\n"
        10915  +  ".scanstats on|off      Turn sqlite3_stmt_scanstatus() metrics on or off\n"
        10916  +  ".schema ?PATTERN?      Show the CREATE statements matching PATTERN\n"
        10917  +  "                          Add --indent for pretty-printing\n"
        10918  +  ".selftest ?--init?     Run tests defined in the SELFTEST table\n"
        10919  +  ".separator COL ?ROW?   Change the column separator and optionally the row\n"
        10920  +  "                         separator for both the output mode and .import\n"
 11008  10921   #if defined(SQLITE_ENABLE_SESSION)
 11009         -  ".session ?NAME? CMD ...  Create or control sessions",
 11010         -  "   Subcommands:",
 11011         -  "     attach TABLE             Attach TABLE",
 11012         -  "     changeset FILE           Write a changeset into FILE",
 11013         -  "     close                    Close one session",
 11014         -  "     enable ?BOOLEAN?         Set or query the enable bit",
 11015         -  "     filter GLOB...           Reject tables matching GLOBs",
 11016         -  "     indirect ?BOOLEAN?       Mark or query the indirect status",
 11017         -  "     isempty                  Query whether the session is empty",
 11018         -  "     list                     List currently open session names",
 11019         -  "     open DB NAME             Open a new session on DB",
 11020         -  "     patchset FILE            Write a patchset into FILE",
 11021         -  "   If ?NAME? is omitted, the first defined session is used.",
        10922  +  ".session CMD ...       Create or control sessions\n"
 11022  10923   #endif
 11023         -  ".sha3sum ...             Compute a SHA3 hash of database content",
 11024         -  "    Options:",
 11025         -  "      --schema              Also hash the sqlite_master table",
 11026         -  "      --sha3-224            Use the sha3-224 algorithm",
 11027         -  "      --sha3-256            Use the sha3-256 algorithm.  This is the default.",
 11028         -  "      --sha3-384            Use the sha3-384 algorithm",
 11029         -  "      --sha3-512            Use the sha3-512 algorithm",
 11030         -  "    Any other argument is a LIKE pattern for tables to hash",
        10924  +  ".sha3sum ?OPTIONS...?  Compute a SHA3 hash of database content\n"
        10925  +#ifndef SQLITE_NOHAVE_SYSTEM
        10926  +  ".shell CMD ARGS...     Run CMD ARGS... in a system shell\n"
        10927  +#endif
        10928  +  ".show                  Show the current values for various settings\n"
        10929  +  ".stats ?on|off?        Show stats or turn stats on or off\n"
 11031  10930   #ifndef SQLITE_NOHAVE_SYSTEM
 11032         -  ".shell CMD ARGS...       Run CMD ARGS... in a system shell",
 11033         -#endif
 11034         -  ".show                    Show the current values for various settings",
 11035         -  ".stats ?on|off?          Show stats or turn stats on or off",
 11036         -#ifndef SQLITE_NOHAVE_SYSTEM
 11037         -  ".system CMD ARGS...      Run CMD ARGS... in a system shell",
 11038         -#endif
 11039         -  ".tables ?TABLE?          List names of tables matching LIKE pattern TABLE",
 11040         -  ".testcase NAME           Begin redirecting output to 'testcase-out.txt'",
 11041         -  ".timeout MS              Try opening locked tables for MS milliseconds",
 11042         -  ".timer on|off            Turn SQL timer on or off",
 11043         -  ".trace FILE|off          Output each SQL statement as it is run",
 11044         -  ".vfsinfo ?AUX?           Information about the top-level VFS",
 11045         -  ".vfslist                 List all available VFSes",
 11046         -  ".vfsname ?AUX?           Print the name of the VFS stack",
 11047         -  ".width NUM1 NUM2 ...     Set column widths for \"column\" mode",
 11048         -  "     Negative values right-justify",
 11049         -};
 11050         -
 11051         -/*
 11052         -** Output help text.
 11053         -**
 11054         -** zPattern describes the set of commands for which help text is provided.
 11055         -** If zPattern is NULL, then show all commands, but only give a one-line
 11056         -** description of each.
 11057         -**
 11058         -** Return the number of matches.
 11059         -*/
 11060         -static int showHelp(FILE *out, const char *zPattern){
 11061         -  int i = 0;
 11062         -  int j = 0;
 11063         -  int n = 0;
 11064         -  char *zPat;
 11065         -  if( zPattern==0
 11066         -   || zPattern[0]=='0'
 11067         -   || strcmp(zPattern,"-a")==0
 11068         -   || strcmp(zPattern,"-all")==0
 11069         -  ){
 11070         -    /* Show all commands, but only one line per command */
 11071         -    if( zPattern==0 ) zPattern = "";
 11072         -    for(i=0; i<ArraySize(azHelp); i++){
 11073         -      if( azHelp[i][0]=='.' || zPattern[0] ){
 11074         -        utf8_printf(out, "%s\n", azHelp[i]);
 11075         -        n++;
 11076         -      }
 11077         -    }
 11078         -  }else{
 11079         -    /* Look for commands that for which zPattern is an exact prefix */
 11080         -    zPat = sqlite3_mprintf(".%s*", zPattern);
 11081         -    for(i=0; i<ArraySize(azHelp); i++){
 11082         -      if( sqlite3_strglob(zPat, azHelp[i])==0 ){
 11083         -        utf8_printf(out, "%s\n", azHelp[i]);
 11084         -        j = i+1;
 11085         -        n++;
 11086         -      }
 11087         -    }
 11088         -    sqlite3_free(zPat);
 11089         -    if( n ){
 11090         -      if( n==1 ){
 11091         -        /* when zPattern is a prefix of exactly one command, then include the
 11092         -        ** details of that command, which should begin at offset j */
 11093         -        while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){
 11094         -          utf8_printf(out, "%s\n", azHelp[j]);
 11095         -          j++;
 11096         -        }
 11097         -      }
 11098         -      return n;
 11099         -    }
 11100         -    /* Look for commands that contain zPattern anywhere.  Show the complete
 11101         -    ** text of all commands that match. */
 11102         -    zPat = sqlite3_mprintf("%%%s%%", zPattern);
 11103         -    for(i=0; i<ArraySize(azHelp); i++){
 11104         -      if( azHelp[i][0]=='.' ) j = i;
 11105         -      if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
 11106         -        utf8_printf(out, "%s\n", azHelp[j]);
 11107         -        while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){
 11108         -          j++;
 11109         -          utf8_printf(out, "%s\n", azHelp[j]);
 11110         -        }
 11111         -        i = j;
 11112         -        n++;
 11113         -      }
 11114         -    }
 11115         -    sqlite3_free(zPat);
 11116         -  }
 11117         -  return n;
 11118         -}
        10931  +  ".system CMD ARGS...    Run CMD ARGS... in a system shell\n"
        10932  +#endif
        10933  +  ".tables ?TABLE?        List names of tables\n"
        10934  +  "                         If TABLE specified, only list tables matching\n"
        10935  +  "                         LIKE pattern TABLE.\n"
        10936  +  ".testcase NAME         Begin redirecting output to 'testcase-out.txt'\n"
        10937  +  ".timeout MS            Try opening locked tables for MS milliseconds\n"
        10938  +  ".timer on|off          Turn SQL timer on or off\n"
        10939  +  ".trace FILE|off        Output each SQL statement as it is run\n"
        10940  +  ".vfsinfo ?AUX?         Information about the top-level VFS\n"
        10941  +  ".vfslist               List all available VFSes\n"
        10942  +  ".vfsname ?AUX?         Print the name of the VFS stack\n"
        10943  +  ".width NUM1 NUM2 ...   Set column widths for \"column\" mode\n"
        10944  +  "                         Negative values right-justify\n"
        10945  +;
        10946  +
        10947  +#if defined(SQLITE_ENABLE_SESSION)
        10948  +/*
        10949  +** Print help information for the ".sessions" command
        10950  +*/
        10951  +void session_help(ShellState *p){
        10952  +  raw_printf(p->out,
        10953  +    ".session ?NAME? SUBCOMMAND ?ARGS...?\n"
        10954  +    "If ?NAME? is omitted, the first defined session is used.\n"
        10955  +    "Subcommands:\n"
        10956  +    "   attach TABLE             Attach TABLE\n"
        10957  +    "   changeset FILE           Write a changeset into FILE\n"
        10958  +    "   close                    Close one session\n"
        10959  +    "   enable ?BOOLEAN?         Set or query the enable bit\n"
        10960  +    "   filter GLOB...           Reject tables matching GLOBs\n"
        10961  +    "   indirect ?BOOLEAN?       Mark or query the indirect status\n"
        10962  +    "   isempty                  Query whether the session is empty\n"
        10963  +    "   list                     List currently open session names\n"
        10964  +    "   open DB NAME             Open a new session on DB\n"
        10965  +    "   patchset FILE            Write a patchset into FILE\n"
        10966  +  );
        10967  +}
        10968  +#endif
        10969  +
 11119  10970   
 11120  10971   /* Forward reference */
 11121  10972   static int process_input(ShellState *p, FILE *in);
 11122  10973   
 11123  10974   /*
 11124  10975   ** Read the content of file zName into memory obtained from sqlite3_malloc64()
 11125  10976   ** and return a pointer to the buffer. The caller is responsible for freeing
................................................................................
 11141  10992     size_t nRead;
 11142  10993     char *pBuf;
 11143  10994     if( in==0 ) return 0;
 11144  10995     fseek(in, 0, SEEK_END);
 11145  10996     nIn = ftell(in);
 11146  10997     rewind(in);
 11147  10998     pBuf = sqlite3_malloc64( nIn+1 );
 11148         -  if( pBuf==0 ){ fclose(in); return 0; }
        10999  +  if( pBuf==0 ) return 0;
 11149  11000     nRead = fread(pBuf, nIn, 1, in);
 11150  11001     fclose(in);
 11151  11002     if( nRead!=1 ){
 11152  11003       sqlite3_free(pBuf);
 11153  11004       return 0;
 11154  11005     }
 11155  11006     pBuf[nIn] = 0;
................................................................................
 11221  11072     if( f==0 ){
 11222  11073       if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
 11223  11074          return SHELL_OPEN_ZIPFILE;
 11224  11075       }else{
 11225  11076          return SHELL_OPEN_NORMAL;
 11226  11077       }
 11227  11078     }
 11228         -  n = fread(zBuf, 16, 1, f);
 11229         -  if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
 11230         -    fclose(f);
 11231         -    return SHELL_OPEN_NORMAL;
 11232         -  }
 11233  11079     fseek(f, -25, SEEK_END);
 11234  11080     n = fread(zBuf, 25, 1, f);
 11235  11081     if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
 11236  11082       rc = SHELL_OPEN_APPENDVFS;
 11237  11083     }else{
 11238  11084       fseek(f, -22, SEEK_END);
 11239  11085       n = fread(zBuf, 22, 1, f);
................................................................................
 11277  11123       }
 11278  11124       switch( p->openMode ){
 11279  11125         case SHELL_OPEN_APPENDVFS: {
 11280  11126           sqlite3_open_v2(p->zDbFilename, &p->db, 
 11281  11127              SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, "apndvfs");
 11282  11128           break;
 11283  11129         }
 11284         -      case SHELL_OPEN_DESERIALIZE: {
 11285         -        sqlite3_open(0, &p->db);
 11286         -        break;
 11287         -      }
 11288  11130         case SHELL_OPEN_ZIPFILE: {
 11289  11131           sqlite3_open(":memory:", &p->db);
 11290  11132           break;
 11291  11133         }
 11292  11134         case SHELL_OPEN_READONLY: {
 11293  11135           sqlite3_open_v2(p->zDbFilename, &p->db, SQLITE_OPEN_READONLY, 0);
 11294  11136           break;
................................................................................
 11330  11172   #endif
 11331  11173       if( p->openMode==SHELL_OPEN_ZIPFILE ){
 11332  11174         char *zSql = sqlite3_mprintf(
 11333  11175            "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", p->zDbFilename);
 11334  11176         sqlite3_exec(p->db, zSql, 0, 0, 0);
 11335  11177         sqlite3_free(zSql);
 11336  11178       }
 11337         -#ifdef SQLITE_ENABLE_DESERIALIZE
 11338         -    else if( p->openMode==SHELL_OPEN_DESERIALIZE ){
 11339         -      int nData = 0;
 11340         -      unsigned char *aData = (unsigned char*)readFile(p->zDbFilename, &nData);
 11341         -      int rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
 11342         -                   SQLITE_DESERIALIZE_RESIZEABLE |
 11343         -                   SQLITE_DESERIALIZE_FREEONCLOSE);
 11344         -      if( rc ){
 11345         -        utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc);
 11346         -      }
 11347         -    }
 11348         -#endif
 11349  11179     }
 11350  11180   }
 11351  11181   
 11352  11182   /*
 11353  11183   ** Attempt to close the databaes connection.  Report errors.
 11354  11184   */
 11355  11185   void close_db(sqlite3 *db){
................................................................................
 12546  12376   ){
 12547  12377     *ppStmt = 0;
 12548  12378     if( *pRc==SQLITE_OK ){
 12549  12379       va_list ap;
 12550  12380       char *z;
 12551  12381       va_start(ap, zFmt);
 12552  12382       z = sqlite3_vmprintf(zFmt, ap);
 12553         -    va_end(ap);
 12554  12383       if( z==0 ){
 12555  12384         *pRc = SQLITE_NOMEM;
 12556  12385       }else{
 12557  12386         shellPrepare(db, pRc, z, ppStmt);
 12558  12387         sqlite3_free(z);
 12559  12388       }
 12560  12389     }
................................................................................
 12609  12438     sqlite3 *db;                    /* Database containing the archive */
 12610  12439   };
 12611  12440   
 12612  12441   /*
 12613  12442   ** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
 12614  12443   */
 12615  12444   static int arUsage(FILE *f){
 12616         -  showHelp(f,"archive");
        12445  +  raw_printf(f,
        12446  +"\n"
        12447  +"Usage: .ar [OPTION...] [FILE...]\n"
        12448  +"The .ar command manages sqlar archives.\n"
        12449  +"\n"
        12450  +"Examples:\n"
        12451  +"  .ar -cf archive.sar foo bar    # Create archive.sar from files foo and bar\n"
        12452  +"  .ar -tf archive.sar            # List members of archive.sar\n"
        12453  +"  .ar -xvf archive.sar           # Verbosely extract files from archive.sar\n"
        12454  +"\n"
        12455  +"Each command line must feature exactly one command option:\n"
        12456  +"  -c, --create               Create a new archive\n"
        12457  +"  -u, --update               Update or add files to an existing archive\n"
        12458  +"  -t, --list                 List contents of archive\n"
        12459  +"  -x, --extract              Extract files from archive\n"
        12460  +"\n"
        12461  +"And zero or more optional options:\n"
        12462  +"  -v, --verbose              Print each filename as it is processed\n"
        12463  +"  -f FILE, --file FILE       Operate on archive FILE (default is current db)\n"
        12464  +"  -a FILE, --append FILE     Operate on FILE opened using the apndvfs VFS\n"
        12465  +"  -C DIR, --directory DIR    Change to directory DIR to read/extract files\n"
        12466  +"  -n, --dryrun               Show the SQL that would have occurred\n"
        12467  +"\n"
        12468  +"See also: http://sqlite.org/cli.html#sqlar_archive_support\n"
        12469  +"\n"
        12470  +);
 12617  12471     return SQLITE_ERROR;
 12618  12472   }
 12619  12473   
 12620  12474   /*
 12621  12475   ** Print an error message for the .ar command to stderr and return 
 12622  12476   ** SQLITE_ERROR.
 12623  12477   */
................................................................................
 12716  12570       { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
 12717  12571       { "dryrun",    'n', AR_SWITCH_DRYRUN,    0 },
 12718  12572     };
 12719  12573     int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
 12720  12574     struct ArSwitch *pEnd = &aSwitch[nSwitch];
 12721  12575   
 12722  12576     if( nArg<=1 ){
 12723         -    utf8_printf(stderr, "Wrong number of arguments.  Usage:\n");
 12724  12577       return arUsage(stderr);
 12725  12578     }else{
 12726  12579       char *z = azArg[1];
 12727  12580       if( z[0]!='-' ){
 12728  12581         /* Traditional style [tar] invocation */
 12729  12582         int i;
 12730  12583         int iArg = 2;
................................................................................
 13488  13341         utf8_printf(stderr,"Error: %s\n", zErrMsg);
 13489  13342         sqlite3_free(zErrMsg);
 13490  13343         rc = 1;
 13491  13344       }
 13492  13345     }else
 13493  13346   
 13494  13347     if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){
 13495         -    static const struct DbConfigChoices {
 13496         -      const char *zName;
 13497         -      int op;
 13498         -    } aDbConfig[] = {
        13348  +    static const struct DbConfigChoices {const char *zName; int op;} aDbConfig[] = {
 13499  13349           { "enable_fkey",      SQLITE_DBCONFIG_ENABLE_FKEY            },
 13500  13350           { "enable_trigger",   SQLITE_DBCONFIG_ENABLE_TRIGGER         },
 13501  13351           { "fts3_tokenizer",   SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER  },
 13502  13352           { "load_extension",   SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION  },
 13503  13353           { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE       },
 13504  13354           { "enable_qpsg",      SQLITE_DBCONFIG_ENABLE_QPSG            },
 13505  13355           { "trigger_eqp",      SQLITE_DBCONFIG_TRIGGER_EQP            },
 13506  13356           { "reset_database",   SQLITE_DBCONFIG_RESET_DATABASE         },
 13507         -        { "defensive",        SQLITE_DBCONFIG_DEFENSIVE              },
 13508  13357       };
 13509  13358       int ii, v;
 13510  13359       open_db(p, 0);
 13511  13360       for(ii=0; ii<ArraySize(aDbConfig); ii++){
 13512  13361         if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
 13513  13362         if( nArg>=3 ){
 13514  13363           sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
................................................................................
 13739  13588       }else{
 13740  13589         raw_printf(stderr, "Usage: .headers on|off\n");
 13741  13590         rc = 1;
 13742  13591       }
 13743  13592     }else
 13744  13593   
 13745  13594     if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
 13746         -    if( nArg>=2 ){
 13747         -      n = showHelp(p->out, azArg[1]);
 13748         -      if( n==0 ){
 13749         -        utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
 13750         -      }
 13751         -    }else{
 13752         -      showHelp(p->out, 0);
 13753         -    }
        13595  +    utf8_printf(p->out, "%s", zHelp);
 13754  13596     }else
 13755  13597   
 13756  13598     if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
 13757  13599       char *zTable;               /* Insert data into this table */
 13758  13600       char *zFile;                /* Name of file to extra content from */
 13759  13601       sqlite3_stmt *pStmt = NULL; /* A statement */
 13760  13602       int nCol;                   /* Number of columns in the table */
................................................................................
 14223  14065         }else if( optionMatch(z, "zip") ){
 14224  14066           p->openMode = SHELL_OPEN_ZIPFILE;
 14225  14067   #endif
 14226  14068         }else if( optionMatch(z, "append") ){
 14227  14069           p->openMode = SHELL_OPEN_APPENDVFS;
 14228  14070         }else if( optionMatch(z, "readonly") ){
 14229  14071           p->openMode = SHELL_OPEN_READONLY;
 14230         -#ifdef SQLITE_ENABLE_DESERIALIZE
 14231         -      }else if( optionMatch(z, "deserialize") ){
 14232         -        p->openMode = SHELL_OPEN_DESERIALIZE;
 14233         -#endif
 14234  14072         }else if( z[0]=='-' ){
 14235  14073           utf8_printf(stderr, "unknown option: %s\n", z);
 14236  14074           rc = 1;
 14237  14075           goto meta_command_exit;
 14238  14076         }
 14239  14077       }
 14240  14078       /* If a filename is specified, try to open it first */
................................................................................
 14754  14592         pSession->nFilter = 0;
 14755  14593         sqlite3session_table_filter(pSession->p, session_filter, pSession);
 14756  14594         p->nSession++;
 14757  14595         pSession->zName = sqlite3_mprintf("%s", zName);
 14758  14596       }else
 14759  14597       /* If no command name matches, show a syntax error */
 14760  14598       session_syntax_error:
 14761         -    showHelp(p->out, "session");
        14599  +    session_help(p);
 14762  14600     }else
 14763  14601   #endif
 14764  14602   
 14765  14603   #ifdef SQLITE_DEBUG
 14766  14604     /* Undocumented commands for internal testing.  Subject to change
 14767  14605     ** without notice. */
 14768  14606     if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
................................................................................
 15221  15059         { "always",             SQLITE_TESTCTRL_ALWAYS,        "BOOLEAN"            },
 15222  15060         { "assert",             SQLITE_TESTCTRL_ASSERT,        "BOOLEAN"            },
 15223  15061       /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, ""          },*/
 15224  15062       /*{ "bitvec_test",        SQLITE_TESTCTRL_BITVEC_TEST,   ""                },*/
 15225  15063         { "byteorder",          SQLITE_TESTCTRL_BYTEORDER,     ""                   },
 15226  15064       /*{ "fault_install",      SQLITE_TESTCTRL_FAULT_INSTALL, ""                }, */
 15227  15065         { "imposter",           SQLITE_TESTCTRL_IMPOSTER,   "SCHEMA ON/OFF ROOTPAGE"},
 15228         -      { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, "BOOLEAN"       },
 15229  15066         { "localtime_fault",    SQLITE_TESTCTRL_LOCALTIME_FAULT,"BOOLEAN"           },
 15230  15067         { "never_corrupt",      SQLITE_TESTCTRL_NEVER_CORRUPT, "BOOLEAN"            },
 15231  15068         { "optimizations",      SQLITE_TESTCTRL_OPTIMIZATIONS, "DISABLE-MASK"       },
 15232  15069   #ifdef YYCOVERAGE
 15233  15070         { "parser_coverage",    SQLITE_TESTCTRL_PARSER_COVERAGE, ""                 },
 15234  15071   #endif
 15235  15072         { "pending_byte",       SQLITE_TESTCTRL_PENDING_BYTE,  "OFFSET  "           },
................................................................................
 15316  15153               isOk = 3;
 15317  15154             }
 15318  15155             break;
 15319  15156   
 15320  15157           /* sqlite3_test_control(int, int) */
 15321  15158           case SQLITE_TESTCTRL_ASSERT:
 15322  15159           case SQLITE_TESTCTRL_ALWAYS:
 15323         -        case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
 15324  15160             if( nArg==3 ){
 15325  15161               int opt = booleanValue(azArg[2]);
 15326  15162               rc2 = sqlite3_test_control(testctrl, opt);
 15327  15163               isOk = 1;
 15328  15164             }
 15329  15165             break;
 15330  15166   
................................................................................
 15611  15447   /*
 15612  15448   ** We need a default sqlite3_complete() implementation to use in case
 15613  15449   ** the shell is compiled with SQLITE_OMIT_COMPLETE.  The default assumes
 15614  15450   ** any arbitrary text is a complete SQL statement.  This is not very
 15615  15451   ** user-friendly, but it does seem to work.
 15616  15452   */
 15617  15453   #ifdef SQLITE_OMIT_COMPLETE
 15618         -#define sqlite3_complete(x) 1
        15454  +int sqlite3_complete(const char *zSql){ return 1; }
 15619  15455   #endif
 15620  15456   
 15621  15457   /*
 15622  15458   ** Return true if zSql is a complete SQL statement.  Return false if it
 15623  15459   ** ends in the middle of a string literal or C-style comment.
 15624  15460   */
 15625  15461   static int line_is_complete(char *zSql, int nSql){
................................................................................
 16197  16033         zVfs = cmdline_option_value(argc, argv, ++i);
 16198  16034   #ifdef SQLITE_HAVE_ZLIB
 16199  16035       }else if( strcmp(z,"-zip")==0 ){
 16200  16036         data.openMode = SHELL_OPEN_ZIPFILE;
 16201  16037   #endif
 16202  16038       }else if( strcmp(z,"-append")==0 ){
 16203  16039         data.openMode = SHELL_OPEN_APPENDVFS;
 16204         -#ifdef SQLITE_ENABLE_DESERIALIZE
 16205         -    }else if( strcmp(z,"-deserialize")==0 ){
 16206         -      data.openMode = SHELL_OPEN_DESERIALIZE;
 16207         -#endif
 16208  16040       }else if( strcmp(z,"-readonly")==0 ){
 16209  16041         data.openMode = SHELL_OPEN_READONLY;
 16210  16042   #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
 16211  16043       }else if( strncmp(z, "-A",2)==0 ){
 16212  16044         /* All remaining command-line arguments are passed to the ".archive"
 16213  16045         ** command, so ignore them */
 16214  16046         break;
................................................................................
 16296  16128         memcpy(data.colSeparator,",",2);
 16297  16129   #ifdef SQLITE_HAVE_ZLIB
 16298  16130       }else if( strcmp(z,"-zip")==0 ){
 16299  16131         data.openMode = SHELL_OPEN_ZIPFILE;
 16300  16132   #endif
 16301  16133       }else if( strcmp(z,"-append")==0 ){
 16302  16134         data.openMode = SHELL_OPEN_APPENDVFS;
 16303         -#ifdef SQLITE_ENABLE_DESERIALIZE
 16304         -    }else if( strcmp(z,"-deserialize")==0 ){
 16305         -      data.openMode = SHELL_OPEN_DESERIALIZE;
 16306         -#endif
 16307  16135       }else if( strcmp(z,"-readonly")==0 ){
 16308  16136         data.openMode = SHELL_OPEN_READONLY;
 16309  16137       }else if( strcmp(z,"-ascii")==0 ){
 16310  16138         data.mode = MODE_Ascii;
 16311  16139         sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
 16312  16140                          SEP_Unit);
 16313  16141         sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
................................................................................
 16444  16272       }
 16445  16273       free(azCmd);
 16446  16274     }else{
 16447  16275       /* Run commands received from standard input
 16448  16276       */
 16449  16277       if( stdin_is_interactive ){
 16450  16278         char *zHome;
 16451         -      char *zHistory;
        16279  +      char *zHistory = 0;
 16452  16280         int nHistory;
 16453  16281         printf(
 16454  16282           "SQLite version %s %.19s\n" /*extra-version-info*/
 16455  16283           "Enter \".help\" for usage hints.\n",
 16456  16284           sqlite3_libversion(), sqlite3_sourceid()
 16457  16285         );
 16458  16286         if( warnInmemoryDb ){
 16459  16287           printf("Connected to a ");
 16460  16288           printBold("transient in-memory database");
 16461  16289           printf(".\nUse \".open FILENAME\" to reopen on a "
 16462  16290                  "persistent database.\n");
 16463  16291         }
 16464         -      zHistory = getenv("SQLITE_HISTORY");
 16465         -      if( zHistory ){
 16466         -        zHistory = strdup(zHistory);
 16467         -      }else if( (zHome = find_home_dir(0))!=0 ){
        16292  +      zHome = find_home_dir(0);
        16293  +      if( zHome ){
 16468  16294           nHistory = strlen30(zHome) + 20;
 16469  16295           if( (zHistory = malloc(nHistory))!=0 ){
 16470  16296             sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
 16471  16297           }
 16472  16298         }
 16473  16299         if( zHistory ){ shell_read_history(zHistory); }
 16474  16300   #if HAVE_READLINE || HAVE_EDITLINE

Changes to src/skins.c.

   457    457     const char *zCurrent = 0;  /* Current skin */
   458    458     int i;                     /* Loop counter */
   459    459     Stmt q;
   460    460     int seenCurrent = 0;
   461    461     int once;
   462    462   
   463    463     login_check_credentials();
   464         -  if( !g.perm.Admin ){
          464  +  if( !g.perm.Setup ){
   465    465       login_needed(0);
   466    466       return;
   467    467     }
   468    468     db_begin_transaction();
   469    469     zCurrent = getSkin(0);
   470    470     for(i=0; i<count(aBuiltinSkin); i++){
   471    471       aBuiltinSkin[i].zSQL = getSkin(aBuiltinSkin[i].zLabel);
................................................................................
   674    674   static const char *skin_file_content(const char *zLabel, const char *zFile){
   675    675     const char *zResult;
   676    676     if( fossil_strcmp(zLabel, "current")==0 ){
   677    677       zResult = db_get(zFile, "");
   678    678     }else if( sqlite3_strglob("draft[1-9]", zLabel)==0 ){
   679    679       zResult = db_get_mprintf("", "%s-%s", zLabel, zFile);
   680    680     }else{
   681         -    int i;
   682         -    for(i=0; i<2; i++){
          681  +    while( 1 ){
   683    682         char *zKey = mprintf("skins/%s/%s.txt", zLabel, zFile);
   684    683         zResult = builtin_text(zKey);
   685    684         fossil_free(zKey);
   686         -      if( zResult!=0 ) break;
   687         -      zLabel = "default";
          685  +      if( zResult!=0 || fossil_strcmp(zLabel,"default")==0 ) break;
   688    686       }
   689    687     }
   690    688     return zResult;
   691    689   }
   692    690   
   693    691   
   694    692   /*
   695    693   ** WEBPAGE: setup_skinedit
   696    694   **
   697    695   ** Edit aspects of a skin determined by the w= query parameter.
   698         -** Requires Admin or Setup privileges.
          696  +** Requires Setup privileges.
   699    697   **
   700    698   **    w=NUM     -- 0=CSS, 1=footer, 2=header, 3=details, 4=js
   701    699   **    sk=NUM    -- the draft skin number
   702    700   */
   703    701   void setup_skinedit(void){
   704    702     static const struct sSkinAddr {
   705    703       const char *zFile;
................................................................................
   728    726     login_check_credentials();
   729    727   
   730    728     /* Figure out which skin we are editing */
   731    729     iSkin = atoi(PD("sk","1"));
   732    730     if( iSkin<1 || iSkin>9 ) iSkin = 1;
   733    731   
   734    732     /* Check that the user is authorized to edit this skin. */
   735         -  if( !g.perm.Admin ){
          733  +  if( !g.perm.Setup ){
   736    734       char *zAllowedEditors = "";
   737    735       Glob *pAllowedEditors;
   738    736       int isMatch = 0;
   739    737       if( login_is_individual() ){
   740    738         zAllowedEditors = db_get_mprintf("", "draft%d-users", iSkin);
   741    739       }
   742    740       if( zAllowedEditors[0] ){
................................................................................
   901    899     */
   902    900     login_check_credentials();
   903    901     if( !login_is_individual() ){
   904    902       login_needed(0);
   905    903       return;
   906    904     }
   907    905     zAllowedEditors = db_get_mprintf("", "draft%d-users", iSkin);
   908         -  if( g.perm.Admin ){
          906  +  if( g.perm.Setup ){
   909    907       isSetup = isEditor = 1;
   910    908     }else{
   911    909       Glob *pAllowedEditors;
   912    910       isSetup = isEditor = 0;
   913    911       if( zAllowedEditors[0] ){
   914    912         pAllowedEditors = glob_create(zAllowedEditors);
   915    913         isEditor = glob_match(pAllowedEditors, g.zLogin);
................................................................................
  1055   1053     @ <p>Repeat <a href='#step4'>step 4</a> and
  1056   1054     @ <a href='#step5'>step 5</a> as many times as necessary to create
  1057   1055     @ a production-ready skin.
  1058   1056     @
  1059   1057     @ <a name='step7'></a>
  1060   1058     @ <h1>Step 7: Publish</h1>
  1061   1059     @
  1062         -  if( !g.perm.Admin ){
         1060  +  if( !g.perm.Setup ){
  1063   1061       @ <p>Only administrators are allowed to publish draft skins.  Contact
  1064   1062       @ an administrator to get this "draft%d(iSkin)" skin published.</p>
  1065   1063     }else{
  1066   1064       @ <p>When the draft%d(iSkin) skin is ready for production use,
  1067   1065       @ make it the default scan by clicking the acknowledgements and
  1068   1066       @ pressing the button below:</p>
  1069   1067       @
................................................................................
  1080   1078       @ <p>You will probably need to press Reload on your browser after
  1081   1079       @ publishing the new skin.</p>
  1082   1080     }
  1083   1081     @
  1084   1082     @ <a name='step8'></a>
  1085   1083     @ <h1>Step 8: Cleanup and Undo Actions</h1>
  1086   1084     @
  1087         -  if( !g.perm.Admin ){
         1085  +  if( !g.perm.Setup ){
  1088   1086       @ <p>Administrators can optionally save or restore legacy skins, and/or
  1089   1087       @ undo a prior publish.
  1090   1088     }else{
  1091   1089       @ <p>Visit the <a href='%R/setup_skin_admin'>Skin Admin</a> page
  1092   1090       @ for cleanup and recovery actions.
  1093   1091     }
  1094   1092     style_load_one_js_file("skin.js");
  1095   1093     style_footer();
  1096   1094   }

Changes to src/smtp.c.

    17     17   **
    18     18   ** Implementation of SMTP (Simple Mail Transport Protocol) according
    19     19   ** to RFC 5321.
    20     20   */
    21     21   #include "config.h"
    22     22   #include "smtp.h"
    23     23   #include <assert.h>
    24         -#if (HAVE_DN_EXPAND || HAVE___NS_NAME_UNCOMPRESS || HAVE_NS_NAME_UNCOMPRESS) && \
    25         -    (HAVE_NS_PARSERR || HAVE___NS_PARSERR) && !defined(FOSSIL_OMIT_DNS)
           24  +#if defined(__linux__) && !defined(FOSSIL_OMIT_DNS)
    26     25   #  include <sys/types.h>
    27     26   #  include <netinet/in.h>
    28         -#  if defined(HAVE_BIND_RESOLV_H)
    29         -#    include <bind/resolv.h>
    30         -#    include <bind/arpa/nameser_compat.h>
    31         -#  else
    32         -#    include <arpa/nameser.h>
    33         -#    include <resolv.h>
    34         -#  endif
    35         -#  if defined(HAVENS_NAME_UNCOMPRESS) && !defined(dn_expand)
    36         -#    define dn_expand ns_name_uncompress
    37         -#  endif
    38         -#  if defined(HAVE__NS_NAME_UNCOMPRESS) && !defined(dn_expand)
    39         -#    define dn_expand __ns_name_uncompress
    40         -#  endif
           27  +#  include <arpa/nameser.h>
           28  +#  include <resolv.h>
    41     29   #  define FOSSIL_UNIX_STYLE_DNS 1
    42     30   #endif
    43     31   #if defined(_WIN32) && !defined(__MINGW32__) && !defined(__MINGW64__)
    44     32   #  include <windows.h>
    45     33   #  include <windns.h>
    46     34   #  define FOSSIL_WINDOWS_STYLE_DNS 1
    47     35   #endif
................................................................................
    87     75         if( priority<iBestPriority ){
    88     76           pBest = p;
    89     77           iBestPriority = priority;
    90     78         }
    91     79       }
    92     80     }
    93     81     if( pBest ){
    94         -    dn_expand(aDns, aDns+nDns, pBest+2, zHostname, sizeof(zHostname));
           82  +    ns_name_uncompress(aDns, aDns+nDns, pBest+2,
           83  +                       zHostname, sizeof(zHostname));
    95     84       return fossil_strdup(zHostname);
    96     85     }
    97     86     return 0;
    98     87   #elif defined(FOSSIL_WINDOWS_STYLE_DNS)
    99     88     DNS_STATUS status;           /* Return status */
   100     89     PDNS_RECORDA pDnsRecord, p;  /* Pointer to DNS_RECORD structure */
   101     90     int iBestPriority = 9999999; /* Best priority */
................................................................................
  1308   1297     if( nErr ){
  1309   1298       fossil_print("Number of incorrect emailblob.enref values: %d\n",nErr);
  1310   1299     }
  1311   1300   }
  1312   1301   
  1313   1302   
  1314   1303   /*
  1315         -** COMMAND: smtpd*
         1304  +** COMMAND: smtpd
  1316   1305   **
  1317   1306   ** Usage: %fossil smtpd [OPTIONS] REPOSITORY
  1318   1307   **
  1319   1308   ** Begin a SMTP conversation with a client using stdin/stdout.  The
  1320   1309   ** received email is stored in REPOSITORY.
  1321   1310   **
  1322   1311   ** Options:
................................................................................
  1455   1444   ** found in the user table's info field, in angle brackets.
  1456   1445   */
  1457   1446   static int pop3_login(const char *zUser, char *zPass){
  1458   1447     return login_search_uid(&zUser, zPass) != 0;
  1459   1448   }
  1460   1449   
  1461   1450   /*
  1462         -** COMMAND: pop3d*
         1451  +** COMMAND: pop3d
  1463   1452   **
  1464   1453   ** Usage: %fossil pop3d [OPTIONS] REPOSITORY
  1465   1454   **
  1466   1455   ** Begin a POP3 conversation with a client using stdin/stdout using
  1467   1456   ** the mailboxes stored in REPOSITORY.
  1468   1457   **
  1469   1458   ** If launched as root, the process first enters a chroot jail using

Changes to src/sqlite3.c.

     1      1   /******************************************************************************
     2      2   ** This file is an amalgamation of many separate C source files from SQLite
     3         -** version 3.26.0.  By combining all the individual C code files into this
            3  +** version 3.25.1.  By combining all the individual C code files into this
     4      4   ** single large file, the entire code can be compiled as a single translation
     5      5   ** unit.  This allows many compilers to do optimizations that would not be
     6      6   ** possible if the files were compiled separately.  Performance improvements
     7      7   ** of 5% or more are commonly seen when SQLite is compiled as a single
     8      8   ** translation unit.
     9      9   **
    10     10   ** This file is all you need to compile SQLite.  To use SQLite in other
................................................................................
   256    256   #endif
   257    257   #if SQLITE_ENABLE_FTS4
   258    258     "ENABLE_FTS4",
   259    259   #endif
   260    260   #if SQLITE_ENABLE_FTS5
   261    261     "ENABLE_FTS5",
   262    262   #endif
   263         -#if SQLITE_ENABLE_GEOPOLY
   264         -  "ENABLE_GEOPOLY",
   265         -#endif
   266    263   #if SQLITE_ENABLE_HIDDEN_COLUMNS
   267    264     "ENABLE_HIDDEN_COLUMNS",
   268    265   #endif
   269    266   #if SQLITE_ENABLE_ICU
   270    267     "ENABLE_ICU",
   271    268   #endif
   272    269   #if SQLITE_ENABLE_IOTRACE
................................................................................
   289    286   #endif
   290    287   #if SQLITE_ENABLE_MEMSYS5
   291    288     "ENABLE_MEMSYS5",
   292    289   #endif
   293    290   #if SQLITE_ENABLE_MULTIPLEX
   294    291     "ENABLE_MULTIPLEX",
   295    292   #endif
   296         -#if SQLITE_ENABLE_NORMALIZE
   297         -  "ENABLE_NORMALIZE",
   298         -#endif
   299    293   #if SQLITE_ENABLE_NULL_TRIM
   300    294     "ENABLE_NULL_TRIM",
   301    295   #endif
   302    296   #if SQLITE_ENABLE_OVERSIZE_CELL_CHECK
   303    297     "ENABLE_OVERSIZE_CELL_CHECK",
   304    298   #endif
   305    299   #if SQLITE_ENABLE_PREUPDATE_HOOK
................................................................................
  1158   1152   ** been edited in any way since it was last checked in, then the last
  1159   1153   ** four hexadecimal digits of the hash may be modified.
  1160   1154   **
  1161   1155   ** See also: [sqlite3_libversion()],
  1162   1156   ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
  1163   1157   ** [sqlite_version()] and [sqlite_source_id()].
  1164   1158   */
  1165         -#define SQLITE_VERSION        "3.26.0"
  1166         -#define SQLITE_VERSION_NUMBER 3026000
  1167         -#define SQLITE_SOURCE_ID      "2018-12-01 12:34:55 bf8c1b2b7a5960c282e543b9c293686dccff272512d08865f4600fb58238b4f9"
         1159  +#define SQLITE_VERSION        "3.25.1"
         1160  +#define SQLITE_VERSION_NUMBER 3025001
         1161  +#define SQLITE_SOURCE_ID      "2018-09-18 20:20:44 2ac9003de44da7dafa3fbb1915ac5725a9275c86bf2f3b7aa19321bf1460b386"
  1168   1162   
  1169   1163   /*
  1170   1164   ** CAPI3REF: Run-Time Library Version Numbers
  1171   1165   ** KEYWORDS: sqlite3_version sqlite3_sourceid
  1172   1166   **
  1173   1167   ** These interfaces provide the same information as the [SQLITE_VERSION],
  1174   1168   ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
................................................................................
  3052   3046   ** Existing configuration options might be discontinued.  Applications
  3053   3047   ** should check the return code from [sqlite3_db_config()] to make sure that
  3054   3048   ** the call worked.  ^The [sqlite3_db_config()] interface will return a
  3055   3049   ** non-zero [error code] if a discontinued or unsupported configuration option
  3056   3050   ** is invoked.
  3057   3051   **
  3058   3052   ** <dl>
  3059         -** [[SQLITE_DBCONFIG_LOOKASIDE]]
  3060   3053   ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
  3061   3054   ** <dd> ^This option takes three additional arguments that determine the 
  3062   3055   ** [lookaside memory allocator] configuration for the [database connection].
  3063   3056   ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
  3064   3057   ** pointer to a memory buffer to use for lookaside memory.
  3065   3058   ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
  3066   3059   ** may be NULL in which case SQLite will allocate the
................................................................................
  3075   3068   ** connection is not currently using lookaside memory, or in other words
  3076   3069   ** when the "current value" returned by
  3077   3070   ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
  3078   3071   ** Any attempt to change the lookaside memory configuration when lookaside
  3079   3072   ** memory is in use leaves the configuration unchanged and returns 
  3080   3073   ** [SQLITE_BUSY].)^</dd>
  3081   3074   **
  3082         -** [[SQLITE_DBCONFIG_ENABLE_FKEY]]
  3083   3075   ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
  3084   3076   ** <dd> ^This option is used to enable or disable the enforcement of
  3085   3077   ** [foreign key constraints].  There should be two additional arguments.
  3086   3078   ** The first argument is an integer which is 0 to disable FK enforcement,
  3087   3079   ** positive to enable FK enforcement or negative to leave FK enforcement
  3088   3080   ** unchanged.  The second parameter is a pointer to an integer into which
  3089   3081   ** is written 0 or 1 to indicate whether FK enforcement is off or on
  3090   3082   ** following this call.  The second parameter may be a NULL pointer, in
  3091   3083   ** which case the FK enforcement setting is not reported back. </dd>
  3092   3084   **
  3093         -** [[SQLITE_DBCONFIG_ENABLE_TRIGGER]]
  3094   3085   ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
  3095   3086   ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
  3096   3087   ** There should be two additional arguments.
  3097   3088   ** The first argument is an integer which is 0 to disable triggers,
  3098   3089   ** positive to enable triggers or negative to leave the setting unchanged.
  3099   3090   ** The second parameter is a pointer to an integer into which
  3100   3091   ** is written 0 or 1 to indicate whether triggers are disabled or enabled
  3101   3092   ** following this call.  The second parameter may be a NULL pointer, in
  3102   3093   ** which case the trigger setting is not reported back. </dd>
  3103   3094   **
  3104         -** [[SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER]]
  3105   3095   ** <dt>SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER</dt>
  3106   3096   ** <dd> ^This option is used to enable or disable the two-argument
  3107   3097   ** version of the [fts3_tokenizer()] function which is part of the
  3108   3098   ** [FTS3] full-text search engine extension.
  3109   3099   ** There should be two additional arguments.
  3110   3100   ** The first argument is an integer which is 0 to disable fts3_tokenizer() or
  3111   3101   ** positive to enable fts3_tokenizer() or negative to leave the setting
  3112   3102   ** unchanged.
  3113   3103   ** The second parameter is a pointer to an integer into which
  3114   3104   ** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled
  3115   3105   ** following this call.  The second parameter may be a NULL pointer, in
  3116   3106   ** which case the new setting is not reported back. </dd>
  3117   3107   **
  3118         -** [[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION]]
  3119   3108   ** <dt>SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION</dt>
  3120   3109   ** <dd> ^This option is used to enable or disable the [sqlite3_load_extension()]
  3121   3110   ** interface independently of the [load_extension()] SQL function.
  3122   3111   ** The [sqlite3_enable_load_extension()] API enables or disables both the
  3123   3112   ** C-API [sqlite3_load_extension()] and the SQL function [load_extension()].
  3124   3113   ** There should be two additional arguments.
  3125   3114   ** When the first argument to this interface is 1, then only the C-API is
................................................................................
  3129   3118   ** C-API or the SQL function.
  3130   3119   ** The second parameter is a pointer to an integer into which
  3131   3120   ** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface
  3132   3121   ** is disabled or enabled following this call.  The second parameter may
  3133   3122   ** be a NULL pointer, in which case the new setting is not reported back.
  3134   3123   ** </dd>
  3135   3124   **
  3136         -** [[SQLITE_DBCONFIG_MAINDBNAME]] <dt>SQLITE_DBCONFIG_MAINDBNAME</dt>
         3125  +** <dt>SQLITE_DBCONFIG_MAINDBNAME</dt>
  3137   3126   ** <dd> ^This option is used to change the name of the "main" database
  3138   3127   ** schema.  ^The sole argument is a pointer to a constant UTF8 string
  3139   3128   ** which will become the new schema name in place of "main".  ^SQLite
  3140   3129   ** does not make a copy of the new main schema name string, so the application
  3141   3130   ** must ensure that the argument passed into this DBCONFIG option is unchanged
  3142   3131   ** until after the database connection closes.
  3143   3132   ** </dd>
  3144   3133   **
  3145         -** [[SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE]] 
  3146   3134   ** <dt>SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE</dt>
  3147   3135   ** <dd> Usually, when a database in wal mode is closed or detached from a 
  3148   3136   ** database handle, SQLite checks if this will mean that there are now no 
  3149   3137   ** connections at all to the database. If so, it performs a checkpoint 
  3150   3138   ** operation before closing the connection. This option may be used to
  3151   3139   ** override this behaviour. The first parameter passed to this operation
  3152   3140   ** is an integer - positive to disable checkpoints-on-close, or zero (the
  3153   3141   ** default) to enable them, and negative to leave the setting unchanged.
  3154   3142   ** The second parameter is a pointer to an integer
  3155   3143   ** into which is written 0 or 1 to indicate whether checkpoints-on-close
  3156   3144   ** have been disabled - 0 if they are not disabled, 1 if they are.
  3157   3145   ** </dd>
  3158   3146   **
  3159         -** [[SQLITE_DBCONFIG_ENABLE_QPSG]] <dt>SQLITE_DBCONFIG_ENABLE_QPSG</dt>
         3147  +** <dt>SQLITE_DBCONFIG_ENABLE_QPSG</dt>
  3160   3148   ** <dd>^(The SQLITE_DBCONFIG_ENABLE_QPSG option activates or deactivates
  3161   3149   ** the [query planner stability guarantee] (QPSG).  When the QPSG is active,
  3162   3150   ** a single SQL query statement will always use the same algorithm regardless
  3163   3151   ** of values of [bound parameters].)^ The QPSG disables some query optimizations
  3164   3152   ** that look at the values of bound parameters, which can make some queries
  3165   3153   ** slower.  But the QPSG has the advantage of more predictable behavior.  With
  3166   3154   ** the QPSG active, SQLite will always use the same query plan in the field as
................................................................................
  3168   3156   ** The first argument to this setting is an integer which is 0 to disable 
  3169   3157   ** the QPSG, positive to enable QPSG, or negative to leave the setting
  3170   3158   ** unchanged. The second parameter is a pointer to an integer into which
  3171   3159   ** is written 0 or 1 to indicate whether the QPSG is disabled or enabled
  3172   3160   ** following this call.
  3173   3161   ** </dd>
  3174   3162   **
  3175         -** [[SQLITE_DBCONFIG_TRIGGER_EQP]] <dt>SQLITE_DBCONFIG_TRIGGER_EQP</dt>
         3163  +** <dt>SQLITE_DBCONFIG_TRIGGER_EQP</dt>
  3176   3164   ** <dd> By default, the output of EXPLAIN QUERY PLAN commands does not 
  3177   3165   ** include output for any operations performed by trigger programs. This
  3178   3166   ** option is used to set or clear (the default) a flag that governs this
  3179   3167   ** behavior. The first parameter passed to this operation is an integer -
  3180   3168   ** positive to enable output for trigger programs, or zero to disable it,
  3181   3169   ** or negative to leave the setting unchanged.
  3182   3170   ** The second parameter is a pointer to an integer into which is written 
  3183   3171   ** 0 or 1 to indicate whether output-for-triggers has been disabled - 0 if 
  3184   3172   ** it is not disabled, 1 if it is.  
  3185   3173   ** </dd>
  3186   3174   **
  3187         -** [[SQLITE_DBCONFIG_RESET_DATABASE]] <dt>SQLITE_DBCONFIG_RESET_DATABASE</dt>
         3175  +** <dt>SQLITE_DBCONFIG_RESET_DATABASE</dt>
  3188   3176   ** <dd> Set the SQLITE_DBCONFIG_RESET_DATABASE flag and then run
  3189   3177   ** [VACUUM] in order to reset a database back to an empty database
  3190   3178   ** with no schema and no content. The following process works even for
  3191   3179   ** a badly corrupted database file:
  3192   3180   ** <ol>
  3193   3181   ** <li> If the database connection is newly opened, make sure it has read the
  3194   3182   **      database schema by preparing then discarding some query against the
................................................................................
  3199   3187   ** <li> sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0);
  3200   3188   ** <li> [sqlite3_exec](db, "[VACUUM]", 0, 0, 0);
  3201   3189   ** <li> sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0);
  3202   3190   ** </ol>
  3203   3191   ** Because resetting a database is destructive and irreversible, the
  3204   3192   ** process requires the use of this obscure API and multiple steps to help
  3205   3193   ** ensure that it does not happen by accident.
  3206         -**
  3207         -** [[SQLITE_DBCONFIG_DEFENSIVE]] <dt>SQLITE_DBCONFIG_DEFENSIVE</dt>
  3208         -** <dd>The SQLITE_DBCONFIG_DEFENSIVE option activates or deactivates the
  3209         -** "defensive" flag for a database connection.  When the defensive
  3210         -** flag is enabled, language features that allow ordinary SQL to 
  3211         -** deliberately corrupt the database file are disabled.  The disabled
  3212         -** features include but are not limited to the following:
  3213         -** <ul>
  3214         -** <li> The [PRAGMA writable_schema=ON] statement.
  3215         -** <li> Writes to the [sqlite_dbpage] virtual table.
  3216         -** <li> Direct writes to [shadow tables].
  3217         -** </ul>
  3218   3194   ** </dd>
  3219   3195   ** </dl>
  3220   3196   */
  3221   3197   #define SQLITE_DBCONFIG_MAINDBNAME            1000 /* const char* */
  3222   3198   #define SQLITE_DBCONFIG_LOOKASIDE             1001 /* void* int int */
  3223   3199   #define SQLITE_DBCONFIG_ENABLE_FKEY           1002 /* int int* */
  3224   3200   #define SQLITE_DBCONFIG_ENABLE_TRIGGER        1003 /* int int* */
  3225   3201   #define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */
  3226   3202   #define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */
  3227   3203   #define SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      1006 /* int int* */
  3228   3204   #define SQLITE_DBCONFIG_ENABLE_QPSG           1007 /* int int* */
  3229   3205   #define SQLITE_DBCONFIG_TRIGGER_EQP           1008 /* int int* */
  3230   3206   #define SQLITE_DBCONFIG_RESET_DATABASE        1009 /* int int* */
  3231         -#define SQLITE_DBCONFIG_DEFENSIVE             1010 /* int int* */
  3232         -#define SQLITE_DBCONFIG_MAX                   1010 /* Largest DBCONFIG */
         3207  +#define SQLITE_DBCONFIG_MAX                   1009 /* Largest DBCONFIG */
  3233   3208   
  3234   3209   /*
  3235   3210   ** CAPI3REF: Enable Or Disable Extended Result Codes
  3236   3211   ** METHOD: sqlite3
  3237   3212   **
  3238   3213   ** ^The sqlite3_extended_result_codes() routine enables or disables the
  3239   3214   ** [extended result codes] feature of SQLite. ^The extended result
................................................................................
  4663   4638   ** probably reused many times.)^ ^Without this flag, [sqlite3_prepare_v3()]
  4664   4639   ** and [sqlite3_prepare16_v3()] assume that the prepared statement will 
  4665   4640   ** be used just once or at most a few times and then destroyed using
  4666   4641   ** [sqlite3_finalize()] relatively soon. The current implementation acts
  4667   4642   ** on this hint by avoiding the use of [lookaside memory] so as not to
  4668   4643   ** deplete the limited store of lookaside memory. Future versions of
  4669   4644   ** SQLite may act on this hint differently.
  4670         -**
  4671         -** [[SQLITE_PREPARE_NORMALIZE]] ^(<dt>SQLITE_PREPARE_NORMALIZE</dt>
  4672         -** <dd>The SQLITE_PREPARE_NORMALIZE flag indicates that a normalized
  4673         -** representation of the SQL statement should be calculated and then
  4674         -** associated with the prepared statement, which can be obtained via
  4675         -** the [sqlite3_normalized_sql()] interface.)^  The semantics used to
  4676         -** normalize a SQL statement are unspecified and subject to change.
  4677         -** At a minimum, literal values will be replaced with suitable
  4678         -** placeholders.
  4679   4645   ** </dl>
  4680   4646   */
  4681   4647   #define SQLITE_PREPARE_PERSISTENT              0x01
  4682         -#define SQLITE_PREPARE_NORMALIZE               0x02
  4683   4648   
  4684   4649   /*
  4685   4650   ** CAPI3REF: Compiling An SQL Statement
  4686   4651   ** KEYWORDS: {SQL statement compiler}
  4687   4652   ** METHOD: sqlite3
  4688   4653   ** CONSTRUCTOR: sqlite3_stmt
  4689   4654   **
................................................................................
  4833   4798   ** ^The sqlite3_sql(P) interface returns a pointer to a copy of the UTF-8
  4834   4799   ** SQL text used to create [prepared statement] P if P was
  4835   4800   ** created by [sqlite3_prepare_v2()], [sqlite3_prepare_v3()],
  4836   4801   ** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()].
  4837   4802   ** ^The sqlite3_expanded_sql(P) interface returns a pointer to a UTF-8
  4838   4803   ** string containing the SQL text of prepared statement P with
  4839   4804   ** [bound parameters] expanded.
  4840         -** ^The sqlite3_normalized_sql(P) interface returns a pointer to a UTF-8
  4841         -** string containing the normalized SQL text of prepared statement P.  The
  4842         -** semantics used to normalize a SQL statement are unspecified and subject
  4843         -** to change.  At a minimum, literal values will be replaced with suitable
  4844         -** placeholders.
  4845   4805   **
  4846   4806   ** ^(For example, if a prepared statement is created using the SQL
  4847   4807   ** text "SELECT $abc,:xyz" and if parameter $abc is bound to integer 2345
  4848   4808   ** and parameter :xyz is unbound, then sqlite3_sql() will return
  4849   4809   ** the original string, "SELECT $abc,:xyz" but sqlite3_expanded_sql()
  4850   4810   ** will return "SELECT 2345,NULL".)^
  4851   4811   **
................................................................................
  4853   4813   ** is available to hold the result, or if the result would exceed the
  4854   4814   ** the maximum string length determined by the [SQLITE_LIMIT_LENGTH].
  4855   4815   **
  4856   4816   ** ^The [SQLITE_TRACE_SIZE_LIMIT] compile-time option limits the size of
  4857   4817   ** bound parameter expansions.  ^The [SQLITE_OMIT_TRACE] compile-time
  4858   4818   ** option causes sqlite3_expanded_sql() to always return NULL.
  4859   4819   **
  4860         -** ^The strings returned by sqlite3_sql(P) and sqlite3_normalized_sql(P)
  4861         -** are managed by SQLite and are automatically freed when the prepared
  4862         -** statement is finalized.
         4820  +** ^The string returned by sqlite3_sql(P) is managed by SQLite and is
         4821  +** automatically freed when the prepared statement is finalized.
  4863   4822   ** ^The string returned by sqlite3_expanded_sql(P), on the other hand,
  4864   4823   ** is obtained from [sqlite3_malloc()] and must be free by the application
  4865   4824   ** by passing it to [sqlite3_free()].
  4866   4825   */
  4867   4826   SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
  4868   4827   SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt);
  4869         -SQLITE_API const char *sqlite3_normalized_sql(sqlite3_stmt *pStmt);
  4870   4828   
  4871   4829   /*
  4872   4830   ** CAPI3REF: Determine If An SQL Statement Writes The Database
  4873   4831   ** METHOD: sqlite3_stmt
  4874   4832   **
  4875   4833   ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
  4876   4834   ** and only if the [prepared statement] X makes no direct changes to
................................................................................
  7352   7310                          void **ppArg);
  7353   7311     int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
  7354   7312     /* The methods above are in version 1 of the sqlite_module object. Those 
  7355   7313     ** below are for version 2 and greater. */
  7356   7314     int (*xSavepoint)(sqlite3_vtab *pVTab, int);
  7357   7315     int (*xRelease)(sqlite3_vtab *pVTab, int);
  7358   7316     int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
  7359         -  /* The methods above are in versions 1 and 2 of the sqlite_module object.
  7360         -  ** Those below are for version 3 and greater. */
  7361         -  int (*xShadowName)(const char*);
  7362   7317   };
  7363   7318   
  7364   7319   /*
  7365   7320   ** CAPI3REF: Virtual Table Indexing Information
  7366   7321   ** KEYWORDS: sqlite3_index_info
  7367   7322   **
  7368   7323   ** The sqlite3_index_info structure and its substructures is used as part
................................................................................
  8277   8232   #define SQLITE_TESTCTRL_PENDING_BYTE            11
  8278   8233   #define SQLITE_TESTCTRL_ASSERT                  12
  8279   8234   #define SQLITE_TESTCTRL_ALWAYS                  13
  8280   8235   #define SQLITE_TESTCTRL_RESERVE                 14
  8281   8236   #define SQLITE_TESTCTRL_OPTIMIZATIONS           15
  8282   8237   #define SQLITE_TESTCTRL_ISKEYWORD               16  /* NOT USED */
  8283   8238   #define SQLITE_TESTCTRL_SCRATCHMALLOC           17  /* NOT USED */
  8284         -#define SQLITE_TESTCTRL_INTERNAL_FUNCTIONS      17
  8285   8239   #define SQLITE_TESTCTRL_LOCALTIME_FAULT         18
  8286   8240   #define SQLITE_TESTCTRL_EXPLAIN_STMT            19  /* NOT USED */
  8287   8241   #define SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD    19
  8288   8242   #define SQLITE_TESTCTRL_NEVER_CORRUPT           20
  8289   8243   #define SQLITE_TESTCTRL_VDBE_COVERAGE           21
  8290   8244   #define SQLITE_TESTCTRL_BYTEORDER               22
  8291   8245   #define SQLITE_TESTCTRL_ISINIT                  23
................................................................................
  9690   9644   ** CAPI3REF: Virtual Table Configuration Options
  9691   9645   **
  9692   9646   ** These macros define the various options to the
  9693   9647   ** [sqlite3_vtab_config()] interface that [virtual table] implementations
  9694   9648   ** can use to customize and optimize their behavior.
  9695   9649   **
  9696   9650   ** <dl>
  9697         -** [[SQLITE_VTAB_CONSTRAINT_SUPPORT]]
  9698   9651   ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
  9699   9652   ** <dd>Calls of the form
  9700   9653   ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
  9701   9654   ** where X is an integer.  If X is zero, then the [virtual table] whose
  9702   9655   ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
  9703   9656   ** support constraints.  In this configuration (which is the default) if
  9704   9657   ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
................................................................................
 10460  10413     unsigned int *anQueue;            /* Number of pending entries in the queue */
 10461  10414     int nCoord;                       /* Number of coordinates */
 10462  10415     int iLevel;                       /* Level of current node or entry */
 10463  10416     int mxLevel;                      /* The largest iLevel value in the tree */
 10464  10417     sqlite3_int64 iRowid;             /* Rowid for current entry */
 10465  10418     sqlite3_rtree_dbl rParentScore;   /* Score of parent node */
 10466  10419     int eParentWithin;                /* Visibility of parent node */
 10467         -  int eWithin;                      /* OUT: Visibility */
        10420  +  int eWithin;                      /* OUT: Visiblity */
 10468  10421     sqlite3_rtree_dbl rScore;         /* OUT: Write the score here */
 10469  10422     /* The following fields are only available in 3.8.11 and later */
 10470  10423     sqlite3_value **apSqlParam;       /* Original SQL values of parameters */
 10471  10424   };
 10472  10425   
 10473  10426   /*
 10474  10427   ** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.
................................................................................
 10956  10909   ** [sqlite3changeset_invert()] functions, all changes within the changeset 
 10957  10910   ** that apply to a single table are grouped together. This means that when 
 10958  10911   ** an application iterates through a changeset using an iterator created by 
 10959  10912   ** this function, all changes that relate to a single table are visited 
 10960  10913   ** consecutively. There is no chance that the iterator will visit a change 
 10961  10914   ** the applies to table X, then one for table Y, and then later on visit 
 10962  10915   ** another change for table X.
 10963         -**
 10964         -** The behavior of sqlite3changeset_start_v2() and its streaming equivalent
 10965         -** may be modified by passing a combination of
 10966         -** [SQLITE_CHANGESETSTART_INVERT | supported flags] as the 4th parameter.
 10967         -**
 10968         -** Note that the sqlite3changeset_start_v2() API is still <b>experimental</b>
 10969         -** and therefore subject to change.
 10970  10916   */
 10971  10917   SQLITE_API int sqlite3changeset_start(
 10972  10918     sqlite3_changeset_iter **pp,    /* OUT: New changeset iterator handle */
 10973  10919     int nChangeset,                 /* Size of changeset blob in bytes */
 10974  10920     void *pChangeset                /* Pointer to blob containing changeset */
 10975  10921   );
 10976         -SQLITE_API int sqlite3changeset_start_v2(
 10977         -  sqlite3_changeset_iter **pp,    /* OUT: New changeset iterator handle */
 10978         -  int nChangeset,                 /* Size of changeset blob in bytes */
 10979         -  void *pChangeset,               /* Pointer to blob containing changeset */
 10980         -  int flags                       /* SESSION_CHANGESETSTART_* flags */
 10981         -);
 10982         -
 10983         -/*
 10984         -** CAPI3REF: Flags for sqlite3changeset_start_v2
 10985         -**
 10986         -** The following flags may passed via the 4th parameter to
 10987         -** [sqlite3changeset_start_v2] and [sqlite3changeset_start_v2_strm]:
 10988         -**
 10989         -** <dt>SQLITE_CHANGESETAPPLY_INVERT <dd>
 10990         -**   Invert the changeset while iterating through it. This is equivalent to
 10991         -**   inverting a changeset using sqlite3changeset_invert() before applying it.
 10992         -**   It is an error to specify this flag with a patchset.
 10993         -*/
 10994         -#define SQLITE_CHANGESETSTART_INVERT        0x0002
 10995  10922   
 10996  10923   
 10997  10924   /*
 10998  10925   ** CAPI3REF: Advance A Changeset Iterator
 10999  10926   ** METHOD: sqlite3_changeset_iter
 11000  10927   **
 11001  10928   ** This function may only be used with iterators created by function
................................................................................
 11642  11569     int(*xConflict)(
 11643  11570       void *pCtx,                   /* Copy of sixth arg to _apply() */
 11644  11571       int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
 11645  11572       sqlite3_changeset_iter *p     /* Handle describing change and conflict */
 11646  11573     ),
 11647  11574     void *pCtx,                     /* First argument passed to xConflict */
 11648  11575     void **ppRebase, int *pnRebase, /* OUT: Rebase data */
 11649         -  int flags                       /* SESSION_CHANGESETAPPLY_* flags */
        11576  +  int flags                       /* Combination of SESSION_APPLY_* flags */
 11650  11577   );
 11651  11578   
 11652  11579   /*
 11653  11580   ** CAPI3REF: Flags for sqlite3changeset_apply_v2
 11654  11581   **
 11655  11582   ** The following flags may passed via the 9th parameter to
 11656  11583   ** [sqlite3changeset_apply_v2] and [sqlite3changeset_apply_v2_strm]:
................................................................................
 11660  11587   **   Usually, the sessions module encloses all operations performed by
 11661  11588   **   a single call to apply_v2() or apply_v2_strm() in a [SAVEPOINT]. The
 11662  11589   **   SAVEPOINT is committed if the changeset or patchset is successfully
 11663  11590   **   applied, or rolled back if an error occurs. Specifying this flag
 11664  11591   **   causes the sessions module to omit this savepoint. In this case, if the
 11665  11592   **   caller has an open transaction or savepoint when apply_v2() is called, 
 11666  11593   **   it may revert the partially applied changeset by rolling it back.
 11667         -**
 11668         -** <dt>SQLITE_CHANGESETAPPLY_INVERT <dd>
 11669         -**   Invert the changeset before applying it. This is equivalent to inverting
 11670         -**   a changeset using sqlite3changeset_invert() before applying it. It is
 11671         -**   an error to specify this flag with a patchset.
 11672  11594   */
 11673  11595   #define SQLITE_CHANGESETAPPLY_NOSAVEPOINT   0x0001
 11674         -#define SQLITE_CHANGESETAPPLY_INVERT        0x0002
 11675  11596   
 11676  11597   /* 
 11677  11598   ** CAPI3REF: Constants Passed To The Conflict Handler
 11678  11599   **
 11679  11600   ** Values that may be passed as the second argument to a conflict-handler.
 11680  11601   **
 11681  11602   ** <dl>
................................................................................
 12061  11982     void *pOut
 12062  11983   );
 12063  11984   SQLITE_API int sqlite3changeset_start_strm(
 12064  11985     sqlite3_changeset_iter **pp,
 12065  11986     int (*xInput)(void *pIn, void *pData, int *pnData),
 12066  11987     void *pIn
 12067  11988   );
 12068         -SQLITE_API int sqlite3changeset_start_v2_strm(
 12069         -  sqlite3_changeset_iter **pp,
 12070         -  int (*xInput)(void *pIn, void *pData, int *pnData),
 12071         -  void *pIn,
 12072         -  int flags
 12073         -);
 12074  11989   SQLITE_API int sqlite3session_changeset_strm(
 12075  11990     sqlite3_session *pSession,
 12076  11991     int (*xOutput)(void *pOut, const void *pData, int nData),
 12077  11992     void *pOut
 12078  11993   );
 12079  11994   SQLITE_API int sqlite3session_patchset_strm(
 12080  11995     sqlite3_session *pSession,
................................................................................
 12093  12008     sqlite3_rebaser *pRebaser,
 12094  12009     int (*xInput)(void *pIn, void *pData, int *pnData),
 12095  12010     void *pIn,
 12096  12011     int (*xOutput)(void *pOut, const void *pData, int nData),
 12097  12012     void *pOut
 12098  12013   );
 12099  12014   
 12100         -/*
 12101         -** CAPI3REF: Configure global parameters
 12102         -**
 12103         -** The sqlite3session_config() interface is used to make global configuration
 12104         -** changes to the sessions module in order to tune it to the specific needs 
 12105         -** of the application.
 12106         -**
 12107         -** The sqlite3session_config() interface is not threadsafe. If it is invoked
 12108         -** while any other thread is inside any other sessions method then the
 12109         -** results are undefined. Furthermore, if it is invoked after any sessions
 12110         -** related objects have been created, the results are also undefined. 
 12111         -**
 12112         -** The first argument to the sqlite3session_config() function must be one
 12113         -** of the SQLITE_SESSION_CONFIG_XXX constants defined below. The 
 12114         -** interpretation of the (void*) value passed as the second parameter and
 12115         -** the effect of calling this function depends on the value of the first
 12116         -** parameter.
 12117         -**
 12118         -** <dl>
 12119         -** <dt>SQLITE_SESSION_CONFIG_STRMSIZE<dd>
 12120         -**    By default, the sessions module streaming interfaces attempt to input
 12121         -**    and output data in approximately 1 KiB chunks. This operand may be used
 12122         -**    to set and query the value of this configuration setting. The pointer
 12123         -**    passed as the second argument must point to a value of type (int).
 12124         -**    If this value is greater than 0, it is used as the new streaming data
 12125         -**    chunk size for both input and output. Before returning, the (int) value
 12126         -**    pointed to by pArg is set to the final value of the streaming interface
 12127         -**    chunk size.
 12128         -** </dl>
 12129         -**
 12130         -** This function returns SQLITE_OK if successful, or an SQLite error code
 12131         -** otherwise.
 12132         -*/
 12133         -SQLITE_API int sqlite3session_config(int op, void *pArg);
 12134         -
 12135         -/*
 12136         -** CAPI3REF: Values for sqlite3session_config().
 12137         -*/
 12138         -#define SQLITE_SESSION_CONFIG_STRMSIZE 1
 12139  12015   
 12140  12016   /*
 12141  12017   ** Make sure we can call this stuff from C++.
 12142  12018   */
 12143  12019   #if 0
 12144  12020   }
 12145  12021   #endif
................................................................................
 15397  15273   
 15398  15274   #ifndef SQLITE_OMIT_WAL
 15399  15275   SQLITE_PRIVATE   int sqlite3PagerCheckpoint(Pager *pPager, sqlite3*, int, int*, int*);
 15400  15276   SQLITE_PRIVATE   int sqlite3PagerWalSupported(Pager *pPager);
 15401  15277   SQLITE_PRIVATE   int sqlite3PagerWalCallback(Pager *pPager);
 15402  15278   SQLITE_PRIVATE   int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
 15403  15279   SQLITE_PRIVATE   int sqlite3PagerCloseWal(Pager *pPager, sqlite3*);
        15280  +# ifdef SQLITE_DIRECT_OVERFLOW_READ
        15281  +SQLITE_PRIVATE   int sqlite3PagerUseWal(Pager *pPager, Pgno);
        15282  +# endif
 15404  15283   # ifdef SQLITE_ENABLE_SNAPSHOT
 15405  15284   SQLITE_PRIVATE   int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot);
 15406  15285   SQLITE_PRIVATE   int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot);
 15407  15286   SQLITE_PRIVATE   int sqlite3PagerSnapshotRecover(Pager *pPager);
 15408  15287   SQLITE_PRIVATE   int sqlite3PagerSnapshotCheck(Pager *pPager, sqlite3_snapshot *pSnapshot);
 15409  15288   SQLITE_PRIVATE   void sqlite3PagerSnapshotUnlock(Pager *pPager);
 15410  15289   # endif
 15411         -#endif
 15412         -
 15413         -#ifdef SQLITE_DIRECT_OVERFLOW_READ
 15414         -SQLITE_PRIVATE   int sqlite3PagerDirectReadOk(Pager *pPager, Pgno pgno);
        15290  +#else
        15291  +# define sqlite3PagerUseWal(x,y) 0
 15415  15292   #endif
 15416  15293   
 15417  15294   #ifdef SQLITE_ENABLE_ZIPVFS
 15418  15295   SQLITE_PRIVATE   int sqlite3PagerWalFramesize(Pager *pPager);
 15419  15296   #endif
 15420  15297   
 15421  15298   /* Functions used to query pager state and configuration. */
................................................................................
 15652  15529   /* Return the header size */
 15653  15530   SQLITE_PRIVATE int sqlite3HeaderSizePcache(void);
 15654  15531   SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void);
 15655  15532   
 15656  15533   /* Number of dirty pages as a percentage of the configured cache size */
 15657  15534   SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache*);
 15658  15535   
 15659         -#ifdef SQLITE_DIRECT_OVERFLOW_READ
 15660         -SQLITE_PRIVATE int sqlite3PCacheIsDirty(PCache *pCache);
 15661         -#endif
 15662         -
 15663  15536   #endif /* _PCACHE_H_ */
 15664  15537   
 15665  15538   /************** End of pcache.h **********************************************/
 15666  15539   /************** Continuing where we left off in sqliteInt.h ******************/
 15667  15540   /************** Include os.h in the middle of sqliteInt.h ********************/
 15668  15541   /************** Begin file os.h **********************************************/
 15669  15542   /*
................................................................................
 16161  16034   };
 16162  16035   
 16163  16036   /*
 16164  16037   ** A hash table for built-in function definitions.  (Application-defined
 16165  16038   ** functions use a regular table table from hash.h.)
 16166  16039   **
 16167  16040   ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
 16168         -** Collisions are on the FuncDef.u.pHash chain.  Use the SQLITE_FUNC_HASH()
 16169         -** macro to compute a hash on the function name.
        16041  +** Collisions are on the FuncDef.u.pHash chain.
 16170  16042   */
 16171  16043   #define SQLITE_FUNC_HASH_SZ 23
 16172  16044   struct FuncDefHash {
 16173  16045     FuncDef *a[SQLITE_FUNC_HASH_SZ];       /* Hash table for functions */
 16174  16046   };
 16175         -#define SQLITE_FUNC_HASH(C,L) (((C)+(L))%SQLITE_FUNC_HASH_SZ)
 16176  16047   
 16177  16048   #ifdef SQLITE_USER_AUTHENTICATION
 16178  16049   /*
 16179  16050   ** Information held in the "sqlite3" database connection object and used
 16180  16051   ** to manage user authentication.
 16181  16052   */
 16182  16053   typedef struct sqlite3_userauth sqlite3_userauth;
................................................................................
 16229  16100     sqlite3_vfs *pVfs;            /* OS Interface */
 16230  16101     struct Vdbe *pVdbe;           /* List of active virtual machines */
 16231  16102     CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
 16232  16103     sqlite3_mutex *mutex;         /* Connection mutex */
 16233  16104     Db *aDb;                      /* All backends */
 16234  16105     int nDb;                      /* Number of backends currently in use */
 16235  16106     u32 mDbFlags;                 /* flags recording internal state */
 16236         -  u64 flags;                    /* flags settable by pragmas. See below */
        16107  +  u32 flags;                    /* flags settable by pragmas. See below */
 16237  16108     i64 lastRowid;                /* ROWID of most recent insert (see above) */
 16238  16109     i64 szMmap;                   /* Default mmap_size setting */
 16239  16110     u32 nSchemaLock;              /* Do not reset the schema when non-zero */
 16240  16111     unsigned int openFlags;       /* Flags passed to sqlite3_vfs.xOpen() */
 16241  16112     int errCode;                  /* Most recent error code (SQLITE_*) */
 16242  16113     int errMask;                  /* & result codes with this before returning */
 16243  16114     int iSysErrno;                /* Errno value from last system error */
................................................................................
 16394  16265   #define SQLITE_DeferFKs       0x00080000  /* Defer all FK constraints */
 16395  16266   #define SQLITE_QueryOnly      0x00100000  /* Disable database changes */
 16396  16267   #define SQLITE_CellSizeCk     0x00200000  /* Check btree cell sizes on load */
 16397  16268   #define SQLITE_Fts3Tokenizer  0x00400000  /* Enable fts3_tokenizer(2) */
 16398  16269   #define SQLITE_EnableQPSG     0x00800000  /* Query Planner Stability Guarantee*/
 16399  16270   #define SQLITE_TriggerEQP     0x01000000  /* Show trigger EXPLAIN QUERY PLAN */
 16400  16271   #define SQLITE_ResetDatabase  0x02000000  /* Reset the database */
 16401         -#define SQLITE_LegacyAlter    0x04000000  /* Legacy ALTER TABLE behaviour */
 16402         -#define SQLITE_NoSchemaError  0x08000000  /* Do not report schema parse errors*/
 16403         -#define SQLITE_Defensive      0x10000000  /* Input SQL is likely hostile */
 16404  16272   
 16405  16273   /* Flags used only if debugging */
 16406         -#define HI(X)  ((u64)(X)<<32)
 16407  16274   #ifdef SQLITE_DEBUG
 16408         -#define SQLITE_SqlTrace       HI(0x0001)  /* Debug print SQL as it executes */
 16409         -#define SQLITE_VdbeListing    HI(0x0002)  /* Debug listings of VDBE progs */
 16410         -#define SQLITE_VdbeTrace      HI(0x0004)  /* True to trace VDBE execution */
 16411         -#define SQLITE_VdbeAddopTrace HI(0x0008)  /* Trace sqlite3VdbeAddOp() calls */
 16412         -#define SQLITE_VdbeEQP        HI(0x0010)  /* Debug EXPLAIN QUERY PLAN */
        16275  +#define SQLITE_SqlTrace       0x08000000  /* Debug print SQL as it executes */
        16276  +#define SQLITE_VdbeListing    0x10000000  /* Debug listings of VDBE programs */
        16277  +#define SQLITE_VdbeTrace      0x20000000  /* True to trace VDBE execution */
        16278  +#define SQLITE_VdbeAddopTrace 0x40000000  /* Trace sqlite3VdbeAddOp() calls */
        16279  +#define SQLITE_VdbeEQP        0x80000000  /* Debug EXPLAIN QUERY PLAN */
 16413  16280   #endif
 16414  16281   
 16415  16282   /*
 16416  16283   ** Allowed values for sqlite3.mDbFlags
 16417  16284   */
 16418  16285   #define DBFLAG_SchemaChange   0x0001  /* Uncommitted Hash table changes */
 16419  16286   #define DBFLAG_PreferBuiltin  0x0002  /* Preference to built-in funcs */
................................................................................
 16539  16406   #define SQLITE_FUNC_UNLIKELY 0x0400 /* Built-in unlikely() function */
 16540  16407   #define SQLITE_FUNC_CONSTANT 0x0800 /* Constant inputs give a constant output */
 16541  16408   #define SQLITE_FUNC_MINMAX   0x1000 /* True for min() and max() aggregates */
 16542  16409   #define SQLITE_FUNC_SLOCHNG  0x2000 /* "Slow Change". Value constant during a
 16543  16410                                       ** single query - might change over time */
 16544  16411   #define SQLITE_FUNC_AFFINITY 0x4000 /* Built-in affinity() function */
 16545  16412   #define SQLITE_FUNC_OFFSET   0x8000 /* Built-in sqlite_offset() function */
 16546         -#define SQLITE_FUNC_WINDOW   0x00010000 /* Built-in window-only function */
 16547         -#define SQLITE_FUNC_WINDOW_SIZE 0x20000 /* Requires partition size as arg. */
 16548         -#define SQLITE_FUNC_INTERNAL 0x00040000 /* For use by NestedParse() only */
        16413  +#define SQLITE_FUNC_WINDOW  0x10000 /* Built-in window-only function */
        16414  +#define SQLITE_FUNC_WINDOW_SIZE  0x20000  /* Requires partition size as arg. */
 16549  16415   
 16550  16416   /*
 16551  16417   ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
 16552  16418   ** used to create the initializers for the FuncDef structures.
 16553  16419   **
 16554  16420   **   FUNCTION(zName, nArg, iArg, bNC, xFunc)
 16555  16421   **     Used to create a scalar function definition of a function zName
................................................................................
 16617  16483      (void *)arg, 0, likeFunc, 0, 0, 0, #zName, {0} }
 16618  16484   #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal, xValue) \
 16619  16485     {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
 16620  16486      SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,xValue,0,#zName, {0}}
 16621  16487   #define AGGREGATE2(zName, nArg, arg, nc, xStep, xFinal, extraFlags) \
 16622  16488     {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
 16623  16489      SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,xFinal,0,#zName, {0}}
        16490  +
 16624  16491   #define WAGGREGATE(zName, nArg, arg, nc, xStep, xFinal, xValue, xInverse, f) \
 16625  16492     {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|f, \
 16626  16493      SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,xValue,xInverse,#zName, {0}}
 16627         -#define INTERNAL_FUNCTION(zName, nArg, xFunc) \
 16628         -  {nArg, SQLITE_FUNC_INTERNAL|SQLITE_UTF8|SQLITE_FUNC_CONSTANT, \
 16629         -   0, 0, xFunc, 0, 0, 0, #zName, {0} }
 16630         -
 16631  16494   
 16632  16495   /*
 16633  16496   ** All current savepoints are stored in a linked list starting at
 16634  16497   ** sqlite3.pSavepoint. The first element in the list is the most recently
 16635  16498   ** opened savepoint. Savepoints are added to the list by the vdbe
 16636  16499   ** OP_Savepoint instruction.
 16637  16500   */
................................................................................
 16808  16671   /*
 16809  16672   ** The schema for each SQL table and view is represented in memory
 16810  16673   ** by an instance of the following structure.
 16811  16674   */
 16812  16675   struct Table {
 16813  16676     char *zName;         /* Name of the table or view */
 16814  16677     Column *aCol;        /* Information about each column */
 16815         -#ifdef SQLITE_ENABLE_NORMALIZE
 16816         -  Hash *pColHash;      /* All columns indexed by name */
 16817         -#endif
 16818  16678     Index *pIndex;       /* List of SQL indexes on this table. */
 16819  16679     Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
 16820  16680     FKey *pFKey;         /* Linked list of all foreign keys in this table */
 16821  16681     char *zColAff;       /* String defining the affinity of each column */
 16822  16682     ExprList *pCheck;    /* All CHECK constraints */
 16823  16683                          /*   ... also used as column name list in a VIEW */
 16824  16684     int tnum;            /* Root BTree page for this table */
................................................................................
 16861  16721   #define TF_HasStat1        0x0010    /* nRowLogEst set from sqlite_stat1 */
 16862  16722   #define TF_WithoutRowid    0x0020    /* No rowid.  PRIMARY KEY is the key */
 16863  16723   #define TF_NoVisibleRowid  0x0040    /* No user-visible "rowid" column */
 16864  16724   #define TF_OOOHidden       0x0080    /* Out-of-Order hidden columns */
 16865  16725   #define TF_StatsUsed       0x0100    /* Query planner decisions affected by
 16866  16726                                        ** Index.aiRowLogEst[] values */
 16867  16727   #define TF_HasNotNull      0x0200    /* Contains NOT NULL constraints */
 16868         -#define TF_Shadow          0x0400    /* True for a shadow table */
 16869  16728   
 16870  16729   /*
 16871  16730   ** Test to see whether or not a table is a virtual table.  This is
 16872  16731   ** done as a macro so that it will be optimized out when virtual
 16873  16732   ** table support is omitted from the build.
 16874  16733   */
 16875  16734   #ifndef SQLITE_OMIT_VIRTUALTABLE
................................................................................
 17148  17007     void *p;          /* Pointer to sampled record */
 17149  17008     int n;            /* Size of record in bytes */
 17150  17009     tRowcnt *anEq;    /* Est. number of rows where the key equals this sample */
 17151  17010     tRowcnt *anLt;    /* Est. number of rows where key is less than this sample */
 17152  17011     tRowcnt *anDLt;   /* Est. number of distinct keys less than this sample */
 17153  17012   };
 17154  17013   
 17155         -/*
 17156         -** Possible values to use within the flags argument to sqlite3GetToken().
 17157         -*/
 17158         -#define SQLITE_TOKEN_QUOTED    0x1 /* Token is a quoted identifier. */
 17159         -#define SQLITE_TOKEN_KEYWORD   0x2 /* Token is a keyword. */
 17160         -
 17161  17014   /*
 17162  17015   ** Each token coming out of the lexer is an instance of
 17163  17016   ** this structure.  Tokens are also used as part of an expression.
 17164  17017   **
 17165  17018   ** The memory that "z" points to is owned by other objects.  Take care
 17166  17019   ** that the owner of the "z" string does not deallocate the string before
 17167  17020   ** the Token goes out of scope!  Very often, the "z" points to some place
................................................................................
 17335  17188                            ** TK_SELECT_COLUMN: column of the result vector */
 17336  17189     i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
 17337  17190     i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
 17338  17191     u8 op2;                /* TK_REGISTER: original value of Expr.op
 17339  17192                            ** TK_COLUMN: the value of p5 for OP_Column
 17340  17193                            ** TK_AGG_FUNCTION: nesting depth */
 17341  17194     AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
 17342         -  union {
 17343         -    Table *pTab;           /* TK_COLUMN: Table containing column. Can be NULL
 17344         -                           ** for a column of an index on an expression */
 17345         -    Window *pWin;          /* TK_FUNCTION: Window definition for the func */
 17346         -  } y;
        17195  +  Table *pTab;           /* Table for TK_COLUMN expressions.  Can be NULL
        17196  +                         ** for a column of an index on an expression */
        17197  +#ifndef SQLITE_OMIT_WINDOWFUNC
        17198  +  Window *pWin;          /* Window definition for window functions */
        17199  +#endif
 17347  17200   };
 17348  17201   
 17349  17202   /*
 17350  17203   ** The following are the meanings of bits in the Expr.flags field.
 17351  17204   */
 17352  17205   #define EP_FromJoin  0x000001 /* Originates in ON/USING clause of outer join */
 17353  17206   #define EP_Agg       0x000002 /* Contains one or more aggregate functions */
................................................................................
 17369  17222   #define EP_NoReduce  0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
 17370  17223   #define EP_Unlikely  0x040000 /* unlikely() or likelihood() function */
 17371  17224   #define EP_ConstFunc 0x080000 /* A SQLITE_FUNC_CONSTANT or _SLOCHNG function */
 17372  17225   #define EP_CanBeNull 0x100000 /* Can be null despite NOT NULL constraint */
 17373  17226   #define EP_Subquery  0x200000 /* Tree contains a TK_SELECT operator */
 17374  17227   #define EP_Alias     0x400000 /* Is an alias for a result set column */
 17375  17228   #define EP_Leaf      0x800000 /* Expr.pLeft, .pRight, .u.pSelect all NULL */
 17376         -#define EP_WinFunc  0x1000000 /* TK_FUNCTION with Expr.y.pWin set */
 17377  17229   
 17378  17230   /*
 17379  17231   ** The EP_Propagate mask is a set of properties that automatically propagate
 17380  17232   ** upwards into parent nodes.
 17381  17233   */
 17382  17234   #define EP_Propagate (EP_Collate|EP_Subquery|EP_HasFunc)
 17383  17235   
................................................................................
 18055  17907   **    OPFLAG_SEEKEQ       == BTREE_SEEK_EQ
 18056  17908   **    OPFLAG_FORDELETE    == BTREE_FORDELETE
 18057  17909   **    OPFLAG_SAVEPOSITION == BTREE_SAVEPOSITION
 18058  17910   **    OPFLAG_AUXDELETE    == BTREE_AUXDELETE
 18059  17911   */
 18060  17912   #define OPFLAG_NCHANGE       0x01    /* OP_Insert: Set to update db->nChange */
 18061  17913                                        /* Also used in P2 (not P5) of OP_Delete */
 18062         -#define OPFLAG_NOCHNG        0x01    /* OP_VColumn nochange for UPDATE */
 18063  17914   #define OPFLAG_EPHEM         0x01    /* OP_Column: Ephemeral output is ok */
 18064  17915   #define OPFLAG_LASTROWID     0x20    /* Set to update db->lastRowid */
 18065  17916   #define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
 18066  17917   #define OPFLAG_APPEND        0x08    /* This is likely to be an append */
 18067  17918   #define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
 18068  17919   #define OPFLAG_ISNOOP        0x40    /* OP_Delete does pre-update-hook only */
 18069  17920   #define OPFLAG_LENGTHARG     0x40    /* OP_Column only used for length() */
................................................................................
 18274  18125     void (*xVdbeBranch)(void*,unsigned iSrcLine,u8 eThis,u8 eMx);  /* Callback */
 18275  18126     void *pVdbeBranchArg;                                     /* 1st argument */
 18276  18127   #endif
 18277  18128   #ifndef SQLITE_UNTESTABLE
 18278  18129     int (*xTestCallback)(int);        /* Invoked by sqlite3FaultSim() */
 18279  18130   #endif
 18280  18131     int bLocaltimeFault;              /* True to fail localtime() calls */
 18281         -  int bInternalFunctions;           /* Internal SQL functions are visible */
 18282  18132     int iOnceResetThreshold;          /* When to reset OP_Once counters */
 18283  18133     u32 szSorterRef;                  /* Min size in bytes to use sorter-refs */
 18284  18134   };
 18285  18135   
 18286  18136   /*
 18287  18137   ** This macro is used inside of assert() statements to indicate that
 18288  18138   ** the assert is only valid on a well-formed database.  Instead of:
................................................................................
 18528  18378   SQLITE_PRIVATE int sqlite3IsIdChar(u8);
 18529  18379   
 18530  18380   /*
 18531  18381   ** Internal function prototypes
 18532  18382   */
 18533  18383   SQLITE_PRIVATE int sqlite3StrICmp(const char*,const char*);
 18534  18384   SQLITE_PRIVATE int sqlite3Strlen30(const char*);
 18535         -#define sqlite3Strlen30NN(C) (strlen(C)&0x3fffffff)
 18536  18385   SQLITE_PRIVATE char *sqlite3ColumnType(Column*,char*);
 18537  18386   #define sqlite3StrNICmp sqlite3_strnicmp
 18538  18387   
 18539  18388   SQLITE_PRIVATE int sqlite3MallocInit(void);
 18540  18389   SQLITE_PRIVATE void sqlite3MallocEnd(void);
 18541  18390   SQLITE_PRIVATE void *sqlite3Malloc(u64);
 18542  18391   SQLITE_PRIVATE void *sqlite3MallocZero(u64);
................................................................................
 18645  18494   SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
 18646  18495   #endif
 18647  18496   
 18648  18497   #if defined(SQLITE_DEBUG)
 18649  18498   SQLITE_PRIVATE   void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
 18650  18499   SQLITE_PRIVATE   void sqlite3TreeViewBareExprList(TreeView*, const ExprList*, const char*);
 18651  18500   SQLITE_PRIVATE   void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*);
 18652         -SQLITE_PRIVATE   void sqlite3TreeViewSrcList(TreeView*, const SrcList*);
 18653  18501   SQLITE_PRIVATE   void sqlite3TreeViewSelect(TreeView*, const Select*, u8);
 18654  18502   SQLITE_PRIVATE   void sqlite3TreeViewWith(TreeView*, const With*, u8);
 18655  18503   #ifndef SQLITE_OMIT_WINDOWFUNC
 18656  18504   SQLITE_PRIVATE   void sqlite3TreeViewWindow(TreeView*, const Window*, u8);
 18657  18505   SQLITE_PRIVATE   void sqlite3TreeViewWinFunc(TreeView*, const Window*, u8);
 18658  18506   #endif
 18659  18507   #endif
................................................................................
 18878  18726   #ifdef SQLITE_ENABLE_CURSOR_HINTS
 18879  18727   SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr*);
 18880  18728   #endif
 18881  18729   SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
 18882  18730   SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
 18883  18731   SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
 18884  18732   SQLITE_PRIVATE int sqlite3IsRowid(const char*);
 18885         -#ifdef SQLITE_ENABLE_NORMALIZE
 18886         -SQLITE_PRIVATE int sqlite3IsRowidN(const char*, int);
 18887         -#endif
 18888  18733   SQLITE_PRIVATE void sqlite3GenerateRowDelete(
 18889  18734       Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8,int);
 18890  18735   SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*, int);
 18891  18736   SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
 18892  18737   SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse*,int);
 18893         -SQLITE_PRIVATE int sqlite3ExprReferencesUpdatedColumn(Expr*,int*,int);
 18894  18738   SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
 18895  18739                                        u8,u8,int,int*,int*,Upsert*);
 18896  18740   #ifdef SQLITE_ENABLE_NULL_TRIM
 18897  18741   SQLITE_PRIVATE   void sqlite3SetMakeRecordP5(Vdbe*,Table*);
 18898  18742   #else
 18899  18743   # define sqlite3SetMakeRecordP5(A,B)
 18900  18744   #endif
................................................................................
 18907  18751   SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*);
 18908  18752   SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*);
 18909  18753   SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
 18910  18754   SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
 18911  18755   SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
 18912  18756   SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
 18913  18757   SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
 18914         -#ifdef SQLITE_ENABLE_NORMALIZE
 18915         -SQLITE_PRIVATE FuncDef *sqlite3FunctionSearchN(int,const char*,int);
 18916         -#endif
 18917  18758   SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(FuncDef*,int);
 18918  18759   SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,u8,u8);
 18919  18760   SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void);
 18920  18761   SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
 18921  18762   SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3*);
 18922  18763   SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
 18923  18764   SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
................................................................................
 19067  18908   SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
 19068  18909   SQLITE_PRIVATE CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, Expr *pExpr);
 19069  18910   SQLITE_PRIVATE int sqlite3ExprCollSeqMatch(Parse*,Expr*,Expr*);
 19070  18911   SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*, int);
 19071  18912   SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
 19072  18913   SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
 19073  18914   SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
 19074         -SQLITE_PRIVATE int sqlite3WritableSchema(sqlite3*);
 19075  18915   SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
 19076  18916   SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
 19077  18917   SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
 19078  18918   SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
 19079  18919   SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
 19080  18920   SQLITE_PRIVATE int sqlite3AbsInt32(int);
 19081  18921   #ifdef SQLITE_ENABLE_8_3_NAMES
................................................................................
 19114  18954   #endif
 19115  18955   SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
 19116  18956   SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
 19117  18957   SQLITE_PRIVATE void sqlite3AlterFunctions(void);
 19118  18958   SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
 19119  18959   SQLITE_PRIVATE void sqlite3AlterRenameColumn(Parse*, SrcList*, Token*, Token*);
 19120  18960   SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
 19121         -#ifdef SQLITE_ENABLE_NORMALIZE
 19122         -SQLITE_PRIVATE int sqlite3GetTokenNormalized(const unsigned char *, int *, int *);
 19123         -#endif
 19124  18961   SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
 19125  18962   SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*, int);
 19126  18963   SQLITE_PRIVATE int sqlite3CodeSubselect(Parse*, Expr *, int, int);
 19127  18964   SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
 19128  18965   SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p);
 19129  18966   SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
 19130  18967   SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
................................................................................
 19274  19111   SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
 19275  19112   SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
 19276  19113   SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
 19277  19114   SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
 19278  19115   SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
 19279  19116   SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
 19280  19117   SQLITE_PRIVATE void sqlite3ParserReset(Parse*);
 19281         -#ifdef SQLITE_ENABLE_NORMALIZE
 19282         -SQLITE_PRIVATE void sqlite3Normalize(Vdbe*, const char*, int, u8);
 19283         -#endif
 19284  19118   SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
 19285  19119   SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
 19286  19120   SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
 19287  19121   SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
 19288  19122   SQLITE_PRIVATE const char *sqlite3JournalModename(int);
 19289  19123   #ifndef SQLITE_OMIT_WAL
 19290  19124   SQLITE_PRIVATE   int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
................................................................................
 19738  19572      0,                         /* xVdbeBranch */
 19739  19573      0,                         /* pVbeBranchArg */
 19740  19574   #endif
 19741  19575   #ifndef SQLITE_UNTESTABLE
 19742  19576      0,                         /* xTestCallback */
 19743  19577   #endif
 19744  19578      0,                         /* bLocaltimeFault */
 19745         -   0,                         /* bInternalFunctions */
 19746  19579      0x7ffffffe,                /* iOnceResetThreshold */
 19747  19580      SQLITE_DEFAULT_SORTERREF_SIZE   /* szSorterRef */
 19748  19581   };
 19749  19582   
 19750  19583   /*
 19751  19584   ** Hash table for global functions - functions common to all
 19752  19585   ** database connections.  After initialization, this table is
................................................................................
 20230  20063     bft usesStmtJournal:1;  /* True if uses a statement journal */
 20231  20064     bft readOnly:1;         /* True for statements that do not write */
 20232  20065     bft bIsReader:1;        /* True for statements that read */
 20233  20066     yDbMask btreeMask;      /* Bitmask of db->aDb[] entries referenced */
 20234  20067     yDbMask lockMask;       /* Subset of btreeMask that requires a lock */
 20235  20068     u32 aCounter[7];        /* Counters used by sqlite3_stmt_status() */
 20236  20069     char *zSql;             /* Text of the SQL statement that generated this */
 20237         -#ifdef SQLITE_ENABLE_NORMALIZE
 20238         -  char *zNormSql;         /* Normalization of the associated SQL statement */
 20239         -#endif
 20240  20070     void *pFree;            /* Free this when deleting the vdbe */
 20241  20071     VdbeFrame *pFrame;      /* Parent frame */
 20242  20072     VdbeFrame *pDelFrame;   /* List of frame objects to free on VM reset */
 20243  20073     int nFrame;             /* Number of frames in pFrame list */
 20244  20074     u32 expmask;            /* Binding to these vars invalidates VM */
 20245  20075     SubProgram *pProgram;   /* Linked list of all sub-programs used by VM */
 20246  20076     AuxData *pAuxData;      /* Linked list of auxdata allocations */
................................................................................
 20295  20125   SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
 20296  20126   SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3*, AuxData**, int, int);
 20297  20127   
 20298  20128   int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
 20299  20129   SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord*,int*);
 20300  20130   SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*);
 20301  20131   SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
 20302         -#ifndef SQLITE_OMIT_EXPLAIN
 20303  20132   SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
 20304         -#endif
 20305  20133   SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
 20306  20134   SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
 20307  20135   SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
 20308  20136   SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
 20309  20137   SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
 20310  20138   SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
 20311  20139   SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
................................................................................
 20336  20164   SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem*,u8,u8);
 20337  20165   SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,Mem*);
 20338  20166   SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
 20339  20167   SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
 20340  20168   #ifndef SQLITE_OMIT_WINDOWFUNC
 20341  20169   SQLITE_PRIVATE int sqlite3VdbeMemAggValue(Mem*, Mem*, FuncDef*);
 20342  20170   #endif
 20343         -#ifndef SQLITE_OMIT_EXPLAIN
 20344  20171   SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
 20345         -#endif
 20346  20172   SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
 20347  20173   SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n);
 20348  20174   SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
 20349  20175   #ifdef SQLITE_DEBUG
 20350  20176   SQLITE_PRIVATE int sqlite3VdbeFrameIsValid(VdbeFrame*);
 20351  20177   #endif
 20352  20178   SQLITE_PRIVATE void sqlite3VdbeFrameMemDel(void*);      /* Destructor on Mem */
................................................................................
 28465  28291         sqlite3TreeViewSelect(pView, pCte->pSelect, 0);
 28466  28292         sqlite3TreeViewPop(pView);
 28467  28293       }
 28468  28294       sqlite3TreeViewPop(pView);
 28469  28295     }
 28470  28296   }
 28471  28297   
 28472         -/*
 28473         -** Generate a human-readable description of a SrcList object.
 28474         -*/
 28475         -SQLITE_PRIVATE void sqlite3TreeViewSrcList(TreeView *pView, const SrcList *pSrc){
 28476         -  int i;
 28477         -  for(i=0; i<pSrc->nSrc; i++){
 28478         -    const struct SrcList_item *pItem = &pSrc->a[i];
 28479         -    StrAccum x;
 28480         -    char zLine[100];
 28481         -    sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
 28482         -    sqlite3_str_appendf(&x, "{%d,*}", pItem->iCursor);
 28483         -    if( pItem->zDatabase ){
 28484         -      sqlite3_str_appendf(&x, " %s.%s", pItem->zDatabase, pItem->zName);
 28485         -    }else if( pItem->zName ){
 28486         -      sqlite3_str_appendf(&x, " %s", pItem->zName);
 28487         -    }
 28488         -    if( pItem->pTab ){
 28489         -      sqlite3_str_appendf(&x, " tabname=%Q", pItem->pTab->zName);
 28490         -    }
 28491         -    if( pItem->zAlias ){
 28492         -      sqlite3_str_appendf(&x, " (AS %s)", pItem->zAlias);
 28493         -    }
 28494         -    if( pItem->fg.jointype & JT_LEFT ){
 28495         -      sqlite3_str_appendf(&x, " LEFT-JOIN");
 28496         -    }
 28497         -    sqlite3StrAccumFinish(&x);
 28498         -    sqlite3TreeViewItem(pView, zLine, i<pSrc->nSrc-1); 
 28499         -    if( pItem->pSelect ){
 28500         -      sqlite3TreeViewSelect(pView, pItem->pSelect, 0);
 28501         -    }
 28502         -    if( pItem->fg.isTabFunc ){
 28503         -      sqlite3TreeViewExprList(pView, pItem->u1.pFuncArg, 0, "func-args:");
 28504         -    }
 28505         -    sqlite3TreeViewPop(pView);
 28506         -  }
 28507         -}
 28508  28298   
 28509  28299   /*
 28510  28300   ** Generate a human-readable description of a Select object.
 28511  28301   */
 28512  28302   SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){
 28513  28303     int n = 0;
 28514  28304     int cnt = 0;
................................................................................
 28555  28345         for(pX=p->pWin; pX; pX=pX->pNextWin){
 28556  28346           sqlite3TreeViewWinFunc(pView, pX, pX->pNextWin!=0);
 28557  28347         }
 28558  28348         sqlite3TreeViewPop(pView);
 28559  28349       }
 28560  28350   #endif
 28561  28351       if( p->pSrc && p->pSrc->nSrc ){
        28352  +      int i;
 28562  28353         pView = sqlite3TreeViewPush(pView, (n--)>0);
 28563  28354         sqlite3TreeViewLine(pView, "FROM");
 28564         -      sqlite3TreeViewSrcList(pView, p->pSrc);
        28355  +      for(i=0; i<p->pSrc->nSrc; i++){
        28356  +        struct SrcList_item *pItem = &p->pSrc->a[i];
        28357  +        StrAccum x;
        28358  +        char zLine[100];
        28359  +        sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
        28360  +        sqlite3_str_appendf(&x, "{%d,*}", pItem->iCursor);
        28361  +        if( pItem->zDatabase ){
        28362  +          sqlite3_str_appendf(&x, " %s.%s", pItem->zDatabase, pItem->zName);
        28363  +        }else if( pItem->zName ){
        28364  +          sqlite3_str_appendf(&x, " %s", pItem->zName);
        28365  +        }
        28366  +        if( pItem->pTab ){
        28367  +          sqlite3_str_appendf(&x, " tabname=%Q", pItem->pTab->zName);
        28368  +        }
        28369  +        if( pItem->zAlias ){
        28370  +          sqlite3_str_appendf(&x, " (AS %s)", pItem->zAlias);
        28371  +        }
        28372  +        if( pItem->fg.jointype & JT_LEFT ){
        28373  +          sqlite3_str_appendf(&x, " LEFT-JOIN");
        28374  +        }
        28375  +        sqlite3StrAccumFinish(&x);
        28376  +        sqlite3TreeViewItem(pView, zLine, i<p->pSrc->nSrc-1); 
        28377  +        if( pItem->pSelect ){
        28378  +          sqlite3TreeViewSelect(pView, pItem->pSelect, 0);
        28379  +        }
        28380  +        if( pItem->fg.isTabFunc ){
        28381  +          sqlite3TreeViewExprList(pView, pItem->u1.pFuncArg, 0, "func-args:");
        28382  +        }
        28383  +        sqlite3TreeViewPop(pView);
        28384  +      }
 28565  28385         sqlite3TreeViewPop(pView);
 28566  28386       }
 28567  28387       if( p->pWhere ){
 28568  28388         sqlite3TreeViewItem(pView, "WHERE", (n--)>0);
 28569  28389         sqlite3TreeViewExpr(pView, p->pWhere, 0);
 28570  28390         sqlite3TreeViewPop(pView);
 28571  28391       }
................................................................................
 28847  28667         Window *pWin;
 28848  28668         if( ExprHasProperty(pExpr, EP_TokenOnly) ){
 28849  28669           pFarg = 0;
 28850  28670           pWin = 0;
 28851  28671         }else{
 28852  28672           pFarg = pExpr->x.pList;
 28853  28673   #ifndef SQLITE_OMIT_WINDOWFUNC
 28854         -        pWin = pExpr->y.pWin;
        28674  +        pWin = pExpr->pWin;
 28855  28675   #else
 28856  28676           pWin = 0;
 28857  28677   #endif 
 28858  28678         }
 28859  28679         if( pExpr->op==TK_AGG_FUNCTION ){
 28860  28680           sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q",
 28861  28681                                pExpr->op2, pExpr->u.zToken);
................................................................................
 31675  31495       ** 0x9e3779b1 is 2654435761 which is the closest prime number to
 31676  31496       ** (2**32)*golden_ratio, where golden_ratio = (sqrt(5) - 1)/2. */
 31677  31497       h += sqlite3UpperToLower[c];
 31678  31498       h *= 0x9e3779b1;
 31679  31499     }
 31680  31500     return h;
 31681  31501   }
 31682         -#ifdef SQLITE_ENABLE_NORMALIZE
 31683         -static unsigned int strHashN(const char *z, int n){
 31684         -  unsigned int h = 0;
 31685         -  int i;
 31686         -  for(i=0; i<n; i++){
 31687         -    /* Knuth multiplicative hashing.  (Sorting & Searching, p. 510).
 31688         -    ** 0x9e3779b1 is 2654435761 which is the closest prime number to
 31689         -    ** (2**32)*golden_ratio, where golden_ratio = (sqrt(5) - 1)/2. */
 31690         -    h += sqlite3UpperToLower[z[i]];
 31691         -    h *= 0x9e3779b1;
 31692         -  }
 31693         -  return h;
 31694         -}
 31695         -#endif /* SQLITE_ENABLE_NORMALIZE */
 31696  31502   
 31697  31503   
 31698  31504   /* Link pNew element into the hash table pH.  If pEntry!=0 then also
 31699  31505   ** insert pNew into the pEntry hash bucket.
 31700  31506   */
 31701  31507   static void insertElement(
 31702  31508     Hash *pH,              /* The complete hash table */
................................................................................
 31800  31606       if( sqlite3StrICmp(elem->pKey,pKey)==0 ){ 
 31801  31607         return elem;
 31802  31608       }
 31803  31609       elem = elem->next;
 31804  31610     }
 31805  31611     return &nullElement;
 31806  31612   }
 31807         -#ifdef SQLITE_ENABLE_NORMALIZE
 31808         -static HashElem *findElementWithHashN(
 31809         -  const Hash *pH,     /* The pH to be searched */
 31810         -  const char *pKey,   /* The key we are searching for */
 31811         -  int nKey,           /* Number of key bytes to use */
 31812         -  unsigned int *pHash /* Write the hash value here */
 31813         -){
 31814         -  HashElem *elem;                /* Used to loop thru the element list */
 31815         -  int count;                     /* Number of elements left to test */
 31816         -  unsigned int h;                /* The computed hash */
 31817         -  static HashElem nullElement = { 0, 0, 0, 0 };
 31818         -
 31819         -  if( pH->ht ){   /*OPTIMIZATION-IF-TRUE*/
 31820         -    struct _ht *pEntry;
 31821         -    h = strHashN(pKey, nKey) % pH->htsize;
 31822         -    pEntry = &pH->ht[h];
 31823         -    elem = pEntry->chain;
 31824         -    count = pEntry->count;
 31825         -  }else{
 31826         -    h = 0;
 31827         -    elem = pH->first;
 31828         -    count = pH->count;
 31829         -  }
 31830         -  if( pHash ) *pHash = h;
 31831         -  while( count-- ){
 31832         -    assert( elem!=0 );
 31833         -    if( sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){ 
 31834         -      return elem;
 31835         -    }
 31836         -    elem = elem->next;
 31837         -  }
 31838         -  return &nullElement;
 31839         -}
 31840         -#endif /* SQLITE_ENABLE_NORMALIZE */
 31841  31613   
 31842  31614   /* Remove a single entry from the hash table given a pointer to that
 31843  31615   ** element and a hash on the element's key.
 31844  31616   */
 31845  31617   static void removeElementGivenHash(
 31846  31618     Hash *pH,         /* The pH containing "elem" */
 31847  31619     HashElem* elem,   /* The element to be removed from the pH */
................................................................................
 31878  31650   ** found, or NULL if there is no match.
 31879  31651   */
 31880  31652   SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey){
 31881  31653     assert( pH!=0 );
 31882  31654     assert( pKey!=0 );
 31883  31655     return findElementWithHash(pH, pKey, 0)->data;
 31884  31656   }
 31885         -#ifdef SQLITE_ENABLE_NORMALIZE
 31886         -SQLITE_PRIVATE void *sqlite3HashFindN(const Hash *pH, const char *pKey, int nKey){
 31887         -  assert( pH!=0 );
 31888         -  assert( pKey!=0 );
 31889         -  assert( nKey>=0 );
 31890         -  return findElementWithHashN(pH, pKey, nKey, 0)->data;
 31891         -}
 31892         -#endif /* SQLITE_ENABLE_NORMALIZE */
 31893  31657   
 31894  31658   /* Insert an element into the hash table pH.  The key is pKey
 31895  31659   ** and the data is "data".
 31896  31660   **
 31897  31661   ** If no element exists with a matching key, then a new
 31898  31662   ** element is created and NULL is returned.
 31899  31663   **
................................................................................
 32268  32032   
 32269  32033   /*
 32270  32034   ** Allowed values of unixFile.fsFlags
 32271  32035   */
 32272  32036   #define SQLITE_FSFLAGS_IS_MSDOS     0x1
 32273  32037   
 32274  32038   /*
 32275         -** If we are to be thread-safe, include the pthreads header.
        32039  +** If we are to be thread-safe, include the pthreads header and define
        32040  +** the SQLITE_UNIX_THREADS macro.
 32276  32041   */
 32277  32042   #if SQLITE_THREADSAFE
 32278  32043   /* # include <pthread.h> */
        32044  +# define SQLITE_UNIX_THREADS 1
 32279  32045   #endif
 32280  32046   
 32281  32047   /*
 32282  32048   ** Default permissions when creating a new file
 32283  32049   */
 32284  32050   #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
 32285  32051   # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
................................................................................
 32849  32615     { "lstat",         (sqlite3_syscall_ptr)lstat,          0 },
 32850  32616   #else
 32851  32617     { "lstat",         (sqlite3_syscall_ptr)0,              0 },
 32852  32618   #endif
 32853  32619   #define osLstat      ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)
 32854  32620   
 32855  32621   #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
 32856         -# ifdef __ANDROID__
 32857         -  { "ioctl", (sqlite3_syscall_ptr)(int(*)(int, int, ...))ioctl, 0 },
 32858         -# else
 32859  32622     { "ioctl",         (sqlite3_syscall_ptr)ioctl,          0 },
 32860         -# endif
 32861  32623   #else
 32862  32624     { "ioctl",         (sqlite3_syscall_ptr)0,              0 },
 32863  32625   #endif
 32864  32626   #define osIoctl ((int(*)(int,int,...))aSyscall[28].pCurrent)
 32865  32627   
 32866  32628   }; /* End of the overrideable system calls */
 32867  32629   
................................................................................
 33447  33209     /* WAS:  ino_t ino;   */
 33448  33210     u64 ino;                   /* Inode number */
 33449  33211   #endif
 33450  33212   };
 33451  33213   
 33452  33214   /*
 33453  33215   ** An instance of the following structure is allocated for each open
 33454         -** inode.
        33216  +** inode.  Or, on LinuxThreads, there is one of these structures for
        33217  +** each inode opened by each thread.
 33455  33218   **
 33456  33219   ** A single inode can have multiple file descriptors, so each unixFile
 33457  33220   ** structure contains a pointer to an instance of this object and this
 33458  33221   ** object keeps a count of the number of unixFile pointing to it.
 33459  33222   **
 33460  33223   ** Mutex rules:
 33461  33224   **
................................................................................
 33493  33256     sem_t *pSem;                    /* Named POSIX semaphore */
 33494  33257     char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
 33495  33258   #endif
 33496  33259   };
 33497  33260   
 33498  33261   /*
 33499  33262   ** A lists of all unixInodeInfo objects.
 33500         -**
 33501         -** Must hold unixBigLock in order to read or write this variable.
 33502  33263   */
 33503  33264   static unixInodeInfo *inodeList = 0;  /* All unixInodeInfo objects */
 33504  33265   
 33505  33266   #ifdef SQLITE_DEBUG
 33506  33267   /*
 33507         -** True if the inode mutex (on the unixFile.pFileMutex field) is held, or not.
 33508         -** This routine is used only within assert() to help verify correct mutex
 33509         -** usage.
        33268  +** True if the inode mutex is held, or not.  Used only within assert()
        33269  +** to help verify correct mutex usage.
 33510  33270   */
 33511  33271   int unixFileMutexHeld(unixFile *pFile){
 33512  33272     assert( pFile->pInode );
 33513  33273     return sqlite3_mutex_held(pFile->pInode->pLockMutex);
 33514  33274   }
 33515  33275   int unixFileMutexNotheld(unixFile *pFile){
 33516  33276     assert( pFile->pInode );
................................................................................
 33630  33390     }
 33631  33391     pInode->pUnused = 0;
 33632  33392   }
 33633  33393   
 33634  33394   /*
 33635  33395   ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
 33636  33396   **
 33637         -** The global mutex must be held when this routine is called, but the mutex
 33638         -** on the inode being deleted must NOT be held.
        33397  +** The mutex entered using the unixEnterMutex() function must be held
        33398  +** when this function is called.
 33639  33399   */
 33640  33400   static void releaseInodeInfo(unixFile *pFile){
 33641  33401     unixInodeInfo *pInode = pFile->pInode;
 33642  33402     assert( unixMutexHeld() );
 33643  33403     assert( unixFileMutexNotheld(pFile) );
 33644  33404     if( ALWAYS(pInode) ){
 33645  33405       pInode->nRef--;
................................................................................
 33666  33426   }
 33667  33427   
 33668  33428   /*
 33669  33429   ** Given a file descriptor, locate the unixInodeInfo object that
 33670  33430   ** describes that file descriptor.  Create a new one if necessary.  The
 33671  33431   ** return value might be uninitialized if an error occurs.
 33672  33432   **
 33673         -** The global mutex must held when calling this routine.
        33433  +** The mutex entered using the unixEnterMutex() function must be held
        33434  +** when this function is called.
 33674  33435   **
 33675  33436   ** Return an appropriate error code.
 33676  33437   */
 33677  33438   static int findInodeInfo(
 33678  33439     unixFile *pFile,               /* Unix file with file desc used in the key */
 33679  33440     unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
 33680  33441   ){
................................................................................
 33727  33488     memset(&fileId, 0, sizeof(fileId));
 33728  33489     fileId.dev = statbuf.st_dev;
 33729  33490   #if OS_VXWORKS
 33730  33491     fileId.pId = pFile->pId;
 33731  33492   #else
 33732  33493     fileId.ino = (u64)statbuf.st_ino;
 33733  33494   #endif
 33734         -  assert( unixMutexHeld() );
 33735  33495     pInode = inodeList;
 33736  33496     while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
 33737  33497       pInode = pInode->pNext;
 33738  33498     }
 33739  33499     if( pInode==0 ){
 33740  33500       pInode = sqlite3_malloc64( sizeof(*pInode) );
 33741  33501       if( pInode==0 ){
................................................................................
 33747  33507         pInode->pLockMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
 33748  33508         if( pInode->pLockMutex==0 ){
 33749  33509           sqlite3_free(pInode);
 33750  33510           return SQLITE_NOMEM_BKPT;
 33751  33511         }
 33752  33512       }
 33753  33513       pInode->nRef = 1;
 33754         -    assert( unixMutexHeld() );
 33755  33514       pInode->pNext = inodeList;
 33756  33515       pInode->pPrev = 0;
 33757  33516       if( inodeList ) inodeList->pPrev = pInode;
 33758  33517       inodeList = pInode;
 33759  33518     }else{
 33760  33519       pInode->nRef++;
 33761  33520     }
................................................................................
 36545  36304   ** unixMutexHeld() must be true when creating or destroying
 36546  36305   ** this object or while reading or writing the following fields:
 36547  36306   **
 36548  36307   **      nRef
 36549  36308   **
 36550  36309   ** The following fields are read-only after the object is created:
 36551  36310   ** 
 36552         -**      hShm
        36311  +**      fid
 36553  36312   **      zFilename
 36554  36313   **
 36555         -** Either unixShmNode.pShmMutex must be held or unixShmNode.nRef==0 and
        36314  +** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
 36556  36315   ** unixMutexHeld() is true when reading or writing any other field
 36557  36316   ** in this structure.
 36558  36317   */
 36559  36318   struct unixShmNode {
 36560  36319     unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
 36561         -  sqlite3_mutex *pShmMutex;  /* Mutex to access this object */
        36320  +  sqlite3_mutex *mutex;      /* Mutex to access this object */
 36562  36321     char *zFilename;           /* Name of the mmapped file */
 36563         -  int hShm;                  /* Open file descriptor */
        36322  +  int h;                     /* Open file descriptor */
 36564  36323     int szRegion;              /* Size of shared-memory regions */
 36565  36324     u16 nRegion;               /* Size of array apRegion */
 36566  36325     u8 isReadonly;             /* True if read-only */
 36567  36326     u8 isUnlocked;             /* True if no DMS lock held */
 36568  36327     char **apRegion;           /* Array of mapped shared-memory regions */
 36569  36328     int nRef;                  /* Number of unixShm objects pointing to this */
 36570  36329     unixShm *pFirst;           /* All unixShm objects pointing to this */
................................................................................
 36578  36337   /*
 36579  36338   ** Structure used internally by this VFS to record the state of an
 36580  36339   ** open shared memory connection.
 36581  36340   **
 36582  36341   ** The following fields are initialized when this object is created and
 36583  36342   ** are read-only thereafter:
 36584  36343   **
 36585         -**    unixShm.pShmNode
        36344  +**    unixShm.pFile
 36586  36345   **    unixShm.id
 36587  36346   **
 36588         -** All other fields are read/write.  The unixShm.pShmNode->pShmMutex must
 36589         -** be held while accessing any read/write fields.
        36347  +** All other fields are read/write.  The unixShm.pFile->mutex must be held
        36348  +** while accessing any read/write fields.
 36590  36349   */
 36591  36350   struct unixShm {
 36592  36351     unixShmNode *pShmNode;     /* The underlying unixShmNode object */
 36593  36352     unixShm *pNext;            /* Next unixShm with the same unixShmNode */
 36594         -  u8 hasMutex;               /* True if holding the unixShmNode->pShmMutex */
        36353  +  u8 hasMutex;               /* True if holding the unixShmNode mutex */
 36595  36354     u8 id;                     /* Id of this connection within its unixShmNode */
 36596  36355     u16 sharedMask;            /* Mask of shared locks held */
 36597  36356     u16 exclMask;              /* Mask of exclusive locks held */
 36598  36357   };
 36599  36358   
 36600  36359   /*
 36601  36360   ** Constants used for locking
................................................................................
 36617  36376   ){
 36618  36377     unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
 36619  36378     struct flock f;        /* The posix advisory locking structure */
 36620  36379     int rc = SQLITE_OK;    /* Result code form fcntl() */
 36621  36380   
 36622  36381     /* Access to the unixShmNode object is serialized by the caller */
 36623  36382     pShmNode = pFile->pInode->pShmNode;
 36624         -  assert( pShmNode->nRef==0 || sqlite3_mutex_held(pShmNode->pShmMutex) );
 36625         -  assert( pShmNode->nRef>0 || unixMutexHeld() );
        36383  +  assert( pShmNode->nRef==0 || sqlite3_mutex_held(pShmNode->mutex) );
 36626  36384   
 36627  36385     /* Shared locks never span more than one byte */
 36628  36386     assert( n==1 || lockType!=F_RDLCK );
 36629  36387   
 36630  36388     /* Locks are within range */
 36631  36389     assert( n>=1 && n<=SQLITE_SHM_NLOCK );
 36632  36390   
 36633         -  if( pShmNode->hShm>=0 ){
        36391  +  if( pShmNode->h>=0 ){
 36634  36392       /* Initialize the locking parameters */
 36635  36393       f.l_type = lockType;
 36636  36394       f.l_whence = SEEK_SET;
 36637  36395       f.l_start = ofst;
 36638  36396       f.l_len = n;
 36639         -    rc = osSetPosixAdvisoryLock(pShmNode->hShm, &f, pFile);
        36397  +    rc = osSetPosixAdvisoryLock(pShmNode->h, &f, pFile);
 36640  36398       rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
 36641  36399     }
 36642  36400   
 36643  36401     /* Update the global lock state and do debug tracing */
 36644  36402   #ifdef SQLITE_DEBUG
 36645  36403     { u16 mask;
 36646  36404     OSTRACE(("SHM-LOCK "));
................................................................................
 36704  36462   static void unixShmPurge(unixFile *pFd){
 36705  36463     unixShmNode *p = pFd->pInode->pShmNode;
 36706  36464     assert( unixMutexHeld() );
 36707  36465     if( p && ALWAYS(p->nRef==0) ){
 36708  36466       int nShmPerMap = unixShmRegionPerMap();
 36709  36467       int i;
 36710  36468       assert( p->pInode==pFd->pInode );
 36711         -    sqlite3_mutex_free(p->pShmMutex);
        36469  +    sqlite3_mutex_free(p->mutex);
 36712  36470       for(i=0; i<p->nRegion; i+=nShmPerMap){
 36713         -      if( p->hShm>=0 ){
        36471  +      if( p->h>=0 ){
 36714  36472           osMunmap(p->apRegion[i], p->szRegion);
 36715  36473         }else{
 36716  36474           sqlite3_free(p->apRegion[i]);
 36717  36475         }
 36718  36476       }
 36719  36477       sqlite3_free(p->apRegion);
 36720         -    if( p->hShm>=0 ){
 36721         -      robust_close(pFd, p->hShm, __LINE__);
 36722         -      p->hShm = -1;
        36478  +    if( p->h>=0 ){
        36479  +      robust_close(pFd, p->h, __LINE__);
        36480  +      p->h = -1;
 36723  36481       }
 36724  36482       p->pInode->pShmNode = 0;
 36725  36483       sqlite3_free(p);
 36726  36484     }
 36727  36485   }
 36728  36486   
 36729  36487   /*
................................................................................
 36757  36515     ** process might open and use the *-shm file without truncating it.
 36758  36516     ** And if the *-shm file has been corrupted by a power failure or
 36759  36517     ** system crash, the database itself may also become corrupt.  */
 36760  36518     lock.l_whence = SEEK_SET;
 36761  36519     lock.l_start = UNIX_SHM_DMS;
 36762  36520     lock.l_len = 1;
 36763  36521     lock.l_type = F_WRLCK;
 36764         -  if( osFcntl(pShmNode->hShm, F_GETLK, &lock)!=0 ) {
        36522  +  if( osFcntl(pShmNode->h, F_GETLK, &lock)!=0 ) {
 36765  36523       rc = SQLITE_IOERR_LOCK;
 36766  36524     }else if( lock.l_type==F_UNLCK ){
 36767  36525       if( pShmNode->isReadonly ){
 36768  36526         pShmNode->isUnlocked = 1;
 36769  36527         rc = SQLITE_READONLY_CANTINIT;
 36770  36528       }else{
 36771  36529         rc = unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1);
 36772         -      /* The first connection to attach must truncate the -shm file.  We
 36773         -      ** truncate to 3 bytes (an arbitrary small number, less than the
 36774         -      ** -shm header size) rather than 0 as a system debugging aid, to
 36775         -      ** help detect if a -shm file truncation is legitimate or is the work
 36776         -      ** or a rogue process. */
 36777         -      if( rc==SQLITE_OK && robust_ftruncate(pShmNode->hShm, 3) ){
        36530  +      if( rc==SQLITE_OK && robust_ftruncate(pShmNode->h, 0) ){
 36778  36531           rc = unixLogError(SQLITE_IOERR_SHMOPEN,"ftruncate",pShmNode->zFilename);
 36779  36532         }
 36780  36533       }
 36781  36534     }else if( lock.l_type==F_WRLCK ){
 36782  36535       rc = SQLITE_BUSY;
 36783  36536     }
 36784  36537   
................................................................................
 36876  36629       sqlite3_snprintf(nShmFilename, zShm, 
 36877  36630                        SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
 36878  36631                        (u32)sStat.st_ino, (u32)sStat.st_dev);
 36879  36632   #else
 36880  36633       sqlite3_snprintf(nShmFilename, zShm, "%s-shm", zBasePath);
 36881  36634       sqlite3FileSuffix3(pDbFd->zPath, zShm);
 36882  36635   #endif
 36883         -    pShmNode->hShm = -1;
        36636  +    pShmNode->h = -1;
 36884  36637       pDbFd->pInode->pShmNode = pShmNode;
 36885  36638       pShmNode->pInode = pDbFd->pInode;
 36886  36639       if( sqlite3GlobalConfig.bCoreMutex ){
 36887         -      pShmNode->pShmMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
 36888         -      if( pShmNode->pShmMutex==0 ){
        36640  +      pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
        36641  +      if( pShmNode->mutex==0 ){
 36889  36642           rc = SQLITE_NOMEM_BKPT;
 36890  36643           goto shm_open_err;
 36891  36644         }
 36892  36645       }
 36893  36646   
 36894  36647       if( pInode->bProcessLock==0 ){
 36895  36648         if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
 36896         -        pShmNode->hShm = robust_open(zShm, O_RDWR|O_CREAT,(sStat.st_mode&0777));
        36649  +        pShmNode->h = robust_open(zShm, O_RDWR|O_CREAT, (sStat.st_mode&0777));
 36897  36650         }
 36898         -      if( pShmNode->hShm<0 ){
 36899         -        pShmNode->hShm = robust_open(zShm, O_RDONLY, (sStat.st_mode&0777));
 36900         -        if( pShmNode->hShm<0 ){
        36651  +      if( pShmNode->h<0 ){
        36652  +        pShmNode->h = robust_open(zShm, O_RDONLY, (sStat.st_mode&0777));
        36653  +        if( pShmNode->h<0 ){
 36901  36654             rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShm);
 36902  36655             goto shm_open_err;
 36903  36656           }
 36904  36657           pShmNode->isReadonly = 1;
 36905  36658         }
 36906  36659   
 36907  36660         /* If this process is running as root, make sure that the SHM file
 36908  36661         ** is owned by the same user that owns the original database.  Otherwise,
 36909  36662         ** the original owner will not be able to connect.
 36910  36663         */
 36911         -      robustFchown(pShmNode->hShm, sStat.st_uid, sStat.st_gid);
        36664  +      robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
 36912  36665   
 36913  36666         rc = unixLockSharedMemory(pDbFd, pShmNode);
 36914  36667         if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err;
 36915  36668       }
 36916  36669     }
 36917  36670   
 36918  36671     /* Make the new connection a child of the unixShmNode */
................................................................................
 36924  36677     pDbFd->pShm = p;
 36925  36678     unixLeaveMutex();
 36926  36679   
 36927  36680     /* The reference count on pShmNode has already been incremented under
 36928  36681     ** the cover of the unixEnterMutex() mutex and the pointer from the
 36929  36682     ** new (struct unixShm) object to the pShmNode has been set. All that is
 36930  36683     ** left to do is to link the new object into the linked list starting
 36931         -  ** at pShmNode->pFirst. This must be done while holding the
 36932         -  ** pShmNode->pShmMutex.
        36684  +  ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex 
        36685  +  ** mutex.
 36933  36686     */
 36934         -  sqlite3_mutex_enter(pShmNode->pShmMutex);
        36687  +  sqlite3_mutex_enter(pShmNode->mutex);
 36935  36688     p->pNext = pShmNode->pFirst;
 36936  36689     pShmNode->pFirst = p;
 36937         -  sqlite3_mutex_leave(pShmNode->pShmMutex);
        36690  +  sqlite3_mutex_leave(pShmNode->mutex);
 36938  36691     return rc;
 36939  36692   
 36940  36693     /* Jump here on any error */
 36941  36694   shm_open_err:
 36942  36695     unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
 36943  36696     sqlite3_free(p);
 36944  36697     unixLeaveMutex();
................................................................................
 36982  36735     if( pDbFd->pShm==0 ){
 36983  36736       rc = unixOpenSharedMemory(pDbFd);
 36984  36737       if( rc!=SQLITE_OK ) return rc;
 36985  36738     }
 36986  36739   
 36987  36740     p = pDbFd->pShm;
 36988  36741     pShmNode = p->pShmNode;
 36989         -  sqlite3_mutex_enter(pShmNode->pShmMutex);
        36742  +  sqlite3_mutex_enter(pShmNode->mutex);
 36990  36743     if( pShmNode->isUnlocked ){
 36991  36744       rc = unixLockSharedMemory(pDbFd, pShmNode);
 36992  36745       if( rc!=SQLITE_OK ) goto shmpage_out;
 36993  36746       pShmNode->isUnlocked = 0;
 36994  36747     }
 36995  36748     assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
 36996  36749     assert( pShmNode->pInode==pDbFd->pInode );
 36997         -  assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 );
 36998         -  assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 );
        36750  +  assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
        36751  +  assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
 36999  36752   
 37000  36753     /* Minimum number of regions required to be mapped. */
 37001  36754     nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
 37002  36755   
 37003  36756     if( pShmNode->nRegion<nReqRegion ){
 37004  36757       char **apNew;                      /* New apRegion[] array */
 37005  36758       int nByte = nReqRegion*szRegion;   /* Minimum required file size */
 37006  36759       struct stat sStat;                 /* Used by fstat() */
 37007  36760   
 37008  36761       pShmNode->szRegion = szRegion;
 37009  36762   
 37010         -    if( pShmNode->hShm>=0 ){
        36763  +    if( pShmNode->h>=0 ){
 37011  36764         /* The requested region is not mapped into this processes address space.
 37012  36765         ** Check to see if it has been allocated (i.e. if the wal-index file is
 37013  36766         ** large enough to contain the requested region).
 37014  36767         */
 37015         -      if( osFstat(pShmNode->hShm, &sStat) ){
        36768  +      if( osFstat(pShmNode->h, &sStat) ){
 37016  36769           rc = SQLITE_IOERR_SHMSIZE;
 37017  36770           goto shmpage_out;
 37018  36771         }
 37019  36772     
 37020  36773         if( sStat.st_size<nByte ){
 37021  36774           /* The requested memory region does not exist. If bExtend is set to
 37022  36775           ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
................................................................................
 37036  36789             static const int pgsz = 4096;
 37037  36790             int iPg;
 37038  36791   
 37039  36792             /* Write to the last byte of each newly allocated or extended page */
 37040  36793             assert( (nByte % pgsz)==0 );
 37041  36794             for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
 37042  36795               int x = 0;
 37043         -            if( seekAndWriteFd(pShmNode->hShm, iPg*pgsz + pgsz-1,"",1,&x)!=1 ){
        36796  +            if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, &x)!=1 ){
 37044  36797                 const char *zFile = pShmNode->zFilename;
 37045  36798                 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
 37046  36799                 goto shmpage_out;
 37047  36800               }
 37048  36801             }
 37049  36802           }
 37050  36803         }
................................................................................
 37059  36812         goto shmpage_out;
 37060  36813       }
 37061  36814       pShmNode->apRegion = apNew;
 37062  36815       while( pShmNode->nRegion<nReqRegion ){
 37063  36816         int nMap = szRegion*nShmPerMap;
 37064  36817         int i;
 37065  36818         void *pMem;
 37066         -      if( pShmNode->hShm>=0 ){
        36819  +      if( pShmNode->h>=0 ){
 37067  36820           pMem = osMmap(0, nMap,
 37068  36821               pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE, 
 37069         -            MAP_SHARED, pShmNode->hShm, szRegion*(i64)pShmNode->nRegion
        36822  +            MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
 37070  36823           );
 37071  36824           if( pMem==MAP_FAILED ){
 37072  36825             rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
 37073  36826             goto shmpage_out;
 37074  36827           }
 37075  36828         }else{
 37076         -        pMem = sqlite3_malloc64(nMap);
        36829  +        pMem = sqlite3_malloc64(szRegion);
 37077  36830           if( pMem==0 ){
 37078  36831             rc = SQLITE_NOMEM_BKPT;
 37079  36832             goto shmpage_out;
 37080  36833           }
 37081         -        memset(pMem, 0, nMap);
        36834  +        memset(pMem, 0, szRegion);
 37082  36835         }
 37083  36836   
 37084  36837         for(i=0; i<nShmPerMap; i++){
 37085  36838           pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
 37086  36839         }
 37087  36840         pShmNode->nRegion += nShmPerMap;
 37088  36841       }
................................................................................
 37091  36844   shmpage_out:
 37092  36845     if( pShmNode->nRegion>iRegion ){
 37093  36846       *pp = pShmNode->apRegion[iRegion];
 37094  36847     }else{
 37095  36848       *pp = 0;
 37096  36849     }
 37097  36850     if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
 37098         -  sqlite3_mutex_leave(pShmNode->pShmMutex);
        36851  +  sqlite3_mutex_leave(pShmNode->mutex);
 37099  36852     return rc;
 37100  36853   }
 37101  36854   
 37102  36855   /*
 37103  36856   ** Change the lock state for a shared-memory segment.
 37104  36857   **
 37105  36858   ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
................................................................................
 37125  36878     assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
 37126  36879     assert( n>=1 );
 37127  36880     assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
 37128  36881          || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
 37129  36882          || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
 37130  36883          || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
 37131  36884     assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
 37132         -  assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 );
 37133         -  assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 );
        36885  +  assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
        36886  +  assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
 37134  36887   
 37135  36888     mask = (1<<(ofst+n)) - (1<<ofst);
 37136  36889     assert( n>1 || mask==(1<<ofst) );
 37137         -  sqlite3_mutex_enter(pShmNode->pShmMutex);
        36890  +  sqlite3_mutex_enter(pShmNode->mutex);
 37138  36891     if( flags & SQLITE_SHM_UNLOCK ){
 37139  36892       u16 allMask = 0; /* Mask of locks held by siblings */
 37140  36893   
 37141  36894       /* See if any siblings hold this same lock */
 37142  36895       for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
 37143  36896         if( pX==p ) continue;
 37144  36897         assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
................................................................................
 37203  36956         rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
 37204  36957         if( rc==SQLITE_OK ){
 37205  36958           assert( (p->sharedMask & mask)==0 );
 37206  36959           p->exclMask |= mask;
 37207  36960         }
 37208  36961       }
 37209  36962     }
 37210         -  sqlite3_mutex_leave(pShmNode->pShmMutex);
        36963  +  sqlite3_mutex_leave(pShmNode->mutex);
 37211  36964     OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
 37212  36965              p->id, osGetpid(0), p->sharedMask, p->exclMask));
 37213  36966     return rc;
 37214  36967   }
 37215  36968   
 37216  36969   /*
 37217  36970   ** Implement a memory barrier or memory fence on shared memory.  
................................................................................
 37253  37006     pShmNode = p->pShmNode;
 37254  37007   
 37255  37008     assert( pShmNode==pDbFd->pInode->pShmNode );
 37256  37009     assert( pShmNode->pInode==pDbFd->pInode );
 37257  37010   
 37258  37011     /* Remove connection p from the set of connections associated
 37259  37012     ** with pShmNode */
 37260         -  sqlite3_mutex_enter(pShmNode->pShmMutex);
        37013  +  sqlite3_mutex_enter(pShmNode->mutex);
 37261  37014     for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
 37262  37015     *pp = p->pNext;
 37263  37016   
 37264  37017     /* Free the connection p */
 37265  37018     sqlite3_free(p);
 37266  37019     pDbFd->pShm = 0;
 37267         -  sqlite3_mutex_leave(pShmNode->pShmMutex);
        37020  +  sqlite3_mutex_leave(pShmNode->mutex);
 37268  37021   
 37269  37022     /* If pShmNode->nRef has reached 0, then close the underlying
 37270  37023     ** shared-memory file, too */
 37271  37024     assert( unixFileMutexNotheld(pDbFd) );
 37272  37025     unixEnterMutex();
 37273  37026     assert( pShmNode->nRef>0 );
 37274  37027     pShmNode->nRef--;
 37275  37028     if( pShmNode->nRef==0 ){
 37276         -    if( deleteFlag && pShmNode->hShm>=0 ){
        37029  +    if( deleteFlag && pShmNode->h>=0 ){
 37277  37030         osUnlink(pShmNode->zFilename);
 37278  37031       }
 37279  37032       unixShmPurge(pDbFd);
 37280  37033     }
 37281  37034     unixLeaveMutex();
 37282  37035   
 37283  37036     return SQLITE_OK;
................................................................................
 40687  40440     winceLock local;        /* Locks obtained by this instance of winFile */
 40688  40441     winceLock *shared;      /* Global shared lock memory for the file  */
 40689  40442   #endif
 40690  40443   #if SQLITE_MAX_MMAP_SIZE>0
 40691  40444     int nFetchOut;                /* Number of outstanding xFetch references */
 40692  40445     HANDLE hMap;                  /* Handle for accessing memory mapping */
 40693  40446     void *pMapRegion;             /* Area memory mapped */
 40694         -  sqlite3_int64 mmapSize;       /* Size of mapped region */
        40447  +  sqlite3_int64 mmapSize;       /* Usable size of mapped region */
        40448  +  sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */
 40695  40449     sqlite3_int64 mmapSizeMax;    /* Configured FCNTL_MMAP_SIZE value */
 40696  40450   #endif
 40697  40451   };
 40698  40452   
 40699  40453   /*
 40700  40454   ** The winVfsAppData structure is used for the pAppData member for all of the
 40701  40455   ** Win32 VFS variants.
................................................................................
 43308  43062   */
 43309  43063   static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
 43310  43064     winFile *pFile = (winFile*)id;  /* File handle object */
 43311  43065     int rc = SQLITE_OK;             /* Return code for this function */
 43312  43066     DWORD lastErrno;
 43313  43067   #if SQLITE_MAX_MMAP_SIZE>0
 43314  43068     sqlite3_int64 oldMmapSize;
 43315         -  if( pFile->nFetchOut>0 ){
 43316         -    /* File truncation is a no-op if there are outstanding memory mapped
 43317         -    ** pages.  This is because truncating the file means temporarily unmapping
 43318         -    ** the file, and that might delete memory out from under existing cursors.
 43319         -    **
 43320         -    ** This can result in incremental vacuum not truncating the file,
 43321         -    ** if there is an active read cursor when the incremental vacuum occurs.
 43322         -    ** No real harm comes of this - the database file is not corrupted,
 43323         -    ** though some folks might complain that the file is bigger than it
 43324         -    ** needs to be.
 43325         -    **
 43326         -    ** The only feasible work-around is to defer the truncation until after
 43327         -    ** all references to memory-mapped content are closed.  That is doable,
 43328         -    ** but involves adding a few branches in the common write code path which
 43329         -    ** could slow down normal operations slightly.  Hence, we have decided for
 43330         -    ** now to simply make trancations a no-op if there are pending reads.  We
 43331         -    ** can maybe revisit this decision in the future.
 43332         -    */
 43333         -    return SQLITE_OK;
 43334         -  }
 43335  43069   #endif
 43336  43070   
 43337  43071     assert( pFile );
 43338  43072     SimulateIOError(return SQLITE_IOERR_TRUNCATE);
 43339  43073     OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, size=%lld, lock=%d\n",
 43340  43074              osGetCurrentProcessId(), pFile, pFile->h, nByte, pFile->locktype));
 43341  43075   
................................................................................
 44756  44490   /*
 44757  44491   ** Cleans up the mapped region of the specified file, if any.
 44758  44492   */
 44759  44493   #if SQLITE_MAX_MMAP_SIZE>0
 44760  44494   static int winUnmapfile(winFile *pFile){
 44761  44495     assert( pFile!=0 );
 44762  44496     OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
 44763         -           "mmapSize=%lld, mmapSizeMax=%lld\n",
        44497  +           "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
 44764  44498              osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
 44765         -           pFile->mmapSize, pFile->mmapSizeMax));
        44499  +           pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax));
 44766  44500     if( pFile->pMapRegion ){
 44767  44501       if( !osUnmapViewOfFile(pFile->pMapRegion) ){
 44768  44502         pFile->lastErrno = osGetLastError();
 44769  44503         OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
 44770  44504                  "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
 44771  44505                  pFile->pMapRegion));
 44772  44506         return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
 44773  44507                            "winUnmapfile1", pFile->zPath);
 44774  44508       }
 44775  44509       pFile->pMapRegion = 0;
 44776  44510       pFile->mmapSize = 0;
        44511  +    pFile->mmapSizeActual = 0;
 44777  44512     }
 44778  44513     if( pFile->hMap!=NULL ){
 44779  44514       if( !osCloseHandle(pFile->hMap) ){
 44780  44515         pFile->lastErrno = osGetLastError();
 44781  44516         OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
 44782  44517                  osGetCurrentProcessId(), pFile, pFile->hMap));
 44783  44518         return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
................................................................................
 44880  44615         /* Log the error, but continue normal operation using xRead/xWrite */
 44881  44616         OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
 44882  44617                  osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
 44883  44618         return SQLITE_OK;
 44884  44619       }
 44885  44620       pFd->pMapRegion = pNew;
 44886  44621       pFd->mmapSize = nMap;
        44622  +    pFd->mmapSizeActual = nMap;
 44887  44623     }
 44888  44624   
 44889  44625     OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
 44890  44626              osGetCurrentProcessId(), pFd));
 44891  44627     return SQLITE_OK;
 44892  44628   }
 44893  44629   #endif /* SQLITE_MAX_MMAP_SIZE>0 */
................................................................................
 45681  45417     }
 45682  45418     pFile->lastErrno = NO_ERROR;
 45683  45419     pFile->zPath = zName;
 45684  45420   #if SQLITE_MAX_MMAP_SIZE>0
 45685  45421     pFile->hMap = NULL;
 45686  45422     pFile->pMapRegion = 0;
 45687  45423     pFile->mmapSize = 0;
        45424  +  pFile->mmapSizeActual = 0;
 45688  45425     pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
 45689  45426   #endif
 45690  45427   
 45691  45428     OpenCounter(+1);
 45692  45429     return rc;
 45693  45430   }
 45694  45431   
................................................................................
 47577  47314   **   such that p was added to the list more recently than p->pDirtyNext.
 47578  47315   **   PCache.pDirty points to the first (newest) element in the list and
 47579  47316   **   pDirtyTail to the last (oldest).
 47580  47317   **
 47581  47318   **   The PCache.pSynced variable is used to optimize searching for a dirty
 47582  47319   **   page to eject from the cache mid-transaction. It is better to eject
 47583  47320   **   a page that does not require a journal sync than one that does. 
 47584         -**   Therefore, pSynced is maintained so that it *almost* always points
        47321  +**   Therefore, pSynced is maintained to that it *almost* always points
 47585  47322   **   to either the oldest page in the pDirty/pDirtyTail list that has a
 47586  47323   **   clear PGHDR_NEED_SYNC flag or to a page that is older than this one
 47587  47324   **   (so that the right page to eject can be found by following pDirtyPrev
 47588  47325   **   pointers).
 47589  47326   */
 47590  47327   struct PCache {
 47591  47328     PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
................................................................................
 48401  48138     PgHdr *pDirty;
 48402  48139     int nDirty = 0;
 48403  48140     int nCache = numberOfCachePages(pCache);
 48404  48141     for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext) nDirty++;
 48405  48142     return nCache ? (int)(((i64)nDirty * 100) / nCache) : 0;
 48406  48143   }
 48407  48144   
 48408         -#ifdef SQLITE_DIRECT_OVERFLOW_READ
 48409         -/* 
 48410         -** Return true if there are one or more dirty pages in the cache. Else false.
 48411         -*/
 48412         -SQLITE_PRIVATE int sqlite3PCacheIsDirty(PCache *pCache){
 48413         -  return (pCache->pDirty!=0);
 48414         -}
 48415         -#endif
 48416         -
 48417  48145   #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
 48418  48146   /*
 48419  48147   ** For all dirty pages currently in the cache, invoke the specified
 48420  48148   ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
 48421  48149   ** defined.
 48422  48150   */
 48423  48151   SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
................................................................................
 48533  48261     PgHdr1 *pNext;                 /* Next in hash table chain */
 48534  48262     PCache1 *pCache;               /* Cache that currently owns this page */
 48535  48263     PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
 48536  48264     PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
 48537  48265   };
 48538  48266   
 48539  48267   /*
 48540         -** A page is pinned if it is not on the LRU list.  To be "pinned" means
 48541         -** that the page is in active use and must not be deallocated.
        48268  +** A page is pinned if it is no on the LRU list
 48542  48269   */
 48543  48270   #define PAGE_IS_PINNED(p)    ((p)->pLruNext==0)
 48544  48271   #define PAGE_IS_UNPINNED(p)  ((p)->pLruNext!=0)
 48545  48272   
 48546  48273   /* Each page cache (or PCache) belongs to a PGroup.  A PGroup is a set 
 48547  48274   ** of one or more PCaches that are able to recycle each other's unpinned
 48548  48275   ** pages when they are under memory pressure.  A PGroup is an instance of
................................................................................
 51174  50901   **
 51175  50902   ** instead of
 51176  50903   **
 51177  50904   **   if( pPager->jfd->pMethods ){ ...
 51178  50905   */
 51179  50906   #define isOpen(pFd) ((pFd)->pMethods!=0)
 51180  50907   
 51181         -#ifdef SQLITE_DIRECT_OVERFLOW_READ
 51182  50908   /*
 51183         -** Return true if page pgno can be read directly from the database file
 51184         -** by the b-tree layer. This is the case if:
 51185         -**
 51186         -**   * the database file is open,
 51187         -**   * there are no dirty pages in the cache, and
 51188         -**   * the desired page is not currently in the wal file.
        50909  +** Return true if this pager uses a write-ahead log to read page pgno.
        50910  +** Return false if the pager reads pgno directly from the database.
 51189  50911   */
 51190         -SQLITE_PRIVATE int sqlite3PagerDirectReadOk(Pager *pPager, Pgno pgno){
 51191         -  if( pPager->fd->pMethods==0 ) return 0;
 51192         -  if( sqlite3PCacheIsDirty(pPager->pPCache) ) return 0;
 51193         -#ifndef SQLITE_OMIT_WAL
 51194         -  if( pPager->pWal ){
 51195         -    u32 iRead = 0;
 51196         -    int rc;
 51197         -    rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iRead);
 51198         -    return (rc==SQLITE_OK && iRead==0);
 51199         -  }
 51200         -#endif
 51201         -  return 1;
        50912  +#if !defined(SQLITE_OMIT_WAL) && defined(SQLITE_DIRECT_OVERFLOW_READ)
        50913  +SQLITE_PRIVATE int sqlite3PagerUseWal(Pager *pPager, Pgno pgno){
        50914  +  u32 iRead = 0;
        50915  +  int rc;
        50916  +  if( pPager->pWal==0 ) return 0;
        50917  +  rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iRead);
        50918  +  return rc || iRead;
 51202  50919   }
 51203  50920   #endif
 51204         -
 51205  50921   #ifndef SQLITE_OMIT_WAL
 51206  50922   # define pagerUseWal(x) ((x)->pWal!=0)
 51207  50923   #else
 51208  50924   # define pagerUseWal(x) 0
 51209  50925   # define pagerRollbackWal(x) 0
 51210  50926   # define pagerWalFrames(v,w,x,y) 0
 51211  50927   # define pagerOpenWalIfPresent(z) SQLITE_OK
................................................................................
 57381  57097   SQLITE_PRIVATE void sqlite3PagerSetCodec(
 57382  57098     Pager *pPager,
 57383  57099     void *(*xCodec)(void*,void*,Pgno,int),
 57384  57100     void (*xCodecSizeChng)(void*,int,int),
 57385  57101     void (*xCodecFree)(void*),
 57386  57102     void *pCodec
 57387  57103   ){
 57388         -  if( pPager->xCodecFree ){
 57389         -    pPager->xCodecFree(pPager->pCodec);
 57390         -  }else{
 57391         -    pager_reset(pPager);
 57392         -  }
        57104  +  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
 57393  57105     pPager->xCodec = pPager->memDb ? 0 : xCodec;
 57394  57106     pPager->xCodecSizeChng = xCodecSizeChng;
 57395  57107     pPager->xCodecFree = xCodecFree;
 57396  57108     pPager->pCodec = pCodec;
 57397  57109     setGetterMethod(pPager);
 57398  57110     pagerReportSize(pPager);
 57399  57111   }
................................................................................
 66045  65757         pBt->usableSize = usableSize;
 66046  65758         pBt->pageSize = pageSize;
 66047  65759         freeTempSpace(pBt);
 66048  65760         rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
 66049  65761                                      pageSize-usableSize);
 66050  65762         return rc;
 66051  65763       }
 66052         -    if( sqlite3WritableSchema(pBt->db)==0 && nPage>nPageFile ){
        65764  +    if( (pBt->db->flags & SQLITE_WriteSchema)==0 && nPage>nPageFile ){
 66053  65765         rc = SQLITE_CORRUPT_BKPT;
 66054  65766         goto page1_init_failed;
 66055  65767       }
 66056  65768       /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
 66057  65769       ** be less than 480. In other words, if the page size is 512, then the
 66058  65770       ** reserved space size cannot exceed 32. */
 66059  65771       if( usableSize<480 ){
................................................................................
 66519  66231     Pager *pPager = pBt->pPager;
 66520  66232     int rc;
 66521  66233   
 66522  66234     assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || 
 66523  66235         eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
 66524  66236     assert( sqlite3_mutex_held(pBt->mutex) );
 66525  66237     assert( pDbPage->pBt==pBt );
 66526         -  if( iDbPage<3 ) return SQLITE_CORRUPT_BKPT;
 66527  66238   
 66528  66239     /* Move page iDbPage from its current location to page number iFreePage */
 66529  66240     TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", 
 66530  66241         iDbPage, iFreePage, iPtrPage, eType));
 66531  66242     rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
 66532  66243     if( rc!=SQLITE_OK ){
 66533  66244       return rc;
................................................................................
 67691  67402             rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
 67692  67403           }
 67693  67404           offset -= ovflSize;
 67694  67405         }else{
 67695  67406           /* Need to read this page properly. It contains some of the
 67696  67407           ** range of data that is being read (eOp==0) or written (eOp!=0).
 67697  67408           */
        67409  +#ifdef SQLITE_DIRECT_OVERFLOW_READ
        67410  +        sqlite3_file *fd;      /* File from which to do direct overflow read */
        67411  +#endif
 67698  67412           int a = amt;
 67699  67413           if( a + offset > ovflSize ){
 67700  67414             a = ovflSize - offset;
 67701  67415           }
 67702  67416   
 67703  67417   #ifdef SQLITE_DIRECT_OVERFLOW_READ
 67704  67418           /* If all the following are true:
 67705  67419           **
 67706  67420           **   1) this is a read operation, and 
 67707  67421           **   2) data is required from the start of this overflow page, and
 67708         -        **   3) there are no dirty pages in the page-cache
        67422  +        **   3) there is no open write-transaction, and
 67709  67423           **   4) the database is file-backed, and
 67710  67424           **   5) the page is not in the WAL file
 67711  67425           **   6) at least 4 bytes have already been read into the output buffer 
 67712  67426           **
 67713  67427           ** then data can be read directly from the database file into the
 67714  67428           ** output buffer, bypassing the page-cache altogether. This speeds
 67715  67429           ** up loading large records that span many overflow pages.
 67716  67430           */
 67717  67431           if( eOp==0                                             /* (1) */
 67718  67432            && offset==0                                          /* (2) */
 67719         -         && sqlite3PagerDirectReadOk(pBt->pPager, nextPage)    /* (3,4,5) */
        67433  +         && pBt->inTransaction==TRANS_READ                     /* (3) */
        67434  +         && (fd = sqlite3PagerFile(pBt->pPager))->pMethods     /* (4) */
        67435  +         && 0==sqlite3PagerUseWal(pBt->pPager, nextPage)       /* (5) */
 67720  67436            && &pBuf[-4]>=pBufStart                               /* (6) */
 67721  67437           ){
 67722         -          sqlite3_file *fd = sqlite3PagerFile(pBt->pPager);
 67723  67438             u8 aSave[4];
 67724  67439             u8 *aWrite = &pBuf[-4];
 67725  67440             assert( aWrite>=pBufStart );                         /* due to (6) */
 67726  67441             memcpy(aSave, aWrite, 4);
 67727  67442             rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
 67728  67443             nextPage = get4byte(aWrite);
 67729  67444             memcpy(aWrite, aSave, 4);
................................................................................
 74311  74026     */
 74312  74027     if( fg & MEM_Int ){
 74313  74028       sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
 74314  74029     }else{
 74315  74030       assert( fg & MEM_Real );
 74316  74031       sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->u.r);
 74317  74032     }
 74318         -  assert( pMem->z!=0 );
 74319         -  pMem->n = sqlite3Strlen30NN(pMem->z);
        74033  +  pMem->n = sqlite3Strlen30(pMem->z);
 74320  74034     pMem->enc = SQLITE_UTF8;
 74321  74035     pMem->flags |= MEM_Str|MEM_Term;
 74322  74036     if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real);
 74323  74037     sqlite3VdbeChangeEncoding(pMem, enc);
 74324  74038     return SQLITE_OK;
 74325  74039   }
 74326  74040   
................................................................................
 75887  75601     if( p==0 ) return;
 75888  75602     p->prepFlags = prepFlags;
 75889  75603     if( (prepFlags & SQLITE_PREPARE_SAVESQL)==0 ){
 75890  75604       p->expmask = 0;
 75891  75605     }
 75892  75606     assert( p->zSql==0 );
 75893  75607     p->zSql = sqlite3DbStrNDup(p->db, z, n);
 75894         -#ifdef SQLITE_ENABLE_NORMALIZE
 75895         -  assert( p->zNormSql==0 );
 75896         -  if( p->zSql && (prepFlags & SQLITE_PREPARE_NORMALIZE)!=0 ){
 75897         -    sqlite3Normalize(p, p->zSql, n, prepFlags);
 75898         -    assert( p->zNormSql!=0 || p->db->mallocFailed );
 75899         -  }
 75900         -#endif
 75901  75608   }
 75902  75609   
 75903  75610   /*
 75904  75611   ** Swap all content between two VDBE structures.
 75905  75612   */
 75906  75613   SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
 75907  75614     Vdbe tmp, *pTmp;
................................................................................
 75915  75622     pB->pNext = pTmp;
 75916  75623     pTmp = pA->pPrev;
 75917  75624     pA->pPrev = pB->pPrev;
 75918  75625     pB->pPrev = pTmp;
 75919  75626     zTmp = pA->zSql;
 75920  75627     pA->zSql = pB->zSql;
 75921  75628     pB->zSql = zTmp;
 75922         -#ifdef SQLITE_ENABLE_NORMALIZE
 75923         -  zTmp = pA->zNormSql;
 75924         -  pA->zNormSql = pB->zNormSql;
 75925         -  pB->zNormSql = zTmp;
 75926         -#endif
 75927  75629     pB->expmask = pA->expmask;
 75928  75630     pB->prepFlags = pA->prepFlags;
 75929  75631     memcpy(pB->aCounter, pA->aCounter, sizeof(pB->aCounter));
 75930  75632     pB->aCounter[SQLITE_STMTSTATUS_REPREPARE]++;
 75931  75633   }
 75932  75634   
 75933  75635   /*
................................................................................
 78991  78693       releaseMemArray(p->aVar, p->nVar);
 78992  78694       sqlite3DbFree(db, p->pVList);
 78993  78695       sqlite3DbFree(db, p->pFree);
 78994  78696     }
 78995  78697     vdbeFreeOpArray(db, p->aOp, p->nOp);
 78996  78698     sqlite3DbFree(db, p->aColName);
 78997  78699     sqlite3DbFree(db, p->zSql);
 78998         -#ifdef SQLITE_ENABLE_NORMALIZE
 78999         -  sqlite3DbFree(db, p->zNormSql);
 79000         -#endif
 79001  78700   #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
 79002  78701     {
 79003  78702       int i;
 79004  78703       for(i=0; i<p->nScan; i++){
 79005  78704         sqlite3DbFree(db, p->aScan[i].zName);
 79006  78705       }
 79007  78706       sqlite3DbFree(db, p->aScan);
................................................................................
 80395  80094       return rc;
 80396  80095     }
 80397  80096   
 80398  80097     /* The index entry must begin with a header size */
 80399  80098     (void)getVarint32((u8*)m.z, szHdr);
 80400  80099     testcase( szHdr==3 );
 80401  80100     testcase( szHdr==m.n );
 80402         -  testcase( szHdr>0x7fffffff );
 80403         -  assert( m.n>=0 );
 80404         -  if( unlikely(szHdr<3 || szHdr>(unsigned)m.n) ){
        80101  +  if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
 80405  80102       goto idx_rowid_corruption;
 80406  80103     }
 80407  80104   
 80408  80105     /* The last field of the index should be an integer - the ROWID.
 80409  80106     ** Verify that the last entry really is an integer. */
 80410  80107     (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
 80411  80108     testcase( typeRowid==1 );
................................................................................
 82408  82105       z = sqlite3VdbeExpandSql(p, zSql);
 82409  82106       sqlite3_mutex_leave(p->db->mutex);
 82410  82107     }
 82411  82108     return z;
 82412  82109   #endif
 82413  82110   }
 82414  82111   
 82415         -#ifdef SQLITE_ENABLE_NORMALIZE
 82416         -/*
 82417         -** Return the normalized SQL associated with a prepared statement.
 82418         -*/
 82419         -SQLITE_API const char *sqlite3_normalized_sql(sqlite3_stmt *pStmt){
 82420         -  Vdbe *p = (Vdbe *)pStmt;
 82421         -  return p ? p->zNormSql : 0;
 82422         -}
 82423         -#endif /* SQLITE_ENABLE_NORMALIZE */
 82424         -
 82425  82112   #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
 82426  82113   /*
 82427  82114   ** Allocate and populate an UnpackedRecord structure based on the serialized
 82428  82115   ** record in nKey/pKey. Return a pointer to the new UnpackedRecord structure
 82429  82116   ** if successful, or a NULL pointer if an OOM error is encountered.
 82430  82117   */
 82431  82118   static UnpackedRecord *vdbeUnpackRecord(
................................................................................
 85857  85544     }else{
 85858  85545       /* Rare case of a really large header */
 85859  85546       nVarint = sqlite3VarintLen(nHdr);
 85860  85547       nHdr += nVarint;
 85861  85548       if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
 85862  85549     }
 85863  85550     nByte = nHdr+nData;
        85551  +  if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
        85552  +    goto too_big;
        85553  +  }
 85864  85554   
 85865  85555     /* Make sure the output register has a buffer large enough to store 
 85866  85556     ** the new record. The output register (pOp->p3) is not allowed to
 85867  85557     ** be one of the input registers (because the following call to
 85868  85558     ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
 85869  85559     */
 85870         -  if( nByte+nZero<=pOut->szMalloc ){
 85871         -    /* The output register is already large enough to hold the record.
 85872         -    ** No error checks or buffer enlargement is required */
 85873         -    pOut->z = pOut->zMalloc;
 85874         -  }else{
 85875         -    /* Need to make sure that the output is not too big and then enlarge
 85876         -    ** the output register to hold the full result */
 85877         -    if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
 85878         -      goto too_big;
 85879         -    }
 85880         -    if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
 85881         -      goto no_mem;
 85882         -    }
        85560  +  if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
        85561  +    goto no_mem;
 85883  85562     }
 85884  85563     zNewRecord = (u8 *)pOut->z;
 85885  85564   
 85886  85565     /* Write the record */
 85887  85566     i = putVarint32(zNewRecord, nHdr);
 85888  85567     j = nHdr;
 85889  85568     assert( pData0<=pLast );
................................................................................
 88731  88410       db->mDbFlags |= DBFLAG_SchemaChange;
 88732  88411       p->expired = 0;
 88733  88412     }else
 88734  88413   #endif
 88735  88414     {
 88736  88415       zMaster = MASTER_NAME;
 88737  88416       initData.db = db;
 88738         -    initData.iDb = iDb;
        88417  +    initData.iDb = pOp->p1;
 88739  88418       initData.pzErrMsg = &p->zErrMsg;
 88740  88419       initData.mInitFlags = 0;
 88741  88420       zSql = sqlite3MPrintf(db,
 88742  88421          "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
 88743  88422          db->aDb[iDb].zDbSName, zMaster, pOp->p4.z);
 88744  88423       if( zSql==0 ){
 88745  88424         rc = SQLITE_NOMEM_BKPT;
................................................................................
 89928  89607   ** Synopsis: r[P3]=vcolumn(P2)
 89929  89608   **
 89930  89609   ** Store in register P3 the value of the P2-th column of
 89931  89610   ** the current row of the virtual-table of cursor P1.
 89932  89611   **
 89933  89612   ** If the VColumn opcode is being used to fetch the value of
 89934  89613   ** an unchanging column during an UPDATE operation, then the P5
 89935         -** value is OPFLAG_NOCHNG.  This will cause the sqlite3_vtab_nochange()
 89936         -** function to return true inside the xColumn method of the virtual
 89937         -** table implementation.  The P5 column might also contain other
 89938         -** bits (OPFLAG_LENGTHARG or OPFLAG_TYPEOFARG) but those bits are
 89939         -** unused by OP_VColumn.
        89614  +** value is 1.  Otherwise, P5 is 0.  The P5 value is returned
        89615  +** by sqlite3_vtab_nochange() routine and can be used
        89616  +** by virtual table implementations to return special "no-change"
        89617  +** marks which can be more efficient, depending on the virtual table.
 89940  89618   */
 89941  89619   case OP_VColumn: {
 89942  89620     sqlite3_vtab *pVtab;
 89943  89621     const sqlite3_module *pModule;
 89944  89622     Mem *pDest;
 89945  89623     sqlite3_context sContext;
 89946  89624   
................................................................................
 89954  89632       break;
 89955  89633     }
 89956  89634     pVtab = pCur->uc.pVCur->pVtab;
 89957  89635     pModule = pVtab->pModule;
 89958  89636     assert( pModule->xColumn );
 89959  89637     memset(&sContext, 0, sizeof(sContext));
 89960  89638     sContext.pOut = pDest;
 89961         -  testcase( (pOp->p5 & OPFLAG_NOCHNG)==0 && pOp->p5!=0 );
 89962         -  if( pOp->p5 & OPFLAG_NOCHNG ){
        89639  +  if( pOp->p5 ){
 89963  89640       sqlite3VdbeMemSetNull(pDest);
 89964  89641       pDest->flags = MEM_Null|MEM_Zero;
 89965  89642       pDest->u.nZero = 0;
 89966  89643     }else{
 89967  89644       MemSetTypeFlag(pDest, MEM_Null);
 89968  89645     }
 89969  89646     rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2);
................................................................................
 90032  89709   ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
 90033  89710   ** This opcode invokes the corresponding xRename method. The value
 90034  89711   ** in register P1 is passed as the zName argument to the xRename method.
 90035  89712   */
 90036  89713   case OP_VRename: {
 90037  89714     sqlite3_vtab *pVtab;
 90038  89715     Mem *pName;
 90039         -  int isLegacy;
 90040         -  
 90041         -  isLegacy = (db->flags & SQLITE_LegacyAlter);
 90042         -  db->flags |= SQLITE_LegacyAlter;
        89716  +
 90043  89717     pVtab = pOp->p4.pVtab->pVtab;
 90044  89718     pName = &aMem[pOp->p1];
 90045  89719     assert( pVtab->pModule->xRename );
 90046  89720     assert( memIsValid(pName) );
 90047  89721     assert( p->readOnly==0 );
 90048  89722     REGISTER_TRACE(pOp->p1, pName);
 90049  89723     assert( pName->flags & MEM_Str );
 90050  89724     testcase( pName->enc==SQLITE_UTF8 );
 90051  89725     testcase( pName->enc==SQLITE_UTF16BE );
 90052  89726     testcase( pName->enc==SQLITE_UTF16LE );
 90053  89727     rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
 90054  89728     if( rc ) goto abort_due_to_error;
 90055  89729     rc = pVtab->pModule->xRename(pVtab, pName->z);
 90056         -  if( isLegacy==0 ) db->flags &= ~SQLITE_LegacyAlter;
 90057  89730     sqlite3VtabImportErrmsg(p, pVtab);
 90058  89731     p->expired = 0;
 90059  89732     if( rc ) goto abort_due_to_error;
 90060  89733     break;
 90061  89734   }
 90062  89735   #endif
 90063  89736   
................................................................................
 94314  93987           continue;
 94315  93988         }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
 94316  93989           if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
 94317  93990         }else if( pExpr->x.pList ){
 94318  93991           if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
 94319  93992         }
 94320  93993   #ifndef SQLITE_OMIT_WINDOWFUNC
 94321         -      if( ExprHasProperty(pExpr, EP_WinFunc) ){
 94322         -        Window *pWin = pExpr->y.pWin;
        93994  +      if( !ExprHasProperty(pExpr, EP_Reduced) && pExpr->pWin ){
        93995  +        Window *pWin = pExpr->pWin;
 94323  93996           if( sqlite3WalkExprList(pWalker, pWin->pPartition) ) return WRC_Abort;
 94324  93997           if( sqlite3WalkExprList(pWalker, pWin->pOrderBy) ) return WRC_Abort;
 94325  93998           if( sqlite3WalkExpr(pWalker, pWin->pFilter) ) return WRC_Abort;
 94326  93999         }
 94327  94000   #endif
 94328  94001       }
 94329  94002       break;
................................................................................
 94588  94261   ** expression node refer back to that source column.  The following changes
 94589  94262   ** are made to pExpr:
 94590  94263   **
 94591  94264   **    pExpr->iDb           Set the index in db->aDb[] of the database X
 94592  94265   **                         (even if X is implied).
 94593  94266   **    pExpr->iTable        Set to the cursor number for the table obtained
 94594  94267   **                         from pSrcList.
 94595         -**    pExpr->y.pTab        Points to the Table structure of X.Y (even if
        94268  +**    pExpr->pTab          Points to the Table structure of X.Y (even if
 94596  94269   **                         X and/or Y are implied.)
 94597  94270   **    pExpr->iColumn       Set to the column number within the table.
 94598  94271   **    pExpr->op            Set to TK_COLUMN.
 94599  94272   **    pExpr->pLeft         Any expression this points to is deleted
 94600  94273   **    pExpr->pRight        Any expression this points to is deleted.
 94601  94274   **
 94602  94275   ** The zDb variable is the name of the database (the "X").  This value may be
................................................................................
 94632  94305   
 94633  94306     assert( pNC );     /* the name context cannot be NULL. */
 94634  94307     assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
 94635  94308     assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
 94636  94309   
 94637  94310     /* Initialize the node to no-match */
 94638  94311     pExpr->iTable = -1;
        94312  +  pExpr->pTab = 0;
 94639  94313     ExprSetVVAProperty(pExpr, EP_NoReduce);
 94640  94314   
 94641  94315     /* Translate the schema name in zDb into a pointer to the corresponding
 94642  94316     ** schema.  If not found, pSchema will remain NULL and nothing will match
 94643  94317     ** resulting in an appropriate error message toward the end of this routine
 94644  94318     */
 94645  94319     if( zDb ){
................................................................................
 94693  94367           if( zTab ){
 94694  94368             const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
 94695  94369             assert( zTabName!=0 );
 94696  94370             if( sqlite3StrICmp(zTabName, zTab)!=0 ){
 94697  94371               continue;
 94698  94372             }
 94699  94373             if( IN_RENAME_OBJECT && pItem->zAlias ){
 94700         -            sqlite3RenameTokenRemap(pParse, 0, (void*)&pExpr->y.pTab);
        94374  +            sqlite3RenameTokenRemap(pParse, 0, (void*)&pExpr->pTab);
 94701  94375             }
 94702  94376           }
 94703  94377           if( 0==(cntTab++) ){
 94704  94378             pMatch = pItem;
 94705  94379           }
 94706  94380           for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
 94707  94381             if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
................................................................................
 94719  94393               pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
 94720  94394               break;
 94721  94395             }
 94722  94396           }
 94723  94397         }
 94724  94398         if( pMatch ){
 94725  94399           pExpr->iTable = pMatch->iCursor;
 94726         -        pExpr->y.pTab = pMatch->pTab;
        94400  +        pExpr->pTab = pMatch->pTab;
 94727  94401           /* RIGHT JOIN not (yet) supported */
 94728  94402           assert( (pMatch->fg.jointype & JT_RIGHT)==0 );
 94729  94403           if( (pMatch->fg.jointype & JT_LEFT)!=0 ){
 94730  94404             ExprSetProperty(pExpr, EP_CanBeNull);
 94731  94405           }
 94732         -        pSchema = pExpr->y.pTab->pSchema;
        94406  +        pSchema = pExpr->pTab->pSchema;
 94733  94407         }
 94734  94408       } /* if( pSrcList ) */
 94735  94409   
 94736  94410   #if !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT)
 94737  94411       /* If we have not already resolved the name, then maybe 
 94738  94412       ** it is a new.* or old.* trigger argument reference.  Or
 94739  94413       ** maybe it is an excluded.* from an upsert.
................................................................................
 94782  94456           if( iCol<pTab->nCol ){
 94783  94457             cnt++;
 94784  94458   #ifndef SQLITE_OMIT_UPSERT
 94785  94459             if( pExpr->iTable==2 ){
 94786  94460               testcase( iCol==(-1) );
 94787  94461               if( IN_RENAME_OBJECT ){
 94788  94462                 pExpr->iColumn = iCol;
 94789         -              pExpr->y.pTab = pTab;
        94463  +              pExpr->pTab = pTab;
 94790  94464                 eNewExprOp = TK_COLUMN;
 94791  94465               }else{
 94792  94466                 pExpr->iTable = pNC->uNC.pUpsert->regData + iCol;
 94793  94467                 eNewExprOp = TK_REGISTER;
 94794  94468                 ExprSetProperty(pExpr, EP_Alias);
 94795  94469               }
 94796  94470             }else
................................................................................
 94804  94478                 testcase( iCol==32 );
 94805  94479                 pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
 94806  94480               }else{
 94807  94481                 testcase( iCol==31 );
 94808  94482                 testcase( iCol==32 );
 94809  94483                 pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
 94810  94484               }
 94811         -            pExpr->y.pTab = pTab;
        94485  +            pExpr->pTab = pTab;
 94812  94486               pExpr->iColumn = (i16)iCol;
 94813  94487               eNewExprOp = TK_TRIGGER;
 94814  94488   #endif /* SQLITE_OMIT_TRIGGER */
 94815  94489             }
 94816  94490           }
 94817  94491         }
 94818  94492       }
................................................................................
 94904  94578     ** Because no reference was made to outer contexts, the pNC->nRef
 94905  94579     ** fields are not changed in any context.
 94906  94580     */
 94907  94581     if( cnt==0 && zTab==0 ){
 94908  94582       assert( pExpr->op==TK_ID );
 94909  94583       if( ExprHasProperty(pExpr,EP_DblQuoted) ){
 94910  94584         pExpr->op = TK_STRING;
 94911         -      pExpr->y.pTab = 0;
        94585  +      pExpr->pTab = 0;
 94912  94586         return WRC_Prune;
 94913  94587       }
 94914  94588       if( sqlite3ExprIdToTrueFalse(pExpr) ){
 94915  94589         return WRC_Prune;
 94916  94590       }
 94917  94591     }
 94918  94592   
................................................................................
 94982  94656   ** Allocate and return a pointer to an expression to load the column iCol
 94983  94657   ** from datasource iSrc in SrcList pSrc.
 94984  94658   */
 94985  94659   SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
 94986  94660     Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
 94987  94661     if( p ){
 94988  94662       struct SrcList_item *pItem = &pSrc->a[iSrc];
 94989         -    p->y.pTab = pItem->pTab;
        94663  +    p->pTab = pItem->pTab;
 94990  94664       p->iTable = pItem->iCursor;
 94991         -    if( p->y.pTab->iPKey==iCol ){
        94665  +    if( p->pTab->iPKey==iCol ){
 94992  94666         p->iColumn = -1;
 94993  94667       }else{
 94994  94668         p->iColumn = (ynVar)iCol;
 94995  94669         testcase( iCol==BMS );
 94996  94670         testcase( iCol==BMS-1 );
 94997  94671         pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
 94998  94672       }
................................................................................
 95074  94748       case TK_ROW: {
 95075  94749         SrcList *pSrcList = pNC->pSrcList;
 95076  94750         struct SrcList_item *pItem;
 95077  94751         assert( pSrcList && pSrcList->nSrc==1 );
 95078  94752         pItem = pSrcList->a;
 95079  94753         assert( HasRowid(pItem->pTab) && pItem->pTab->pSelect==0 );
 95080  94754         pExpr->op = TK_COLUMN;
 95081         -      pExpr->y.pTab = pItem->pTab;
        94755  +      pExpr->pTab = pItem->pTab;
 95082  94756         pExpr->iTable = pItem->iCursor;
 95083  94757         pExpr->iColumn = -1;
 95084  94758         pExpr->affinity = SQLITE_AFF_INTEGER;
 95085  94759         break;
 95086  94760       }
 95087  94761   #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
 95088  94762             && !defined(SQLITE_OMIT_SUBQUERY) */
................................................................................
 95118  94792             pLeft = pRight->pLeft;
 95119  94793             pRight = pRight->pRight;
 95120  94794           }
 95121  94795           zTable = pLeft->u.zToken;
 95122  94796           zColumn = pRight->u.zToken;
 95123  94797           if( IN_RENAME_OBJECT ){
 95124  94798             sqlite3RenameTokenRemap(pParse, (void*)pExpr, (void*)pRight);
 95125         -          sqlite3RenameTokenRemap(pParse, (void*)&pExpr->y.pTab, (void*)pLeft);
        94799  +        }
        94800  +        if( IN_RENAME_OBJECT ){
        94801  +          sqlite3RenameTokenRemap(pParse, (void*)&pExpr->pTab, (void*)pLeft);
 95126  94802           }
 95127  94803         }
 95128  94804         return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
 95129  94805       }
 95130  94806   
 95131  94807       /* Resolve function names
 95132  94808       */
................................................................................
 95200  94876           if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){
 95201  94877             /* Date/time functions that use 'now', and other functions like
 95202  94878             ** sqlite_version() that might change over time cannot be used
 95203  94879             ** in an index. */
 95204  94880             notValid(pParse, pNC, "non-deterministic functions",
 95205  94881                      NC_IdxExpr|NC_PartIdx);
 95206  94882           }
 95207         -        if( (pDef->funcFlags & SQLITE_FUNC_INTERNAL)!=0
 95208         -         && pParse->nested==0
 95209         -         && sqlite3Config.bInternalFunctions==0
 95210         -        ){
 95211         -          /* Internal-use-only functions are disallowed unless the
 95212         -          ** SQL is being compiled using sqlite3NestedParse() */
 95213         -          no_such_func = 1;
 95214         -          pDef = 0;
 95215         -        }
 95216  94883         }
 95217  94884   
 95218  94885         if( 0==IN_RENAME_OBJECT ){
 95219  94886   #ifndef SQLITE_OMIT_WINDOWFUNC
 95220  94887           assert( is_agg==0 || (pDef->funcFlags & SQLITE_FUNC_MINMAX)
 95221  94888             || (pDef->xValue==0 && pDef->xInverse==0)
 95222  94889             || (pDef->xValue && pDef->xInverse && pDef->xSFunc && pDef->xFinalize)
 95223  94890           );
 95224         -        if( pDef && pDef->xValue==0 && ExprHasProperty(pExpr, EP_WinFunc) ){
        94891  +        if( pDef && pDef->xValue==0 && pExpr->pWin ){
 95225  94892             sqlite3ErrorMsg(pParse, 
 95226  94893                 "%.*s() may not be used as a window function", nId, zId
 95227  94894             );
 95228  94895             pNC->nErr++;
 95229  94896           }else if( 
 95230  94897                 (is_agg && (pNC->ncFlags & NC_AllowAgg)==0)
 95231         -           || (is_agg && (pDef->funcFlags&SQLITE_FUNC_WINDOW) && !pExpr->y.pWin)
 95232         -           || (is_agg && pExpr->y.pWin && (pNC->ncFlags & NC_AllowWin)==0)
        94898  +           || (is_agg && (pDef->funcFlags & SQLITE_FUNC_WINDOW) && !pExpr->pWin)
        94899  +           || (is_agg && pExpr->pWin && (pNC->ncFlags & NC_AllowWin)==0)
 95233  94900           ){
 95234  94901             const char *zType;
 95235         -          if( (pDef->funcFlags & SQLITE_FUNC_WINDOW) || pExpr->y.pWin ){
        94902  +          if( (pDef->funcFlags & SQLITE_FUNC_WINDOW) || pExpr->pWin ){
 95236  94903               zType = "window";
 95237  94904             }else{
 95238  94905               zType = "aggregate";
 95239  94906             }
 95240  94907             sqlite3ErrorMsg(pParse, "misuse of %s function %.*s()",zType,nId,zId);
 95241  94908             pNC->nErr++;
 95242  94909             is_agg = 0;
................................................................................
 95258  94925           }else if( wrong_num_args ){
 95259  94926             sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
 95260  94927                  nId, zId);
 95261  94928             pNC->nErr++;
 95262  94929           }
 95263  94930           if( is_agg ){
 95264  94931   #ifndef SQLITE_OMIT_WINDOWFUNC
 95265         -          pNC->ncFlags &= ~(pExpr->y.pWin ? NC_AllowWin : NC_AllowAgg);
        94932  +          pNC->ncFlags &= ~(pExpr->pWin ? NC_AllowWin : NC_AllowAgg);
 95266  94933   #else
 95267  94934             pNC->ncFlags &= ~NC_AllowAgg;
 95268  94935   #endif
 95269  94936           }
 95270  94937         }
 95271  94938         sqlite3WalkExprList(pWalker, pList);
 95272  94939         if( is_agg ){
 95273  94940   #ifndef SQLITE_OMIT_WINDOWFUNC
 95274         -        if( pExpr->y.pWin ){
        94941  +        if( pExpr->pWin ){
 95275  94942             Select *pSel = pNC->pWinSelect;
 95276         -          sqlite3WalkExprList(pWalker, pExpr->y.pWin->pPartition);
 95277         -          sqlite3WalkExprList(pWalker, pExpr->y.pWin->pOrderBy);
 95278         -          sqlite3WalkExpr(pWalker, pExpr->y.pWin->pFilter);
 95279         -          sqlite3WindowUpdate(pParse, pSel->pWinDefn, pExpr->y.pWin, pDef);
        94943  +          sqlite3WalkExprList(pWalker, pExpr->pWin->pPartition);
        94944  +          sqlite3WalkExprList(pWalker, pExpr->pWin->pOrderBy);
        94945  +          sqlite3WalkExpr(pWalker, pExpr->pWin->pFilter);
        94946  +          sqlite3WindowUpdate(pParse, pSel->pWinDefn, pExpr->pWin, pDef);
 95280  94947             if( 0==pSel->pWin 
 95281         -           || 0==sqlite3WindowCompare(pParse, pSel->pWin, pExpr->y.pWin) 
        94948  +           || 0==sqlite3WindowCompare(pParse, pSel->pWin, pExpr->pWin) 
 95282  94949             ){
 95283         -            pExpr->y.pWin->pNextWin = pSel->pWin;
 95284         -            pSel->pWin = pExpr->y.pWin;
        94950  +            pExpr->pWin->pNextWin = pSel->pWin;
        94951  +            pSel->pWin = pExpr->pWin;
 95285  94952             }
 95286  94953             pNC->ncFlags |= NC_AllowWin;
 95287  94954           }else
 95288  94955   #endif /* SQLITE_OMIT_WINDOWFUNC */
 95289  94956           {
 95290  94957             NameContext *pNC2 = pNC;
 95291  94958             pExpr->op = TK_AGG_FUNCTION;
................................................................................
 95700  95367       pItem->u.x.iOrderByCol = 0;
 95701  95368       if( sqlite3ResolveExprNames(pNC, pE) ){
 95702  95369         return 1;
 95703  95370       }
 95704  95371       for(j=0; j<pSelect->pEList->nExpr; j++){
 95705  95372         if( sqlite3ExprCompare(0, pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
 95706  95373   #ifndef SQLITE_OMIT_WINDOWFUNC
 95707         -        if( ExprHasProperty(pE, EP_WinFunc) ){
        95374  +        if( pE->pWin ){
 95708  95375             /* Since this window function is being changed into a reference
 95709  95376             ** to the same window function the result set, remove the instance
 95710  95377             ** of this window function from the Select.pWin list. */
 95711  95378             Window **pp;
 95712  95379             for(pp=&pSelect->pWin; *pp; pp=&(*pp)->pNextWin){
 95713         -            if( *pp==pE->y.pWin ){
        95380  +            if( *pp==pE->pWin ){
 95714  95381                 *pp = (*pp)->pNextWin;
 95715  95382               }    
 95716  95383             }
 95717  95384           }
 95718  95385   #endif
 95719  95386           pItem->u.x.iOrderByCol = j+1;
 95720  95387         }
................................................................................
 96169  95836     if( op==TK_REGISTER ) op = pExpr->op2;
 96170  95837   #ifndef SQLITE_OMIT_CAST
 96171  95838     if( op==TK_CAST ){
 96172  95839       assert( !ExprHasProperty(pExpr, EP_IntValue) );
 96173  95840       return sqlite3AffinityType(pExpr->u.zToken, 0);
 96174  95841     }
 96175  95842   #endif
 96176         -  if( (op==TK_AGG_COLUMN || op==TK_COLUMN) && pExpr->y.pTab ){
 96177         -    return sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
        95843  +  if( (op==TK_AGG_COLUMN || op==TK_COLUMN) && pExpr->pTab ){
        95844  +    return sqlite3TableColumnAffinity(pExpr->pTab, pExpr->iColumn);
 96178  95845     }
 96179  95846     if( op==TK_SELECT_COLUMN ){
 96180  95847       assert( pExpr->pLeft->flags&EP_xIsSelect );
 96181  95848       return sqlite3ExprAffinity(
 96182  95849           pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr
 96183  95850       );
 96184  95851     }
................................................................................
 96254  95921     CollSeq *pColl = 0;
 96255  95922     Expr *p = pExpr;
 96256  95923     while( p ){
 96257  95924       int op = p->op;
 96258  95925       if( p->flags & EP_Generic ) break;
 96259  95926       if( (op==TK_AGG_COLUMN || op==TK_COLUMN
 96260  95927             || op==TK_REGISTER || op==TK_TRIGGER)
 96261         -     && p->y.pTab!=0
        95928  +     && p->pTab!=0
 96262  95929       ){
 96263         -      /* op==TK_REGISTER && p->y.pTab!=0 happens when pExpr was originally
        95930  +      /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
 96264  95931         ** a TK_COLUMN but was previously evaluated and cached in a register */
 96265  95932         int j = p->iColumn;
 96266  95933         if( j>=0 ){
 96267         -        const char *zColl = p->y.pTab->aCol[j].zColl;
        95934  +        const char *zColl = p->pTab->aCol[j].zColl;
 96268  95935           pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
 96269  95936         }
 96270  95937         break;
 96271  95938       }
 96272  95939       if( op==TK_CAST || op==TK_UPLUS ){
 96273  95940         p = p->pLeft;
 96274  95941         continue;
................................................................................
 97163  96830   /*
 97164  96831   ** Recursively delete an expression tree.
 97165  96832   */
 97166  96833   static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
 97167  96834     assert( p!=0 );
 97168  96835     /* Sanity check: Assert that the IntValue is non-negative if it exists */
 97169  96836     assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
 97170         -
 97171         -  assert( !ExprHasProperty(p, EP_WinFunc) || p->y.pWin!=0 || db->mallocFailed );
 97172         -  assert( p->op!=TK_FUNCTION || ExprHasProperty(p, EP_TokenOnly|EP_Reduced)
 97173         -          || p->y.pWin==0 || ExprHasProperty(p, EP_WinFunc) );
 97174  96837   #ifdef SQLITE_DEBUG
 97175  96838     if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){
 97176  96839       assert( p->pLeft==0 );
 97177  96840       assert( p->pRight==0 );
 97178  96841       assert( p->x.pSelect==0 );
 97179  96842     }
 97180  96843   #endif
................................................................................
 97185  96848       if( p->pRight ){
 97186  96849         sqlite3ExprDeleteNN(db, p->pRight);
 97187  96850       }else if( ExprHasProperty(p, EP_xIsSelect) ){
 97188  96851         sqlite3SelectDelete(db, p->x.pSelect);
 97189  96852       }else{
 97190  96853         sqlite3ExprListDelete(db, p->x.pList);
 97191  96854       }
 97192         -    if( ExprHasProperty(p, EP_WinFunc) ){
 97193         -      assert( p->op==TK_FUNCTION );
 97194         -      sqlite3WindowDelete(db, p->y.pWin);
        96855  +    if( !ExprHasProperty(p, EP_Reduced) ){
        96856  +      sqlite3WindowDelete(db, p->pWin);
 97195  96857       }
 97196  96858     }
 97197  96859     if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
 97198  96860     if( !ExprHasProperty(p, EP_Static) ){
 97199  96861       sqlite3DbFreeNN(db, p);
 97200  96862     }
 97201  96863   }
................................................................................
 97251  96913   static int dupedExprStructSize(Expr *p, int flags){
 97252  96914     int nSize;
 97253  96915     assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
 97254  96916     assert( EXPR_FULLSIZE<=0xfff );
 97255  96917     assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
 97256  96918     if( 0==flags || p->op==TK_SELECT_COLUMN 
 97257  96919   #ifndef SQLITE_OMIT_WINDOWFUNC
 97258         -   || ExprHasProperty(p, EP_WinFunc)
        96920  +   || p->pWin 
 97259  96921   #endif
 97260  96922     ){
 97261  96923       nSize = EXPR_FULLSIZE;
 97262  96924     }else{
 97263  96925       assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
 97264  96926       assert( !ExprHasProperty(p, EP_FromJoin) ); 
 97265  96927       assert( !ExprHasProperty(p, EP_MemToken) );
................................................................................
 97278  96940   ** This function returns the space in bytes required to store the copy 
 97279  96941   ** of the Expr structure and a copy of the Expr.u.zToken string (if that
 97280  96942   ** string is defined.)
 97281  96943   */
 97282  96944   static int dupedExprNodeSize(Expr *p, int flags){
 97283  96945     int nByte = dupedExprStructSize(p, flags) & 0xfff;
 97284  96946     if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
 97285         -    nByte += sqlite3Strlen30NN(p->u.zToken)+1;
        96947  +    nByte += sqlite3Strlen30(p->u.zToken)+1;
 97286  96948     }
 97287  96949     return ROUND8(nByte);
 97288  96950   }
 97289  96951   
 97290  96952   /*
 97291  96953   ** Return the number of bytes required to create a duplicate of the 
 97292  96954   ** expression passed as the first argument. The second argument is a
................................................................................
 97381  97043           pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
 97382  97044         }else{
 97383  97045           pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
 97384  97046         }
 97385  97047       }
 97386  97048   
 97387  97049       /* Fill in pNew->pLeft and pNew->pRight. */
 97388         -    if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly|EP_WinFunc) ){
        97050  +    if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
 97389  97051         zAlloc += dupedExprNodeSize(p, dupFlags);
 97390  97052         if( !ExprHasProperty(pNew, EP_TokenOnly|EP_Leaf) ){
 97391  97053           pNew->pLeft = p->pLeft ?
 97392  97054                         exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
 97393  97055           pNew->pRight = p->pRight ?
 97394  97056                          exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0;
 97395  97057         }
 97396         -#ifndef SQLITE_OMIT_WINDOWFUNC
 97397         -      if( ExprHasProperty(p, EP_WinFunc) ){
 97398         -        pNew->y.pWin = sqlite3WindowDup(db, pNew, p->y.pWin);
 97399         -        assert( ExprHasProperty(pNew, EP_WinFunc) );
 97400         -      }
 97401         -#endif /* SQLITE_OMIT_WINDOWFUNC */
 97402  97058         if( pzBuffer ){
 97403  97059           *pzBuffer = zAlloc;
 97404  97060         }
 97405  97061       }else{
        97062  +#ifndef SQLITE_OMIT_WINDOWFUNC
        97063  +      if( ExprHasProperty(p, EP_Reduced|EP_TokenOnly) ){
        97064  +        pNew->pWin = 0;
        97065  +      }else{
        97066  +        pNew->pWin = sqlite3WindowDup(db, pNew, p->pWin);
        97067  +      }
        97068  +#endif /* SQLITE_OMIT_WINDOWFUNC */
 97406  97069         if( !ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
 97407  97070           if( pNew->op==TK_SELECT_COLUMN ){
 97408  97071             pNew->pLeft = p->pLeft;
 97409  97072             assert( p->iColumn==0 || p->pRight==0 );
 97410  97073             assert( p->pRight==0  || p->pRight==p->pLeft );
 97411  97074           }else{
 97412  97075             pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
................................................................................
 98204  97867       case TK_INTEGER:
 98205  97868       case TK_STRING:
 98206  97869       case TK_FLOAT:
 98207  97870       case TK_BLOB:
 98208  97871         return 0;
 98209  97872       case TK_COLUMN:
 98210  97873         return ExprHasProperty(p, EP_CanBeNull) ||
 98211         -             p->y.pTab==0 ||  /* Reference to column of index on expression */
 98212         -             (p->iColumn>=0 && p->y.pTab->aCol[p->iColumn].notNull==0);
        97874  +             p->pTab==0 ||  /* Reference to column of index on expression */
        97875  +             (p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0);
 98213  97876       default:
 98214  97877         return 1;
 98215  97878     }
 98216  97879   }
 98217  97880   
 98218  97881   /*
 98219  97882   ** Return TRUE if the given expression is a constant which would be
................................................................................
 98260  97923   */
 98261  97924   SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
 98262  97925     if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
 98263  97926     if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
 98264  97927     if( sqlite3StrICmp(z, "OID")==0 ) return 1;
 98265  97928     return 0;
 98266  97929   }
 98267         -#ifdef SQLITE_ENABLE_NORMALIZE
 98268         -SQLITE_PRIVATE int sqlite3IsRowidN(const char *z, int n){
 98269         -  if( sqlite3StrNICmp(z, "_ROWID_", n)==0 ) return 1;
 98270         -  if( sqlite3StrNICmp(z, "ROWID", n)==0 ) return 1;
 98271         -  if( sqlite3StrNICmp(z, "OID", n)==0 ) return 1;
 98272         -  return 0;
 98273         -}
 98274         -#endif
 98275  97930   
 98276  97931   /*
 98277  97932   ** pX is the RHS of an IN operator.  If pX is a SELECT statement 
 98278  97933   ** that can be simplified to a direct table access, then return
 98279  97934   ** a pointer to the SELECT statement.  If pX is not a SELECT statement,
 98280  97935   ** or if the SELECT statement needs to be manifested into a transient
 98281  97936   ** table, then return NULL.
................................................................................
 99501  99156           /* This COLUMN expression is really a constant due to WHERE clause
 99502  99157           ** constraints, and that constant is coded by the pExpr->pLeft
 99503  99158           ** expresssion.  However, make sure the constant has the correct
 99504  99159           ** datatype by applying the Affinity of the table column to the
 99505  99160           ** constant.
 99506  99161           */
 99507  99162           int iReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft,target);
 99508         -        int aff = sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
        99163  +        int aff = sqlite3TableColumnAffinity(pExpr->pTab, pExpr->iColumn);
 99509  99164           if( aff!=SQLITE_AFF_BLOB ){
 99510  99165             static const char zAff[] = "B\000C\000D\000E";
 99511  99166             assert( SQLITE_AFF_BLOB=='A' );
 99512  99167             assert( SQLITE_AFF_TEXT=='B' );
 99513  99168             if( iReg!=target ){
 99514  99169               sqlite3VdbeAddOp2(v, OP_SCopy, iReg, target);
 99515  99170               iReg = target;
................................................................................
 99525  99180             return pExpr->iColumn - pParse->iSelfTab;
 99526  99181           }else{
 99527  99182             /* Coding an expression that is part of an index where column names
 99528  99183             ** in the index refer to the table to which the index belongs */
 99529  99184             iTab = pParse->iSelfTab - 1;
 99530  99185           }
 99531  99186         }
 99532         -      return sqlite3ExprCodeGetColumn(pParse, pExpr->y.pTab,
        99187  +      return sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
 99533  99188                                  pExpr->iColumn, iTab, target,
 99534  99189                                  pExpr->op2);
 99535  99190       }
 99536  99191       case TK_INTEGER: {
 99537  99192         codeInteger(pParse, pExpr, 0, target);
 99538  99193         return target;
 99539  99194       }
................................................................................
 99739  99394         u32 constMask = 0;     /* Mask of function arguments that are constant */
 99740  99395         int i;                 /* Loop counter */
 99741  99396         sqlite3 *db = pParse->db;  /* The database connection */
 99742  99397         u8 enc = ENC(db);      /* The text encoding used by this database */
 99743  99398         CollSeq *pColl = 0;    /* A collating sequence */
 99744  99399   
 99745  99400   #ifndef SQLITE_OMIT_WINDOWFUNC
 99746         -      if( ExprHasProperty(pExpr, EP_WinFunc) ){
 99747         -        return pExpr->y.pWin->regResult;
        99401  +      if( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) && pExpr->pWin ){
        99402  +        return pExpr->pWin->regResult;
 99748  99403         }
 99749  99404   #endif
 99750  99405   
 99751  99406         if( ConstFactorOk(pParse) && sqlite3ExprIsConstantNotJoin(pExpr) ){
 99752  99407           /* SQL functions can be expensive. So try to move constant functions
 99753  99408           ** out of the inner loop, even if that means an extra OP_Copy. */
 99754  99409           return sqlite3ExprCodeAtInit(pParse, pExpr, -1);
................................................................................
 99983  99638         **
 99984  99639         ** Then p1 is interpreted as follows:
 99985  99640         **
 99986  99641         **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
 99987  99642         **   p1==1   ->    old.a         p1==4   ->    new.a
 99988  99643         **   p1==2   ->    old.b         p1==5   ->    new.b       
 99989  99644         */
 99990         -      Table *pTab = pExpr->y.pTab;
        99645  +      Table *pTab = pExpr->pTab;
 99991  99646         int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
 99992  99647   
 99993  99648         assert( pExpr->iTable==0 || pExpr->iTable==1 );
 99994  99649         assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
 99995  99650         assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
 99996  99651         assert( p1>=0 && p1<(pTab->nCol*2+2) );
 99997  99652   
 99998  99653         sqlite3VdbeAddOp2(v, OP_Param, p1, target);
 99999  99654         VdbeComment((v, "r[%d]=%s.%s", target,
100000  99655           (pExpr->iTable ? "new" : "old"),
100001         -        (pExpr->iColumn<0 ? "rowid" : pExpr->y.pTab->aCol[pExpr->iColumn].zName)
        99656  +        (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName)
100002  99657         ));
100003  99658   
100004  99659   #ifndef SQLITE_OMIT_FLOATING_POINT
100005  99660         /* If the column has REAL affinity, it may currently be stored as an
100006  99661         ** integer. Use OP_RealAffinity to make sure it is really real.
100007  99662         **
100008  99663         ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
................................................................................
100845 100500         return 1;
100846 100501       }
100847 100502       return 2;
100848 100503     }
100849 100504     if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
100850 100505       if( pA->op==TK_FUNCTION ){
100851 100506         if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
100852         -#ifndef SQLITE_OMIT_WINDOWFUNC
100853         -      /* Justification for the assert():
100854         -      ** window functions have p->op==TK_FUNCTION but aggregate functions
100855         -      ** have p->op==TK_AGG_FUNCTION.  So any comparison between an aggregate
100856         -      ** function and a window function should have failed before reaching
100857         -      ** this point.  And, it is not possible to have a window function and
100858         -      ** a scalar function with the same name and number of arguments.  So
100859         -      ** if we reach this point, either A and B both window functions or
100860         -      ** neither are a window functions. */
100861         -      assert( ExprHasProperty(pA,EP_WinFunc)==ExprHasProperty(pB,EP_WinFunc) );
100862         -      if( ExprHasProperty(pA,EP_WinFunc) ){
100863         -        if( sqlite3WindowCompare(pParse,pA->y.pWin,pB->y.pWin)!=0 ) return 2;
100864         -      }
100865         -#endif
100866 100507       }else if( pA->op==TK_COLLATE ){
100867 100508         if( sqlite3_stricmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
100868 100509       }else if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
100869 100510         return 2;
100870 100511       }
100871 100512     }
100872 100513     if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
................................................................................
100878 100519       if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
100879 100520       assert( (combinedFlags & EP_Reduced)==0 );
100880 100521       if( pA->op!=TK_STRING && pA->op!=TK_TRUEFALSE ){
100881 100522         if( pA->iColumn!=pB->iColumn ) return 2;
100882 100523         if( pA->iTable!=pB->iTable 
100883 100524          && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
100884 100525       }
       100526  +#ifndef SQLITE_OMIT_WINDOWFUNC
       100527  +    /* Justification for the assert():
       100528  +    ** window functions have p->op==TK_FUNCTION but aggregate functions
       100529  +    ** have p->op==TK_AGG_FUNCTION.  So any comparison between an aggregate
       100530  +    ** function and a window function should have failed before reaching
       100531  +    ** this point.  And, it is not possible to have a window function and
       100532  +    ** a scalar function with the same name and number of arguments.  So
       100533  +    ** if we reach this point, either A and B both window functions or
       100534  +    ** neither are a window functions. */
       100535  +    assert( (pA->pWin==0)==(pB->pWin==0) );
       100536  +
       100537  +    if( pA->pWin!=0 ){
       100538  +      if( sqlite3WindowCompare(pParse,pA->pWin,pB->pWin)!=0 ) return 2;
       100539  +    }
       100540  +#endif
100885 100541     }
100886 100542     return 0;
100887 100543   }
100888 100544   
100889 100545   /*
100890 100546   ** Compare two ExprList objects.  Return 0 if they are identical and 
100891 100547   ** non-zero if they differ in any way.
................................................................................
100968 100624     }
100969 100625     return 0;
100970 100626   }
100971 100627   
100972 100628   /*
100973 100629   ** This is the Expr node callback for sqlite3ExprImpliesNotNullRow().
100974 100630   ** If the expression node requires that the table at pWalker->iCur
100975         -** have one or more non-NULL column, then set pWalker->eCode to 1 and abort.
100976         -**
100977         -** This routine controls an optimization.  False positives (setting
100978         -** pWalker->eCode to 1 when it should not be) are deadly, but false-negatives
100979         -** (never setting pWalker->eCode) is a harmless missed optimization.
       100631  +** have a non-NULL column, then set pWalker->eCode to 1 and abort.
100980 100632   */
100981 100633   static int impliesNotNullRow(Walker *pWalker, Expr *pExpr){
100982         -  testcase( pExpr->op==TK_AGG_COLUMN );
       100634  +  /* This routine is only called for WHERE clause expressions and so it
       100635  +  ** cannot have any TK_AGG_COLUMN entries because those are only found
       100636  +  ** in HAVING clauses.  We can get a TK_AGG_FUNCTION in a WHERE clause,
       100637  +  ** but that is an illegal construct and the query will be rejected at
       100638  +  ** a later stage of processing, so the TK_AGG_FUNCTION case does not
       100639  +  ** need to be considered here. */
       100640  +  assert( pExpr->op!=TK_AGG_COLUMN );
100983 100641     testcase( pExpr->op==TK_AGG_FUNCTION );
       100642  +
100984 100643     if( ExprHasProperty(pExpr, EP_FromJoin) ) return WRC_Prune;
100985 100644     switch( pExpr->op ){
100986 100645       case TK_ISNOT:
100987 100646       case TK_NOT:
100988 100647       case TK_ISNULL:
100989 100648       case TK_IS:
100990 100649       case TK_OR:
................................................................................
101018 100677       case TK_GE:
101019 100678         testcase( pExpr->op==TK_EQ );
101020 100679         testcase( pExpr->op==TK_NE );
101021 100680         testcase( pExpr->op==TK_LT );
101022 100681         testcase( pExpr->op==TK_LE );
101023 100682         testcase( pExpr->op==TK_GT );
101024 100683         testcase( pExpr->op==TK_GE );
101025         -      if( (pExpr->pLeft->op==TK_COLUMN && IsVirtual(pExpr->pLeft->y.pTab))
101026         -       || (pExpr->pRight->op==TK_COLUMN && IsVirtual(pExpr->pRight->y.pTab))
       100684  +      if( (pExpr->pLeft->op==TK_COLUMN && IsVirtual(pExpr->pLeft->pTab))
       100685  +       || (pExpr->pRight->op==TK_COLUMN && IsVirtual(pExpr->pRight->pTab))
101027 100686         ){
101028 100687          return WRC_Prune;
101029 100688         }
101030 100689       default:
101031 100690         return WRC_Continue;
101032 100691     }
101033 100692   }
................................................................................
101250 100909                   break;
101251 100910                 }
101252 100911               }
101253 100912               if( (k>=pAggInfo->nColumn)
101254 100913                && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 
101255 100914               ){
101256 100915                 pCol = &pAggInfo->aCol[k];
101257         -              pCol->pTab = pExpr->y.pTab;
       100916  +              pCol->pTab = pExpr->pTab;
101258 100917                 pCol->iTable = pExpr->iTable;
101259 100918                 pCol->iColumn = pExpr->iColumn;
101260 100919                 pCol->iMem = ++pParse->nMem;
101261 100920                 pCol->iSorterColumn = -1;
101262 100921                 pCol->pExpr = pExpr;
101263 100922                 if( pAggInfo->pGroupBy ){
101264 100923                   int j, n;
................................................................................
101634 101293     ** schema). Open a statement transaction if the table is a virtual
101635 101294     ** table.
101636 101295     */
101637 101296     v = sqlite3GetVdbe(pParse);
101638 101297     if( v==0 ){
101639 101298       goto exit_rename_table;
101640 101299     }
       101300  +
       101301  +  /* If this is a virtual table, invoke the xRename() function if
       101302  +  ** one is defined. The xRename() callback will modify the names
       101303  +  ** of any resources used by the v-table implementation (including other
       101304  +  ** SQLite tables) that are identified by the name of the virtual table.
       101305  +  */
       101306  +#ifndef SQLITE_OMIT_VIRTUALTABLE
       101307  +  if( pVTab ){
       101308  +    int i = ++pParse->nMem;
       101309  +    sqlite3VdbeLoadString(v, i, zName);
       101310  +    sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
       101311  +    sqlite3MayAbort(pParse);
       101312  +  }
       101313  +#endif
101641 101314   
101642 101315     /* figure out how many UTF-8 characters are in zName */
101643 101316     zTabName = pTab->zName;
101644 101317     nTabName = sqlite3Utf8CharLen(zTabName, -1);
101645 101318   
101646 101319     /* Rewrite all CREATE TABLE, INDEX, TRIGGER or VIEW statements in
101647 101320     ** the schema to use the new table name.  */
................................................................................
101692 101365                 "CASE WHEN tbl_name=%Q COLLATE nocase AND "
101693 101366                 "          sqlite_rename_test(%Q, sql, type, name, 1) "
101694 101367                 "THEN %Q ELSE tbl_name END "
101695 101368               "WHERE type IN ('view', 'trigger')"
101696 101369           , zDb, zTabName, zName, zTabName, zDb, zName);
101697 101370     }
101698 101371   
101699         -  /* If this is a virtual table, invoke the xRename() function if
101700         -  ** one is defined. The xRename() callback will modify the names
101701         -  ** of any resources used by the v-table implementation (including other
101702         -  ** SQLite tables) that are identified by the name of the virtual table.
101703         -  */
101704         -#ifndef SQLITE_OMIT_VIRTUALTABLE
101705         -  if( pVTab ){
101706         -    int i = ++pParse->nMem;
101707         -    sqlite3VdbeLoadString(v, i, zName);
101708         -    sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
101709         -    sqlite3MayAbort(pParse);
101710         -  }
101711         -#endif
101712         -
101713 101372     renameReloadSchema(pParse, iDb);
101714 101373     renameTestSchema(pParse, zDb, iDb==1);
101715 101374   
101716 101375   exit_rename_table:
101717 101376     sqlite3SrcListDelete(db, pSrc);
101718 101377     sqlite3DbFree(db, zName);
101719 101378     db->mDbFlags = savedDbFlags;
................................................................................
102133 101792     }
102134 101793   }
102135 101794   #else
102136 101795   # define renameTokenCheckAll(x,y)
102137 101796   #endif
102138 101797   
102139 101798   /*
102140         -** Remember that the parser tree element pPtr was created using
102141         -** the token pToken.
       101799  +** Add a new RenameToken object mapping parse tree element pPtr into
       101800  +** token *pToken to the Parse object currently under construction.
102142 101801   **
102143         -** In other words, construct a new RenameToken object and add it
102144         -** to the list of RenameToken objects currently being built up
102145         -** in pParse->pRename.
102146         -**
102147         -** The pPtr argument is returned so that this routine can be used
102148         -** with tail recursion in tokenExpr() routine, for a small performance
102149         -** improvement.
       101802  +** Return a copy of pPtr.
102150 101803   */
102151 101804   SQLITE_PRIVATE void *sqlite3RenameTokenMap(Parse *pParse, void *pPtr, Token *pToken){
102152 101805     RenameToken *pNew;
102153 101806     assert( pPtr || pParse->db->mallocFailed );
102154 101807     renameTokenCheckAll(pParse, pPtr);
102155 101808     pNew = sqlite3DbMallocZero(pParse->db, sizeof(RenameToken));
102156 101809     if( pNew ){
................................................................................
102275 101928     if( pExpr->op==TK_TRIGGER 
102276 101929      && pExpr->iColumn==p->iCol 
102277 101930      && pWalker->pParse->pTriggerTab==p->pTab
102278 101931     ){
102279 101932       renameTokenFind(pWalker->pParse, p, (void*)pExpr);
102280 101933     }else if( pExpr->op==TK_COLUMN 
102281 101934      && pExpr->iColumn==p->iCol 
102282         -   && p->pTab==pExpr->y.pTab
       101935  +   && p->pTab==pExpr->pTab
102283 101936     ){
102284 101937       renameTokenFind(pWalker->pParse, p, (void*)pExpr);
102285 101938     }
102286 101939     return WRC_Continue;
102287 101940   }
102288 101941   
102289 101942   /*
................................................................................
102533 102186     memset(&sNC, 0, sizeof(sNC));
102534 102187     sNC.pParse = pParse;
102535 102188     assert( pNew->pTabSchema );
102536 102189     pParse->pTriggerTab = sqlite3FindTable(db, pNew->table, 
102537 102190         db->aDb[sqlite3SchemaToIndex(db, pNew->pTabSchema)].zDbSName
102538 102191     );
102539 102192     pParse->eTriggerOp = pNew->op;
102540         -  /* ALWAYS() because if the table of the trigger does not exist, the
102541         -  ** error would have been hit before this point */
102542         -  if( ALWAYS(pParse->pTriggerTab) ){
102543         -    rc = sqlite3ViewGetColumnNames(pParse, pParse->pTriggerTab);
102544         -  }
102545 102193   
102546 102194     /* Resolve symbols in WHEN clause */
102547         -  if( rc==SQLITE_OK && pNew->pWhen ){
       102195  +  if( pNew->pWhen ){
102548 102196       rc = sqlite3ResolveExprNames(&sNC, pNew->pWhen);
102549 102197     }
102550 102198   
102551 102199     for(pStep=pNew->step_list; rc==SQLITE_OK && pStep; pStep=pStep->pNext){
102552 102200       if( pStep->pSelect ){
102553 102201         sqlite3SelectPrep(pParse, pStep->pSelect, &sNC);
102554 102202         if( pParse->nErr ) rc = pParse->rc;
................................................................................
102654 102302   **   8. bTemp:    True if zSql comes from temp schema
102655 102303   **
102656 102304   ** Do a column rename operation on the CREATE statement given in zSql.
102657 102305   ** The iCol-th column (left-most is 0) of table zTable is renamed from zCol
102658 102306   ** into zNew.  The name should be quoted if bQuote is true.
102659 102307   **
102660 102308   ** This function is used internally by the ALTER TABLE RENAME COLUMN command.
102661         -** It is only accessible to SQL created using sqlite3NestedParse().  It is
102662         -** not reachable from ordinary SQL passed into sqlite3_prepare().
       102309  +** Though accessible to application code, it is not intended for use by
       102310  +** applications.  The existance of this function, and the way it works,
       102311  +** is subject to change without notice.
       102312  +**
       102313  +** If any of the parameters are out-of-bounds, then simply return NULL.
       102314  +** An out-of-bounds parameter can only occur when the application calls
       102315  +** this function directly.  The parameters will always be well-formed when
       102316  +** this routine is invoked by the bytecode for a legitimate ALTER TABLE
       102317  +** statement.
102663 102318   */
102664 102319   static void renameColumnFunc(
102665 102320     sqlite3_context *context,
102666 102321     int NotUsed,
102667 102322     sqlite3_value **argv
102668 102323   ){
102669 102324     sqlite3 *db = sqlite3_context_db_handle(context);
................................................................................
102811 102466   }
102812 102467   
102813 102468   /*
102814 102469   ** Walker expression callback used by "RENAME TABLE". 
102815 102470   */
102816 102471   static int renameTableExprCb(Walker *pWalker, Expr *pExpr){
102817 102472     RenameCtx *p = pWalker->u.pRename;
102818         -  if( pExpr->op==TK_COLUMN && p->pTab==pExpr->y.pTab ){
102819         -    renameTokenFind(pWalker->pParse, p, (void*)&pExpr->y.pTab);
       102473  +  if( pExpr->op==TK_COLUMN && p->pTab==pExpr->pTab ){
       102474  +    renameTokenFind(pWalker->pParse, p, (void*)&pExpr->pTab);
102820 102475     }
102821 102476     return WRC_Continue;
102822 102477   }
102823 102478   
102824 102479   /*
102825 102480   ** Walker select callback used by "RENAME TABLE". 
102826 102481   */
................................................................................
102892 102547       sWalker.xExprCallback = renameTableExprCb;
102893 102548       sWalker.xSelectCallback = renameTableSelectCb;
102894 102549       sWalker.u.pRename = &sCtx;
102895 102550   
102896 102551       rc = renameParseSql(&sParse, zDb, 1, db, zInput, bTemp);
102897 102552   
102898 102553       if( rc==SQLITE_OK ){
102899         -      int isLegacy = (db->flags & SQLITE_LegacyAlter);
102900 102554         if( sParse.pNewTable ){
102901 102555           Table *pTab = sParse.pNewTable;
102902 102556   
102903 102557           if( pTab->pSelect ){
102904         -          if( isLegacy==0 ){
102905         -            NameContext sNC;
102906         -            memset(&sNC, 0, sizeof(sNC));
102907         -            sNC.pParse = &sParse;
       102558  +          NameContext sNC;
       102559  +          memset(&sNC, 0, sizeof(sNC));
       102560  +          sNC.pParse = &sParse;
102908 102561   
102909         -            sqlite3SelectPrep(&sParse, pTab->pSelect, &sNC);
102910         -            if( sParse.nErr ) rc = sParse.rc;
102911         -            sqlite3WalkSelect(&sWalker, pTab->pSelect);
102912         -          }
       102562  +          sqlite3SelectPrep(&sParse, pTab->pSelect, &sNC);
       102563  +          if( sParse.nErr ) rc = sParse.rc;
       102564  +          sqlite3WalkSelect(&sWalker, pTab->pSelect);
102913 102565           }else{
102914 102566             /* Modify any FK definitions to point to the new table. */
102915 102567   #ifndef SQLITE_OMIT_FOREIGN_KEY
102916         -          if( isLegacy==0 || (db->flags & SQLITE_ForeignKeys) ){
       102568  +          if( db->flags & SQLITE_ForeignKeys ){
102917 102569               FKey *pFKey;
102918 102570               for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
102919 102571                 if( sqlite3_stricmp(pFKey->zTo, zOld)==0 ){
102920 102572                   renameTokenFind(&sParse, &sCtx, (void*)pFKey->zTo);
102921 102573                 }
102922 102574               }
102923 102575             }
................................................................................
102924 102576   #endif
102925 102577   
102926 102578             /* If this is the table being altered, fix any table refs in CHECK
102927 102579             ** expressions. Also update the name that appears right after the
102928 102580             ** "CREATE [VIRTUAL] TABLE" bit. */
102929 102581             if( sqlite3_stricmp(zOld, pTab->zName)==0 ){
102930 102582               sCtx.pTab = pTab;
102931         -            if( isLegacy==0 ){
102932         -              sqlite3WalkExprList(&sWalker, pTab->pCheck);
102933         -            }
       102583  +            sqlite3WalkExprList(&sWalker, pTab->pCheck);
102934 102584               renameTokenFind(&sParse, &sCtx, pTab->zName);
102935 102585             }
102936 102586           }
102937 102587         }
102938 102588   
102939 102589         else if( sParse.pNewIndex ){
102940 102590           renameTokenFind(&sParse, &sCtx, sParse.pNewIndex->zName);
102941         -        if( isLegacy==0 ){
102942         -          sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
102943         -        }
       102591  +        sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
102944 102592         }
102945 102593   
102946 102594   #ifndef SQLITE_OMIT_TRIGGER
102947 102595         else{
102948 102596           Trigger *pTrigger = sParse.pNewTrigger;
102949 102597           TriggerStep *pStep;
102950 102598           if( 0==sqlite3_stricmp(sParse.pNewTrigger->table, zOld) 
102951 102599               && sCtx.pTab->pSchema==pTrigger->pTabSchema
102952 102600             ){
102953 102601             renameTokenFind(&sParse, &sCtx, sParse.pNewTrigger->table);
102954 102602           }
102955 102603   
102956         -        if( isLegacy==0 ){
102957         -          rc = renameResolveTrigger(&sParse, bTemp ? 0 : zDb);
102958         -          if( rc==SQLITE_OK ){
102959         -            renameWalkTrigger(&sWalker, pTrigger);
102960         -            for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
102961         -              if( pStep->zTarget && 0==sqlite3_stricmp(pStep->zTarget, zOld) ){
102962         -                renameTokenFind(&sParse, &sCtx, pStep->zTarget);
102963         -              }
       102604  +        rc = renameResolveTrigger(&sParse, bTemp ? 0 : zDb);
       102605  +        if( rc==SQLITE_OK ){
       102606  +          renameWalkTrigger(&sWalker, pTrigger);
       102607  +          for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
       102608  +            if( pStep->zTarget && 0==sqlite3_stricmp(pStep->zTarget, zOld) ){
       102609  +              renameTokenFind(&sParse, &sCtx, pStep->zTarget);
102964 102610               }
102965 102611             }
102966 102612           }
102967 102613         }
102968 102614   #endif
102969 102615       }
102970 102616   
................................................................................
103014 102660     int NotUsed,
103015 102661     sqlite3_value **argv
103016 102662   ){
103017 102663     sqlite3 *db = sqlite3_context_db_handle(context);
103018 102664     char const *zDb = (const char*)sqlite3_value_text(argv[0]);
103019 102665     char const *zInput = (const char*)sqlite3_value_text(argv[1]);
103020 102666     int bTemp = sqlite3_value_int(argv[4]);
103021         -  int isLegacy = (db->flags & SQLITE_LegacyAlter);
103022 102667   
103023 102668   #ifndef SQLITE_OMIT_AUTHORIZATION
103024 102669     sqlite3_xauth xAuth = db->xAuth;
103025 102670     db->xAuth = 0;
103026 102671   #endif
103027 102672   
103028 102673     UNUSED_PARAMETER(NotUsed);
103029 102674     if( zDb && zInput ){
103030 102675       int rc;
103031 102676       Parse sParse;
103032 102677       rc = renameParseSql(&sParse, zDb, 1, db, zInput, bTemp);
103033 102678       if( rc==SQLITE_OK ){
103034         -      if( isLegacy==0 && sParse.pNewTable && sParse.pNewTable->pSelect ){
       102679  +      if( sParse.pNewTable && sParse.pNewTable->pSelect ){
103035 102680           NameContext sNC;
103036 102681           memset(&sNC, 0, sizeof(sNC));
103037 102682           sNC.pParse = &sParse;
103038 102683           sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, &sNC);
103039 102684           if( sParse.nErr ) rc = sParse.rc;
103040 102685         }
103041 102686   
103042 102687         else if( sParse.pNewTrigger ){
103043         -        if( isLegacy==0 ){
103044         -          rc = renameResolveTrigger(&sParse, bTemp ? 0 : zDb);
103045         -        }
       102688  +        rc = renameResolveTrigger(&sParse, bTemp ? 0 : zDb);
103046 102689           if( rc==SQLITE_OK ){
103047 102690             int i1 = sqlite3SchemaToIndex(db, sParse.pNewTrigger->pTabSchema);
103048 102691             int i2 = sqlite3FindDbName(db, zDb);
103049 102692             if( i1==i2 ) sqlite3_result_int(context, 1);
103050 102693           }
103051 102694         }
103052 102695       }
................................................................................
103063 102706   }
103064 102707   
103065 102708   /*
103066 102709   ** Register built-in functions used to help implement ALTER TABLE
103067 102710   */
103068 102711   SQLITE_PRIVATE void sqlite3AlterFunctions(void){
103069 102712     static FuncDef aAlterTableFuncs[] = {
103070         -    INTERNAL_FUNCTION(sqlite_rename_column, 9, renameColumnFunc),
103071         -    INTERNAL_FUNCTION(sqlite_rename_table,  7, renameTableFunc),
103072         -    INTERNAL_FUNCTION(sqlite_rename_test,   5, renameTableTest),
       102713  +    FUNCTION(sqlite_rename_column,  9, 0, 0, renameColumnFunc),
       102714  +    FUNCTION(sqlite_rename_table,  7, 0, 0, renameTableFunc),
       102715  +    FUNCTION(sqlite_rename_test,  5, 0, 0, renameTableTest),
103073 102716     };
103074 102717     sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
103075 102718   }
103076 102719   #endif  /* SQLITE_ALTER_TABLE */
103077 102720   
103078 102721   /************** End of alter.c ***********************************************/
103079 102722   /************** Begin file analyze.c *****************************************/
................................................................................
105114 104757       ** reopen it as a MemDB */
105115 104758       pVfs = sqlite3_vfs_find("memdb");
105116 104759       if( pVfs==0 ) return;
105117 104760       pNew = &db->aDb[db->init.iDb];
105118 104761       if( pNew->pBt ) sqlite3BtreeClose(pNew->pBt);
105119 104762       pNew->pBt = 0;
105120 104763       pNew->pSchema = 0;
105121         -    rc = sqlite3BtreeOpen(pVfs, "x\0", db, &pNew->pBt, 0, SQLITE_OPEN_MAIN_DB);
       104764  +    rc = sqlite3BtreeOpen(pVfs, "x", db, &pNew->pBt, 0, SQLITE_OPEN_MAIN_DB);
105122 104765     }else{
105123 104766       /* This is a real ATTACH
105124 104767       **
105125 104768       ** Check for the following errors:
105126 104769       **
105127 104770       **     * Too many attached databases,
105128 104771       **     * Transaction currently open
................................................................................
105794 105437     Table *pTab = 0;      /* The table being read */
105795 105438     const char *zCol;     /* Name of the column of the table */
105796 105439     int iSrc;             /* Index in pTabList->a[] of table being read */
105797 105440     int iDb;              /* The index of the database the expression refers to */
105798 105441     int iCol;             /* Index of column in table */
105799 105442   
105800 105443     assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
105801         -  assert( !IN_RENAME_OBJECT || db->xAuth==0 );
105802 105444     if( db->xAuth==0 ) return;
105803 105445     iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
105804 105446     if( iDb<0 ){
105805 105447       /* An attempt to read a column out of a subquery or other
105806 105448       ** temporary table. */
105807 105449       return;
105808 105450     }
................................................................................
105851 105493   ){
105852 105494     sqlite3 *db = pParse->db;
105853 105495     int rc;
105854 105496   
105855 105497     /* Don't do any authorization checks if the database is initialising
105856 105498     ** or if the parser is being invoked from within sqlite3_declare_vtab.
105857 105499     */
105858         -  assert( !IN_RENAME_OBJECT || db->xAuth==0 );
105859 105500     if( db->init.busy || IN_SPECIAL_PARSE ){
105860 105501       return SQLITE_OK;
105861 105502     }
105862 105503   
105863 105504     if( db->xAuth==0 ){
105864 105505       return SQLITE_OK;
105865 105506     }
................................................................................
106275 105916       return 0;
106276 105917     }
106277 105918   
106278 105919     p = sqlite3FindTable(db, zName, zDbase);
106279 105920     if( p==0 ){
106280 105921       const char *zMsg = flags & LOCATE_VIEW ? "no such view" : "no such table";
106281 105922   #ifndef SQLITE_OMIT_VIRTUALTABLE
106282         -    /* If zName is the not the name of a table in the schema created using
106283         -    ** CREATE, then check to see if it is the name of an virtual table that
106284         -    ** can be an eponymous virtual table. */
106285         -    Module *pMod = (Module*)sqlite3HashFind(&db->aModule, zName);
106286         -    if( pMod==0 && sqlite3_strnicmp(zName, "pragma_", 7)==0 ){
106287         -      pMod = sqlite3PragmaVtabRegister(db, zName);
106288         -    }
106289         -    if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){
106290         -      return pMod->pEpoTab;
       105923  +    if( sqlite3FindDbName(db, zDbase)<1 ){
       105924  +      /* If zName is the not the name of a table in the schema created using
       105925  +      ** CREATE, then check to see if it is the name of an virtual table that
       105926  +      ** can be an eponymous virtual table. */
       105927  +      Module *pMod = (Module*)sqlite3HashFind(&db->aModule, zName);
       105928  +      if( pMod==0 && sqlite3_strnicmp(zName, "pragma_", 7)==0 ){
       105929  +        pMod = sqlite3PragmaVtabRegister(db, zName);
       105930  +      }
       105931  +      if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){
       105932  +        return pMod->pEpoTab;
       105933  +      }
106291 105934       }
106292 105935   #endif
106293 105936       if( (flags & LOCATE_NOERR)==0 ){
106294 105937         if( zDbase ){
106295 105938           sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
106296 105939         }else{
106297 105940           sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
................................................................................
106463 106106   /*
106464 106107   ** Erase all schema information from all attached databases (including
106465 106108   ** "main" and "temp") for a single database connection.
106466 106109   */
106467 106110   SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
106468 106111     int i;
106469 106112     sqlite3BtreeEnterAll(db);
       106113  +  assert( db->nSchemaLock==0 );
106470 106114     for(i=0; i<db->nDb; i++){
106471 106115       Db *pDb = &db->aDb[i];
106472 106116       if( pDb->pSchema ){
106473         -      if( db->nSchemaLock==0 ){
106474         -        sqlite3SchemaClear(pDb->pSchema);
106475         -      }else{
106476         -        DbSetProperty(db, i, DB_ResetWanted);
106477         -      }
       106117  +      sqlite3SchemaClear(pDb->pSchema);
106478 106118       }
106479 106119     }
106480 106120     db->mDbFlags &= ~(DBFLAG_SchemaChange|DBFLAG_SchemaKnownOk);
106481 106121     sqlite3VtabUnlockList(db);
106482 106122     sqlite3BtreeLeaveAll(db);
106483         -  if( db->nSchemaLock==0 ){
106484         -    sqlite3CollapseDatabaseArray(db);
106485         -  }
       106123  +  sqlite3CollapseDatabaseArray(db);
106486 106124   }
106487 106125   
106488 106126   /*
106489 106127   ** This routine is called when a commit occurs.
106490 106128   */
106491 106129   SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
106492 106130     db->mDbFlags &= ~DBFLAG_SchemaChange;
................................................................................
106555 106193     }
106556 106194   
106557 106195     /* Delete any foreign keys attached to this table. */
106558 106196     sqlite3FkDelete(db, pTable);
106559 106197   
106560 106198     /* Delete the Table structure itself.
106561 106199     */
106562         -#ifdef SQLITE_ENABLE_NORMALIZE
106563         -  if( pTable->pColHash ){
106564         -    sqlite3HashClear(pTable->pColHash);
106565         -    sqlite3_free(pTable->pColHash);
106566         -  }
106567         -#endif
106568 106200     sqlite3DeleteColumnNames(db, pTable);
106569 106201     sqlite3DbFree(db, pTable->zName);
106570 106202     sqlite3DbFree(db, pTable->zColAff);
106571 106203     sqlite3SelectDelete(db, pTable->pSelect);
106572 106204     sqlite3ExprListDelete(db, pTable->pCheck);
106573 106205   #ifndef SQLITE_OMIT_VIRTUALTABLE
106574 106206     sqlite3VtabClear(db, pTable);
................................................................................
106719 106351                || (db->mDbFlags & DBFLAG_Vacuum)!=0);
106720 106352       iDb = db->init.iDb;
106721 106353       *pUnqual = pName1;
106722 106354     }
106723 106355     return iDb;
106724 106356   }
106725 106357   
106726         -/*
106727         -** True if PRAGMA writable_schema is ON
106728         -*/
106729         -SQLITE_PRIVATE int sqlite3WritableSchema(sqlite3 *db){
106730         -  testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==0 );
106731         -  testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
106732         -               SQLITE_WriteSchema );
106733         -  testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
106734         -               SQLITE_Defensive );
106735         -  testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
106736         -               (SQLITE_WriteSchema|SQLITE_Defensive) );
106737         -  return (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==SQLITE_WriteSchema;
106738         -}
106739         -
106740 106358   /*
106741 106359   ** This routine is used to check if the UTF-8 string zName is a legal
106742 106360   ** unqualified name for a new schema object (table, index, view or
106743 106361   ** trigger). All names are legal except those that begin with the string
106744 106362   ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
106745 106363   ** is reserved for internal use.
106746 106364   */
106747 106365   SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
106748 106366     if( !pParse->db->init.busy && pParse->nested==0 
106749         -          && sqlite3WritableSchema(pParse->db)==0
       106367  +          && (pParse->db->flags & SQLITE_WriteSchema)==0
106750 106368             && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
106751 106369       sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
106752 106370       return SQLITE_ERROR;
106753 106371     }
106754 106372     return SQLITE_OK;
106755 106373   }
106756 106374   
................................................................................
107712 107330     if( !db->init.imposterTable ){
107713 107331       for(i=0; i<pTab->nCol; i++){
107714 107332         if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0 ){
107715 107333           pTab->aCol[i].notNull = OE_Abort;
107716 107334         }
107717 107335       }
107718 107336     }
       107337  +
       107338  +  /* The remaining transformations only apply to b-tree tables, not to
       107339  +  ** virtual tables */
       107340  +  if( IN_DECLARE_VTAB ) return;
107719 107341   
107720 107342     /* Convert the P3 operand of the OP_CreateBtree opcode from BTREE_INTKEY
107721 107343     ** into BTREE_BLOBKEY.
107722 107344     */
107723 107345     if( pParse->addrCrTab ){
107724 107346       assert( v );
107725 107347       sqlite3VdbeChangeP3(v, pParse->addrCrTab, BTREE_BLOBKEY);
................................................................................
107818 107440       assert( pTab->nCol==j );
107819 107441     }else{
107820 107442       pPk->nColumn = pTab->nCol;
107821 107443     }
107822 107444     recomputeColumnsNotIndexed(pPk);
107823 107445   }
107824 107446   
107825         -#ifndef SQLITE_OMIT_VIRTUALTABLE
107826         -/*
107827         -** Return true if zName is a shadow table name in the current database
107828         -** connection.
107829         -**
107830         -** zName is temporarily modified while this routine is running, but is
107831         -** restored to its original value prior to this routine returning.
107832         -*/
107833         -static int isShadowTableName(sqlite3 *db, char *zName){
107834         -  char *zTail;                  /* Pointer to the last "_" in zName */
107835         -  Table *pTab;                  /* Table that zName is a shadow of */
107836         -  Module *pMod;                 /* Module for the virtual table */
107837         -
107838         -  zTail = strrchr(zName, '_');
107839         -  if( zTail==0 ) return 0;
107840         -  *zTail = 0;
107841         -  pTab = sqlite3FindTable(db, zName, 0);
107842         -  *zTail = '_';
107843         -  if( pTab==0 ) return 0;
107844         -  if( !IsVirtual(pTab) ) return 0;
107845         -  pMod = (Module*)sqlite3HashFind(&db->aModule, pTab->azModuleArg[0]);
107846         -  if( pMod==0 ) return 0;
107847         -  if( pMod->pModule->iVersion<3 ) return 0;
107848         -  if( pMod->pModule->xShadowName==0 ) return 0;
107849         -  return pMod->pModule->xShadowName(zTail+1);
107850         -}
107851         -#else
107852         -# define isShadowTableName(x,y) 0
107853         -#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
107854         -
107855 107447   /*
107856 107448   ** This routine is called to report the final ")" that terminates
107857 107449   ** a CREATE TABLE statement.
107858 107450   **
107859 107451   ** The table structure that other action routines have been building
107860 107452   ** is added to the internal hash tables, assuming no errors have
107861 107453   ** occurred.
................................................................................
107887 107479     if( pEnd==0 && pSelect==0 ){
107888 107480       return;
107889 107481     }
107890 107482     assert( !db->mallocFailed );
107891 107483     p = pParse->pNewTable;
107892 107484     if( p==0 ) return;
107893 107485   
107894         -  if( pSelect==0 && isShadowTableName(db, p->zName) ){
107895         -    p->tabFlags |= TF_Shadow;
107896         -  }
107897         -
107898 107486     /* If the db->init.busy is 1 it means we are reading the SQL off the
107899 107487     ** "sqlite_master" or "sqlite_temp_master" table on the disk.
107900 107488     ** So do not write to the disk again.  Extract the root page number
107901 107489     ** for the table from the db->init.newTnum field.  (The page number
107902 107490     ** should have been put there by the sqliteOpenCb routine.)
107903 107491     **
107904 107492     ** If the root page number is 1, that means this is the sqlite_master
................................................................................
108398 107986   ** Also write code to modify the sqlite_master table and internal schema
108399 107987   ** if a root-page of another table is moved by the btree-layer whilst
108400 107988   ** erasing iTable (this can happen with an auto-vacuum database).
108401 107989   */ 
108402 107990   static void destroyRootPage(Parse *pParse, int iTable, int iDb){
108403 107991     Vdbe *v = sqlite3GetVdbe(pParse);
108404 107992     int r1 = sqlite3GetTempReg(pParse);
108405         -  if( iTable<2 ) sqlite3ErrorMsg(pParse, "corrupt schema");
       107993  +  assert( iTable>1 );
108406 107994     sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
108407 107995     sqlite3MayAbort(pParse);
108408 107996   #ifndef SQLITE_OMIT_AUTOVACUUM
108409 107997     /* OP_Destroy stores an in integer r1. If this integer
108410 107998     ** is non-zero, then it is the root page number of a table moved to
108411 107999     ** location iTable. The following code modifies the sqlite_master table to
108412 108000     ** reflect this.
................................................................................
110853 110441     for(p=sqlite3BuiltinFunctions.a[h]; p; p=p->u.pHash){
110854 110442       if( sqlite3StrICmp(p->zName, zFunc)==0 ){
110855 110443         return p;
110856 110444       }
110857 110445     }
110858 110446     return 0;
110859 110447   }
110860         -#ifdef SQLITE_ENABLE_NORMALIZE
110861         -SQLITE_PRIVATE FuncDef *sqlite3FunctionSearchN(
110862         -  int h,               /* Hash of the name */
110863         -  const char *zFunc,   /* Name of function */
110864         -  int nFunc            /* Length of the name */
110865         -){
110866         -  FuncDef *p;
110867         -  for(p=sqlite3BuiltinFunctions.a[h]; p; p=p->u.pHash){
110868         -    if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 ){
110869         -      return p;
110870         -    }
110871         -  }
110872         -  return 0;
110873         -}
110874         -#endif /* SQLITE_ENABLE_NORMALIZE */
110875 110448   
110876 110449   /*
110877 110450   ** Insert a new FuncDef into a FuncDefHash hash table.
110878 110451   */
110879 110452   SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(
110880 110453     FuncDef *aDef,      /* List of global functions to be inserted */
110881 110454     int nDef            /* Length of the apDef[] list */
110882 110455   ){
110883 110456     int i;
110884 110457     for(i=0; i<nDef; i++){
110885 110458       FuncDef *pOther;
110886 110459       const char *zName = aDef[i].zName;
110887 110460       int nName = sqlite3Strlen30(zName);
110888         -    int h = SQLITE_FUNC_HASH(zName[0], nName);
       110461  +    int h = (zName[0] + nName) % SQLITE_FUNC_HASH_SZ;
110889 110462       assert( zName[0]>='a' && zName[0]<='z' );
110890 110463       pOther = functionSearch(h, zName);
110891 110464       if( pOther ){
110892 110465         assert( pOther!=&aDef[i] && pOther->pNext!=&aDef[i] );
110893 110466         aDef[i].pNext = pOther->pNext;
110894 110467         pOther->pNext = &aDef[i];
110895 110468       }else{
................................................................................
110960 110533     ** install a new function.  Whatever FuncDef structure is returned it will
110961 110534     ** have fields overwritten with new information appropriate for the
110962 110535     ** new function.  But the FuncDefs for built-in functions are read-only.
110963 110536     ** So we must not search for built-ins when creating a new function.
110964 110537     */ 
110965 110538     if( !createFlag && (pBest==0 || (db->mDbFlags & DBFLAG_PreferBuiltin)!=0) ){
110966 110539       bestScore = 0;
110967         -    h = SQLITE_FUNC_HASH(sqlite3UpperToLower[(u8)zName[0]], nName);
       110540  +    h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % SQLITE_FUNC_HASH_SZ;
110968 110541       p = functionSearch(h, zName);
110969 110542       while( p ){
110970 110543         int score = matchQuality(p, nArg, enc);
110971 110544         if( score>bestScore ){
110972 110545           pBest = p;
110973 110546           bestScore = score;
110974 110547         }
................................................................................
111108 110681     }
111109 110682     if( sqlite3IndexedByLookup(pParse, pItem) ){
111110 110683       pTab = 0;
111111 110684     }
111112 110685     return pTab;
111113 110686   }
111114 110687   
111115         -/* Return true if table pTab is read-only.
111116         -**
111117         -** A table is read-only if any of the following are true:
111118         -**
111119         -**   1) It is a virtual table and no implementation of the xUpdate method
111120         -**      has been provided
111121         -**
111122         -**   2) It is a system table (i.e. sqlite_master), this call is not
111123         -**      part of a nested parse and writable_schema pragma has not 
111124         -**      been specified
111125         -**
111126         -**   3) The table is a shadow table, the database connection is in
111127         -**      defensive mode, and the current sqlite3_prepare()
111128         -**      is for a top-level SQL statement.
111129         -*/
111130         -static int tabIsReadOnly(Parse *pParse, Table *pTab){
111131         -  sqlite3 *db;
111132         -  if( IsVirtual(pTab) ){
111133         -    return sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0;
111134         -  }
111135         -  if( (pTab->tabFlags & (TF_Readonly|TF_Shadow))==0 ) return 0;
111136         -  db = pParse->db;
111137         -  if( (pTab->tabFlags & TF_Readonly)!=0 ){
111138         -    return sqlite3WritableSchema(db)==0 && pParse->nested==0;
111139         -  }
111140         -  assert( pTab->tabFlags & TF_Shadow );
111141         -  return (db->flags & SQLITE_Defensive)!=0 
111142         -#ifndef SQLITE_OMIT_VIRTUALTABLE
111143         -          && db->pVtabCtx==0
111144         -#endif
111145         -          && db->nVdbeExec==0;
111146         -}
111147         -
111148 110688   /*
111149 110689   ** Check to make sure the given table is writable.  If it is not
111150 110690   ** writable, generate an error message and return 1.  If it is
111151 110691   ** writable return 0;
111152 110692   */
111153 110693   SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
111154         -  if( tabIsReadOnly(pParse, pTab) ){
       110694  +  /* A table is not writable under the following circumstances:
       110695  +  **
       110696  +  **   1) It is a virtual table and no implementation of the xUpdate method
       110697  +  **      has been provided, or
       110698  +  **   2) It is a system table (i.e. sqlite_master), this call is not
       110699  +  **      part of a nested parse and writable_schema pragma has not 
       110700  +  **      been specified.
       110701  +  **
       110702  +  ** In either case leave an error message in pParse and return non-zero.
       110703  +  */
       110704  +  if( ( IsVirtual(pTab) 
       110705  +     && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
       110706  +   || ( (pTab->tabFlags & TF_Readonly)!=0
       110707  +     && (pParse->db->flags & SQLITE_WriteSchema)==0
       110708  +     && pParse->nested==0 )
       110709  +  ){
111155 110710       sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
111156 110711       return 1;
111157 110712     }
       110713  +
111158 110714   #ifndef SQLITE_OMIT_VIEW
111159 110715     if( !viewOk && pTab->pSelect ){
111160 110716       sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
111161 110717       return 1;
111162 110718     }
111163 110719   #endif
111164 110720     return 0;
................................................................................
114554 114110     sqlite3 *db,      /* The database connection */
114555 114111     Table *pTab,      /* The table whose column is desired */
114556 114112     int iCursor,      /* The open cursor on the table */
114557 114113     i16 iCol          /* The column that is wanted */
114558 114114   ){
114559 114115     Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
114560 114116     if( pExpr ){
114561         -    pExpr->y.pTab = pTab;
       114117  +    pExpr->pTab = pTab;
114562 114118       pExpr->iTable = iCursor;
114563 114119       pExpr->iColumn = iCol;
114564 114120     }
114565 114121     return pExpr;
114566 114122   }
114567 114123   
114568 114124   /*
................................................................................
115630 115186         zColAff[i] = pTab->aCol[i].affinity;
115631 115187       }
115632 115188       do{
115633 115189         zColAff[i--] = 0;
115634 115190       }while( i>=0 && zColAff[i]==SQLITE_AFF_BLOB );
115635 115191       pTab->zColAff = zColAff;
115636 115192     }
115637         -  assert( zColAff!=0 );
115638         -  i = sqlite3Strlen30NN(zColAff);
       115193  +  i = sqlite3Strlen30(zColAff);
115639 115194     if( i ){
115640 115195       if( iReg ){
115641 115196         sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
115642 115197       }else{
115643 115198         sqlite3VdbeChangeP4(v, -1, zColAff, i);
115644 115199       }
115645 115200     }
................................................................................
116611 116166    #undef pTrigger
116612 116167   #endif
116613 116168   #ifdef tmask
116614 116169    #undef tmask
116615 116170   #endif
116616 116171   
116617 116172   /*
116618         -** Meanings of bits in of pWalker->eCode for 
116619         -** sqlite3ExprReferencesUpdatedColumn()
       116173  +** Meanings of bits in of pWalker->eCode for checkConstraintUnchanged()
116620 116174   */
116621 116175   #define CKCNSTRNT_COLUMN   0x01    /* CHECK constraint uses a changing column */
116622 116176   #define CKCNSTRNT_ROWID    0x02    /* CHECK constraint references the ROWID */
116623 116177   
116624         -/* This is the Walker callback from sqlite3ExprReferencesUpdatedColumn().
116625         -*  Set bit 0x01 of pWalker->eCode if pWalker->eCode to 0 and if this
116626         -** expression node references any of the
       116178  +/* This is the Walker callback from checkConstraintUnchanged().  Set
       116179  +** bit 0x01 of pWalker->eCode if
       116180  +** pWalker->eCode to 0 if this expression node references any of the
116627 116181   ** columns that are being modifed by an UPDATE statement.
116628 116182   */
116629 116183   static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){
116630 116184     if( pExpr->op==TK_COLUMN ){
116631 116185       assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );
116632 116186       if( pExpr->iColumn>=0 ){
116633 116187         if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){
................................................................................
116641 116195   }
116642 116196   
116643 116197   /*
116644 116198   ** pExpr is a CHECK constraint on a row that is being UPDATE-ed.  The
116645 116199   ** only columns that are modified by the UPDATE are those for which
116646 116200   ** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true.
116647 116201   **
116648         -** Return true if CHECK constraint pExpr uses any of the
       116202  +** Return true if CHECK constraint pExpr does not use any of the
116649 116203   ** changing columns (or the rowid if it is changing).  In other words,
116650         -** return true if this CHECK constraint must be validated for
       116204  +** return true if this CHECK constraint can be skipped when validating
116651 116205   ** the new row in the UPDATE statement.
116652         -**
116653         -** 2018-09-15: pExpr might also be an expression for an index-on-expressions.
116654         -** The operation of this routine is the same - return true if an only if
116655         -** the expression uses one or more of columns identified by the second and
116656         -** third arguments.
116657 116206   */
116658         -SQLITE_PRIVATE int sqlite3ExprReferencesUpdatedColumn(
116659         -  Expr *pExpr,    /* The expression to be checked */
116660         -  int *aiChng,    /* aiChng[x]>=0 if column x changed by the UPDATE */
116661         -  int chngRowid   /* True if UPDATE changes the rowid */
116662         -){
       116207  +static int checkConstraintUnchanged(Expr *pExpr, int *aiChng, int chngRowid){
116663 116208     Walker w;
116664 116209     memset(&w, 0, sizeof(w));
116665 116210     w.eCode = 0;
116666 116211     w.xExprCallback = checkConstraintExprNode;
116667 116212     w.u.aiCol = aiChng;
116668 116213     sqlite3WalkExpr(&w, pExpr);
116669 116214     if( !chngRowid ){
................................................................................
116670 116215       testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 );
116671 116216       w.eCode &= ~CKCNSTRNT_ROWID;
116672 116217     }
116673 116218     testcase( w.eCode==0 );
116674 116219     testcase( w.eCode==CKCNSTRNT_COLUMN );
116675 116220     testcase( w.eCode==CKCNSTRNT_ROWID );
116676 116221     testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) );
116677         -  return w.eCode!=0;
       116222  +  return !w.eCode;
116678 116223   }
116679 116224   
116680 116225   /*
116681 116226   ** Generate code to do constraint checks prior to an INSERT or an UPDATE
116682 116227   ** on table pTab.
116683 116228   **
116684 116229   ** The regNewData parameter is the first register in a range that contains
................................................................................
116876 116421     if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
116877 116422       ExprList *pCheck = pTab->pCheck;
116878 116423       pParse->iSelfTab = -(regNewData+1);
116879 116424       onError = overrideError!=OE_Default ? overrideError : OE_Abort;
116880 116425       for(i=0; i<pCheck->nExpr; i++){
116881 116426         int allOk;
116882 116427         Expr *pExpr = pCheck->a[i].pExpr;
116883         -      if( aiChng
116884         -       && !sqlite3ExprReferencesUpdatedColumn(pExpr, aiChng, pkChng)
116885         -      ){
116886         -        /* The check constraints do not reference any of the columns being
116887         -        ** updated so there is no point it verifying the check constraint */
116888         -        continue;
116889         -      }
       116428  +      if( aiChng && checkConstraintUnchanged(pExpr, aiChng, pkChng) ) continue;
116890 116429         allOk = sqlite3VdbeMakeLabel(v);
116891 116430         sqlite3VdbeVerifyAbortable(v, onError);
116892 116431         sqlite3ExprIfTrue(pParse, pExpr, allOk, SQLITE_JUMPIFNULL);
116893 116432         if( onError==OE_Ignore ){
116894 116433           sqlite3VdbeGoto(v, ignoreDest);
116895 116434         }else{
116896 116435           char *zName = pCheck->a[i].zName;
................................................................................
118383 117922     void (*str_append)(sqlite3_str*, const char *zIn, int N);
118384 117923     void (*str_appendall)(sqlite3_str*, const char *zIn);
118385 117924     void (*str_appendchar)(sqlite3_str*, int N, char C);
118386 117925     void (*str_reset)(sqlite3_str*);
118387 117926     int (*str_errcode)(sqlite3_str*);
118388 117927     int (*str_length)(sqlite3_str*);
118389 117928     char *(*str_value)(sqlite3_str*);
118390         -  /* Version 3.25.0 and later */
118391 117929     int (*create_window_function)(sqlite3*,const char*,int,int,void*,
118392 117930                               void (*xStep)(sqlite3_context*,int,sqlite3_value**),
118393 117931                               void (*xFinal)(sqlite3_context*),
118394 117932                               void (*xValue)(sqlite3_context*),
118395 117933                               void (*xInv)(sqlite3_context*,int,sqlite3_value**),
118396 117934                               void(*xDestroy)(void*));
118397         -  /* Version 3.26.0 and later */
118398         -  const char *(*normalized_sql)(sqlite3_stmt*);
118399 117935   };
118400 117936   
118401 117937   /*
118402 117938   ** This is the function signature used for all extension entry points.  It
118403 117939   ** is also defined in the file "loadext.c".
118404 117940   */
118405 117941   typedef int (*sqlite3_loadext_entry)(
................................................................................
118679 118215   #define sqlite3_str_appendchar         sqlite3_api->str_appendchar
118680 118216   #define sqlite3_str_reset              sqlite3_api->str_reset
118681 118217   #define sqlite3_str_errcode            sqlite3_api->str_errcode
118682 118218   #define sqlite3_str_length             sqlite3_api->str_length
118683 118219   #define sqlite3_str_value              sqlite3_api->str_value
118684 118220   /* Version 3.25.0 and later */
118685 118221   #define sqlite3_create_window_function sqlite3_api->create_window_function
118686         -/* Version 3.26.0 and later */
118687         -#define sqlite3_normalized_sql         sqlite3_api->normalized_sql
118688 118222   #endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */
118689 118223   
118690 118224   #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
118691 118225     /* This case when the file really is being compiled as a loadable 
118692 118226     ** extension */
118693 118227   # define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api=0;
118694 118228   # define SQLITE_EXTENSION_INIT2(v)  sqlite3_api=v;
................................................................................
118769 118303   
118770 118304   #ifdef SQLITE_OMIT_VIRTUALTABLE
118771 118305   # define sqlite3_create_module 0
118772 118306   # define sqlite3_create_module_v2 0
118773 118307   # define sqlite3_declare_vtab 0
118774 118308   # define sqlite3_vtab_config 0
118775 118309   # define sqlite3_vtab_on_conflict 0
118776         -# define sqlite3_vtab_collation 0
118777 118310   #endif
118778 118311   
118779 118312   #ifdef SQLITE_OMIT_SHARED_CACHE
118780 118313   # define sqlite3_enable_shared_cache 0
118781 118314   #endif
118782 118315   
118783 118316   #if defined(SQLITE_OMIT_TRACE) || defined(SQLITE_OMIT_DEPRECATED)
................................................................................
119137 118670     sqlite3_str_appendall,
119138 118671     sqlite3_str_appendchar,
119139 118672     sqlite3_str_reset,
119140 118673     sqlite3_str_errcode,
119141 118674     sqlite3_str_length,
119142 118675     sqlite3_str_value,
119143 118676     /* Version 3.25.0 and later */
119144         -  sqlite3_create_window_function,
119145         -  /* Version 3.26.0 and later */
119146         -#ifdef SQLITE_ENABLE_NORMALIZE
119147         -  sqlite3_normalized_sql
119148         -#else
119149         -  0
119150         -#endif
       118677  +  sqlite3_create_window_function
119151 118678   };
119152 118679   
119153 118680   /*
119154 118681   ** Attempt to load an SQLite extension library contained in the file
119155 118682   ** zFile.  The entry point is zProc.  zProc may be 0 in which case a
119156 118683   ** default entry point name (sqlite3_extension_init) is used.  Use
119157 118684   ** of the default name is recommended.
................................................................................
119593 119120   #define PragTyp_TEMP_STORE_DIRECTORY          36
119594 119121   #define PragTyp_THREADS                       37
119595 119122   #define PragTyp_WAL_AUTOCHECKPOINT            38
119596 119123   #define PragTyp_WAL_CHECKPOINT                39
119597 119124   #define PragTyp_ACTIVATE_EXTENSIONS           40
119598 119125   #define PragTyp_HEXKEY                        41
119599 119126   #define PragTyp_KEY                           42
119600         -#define PragTyp_LOCK_STATUS                   43
119601         -#define PragTyp_PARSER_TRACE                  44
119602         -#define PragTyp_STATS                         45
       119127  +#define PragTyp_REKEY                         43
       119128  +#define PragTyp_LOCK_STATUS                   44
       119129  +#define PragTyp_PARSER_TRACE                  45
       119130  +#define PragTyp_STATS                         46
119603 119131   
119604 119132   /* Property flags associated with various pragma. */
119605 119133   #define PragFlg_NeedSchema 0x01 /* Force schema load before running */
119606 119134   #define PragFlg_NoColumns  0x02 /* OP_ResultRow called with zero columns */
119607 119135   #define PragFlg_NoColumns1 0x04 /* zero columns if RHS argument is present */
119608 119136   #define PragFlg_ReadOnly   0x08 /* Read-only HEADER_VALUE */
119609 119137   #define PragFlg_Result0    0x10 /* Acts as query when no argument */
................................................................................
119612 119140   #define PragFlg_SchemaReq  0x80 /* Schema required - "main" is default */
119613 119141   
119614 119142   /* Names of columns for pragmas that return multi-column result
119615 119143   ** or that return single-column results where the name of the
119616 119144   ** result column is different from the name of the pragma
119617 119145   */
119618 119146   static const char *const pragCName[] = {
119619         -  /*   0 */ "id",          /* Used by: foreign_key_list */
119620         -  /*   1 */ "seq",        
119621         -  /*   2 */ "table",      
119622         -  /*   3 */ "from",       
119623         -  /*   4 */ "to",         
119624         -  /*   5 */ "on_update",  
119625         -  /*   6 */ "on_delete",  
119626         -  /*   7 */ "match",      
119627         -  /*   8 */ "cid",         /* Used by: table_xinfo */
119628         -  /*   9 */ "name",       
119629         -  /*  10 */ "type",       
119630         -  /*  11 */ "notnull",    
119631         -  /*  12 */ "dflt_value", 
119632         -  /*  13 */ "pk",         
119633         -  /*  14 */ "hidden",     
119634         -                           /* table_info reuses 8 */
       119147  +  /*   0 */ "cache_size",  /* Used by: default_cache_size */
       119148  +  /*   1 */ "cid",         /* Used by: table_info */
       119149  +  /*   2 */ "name",       
       119150  +  /*   3 */ "type",       
       119151  +  /*   4 */ "notnull",    
       119152  +  /*   5 */ "dflt_value", 
       119153  +  /*   6 */ "pk",         
       119154  +  /*   7 */ "tbl",         /* Used by: stats */
       119155  +  /*   8 */ "idx",        
       119156  +  /*   9 */ "wdth",       
       119157  +  /*  10 */ "hght",       
       119158  +  /*  11 */ "flgs",       
       119159  +  /*  12 */ "seqno",       /* Used by: index_info */
       119160  +  /*  13 */ "cid",        
       119161  +  /*  14 */ "name",       
119635 119162     /*  15 */ "seqno",       /* Used by: index_xinfo */
119636 119163     /*  16 */ "cid",        
119637 119164     /*  17 */ "name",       
119638 119165     /*  18 */ "desc",       
119639 119166     /*  19 */ "coll",       
119640 119167     /*  20 */ "key",        
119641         -  /*  21 */ "tbl",         /* Used by: stats */
119642         -  /*  22 */ "idx",        
119643         -  /*  23 */ "wdth",       
119644         -  /*  24 */ "hght",       
119645         -  /*  25 */ "flgs",       
119646         -  /*  26 */ "seq",         /* Used by: index_list */
       119168  +  /*  21 */ "seq",         /* Used by: index_list */
       119169  +  /*  22 */ "name",       
       119170  +  /*  23 */ "unique",     
       119171  +  /*  24 */ "origin",     
       119172  +  /*  25 */ "partial",    
       119173  +  /*  26 */ "seq",         /* Used by: database_list */
119647 119174     /*  27 */ "name",       
119648         -  /*  28 */ "unique",     
119649         -  /*  29 */ "origin",     
119650         -  /*  30 */ "partial",    
119651         -  /*  31 */ "table",       /* Used by: foreign_key_check */
119652         -  /*  32 */ "rowid",      
119653         -  /*  33 */ "parent",     
119654         -  /*  34 */ "fkid",       
119655         -                           /* index_info reuses 15 */
119656         -  /*  35 */ "seq",         /* Used by: database_list */
119657         -  /*  36 */ "name",       
119658         -  /*  37 */ "file",       
119659         -  /*  38 */ "busy",        /* Used by: wal_checkpoint */
119660         -  /*  39 */ "log",        
119661         -  /*  40 */ "checkpointed",
119662         -  /*  41 */ "name",        /* Used by: function_list */
119663         -  /*  42 */ "builtin",    
119664         -                           /* collation_list reuses 26 */
119665         -  /*  43 */ "database",    /* Used by: lock_status */
119666         -  /*  44 */ "status",     
119667         -  /*  45 */ "cache_size",  /* Used by: default_cache_size */
119668         -                           /* module_list pragma_list reuses 9 */
119669         -  /*  46 */ "timeout",     /* Used by: busy_timeout */
       119175  +  /*  28 */ "file",       
       119176  +  /*  29 */ "name",        /* Used by: function_list */
       119177  +  /*  30 */ "builtin",    
       119178  +  /*  31 */ "name",        /* Used by: module_list pragma_list */
       119179  +  /*  32 */ "seq",         /* Used by: collation_list */
       119180  +  /*  33 */ "name",       
       119181  +  /*  34 */ "id",          /* Used by: foreign_key_list */
       119182  +  /*  35 */ "seq",        
       119183  +  /*  36 */ "table",      
       119184  +  /*  37 */ "from",       
       119185  +  /*  38 */ "to",         
       119186  +  /*  39 */ "on_update",  
       119187  +  /*  40 */ "on_delete",  
       119188  +  /*  41 */ "match",      
       119189  +  /*  42 */ "table",       /* Used by: foreign_key_check */
       119190  +  /*  43 */ "rowid",      
       119191  +  /*  44 */ "parent",     
       119192  +  /*  45 */ "fkid",       
       119193  +  /*  46 */ "busy",        /* Used by: wal_checkpoint */
       119194  +  /*  47 */ "log",        
       119195  +  /*  48 */ "checkpointed",
       119196  +  /*  49 */ "timeout",     /* Used by: busy_timeout */
       119197  +  /*  50 */ "database",    /* Used by: lock_status */
       119198  +  /*  51 */ "status",     
119670 119199   };
119671 119200   
119672 119201   /* Definitions of all built-in pragmas */
119673 119202   typedef struct PragmaName {
119674 119203     const char *const zName; /* Name of pragma */
119675 119204     u8 ePragTyp;             /* PragTyp_XXX value */
119676 119205     u8 mPragFlg;             /* Zero or more PragFlg_XXX values */
119677 119206     u8 iPragCName;           /* Start of column names in pragCName[] */
119678 119207     u8 nPragCName;           /* Num of col names. 0 means use pragma name */
119679         -  u64 iArg;                /* Extra argument */
       119208  +  u32 iArg;                /* Extra argument */
119680 119209   } PragmaName;
119681 119210   static const PragmaName aPragmaName[] = {
119682 119211   #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
119683 119212    {/* zName:     */ "activate_extensions",
119684 119213     /* ePragTyp:  */ PragTyp_ACTIVATE_EXTENSIONS,
119685 119214     /* ePragFlg:  */ 0,
119686 119215     /* ColNames:  */ 0, 0,
................................................................................
119708 119237     /* ColNames:  */ 0, 0,
119709 119238     /* iArg:      */ SQLITE_AutoIndex },
119710 119239   #endif
119711 119240   #endif
119712 119241    {/* zName:     */ "busy_timeout",
119713 119242     /* ePragTyp:  */ PragTyp_BUSY_TIMEOUT,
119714 119243     /* ePragFlg:  */ PragFlg_Result0,
119715         -  /* ColNames:  */ 46, 1,
       119244  +  /* ColNames:  */ 49, 1,
119716 119245     /* iArg:      */ 0 },
119717 119246   #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
119718 119247    {/* zName:     */ "cache_size",
119719 119248     /* ePragTyp:  */ PragTyp_CACHE_SIZE,
119720 119249     /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
119721 119250     /* ColNames:  */ 0, 0,
119722 119251     /* iArg:      */ 0 },
................................................................................
119745 119274     /* ColNames:  */ 0, 0,
119746 119275     /* iArg:      */ SQLITE_CkptFullFSync },
119747 119276   #endif
119748 119277   #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
119749 119278    {/* zName:     */ "collation_list",
119750 119279     /* ePragTyp:  */ PragTyp_COLLATION_LIST,
119751 119280     /* ePragFlg:  */ PragFlg_Result0,
119752         -  /* ColNames:  */ 26, 2,
       119281  +  /* ColNames:  */ 32, 2,
119753 119282     /* iArg:      */ 0 },
119754 119283   #endif
119755 119284   #if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
119756 119285    {/* zName:     */ "compile_options",
119757 119286     /* ePragTyp:  */ PragTyp_COMPILE_OPTIONS,
119758 119287     /* ePragFlg:  */ PragFlg_Result0,
119759 119288     /* ColNames:  */ 0, 0,
................................................................................
119780 119309     /* ColNames:  */ 0, 0,
119781 119310     /* iArg:      */ BTREE_DATA_VERSION },
119782 119311   #endif
119783 119312   #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
119784 119313    {/* zName:     */ "database_list",
119785 119314     /* ePragTyp:  */ PragTyp_DATABASE_LIST,
119786 119315     /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0,
119787         -  /* ColNames:  */ 35, 3,
       119316  +  /* ColNames:  */ 26, 3,
119788 119317     /* iArg:      */ 0 },
119789 119318   #endif
119790 119319   #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
119791 119320    {/* zName:     */ "default_cache_size",
119792 119321     /* ePragTyp:  */ PragTyp_DEFAULT_CACHE_SIZE,
119793 119322     /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
119794         -  /* ColNames:  */ 45, 1,
       119323  +  /* ColNames:  */ 0, 1,
119795 119324     /* iArg:      */ 0 },
119796 119325   #endif
119797 119326   #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
119798 119327   #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
119799 119328    {/* zName:     */ "defer_foreign_keys",
119800 119329     /* ePragTyp:  */ PragTyp_FLAG,
119801 119330     /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
................................................................................
119817 119346     /* ColNames:  */ 0, 0,
119818 119347     /* iArg:      */ 0 },
119819 119348   #endif
119820 119349   #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
119821 119350    {/* zName:     */ "foreign_key_check",
119822 119351     /* ePragTyp:  */ PragTyp_FOREIGN_KEY_CHECK,
119823 119352     /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0,
119824         -  /* ColNames:  */ 31, 4,
       119353  +  /* ColNames:  */ 42, 4,
119825 119354     /* iArg:      */ 0 },
119826 119355   #endif
119827 119356   #if !defined(SQLITE_OMIT_FOREIGN_KEY)
119828 119357    {/* zName:     */ "foreign_key_list",
119829 119358     /* ePragTyp:  */ PragTyp_FOREIGN_KEY_LIST,
119830 119359     /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
119831         -  /* ColNames:  */ 0, 8,
       119360  +  /* ColNames:  */ 34, 8,
119832 119361     /* iArg:      */ 0 },
119833 119362   #endif
119834 119363   #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
119835 119364   #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
119836 119365    {/* zName:     */ "foreign_keys",
119837 119366     /* ePragTyp:  */ PragTyp_FLAG,
119838 119367     /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
................................................................................
119860 119389     /* iArg:      */ SQLITE_FullFSync },
119861 119390   #endif
119862 119391   #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
119863 119392   #if defined(SQLITE_INTROSPECTION_PRAGMAS)
119864 119393    {/* zName:     */ "function_list",
119865 119394     /* ePragTyp:  */ PragTyp_FUNCTION_LIST,
119866 119395     /* ePragFlg:  */ PragFlg_Result0,
119867         -  /* ColNames:  */ 41, 2,
       119396  +  /* ColNames:  */ 29, 2,
119868 119397     /* iArg:      */ 0 },
119869 119398   #endif
119870 119399   #endif
119871 119400   #if defined(SQLITE_HAS_CODEC)
119872 119401    {/* zName:     */ "hexkey",
119873 119402     /* ePragTyp:  */ PragTyp_HEXKEY,
119874 119403     /* ePragFlg:  */ 0,
119875 119404     /* ColNames:  */ 0, 0,
119876         -  /* iArg:      */ 2 },
       119405  +  /* iArg:      */ 0 },
119877 119406    {/* zName:     */ "hexrekey",
119878 119407     /* ePragTyp:  */ PragTyp_HEXKEY,
119879 119408     /* ePragFlg:  */ 0,
119880 119409     /* ColNames:  */ 0, 0,
119881         -  /* iArg:      */ 3 },
       119410  +  /* iArg:      */ 0 },
119882 119411   #endif
119883 119412   #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
119884 119413   #if !defined(SQLITE_OMIT_CHECK)
119885 119414    {/* zName:     */ "ignore_check_constraints",
119886 119415     /* ePragTyp:  */ PragTyp_FLAG,
119887 119416     /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
119888 119417     /* ColNames:  */ 0, 0,
................................................................................
119896 119425     /* ColNames:  */ 0, 0,
119897 119426     /* iArg:      */ 0 },
119898 119427   #endif
119899 119428   #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
119900 119429    {/* zName:     */ "index_info",
119901 119430     /* ePragTyp:  */ PragTyp_INDEX_INFO,
119902 119431     /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
119903         -  /* ColNames:  */ 15, 3,
       119432  +  /* ColNames:  */ 12, 3,
119904 119433     /* iArg:      */ 0 },
119905 119434    {/* zName:     */ "index_list",
119906 119435     /* ePragTyp:  */ PragTyp_INDEX_LIST,
119907 119436     /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
119908         -  /* ColNames:  */ 26, 5,
       119437  +  /* ColNames:  */ 21, 5,
119909 119438     /* iArg:      */ 0 },
119910 119439    {/* zName:     */ "index_xinfo",
119911 119440     /* ePragTyp:  */ PragTyp_INDEX_INFO,
119912 119441     /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
119913 119442     /* ColNames:  */ 15, 6,
119914 119443     /* iArg:      */ 1 },
119915 119444   #endif
................................................................................
119936 119465    {/* zName:     */ "key",
119937 119466     /* ePragTyp:  */ PragTyp_KEY,
119938 119467     /* ePragFlg:  */ 0,
119939 119468     /* ColNames:  */ 0, 0,
119940 119469     /* iArg:      */ 0 },
119941 119470   #endif
119942 119471   #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
119943         - {/* zName:     */ "legacy_alter_table",
119944         -  /* ePragTyp:  */ PragTyp_FLAG,
119945         -  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
119946         -  /* ColNames:  */ 0, 0,
119947         -  /* iArg:      */ SQLITE_LegacyAlter },
119948 119472    {/* zName:     */ "legacy_file_format",
119949 119473     /* ePragTyp:  */ PragTyp_FLAG,
119950 119474     /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
119951 119475     /* ColNames:  */ 0, 0,
119952 119476     /* iArg:      */ SQLITE_LegacyFileFmt },
119953 119477   #endif
119954 119478   #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
................................................................................
119958 119482     /* ColNames:  */ 0, 0,
119959 119483     /* iArg:      */ 0 },
119960 119484   #endif
119961 119485   #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
119962 119486    {/* zName:     */ "lock_status",
119963 119487     /* ePragTyp:  */ PragTyp_LOCK_STATUS,
119964 119488     /* ePragFlg:  */ PragFlg_Result0,
119965         -  /* ColNames:  */ 43, 2,
       119489  +  /* ColNames:  */ 50, 2,
119966 119490     /* iArg:      */ 0 },
119967 119491   #endif
119968 119492   #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
119969 119493    {/* zName:     */ "locking_mode",
119970 119494     /* ePragTyp:  */ PragTyp_LOCKING_MODE,
119971 119495     /* ePragFlg:  */ PragFlg_Result0|PragFlg_SchemaReq,
119972 119496     /* ColNames:  */ 0, 0,
................................................................................
119984 119508   #endif
119985 119509   #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
119986 119510   #if !defined(SQLITE_OMIT_VIRTUALTABLE)
119987 119511   #if defined(SQLITE_INTROSPECTION_PRAGMAS)
119988 119512    {/* zName:     */ "module_list",
119989 119513     /* ePragTyp:  */ PragTyp_MODULE_LIST,
119990 119514     /* ePragFlg:  */ PragFlg_Result0,
119991         -  /* ColNames:  */ 9, 1,
       119515  +  /* ColNames:  */ 31, 1,
119992 119516     /* iArg:      */ 0 },
119993 119517   #endif
119994 119518   #endif
119995 119519   #endif
119996 119520    {/* zName:     */ "optimize",
119997 119521     /* ePragTyp:  */ PragTyp_OPTIMIZE,
119998 119522     /* ePragFlg:  */ PragFlg_Result1|PragFlg_NeedSchema,
................................................................................
120017 119541     /* ColNames:  */ 0, 0,
120018 119542     /* iArg:      */ 0 },
120019 119543   #endif
120020 119544   #if defined(SQLITE_INTROSPECTION_PRAGMAS)
120021 119545    {/* zName:     */ "pragma_list",
120022 119546     /* ePragTyp:  */ PragTyp_PRAGMA_LIST,
120023 119547     /* ePragFlg:  */ PragFlg_Result0,
120024         -  /* ColNames:  */ 9, 1,
       119548  +  /* ColNames:  */ 31, 1,
120025 119549     /* iArg:      */ 0 },
120026 119550   #endif
120027 119551   #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
120028 119552    {/* zName:     */ "query_only",
120029 119553     /* ePragTyp:  */ PragTyp_FLAG,
120030 119554     /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
120031 119555     /* ColNames:  */ 0, 0,
................................................................................
120048 119572     /* ePragTyp:  */ PragTyp_FLAG,
120049 119573     /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
120050 119574     /* ColNames:  */ 0, 0,
120051 119575     /* iArg:      */ SQLITE_RecTriggers },
120052 119576   #endif
120053 119577   #if defined(SQLITE_HAS_CODEC)
120054 119578    {/* zName:     */ "rekey",
120055         -  /* ePragTyp:  */ PragTyp_KEY,
       119579  +  /* ePragTyp:  */ PragTyp_REKEY,
120056 119580     /* ePragFlg:  */ 0,
120057 119581     /* ColNames:  */ 0, 0,
120058         -  /* iArg:      */ 1 },
       119582  +  /* iArg:      */ 0 },
120059 119583   #endif
120060 119584   #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
120061 119585    {/* zName:     */ "reverse_unordered_selects",
120062 119586     /* ePragTyp:  */ PragTyp_FLAG,
120063 119587     /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
120064 119588     /* ColNames:  */ 0, 0,
120065 119589     /* iArg:      */ SQLITE_ReverseOrder },
................................................................................
120104 119628     /* iArg:      */ SQLITE_SqlTrace },
120105 119629   #endif
120106 119630   #endif
120107 119631   #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) && defined(SQLITE_DEBUG)
120108 119632    {/* zName:     */ "stats",
120109 119633     /* ePragTyp:  */ PragTyp_STATS,
120110 119634     /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
120111         -  /* ColNames:  */ 21, 5,
       119635  +  /* ColNames:  */ 7, 5,
120112 119636     /* iArg:      */ 0 },
120113 119637   #endif
120114 119638   #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
120115 119639    {/* zName:     */ "synchronous",
120116 119640     /* ePragTyp:  */ PragTyp_SYNCHRONOUS,
120117 119641     /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
120118 119642     /* ColNames:  */ 0, 0,
120119 119643     /* iArg:      */ 0 },
120120 119644   #endif
120121 119645   #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
120122 119646    {/* zName:     */ "table_info",
120123 119647     /* ePragTyp:  */ PragTyp_TABLE_INFO,
120124 119648     /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
120125         -  /* ColNames:  */ 8, 6,
       119649  +  /* ColNames:  */ 1, 6,
120126 119650     /* iArg:      */ 0 },
120127         - {/* zName:     */ "table_xinfo",
120128         -  /* ePragTyp:  */ PragTyp_TABLE_INFO,
120129         -  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
120130         -  /* ColNames:  */ 8, 7,
120131         -  /* iArg:      */ 1 },
120132 119651   #endif
120133 119652   #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
120134 119653    {/* zName:     */ "temp_store",
120135 119654     /* ePragTyp:  */ PragTyp_TEMP_STORE,
120136 119655     /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
120137 119656     /* ColNames:  */ 0, 0,
120138 119657     /* iArg:      */ 0 },
120139 119658    {/* zName:     */ "temp_store_directory",
120140 119659     /* ePragTyp:  */ PragTyp_TEMP_STORE_DIRECTORY,
120141 119660     /* ePragFlg:  */ PragFlg_NoColumns1,
120142 119661     /* ColNames:  */ 0, 0,
120143 119662     /* iArg:      */ 0 },
120144 119663   #endif
120145         -#if defined(SQLITE_HAS_CODEC)
120146         - {/* zName:     */ "textkey",
120147         -  /* ePragTyp:  */ PragTyp_KEY,
120148         -  /* ePragFlg:  */ 0,
120149         -  /* ColNames:  */ 0, 0,
120150         -  /* iArg:      */ 4 },
120151         - {/* zName:     */ "textrekey",
120152         -  /* ePragTyp:  */ PragTyp_KEY,
120153         -  /* ePragFlg:  */ 0,
120154         -  /* ColNames:  */ 0, 0,
120155         -  /* iArg:      */ 5 },
120156         -#endif
120157 119664    {/* zName:     */ "threads",
120158 119665     /* ePragTyp:  */ PragTyp_THREADS,
120159 119666     /* ePragFlg:  */ PragFlg_Result0,
120160 119667     /* ColNames:  */ 0, 0,
120161 119668     /* iArg:      */ 0 },
120162 119669   #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
120163 119670    {/* zName:     */ "user_version",
................................................................................
120200 119707     /* ePragTyp:  */ PragTyp_WAL_AUTOCHECKPOINT,
120201 119708     /* ePragFlg:  */ 0,
120202 119709     /* ColNames:  */ 0, 0,
120203 119710     /* iArg:      */ 0 },
120204 119711    {/* zName:     */ "wal_checkpoint",
120205 119712     /* ePragTyp:  */ PragTyp_WAL_CHECKPOINT,
120206 119713     /* ePragFlg:  */ PragFlg_NeedSchema,
120207         -  /* ColNames:  */ 38, 3,
       119714  +  /* ColNames:  */ 46, 3,
120208 119715     /* iArg:      */ 0 },
120209 119716   #endif
120210 119717   #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
120211 119718    {/* zName:     */ "writable_schema",
120212 119719     /* ePragTyp:  */ PragTyp_FLAG,
120213 119720     /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
120214 119721     /* ColNames:  */ 0, 0,
120215         -  /* iArg:      */ SQLITE_WriteSchema|SQLITE_NoSchemaError },
       119722  +  /* iArg:      */ SQLITE_WriteSchema },
120216 119723   #endif
120217 119724   };
120218         -/* Number of pragmas: 62 on by default, 81 total. */
       119725  +/* Number of pragmas: 60 on by default, 77 total. */
120219 119726   
120220 119727   /************** End of pragma.h **********************************************/
120221 119728   /************** Continuing where we left off in pragma.c *********************/
120222 119729   
120223 119730   /*
120224 119731   ** Interpret the given string as a safety level.  Return 0 for OFF,
120225 119732   ** 1 for ON or NORMAL, 2 for FULL, and 3 for EXTRA.  Return 1 for an empty or 
................................................................................
121223 120730   
121224 120731   #ifndef SQLITE_OMIT_FLAG_PRAGMAS
121225 120732     case PragTyp_FLAG: {
121226 120733       if( zRight==0 ){
121227 120734         setPragmaResultColumnNames(v, pPragma);
121228 120735         returnSingleInt(v, (db->flags & pPragma->iArg)!=0 );
121229 120736       }else{
121230         -      u64 mask = pPragma->iArg;    /* Mask of bits to set or clear. */
       120737  +      int mask = pPragma->iArg;    /* Mask of bits to set or clear. */
121231 120738         if( db->autoCommit==0 ){
121232 120739           /* Foreign key support may not be enabled or disabled while not
121233 120740           ** in auto-commit mode.  */
121234 120741           mask &= ~(SQLITE_ForeignKeys);
121235 120742         }
121236 120743   #if SQLITE_USER_AUTHENTICATION
121237 120744         if( db->auth.authLevel==UAUTH_User ){
................................................................................
121272 120779     ** dflt_value: The default value for the column, if any.
121273 120780     ** pk:         Non-zero for PK fields.
121274 120781     */
121275 120782     case PragTyp_TABLE_INFO: if( zRight ){
121276 120783       Table *pTab;
121277 120784       pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb);
121278 120785       if( pTab ){
121279         -      int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
121280 120786         int i, k;
121281 120787         int nHidden = 0;
121282 120788         Column *pCol;
121283 120789         Index *pPk = sqlite3PrimaryKeyIndex(pTab);
121284         -      pParse->nMem = 7;
121285         -      sqlite3CodeVerifySchema(pParse, iTabDb);
       120790  +      pParse->nMem = 6;
       120791  +      sqlite3CodeVerifySchema(pParse, iDb);
121286 120792         sqlite3ViewGetColumnNames(pParse, pTab);
121287 120793         for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
121288         -        int isHidden = IsHiddenColumn(pCol);
121289         -        if( isHidden && pPragma->iArg==0 ){
       120794  +        if( IsHiddenColumn(pCol) ){
121290 120795             nHidden++;
121291 120796             continue;
121292 120797           }
121293 120798           if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
121294 120799             k = 0;
121295 120800           }else if( pPk==0 ){
121296 120801             k = 1;
121297 120802           }else{
121298 120803             for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
121299 120804           }
121300 120805           assert( pCol->pDflt==0 || pCol->pDflt->op==TK_SPAN );
121301         -        sqlite3VdbeMultiLoad(v, 1, pPragma->iArg ? "issisii" : "issisi",
       120806  +        sqlite3VdbeMultiLoad(v, 1, "issisi",
121302 120807                  i-nHidden,
121303 120808                  pCol->zName,
121304 120809                  sqlite3ColumnType(pCol,""),
121305 120810                  pCol->notNull ? 1 : 0,
121306 120811                  pCol->pDflt ? pCol->pDflt->u.zToken : 0,
121307         -               k,
121308         -               isHidden);
       120812  +               k);
121309 120813         }
121310 120814       }
121311 120815     }
121312 120816     break;
121313 120817   
121314 120818   #ifdef SQLITE_DEBUG
121315 120819     case PragTyp_STATS: {
................................................................................
121339 120843   #endif
121340 120844   
121341 120845     case PragTyp_INDEX_INFO: if( zRight ){
121342 120846       Index *pIdx;
121343 120847       Table *pTab;
121344 120848       pIdx = sqlite3FindIndex(db, zRight, zDb);
121345 120849       if( pIdx ){
121346         -      int iIdxDb = sqlite3SchemaToIndex(db, pIdx->pSchema);
121347 120850         int i;
121348 120851         int mx;
121349 120852         if( pPragma->iArg ){
121350 120853           /* PRAGMA index_xinfo (newer version with more rows and columns) */
121351 120854           mx = pIdx->nColumn;
121352 120855           pParse->nMem = 6;
121353 120856         }else{
121354 120857           /* PRAGMA index_info (legacy version) */
121355 120858           mx = pIdx->nKeyCol;
121356 120859           pParse->nMem = 3;
121357 120860         }
121358 120861         pTab = pIdx->pTable;
121359         -      sqlite3CodeVerifySchema(pParse, iIdxDb);
       120862  +      sqlite3CodeVerifySchema(pParse, iDb);
121360 120863         assert( pParse->nMem<=pPragma->nPragCName );
121361 120864         for(i=0; i<mx; i++){
121362 120865           i16 cnum = pIdx->aiColumn[i];
121363 120866           sqlite3VdbeMultiLoad(v, 1, "iisX", i, cnum,
121364 120867                                cnum<0 ? 0 : pTab->aCol[cnum].zName);
121365 120868           if( pPragma->iArg ){
121366 120869             sqlite3VdbeMultiLoad(v, 4, "isiX",
................................................................................
121376 120879   
121377 120880     case PragTyp_INDEX_LIST: if( zRight ){
121378 120881       Index *pIdx;
121379 120882       Table *pTab;
121380 120883       int i;
121381 120884       pTab = sqlite3FindTable(db, zRight, zDb);
121382 120885       if( pTab ){
121383         -      int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
121384 120886         pParse->nMem = 5;
121385         -      sqlite3CodeVerifySchema(pParse, iTabDb);
       120887  +      sqlite3CodeVerifySchema(pParse, iDb);
121386 120888         for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
121387 120889           const char *azOrigin[] = { "c", "u", "pk" };
121388 120890           sqlite3VdbeMultiLoad(v, 1, "isisi",
121389 120891              i,
121390 120892              pIdx->zName,
121391 120893              IsUniqueIndex(pIdx),
121392 120894              azOrigin[pIdx->idxType],
................................................................................
121425 120927     case PragTyp_FUNCTION_LIST: {
121426 120928       int i;
121427 120929       HashElem *j;
121428 120930       FuncDef *p;
121429 120931       pParse->nMem = 2;
121430 120932       for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
121431 120933         for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash ){
121432         -        if( p->funcFlags & SQLITE_FUNC_INTERNAL ) continue;
121433 120934           sqlite3VdbeMultiLoad(v, 1, "si", p->zName, 1);
121434 120935         }
121435 120936       }
121436 120937       for(j=sqliteHashFirst(&db->aFunc); j; j=sqliteHashNext(j)){
121437 120938         p = (FuncDef*)sqliteHashData(j);
121438 120939         sqlite3VdbeMultiLoad(v, 1, "si", p->zName, 0);
121439 120940       }
................................................................................
121467 120968     case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
121468 120969       FKey *pFK;
121469 120970       Table *pTab;
121470 120971       pTab = sqlite3FindTable(db, zRight, zDb);
121471 120972       if( pTab ){
121472 120973         pFK = pTab->pFKey;
121473 120974         if( pFK ){
121474         -        int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
121475 120975           int i = 0; 
121476 120976           pParse->nMem = 8;
121477         -        sqlite3CodeVerifySchema(pParse, iTabDb);
       120977  +        sqlite3CodeVerifySchema(pParse, iDb);
121478 120978           while(pFK){
121479 120979             int j;
121480 120980             for(j=0; j<pFK->nCol; j++){
121481 120981               sqlite3VdbeMultiLoad(v, 1, "iissssss",
121482 120982                      i,
121483 120983                      j,
121484 120984                      pFK->zTo,
................................................................................
121515 121015       int addrOk;            /* Jump here if the key is OK */
121516 121016       int *aiCols;           /* child to parent column mapping */
121517 121017   
121518 121018       regResult = pParse->nMem+1;
121519 121019       pParse->nMem += 4;
121520 121020       regKey = ++pParse->nMem;
121521 121021       regRow = ++pParse->nMem;
       121022  +    sqlite3CodeVerifySchema(pParse, iDb);
121522 121023       k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
121523 121024       while( k ){
121524         -      int iTabDb;
121525 121025         if( zRight ){
121526 121026           pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
121527 121027           k = 0;
121528 121028         }else{
121529 121029           pTab = (Table*)sqliteHashData(k);
121530 121030           k = sqliteHashNext(k);
121531 121031         }
121532 121032         if( pTab==0 || pTab->pFKey==0 ) continue;
121533         -      iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
121534         -      sqlite3CodeVerifySchema(pParse, iTabDb);
121535         -      sqlite3TableLock(pParse, iTabDb, pTab->tnum, 0, pTab->zName);
       121033  +      sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
121536 121034         if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
121537         -      sqlite3OpenTable(pParse, 0, iTabDb, pTab, OP_OpenRead);
       121035  +      sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
121538 121036         sqlite3VdbeLoadString(v, regResult, pTab->zName);
121539 121037         for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
121540 121038           pParent = sqlite3FindTable(db, pFK->zTo, zDb);
121541 121039           if( pParent==0 ) continue;
121542 121040           pIdx = 0;
121543         -        sqlite3TableLock(pParse, iTabDb, pParent->tnum, 0, pParent->zName);
       121041  +        sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
121544 121042           x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
121545 121043           if( x==0 ){
121546 121044             if( pIdx==0 ){
121547         -            sqlite3OpenTable(pParse, i, iTabDb, pParent, OP_OpenRead);
       121045  +            sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
121548 121046             }else{
121549         -            sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iTabDb);
       121047  +            sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
121550 121048               sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
121551 121049             }
121552 121050           }else{
121553 121051             k = 0;
121554 121052             break;
121555 121053           }
121556 121054         }
................................................................................
122311 121809         sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zDbSName, zState);
122312 121810       }
122313 121811       break;
122314 121812     }
122315 121813   #endif
122316 121814   
122317 121815   #ifdef SQLITE_HAS_CODEC
122318         -  /* Pragma        iArg
122319         -  ** ----------   ------
122320         -  **  key           0
122321         -  **  rekey         1
122322         -  **  hexkey        2
122323         -  **  hexrekey      3
122324         -  **  textkey       4
122325         -  **  textrekey     5
122326         -  */
122327 121816     case PragTyp_KEY: {
122328         -    if( zRight ){
122329         -      int n = pPragma->iArg<4 ? sqlite3Strlen30(zRight) : -1;
122330         -      if( (pPragma->iArg & 1)==0 ){
122331         -        sqlite3_key_v2(db, zDb, zRight, n);
122332         -      }else{
122333         -        sqlite3_rekey_v2(db, zDb, zRight, n);
122334         -      }
122335         -    }
       121817  +    if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
       121818  +    break;
       121819  +  }
       121820  +  case PragTyp_REKEY: {
       121821  +    if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
122336 121822       break;
122337 121823     }
122338 121824     case PragTyp_HEXKEY: {
122339 121825       if( zRight ){
122340 121826         u8 iByte;
122341 121827         int i;
122342 121828         char zKey[40];
122343 121829         for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
122344 121830           iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
122345 121831           if( (i&1)!=0 ) zKey[i/2] = iByte;
122346 121832         }
122347         -      if( (pPragma->iArg & 1)==0 ){
       121833  +      if( (zLeft[3] & 0xf)==0xb ){
122348 121834           sqlite3_key_v2(db, zDb, zKey, i/2);
122349 121835         }else{
122350 121836           sqlite3_rekey_v2(db, zDb, zKey, i/2);
122351 121837         }
122352 121838       }
122353 121839       break;
122354 121840     }
................................................................................
122670 122156     0,                           /* xSync - sync transaction */
122671 122157     0,                           /* xCommit - commit transaction */
122672 122158     0,                           /* xRollback - rollback transaction */
122673 122159     0,                           /* xFindFunction - function overloading */
122674 122160     0,                           /* xRename - rename the table */
122675 122161     0,                           /* xSavepoint */
122676 122162     0,                           /* xRelease */
122677         -  0,                           /* xRollbackTo */
122678         -  0                            /* xShadowName */
       122163  +  0                            /* xRollbackTo */
122679 122164   };
122680 122165   
122681 122166   /*
122682 122167   ** Check to see if zTabName is really the name of a pragma.  If it is,
122683 122168   ** then register an eponymous virtual table for that pragma and return
122684 122169   ** a pointer to the Module object for the new virtual table.
122685 122170   */
................................................................................
123024 122509       }
123025 122510   #endif
123026 122511     }
123027 122512     if( db->mallocFailed ){
123028 122513       rc = SQLITE_NOMEM_BKPT;
123029 122514       sqlite3ResetAllSchemasOfConnection(db);
123030 122515     }
123031         -  if( rc==SQLITE_OK || (db->flags&SQLITE_NoSchemaError)){
123032         -    /* Black magic: If the SQLITE_NoSchemaError flag is set, then consider
       122516  +  if( rc==SQLITE_OK || (db->flags&SQLITE_WriteSchema)){
       122517  +    /* Black magic: If the SQLITE_WriteSchema flag is set, then consider
123033 122518       ** the schema loaded, even if errors occurred. In this situation the 
123034 122519       ** current sqlite3_prepare() operation will fail, but the following one
123035 122520       ** will attempt to compile the supplied statement against whatever subset
123036 122521       ** of the schema was loaded before the error occurred. The primary
123037 122522       ** purpose of this is to allow access to the sqlite_master table
123038 122523       ** even when its contents have been corrupted.
123039 122524       */
................................................................................
123406 122891     sqlite3BtreeLeaveAll(db);
123407 122892     rc = sqlite3ApiExit(db, rc);
123408 122893     assert( (rc&db->errMask)==rc );
123409 122894     sqlite3_mutex_leave(db->mutex);
123410 122895     return rc;
123411 122896   }
123412 122897   
123413         -#ifdef SQLITE_ENABLE_NORMALIZE
123414         -/*
123415         -** Checks if the specified token is a table, column, or function name,
123416         -** based on the databases associated with the statement being prepared.
123417         -** If the function fails, zero is returned and pRc is filled with the
123418         -** error code.
123419         -*/
123420         -static int shouldTreatAsIdentifier(
123421         -  sqlite3 *db,        /* Database handle. */
123422         -  const char *zToken, /* Pointer to start of token to be checked */
123423         -  int nToken,         /* Length of token to be checked */
123424         -  int *pRc            /* Pointer to error code upon failure */
123425         -){
123426         -  int bFound = 0;     /* Non-zero if token is an identifier name. */
123427         -  int i, j;           /* Database and column loop indexes. */
123428         -  Schema *pSchema;    /* Schema for current database. */
123429         -  Hash *pHash;        /* Hash table of tables for current database. */
123430         -  HashElem *e;        /* Hash element for hash table iteration. */
123431         -  Table *pTab;        /* Database table for columns being checked. */
123432         -
123433         -  if( sqlite3IsRowidN(zToken, nToken) ){
123434         -    return 1;
123435         -  }
123436         -  if( nToken>0 ){
123437         -    int hash = SQLITE_FUNC_HASH(sqlite3UpperToLower[(u8)zToken[0]], nToken);
123438         -    if( sqlite3FunctionSearchN(hash, zToken, nToken) ) return 1;
123439         -  }
123440         -  assert( db!=0 );
123441         -  sqlite3_mutex_enter(db->mutex);
123442         -  sqlite3BtreeEnterAll(db);
123443         -  for(i=0; i<db->nDb; i++){
123444         -    pHash = &db->aFunc;
123445         -    if( sqlite3HashFindN(pHash, zToken, nToken) ){
123446         -      bFound = 1;
123447         -      break;
123448         -    }
123449         -    pSchema = db->aDb[i].pSchema;
123450         -    if( pSchema==0 ) continue;
123451         -    pHash = &pSchema->tblHash;
123452         -    if( sqlite3HashFindN(pHash, zToken, nToken) ){
123453         -      bFound = 1;
123454         -      break;
123455         -    }
123456         -    for(e=sqliteHashFirst(pHash); e; e=sqliteHashNext(e)){
123457         -      pTab = sqliteHashData(e);
123458         -      if( pTab==0 ) continue;
123459         -      pHash = pTab->pColHash;
123460         -      if( pHash==0 ){
123461         -        pTab->pColHash = pHash = sqlite3_malloc(sizeof(Hash));
123462         -        if( pHash ){
123463         -          sqlite3HashInit(pHash);
123464         -          for(j=0; j<pTab->nCol; j++){
123465         -            Column *pCol = &pTab->aCol[j];
123466         -            sqlite3HashInsert(pHash, pCol->zName, pCol);
123467         -          }
123468         -        }else{
123469         -          *pRc = SQLITE_NOMEM_BKPT;
123470         -          bFound = 0;
123471         -          goto done;
123472         -        }
123473         -      }
123474         -      if( pHash && sqlite3HashFindN(pHash, zToken, nToken) ){
123475         -        bFound = 1;
123476         -        goto done;
123477         -      }
123478         -    }
123479         -  }
123480         -done:
123481         -  sqlite3BtreeLeaveAll(db);
123482         -  sqlite3_mutex_leave(db->mutex);
123483         -  return bFound;
123484         -}
123485         -
123486         -/*
123487         -** Attempt to estimate the final output buffer size needed for the fully
123488         -** normalized version of the specified SQL string.  This should take into
123489         -** account any potential expansion that could occur (e.g. via IN clauses
123490         -** being expanded, etc).  This size returned is the total number of bytes
123491         -** including the NUL terminator.
123492         -*/
123493         -static int estimateNormalizedSize(
123494         -  const char *zSql, /* The original SQL string */
123495         -  int nSql,         /* Length of original SQL string */
123496         -  u8 prepFlags      /* The flags passed to sqlite3_prepare_v3() */
123497         -){
123498         -  int nOut = nSql + 4;
123499         -  const char *z = zSql;
123500         -  while( nOut<nSql*5 ){
123501         -    while( z[0]!=0 && z[0]!='I' && z[0]!='i' ){ z++; }
123502         -    if( z[0]==0 ) break;
123503         -    z++;
123504         -    if( z[0]!='N' && z[0]!='n' ) break;
123505         -    z++;
123506         -    while( sqlite3Isspace(z[0]) ){ z++; }
123507         -    if( z[0]!='(' ) break;
123508         -    z++;
123509         -    nOut += 5; /* ?,?,? */
123510         -  }
123511         -  return nOut;
123512         -}
123513         -
123514         -/*
123515         -** Copy the current token into the output buffer while dealing with quoted
123516         -** identifiers.  By default, all letters will be converted into lowercase.
123517         -** If the bUpper flag is set, uppercase will be used.  The piOut argument
123518         -** will be used to update the target index into the output string.
123519         -*/
123520         -static void copyNormalizedToken(
123521         -  const char *zSql, /* The original SQL string */
123522         -  int iIn,          /* Current index into the original SQL string */
123523         -  int nToken,       /* Number of bytes in the current token */
123524         -  int tokenFlags,   /* Flags returned by the tokenizer */
123525         -  char *zOut,       /* The output string */
123526         -  int *piOut        /* Pointer to target index into the output string */
123527         -){
123528         -  int bQuoted = tokenFlags & SQLITE_TOKEN_QUOTED;
123529         -  int bKeyword = tokenFlags & SQLITE_TOKEN_KEYWORD;
123530         -  int j = *piOut, k = 0;
123531         -  for(; k<nToken; k++){
123532         -    if( bQuoted ){
123533         -      if( k==0 && iIn>0 ){
123534         -        zOut[j++] = '"';
123535         -        continue;
123536         -      }else if( k==nToken-1 ){
123537         -        zOut[j++] = '"';
123538         -        continue;
123539         -      }
123540         -    }
123541         -    if( bKeyword ){
123542         -      zOut[j++] = sqlite3Toupper(zSql[iIn+k]);
123543         -    }else{
123544         -      zOut[j++] = sqlite3Tolower(zSql[iIn+k]);
123545         -    }
123546         -  }
123547         -  *piOut = j;
123548         -}
123549         -
123550         -/*
123551         -** Perform normalization of the SQL contained in the prepared statement and
123552         -** store the result in the zNormSql field.  The schema for the associated
123553         -** databases are consulted while performing the normalization in order to
123554         -** determine if a token appears to be an identifier.  All identifiers are
123555         -** left intact in the normalized SQL and all literals are replaced with a
123556         -** single '?'.
123557         -*/
123558         -SQLITE_PRIVATE void sqlite3Normalize(
123559         -  Vdbe *pVdbe,      /* VM being reprepared */
123560         -  const char *zSql, /* The original SQL string */
123561         -  int nSql,         /* Size of the input string in bytes */
123562         -  u8 prepFlags      /* The flags passed to sqlite3_prepare_v3() */
123563         -){
123564         -  sqlite3 *db;           /* Database handle. */
123565         -  char *z;               /* The output string */
123566         -  int nZ;                /* Size of the output string in bytes */
123567         -  int i;                 /* Next character to read from zSql[] */
123568         -  int j;                 /* Next character to fill in on z[] */
123569         -  int tokenType = 0;     /* Type of the next token */
123570         -  int prevTokenType = 0; /* Type of the previous token, except spaces */
123571         -  int n;                 /* Size of the next token */
123572         -  int nParen = 0;        /* Nesting level of parenthesis */
123573         -  Hash inHash;           /* Table of parenthesis levels to output index. */
123574         -
123575         -  db = sqlite3VdbeDb(pVdbe);
123576         -  assert( db!=0 );
123577         -  assert( pVdbe->zNormSql==0 );
123578         -  if( zSql==0 ) return;
123579         -  nZ = estimateNormalizedSize(zSql, nSql, prepFlags);
123580         -  z = sqlite3DbMallocRawNN(db, nZ);
123581         -  if( z==0 ) return;
123582         -  sqlite3HashInit(&inHash);
123583         -  for(i=j=0; i<nSql && zSql[i]; i+=n){
123584         -    int flags = 0;
123585         -    if( tokenType!=TK_SPACE ) prevTokenType = tokenType;
123586         -    n = sqlite3GetTokenNormalized((unsigned char*)zSql+i, &tokenType, &flags);
123587         -    switch( tokenType ){
123588         -      case TK_SPACE: {
123589         -        break;
123590         -      }
123591         -      case TK_ILLEGAL: {
123592         -        sqlite3DbFree(db, z);
123593         -        sqlite3HashClear(&inHash);
123594         -        return;
123595         -      }
123596         -      case TK_STRING:
123597         -      case TK_INTEGER:
123598         -      case TK_FLOAT:
123599         -      case TK_VARIABLE:
123600         -      case TK_BLOB: {
123601         -        z[j++] = '?';
123602         -        break;
123603         -      }
123604         -      case TK_LP:
123605         -      case TK_RP: {
123606         -        if( tokenType==TK_LP ){
123607         -          nParen++;
123608         -          if( prevTokenType==TK_IN ){
123609         -            assert( nParen<nSql );
123610         -            sqlite3HashInsert(&inHash, zSql+nParen, SQLITE_INT_TO_PTR(j));
123611         -          }
123612         -        }else{
123613         -          int jj;
123614         -          assert( nParen<nSql );
123615         -          jj = SQLITE_PTR_TO_INT(sqlite3HashFind(&inHash, zSql+nParen));
123616         -          if( jj>0 ){
123617         -            sqlite3HashInsert(&inHash, zSql+nParen, 0);
123618         -            assert( jj+6<nZ );
123619         -            memcpy(z+jj+1, "?,?,?", 5);
123620         -            j = jj+6;
123621         -            assert( nZ-1-j>=0 );
123622         -            assert( nZ-1-j<nZ );
123623         -            memset(z+j, 0, nZ-1-j);
123624         -          }
123625         -          nParen--;
123626         -        }
123627         -        assert( nParen>=0 );
123628         -        /* Fall through */
123629         -      }
123630         -      case TK_MINUS:
123631         -      case TK_SEMI:
123632         -      case TK_PLUS:
123633         -      case TK_STAR:
123634         -      case TK_SLASH:
123635         -      case TK_REM:
123636         -      case TK_EQ:
123637         -      case TK_LE:
123638         -      case TK_NE:
123639         -      case TK_LSHIFT:
123640         -      case TK_LT:
123641         -      case TK_RSHIFT:
123642         -      case TK_GT:
123643         -      case TK_GE:
123644         -      case TK_BITOR:
123645         -      case TK_CONCAT:
123646         -      case TK_COMMA:
123647         -      case TK_BITAND:
123648         -      case TK_BITNOT:
123649         -      case TK_DOT:
123650         -      case TK_IN:
123651         -      case TK_IS:
123652         -      case TK_NOT:
123653         -      case TK_NULL:
123654         -      case TK_ID: {
123655         -        if( tokenType==TK_NULL ){
123656         -          if( prevTokenType==TK_IS || prevTokenType==TK_NOT ){
123657         -            /* NULL is a keyword in this case, not a literal value */
123658         -          }else{
123659         -            /* Here the NULL is a literal value */
123660         -            z[j++] = '?';
123661         -            break;
123662         -          }
123663         -        }
123664         -        if( j>0 && sqlite3IsIdChar(z[j-1]) && sqlite3IsIdChar(zSql[i]) ){
123665         -          z[j++] = ' ';
123666         -        }
123667         -        if( tokenType==TK_ID ){
123668         -          int i2 = i, n2 = n, rc = SQLITE_OK;
123669         -          if( nParen>0 ){
123670         -            assert( nParen<nSql );
123671         -            sqlite3HashInsert(&inHash, zSql+nParen, 0);
123672         -          }
123673         -          if( flags&SQLITE_TOKEN_QUOTED ){ i2++; n2-=2; }
123674         -          if( shouldTreatAsIdentifier(db, zSql+i2, n2, &rc)==0 ){
123675         -            if( rc!=SQLITE_OK ){
123676         -              sqlite3DbFree(db, z);
123677         -              sqlite3HashClear(&inHash);
123678         -              return;
123679         -            }
123680         -            if( sqlite3_keyword_check(zSql+i2, n2)==0 ){
123681         -              z[j++] = '?';
123682         -              break;
123683         -            }
123684         -          }
123685         -        }
123686         -        copyNormalizedToken(zSql, i, n, flags, z, &j);
123687         -        break;
123688         -      }
123689         -    }
123690         -  }
123691         -  assert( j<nZ && "one" );
123692         -  while( j>0 && z[j-1]==' ' ){ j--; }
123693         -  if( j>0 && z[j-1]!=';' ){ z[j++] = ';'; }
123694         -  z[j] = 0;
123695         -  assert( j<nZ && "two" );
123696         -  pVdbe->zNormSql = z;
123697         -  sqlite3HashClear(&inHash);
123698         -}
123699         -#endif /* SQLITE_ENABLE_NORMALIZE */
123700         -
123701 122898   /*
123702 122899   ** Rerun the compilation of a statement after a schema change.
123703 122900   **
123704 122901   ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
123705 122902   ** if the statement cannot be recompiled because another connection has
123706 122903   ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
123707 122904   ** occurs, return SQLITE_SCHEMA.
................................................................................
124706 123903     int i;
124707 123904     int nDefer = 0;
124708 123905     ExprList *pExtra = 0;
124709 123906     for(i=0; i<pEList->nExpr; i++){
124710 123907       struct ExprList_item *pItem = &pEList->a[i];
124711 123908       if( pItem->u.x.iOrderByCol==0 ){
124712 123909         Expr *pExpr = pItem->pExpr;
124713         -      Table *pTab = pExpr->y.pTab;
       123910  +      Table *pTab = pExpr->pTab;
124714 123911         if( pExpr->op==TK_COLUMN && pExpr->iColumn>=0 && pTab && !IsVirtual(pTab)
124715 123912          && (pTab->aCol[pExpr->iColumn].colFlags & COLFLAG_SORTERREF)
124716 123913         ){
124717 123914           int j;
124718 123915           for(j=0; j<nDefer; j++){
124719 123916             if( pSort->aDefer[j].iCsr==pExpr->iTable ) break;
124720 123917           }
................................................................................
124729 123926                 pPk = sqlite3PrimaryKeyIndex(pTab);
124730 123927                 nKey = pPk->nKeyCol;
124731 123928               }
124732 123929               for(k=0; k<nKey; k++){
124733 123930                 Expr *pNew = sqlite3PExpr(pParse, TK_COLUMN, 0, 0);
124734 123931                 if( pNew ){
124735 123932                   pNew->iTable = pExpr->iTable;
124736         -                pNew->y.pTab = pExpr->y.pTab;
       123933  +                pNew->pTab = pExpr->pTab;
124737 123934                   pNew->iColumn = pPk ? pPk->aiColumn[k] : -1;
124738 123935                   pExtra = sqlite3ExprListAppend(pParse, pExtra, pNew);
124739 123936                 }
124740 123937               }
124741         -            pSort->aDefer[nDefer].pTab = pExpr->y.pTab;
       123938  +            pSort->aDefer[nDefer].pTab = pExpr->pTab;
124742 123939               pSort->aDefer[nDefer].iCsr = pExpr->iTable;
124743 123940               pSort->aDefer[nDefer].nKey = nKey;
124744 123941               nDefer++;
124745 123942             }
124746 123943           }
124747 123944           pItem->bSorterRef = 1;
124748 123945         }
................................................................................
125583 124780           ** This is not a problem, as the column type of "t1.col" is never
125584 124781           ** used. When columnType() is called on the expression 
125585 124782           ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
125586 124783           ** branch below.  */
125587 124784           break;
125588 124785         }
125589 124786   
125590         -      assert( pTab && pExpr->y.pTab==pTab );
       124787  +      assert( pTab && pExpr->pTab==pTab );
125591 124788         if( pS ){
125592 124789           /* The "table" is actually a sub-select or a view in the FROM clause
125593 124790           ** of the SELECT statement. Return the declaration type and origin
125594 124791           ** data for the result-set column of the sub-select.
125595 124792           */
125596 124793           if( iCol>=0 && iCol<pS->pEList->nExpr ){
125597 124794             /* If iCol is less than zero, then the expression requests the
................................................................................
125768 124965     srcName = (db->flags & SQLITE_ShortColNames)!=0 || fullName;
125769 124966     sqlite3VdbeSetNumCols(v, pEList->nExpr);
125770 124967     for(i=0; i<pEList->nExpr; i++){
125771 124968       Expr *p = pEList->a[i].pExpr;
125772 124969   
125773 124970       assert( p!=0 );
125774 124971       assert( p->op!=TK_AGG_COLUMN );  /* Agg processing has not run yet */
125775         -    assert( p->op!=TK_COLUMN || p->y.pTab!=0 ); /* Covering idx not yet coded */
       124972  +    assert( p->op!=TK_COLUMN || p->pTab!=0 ); /* Covering idx not yet coded */
125776 124973       if( pEList->a[i].zName ){
125777 124974         /* An AS clause always takes first priority */
125778 124975         char *zName = pEList->a[i].zName;
125779 124976         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
125780 124977       }else if( srcName && p->op==TK_COLUMN ){
125781 124978         char *zCol;
125782 124979         int iCol = p->iColumn;
125783         -      pTab = p->y.pTab;
       124980  +      pTab = p->pTab;
125784 124981         assert( pTab!=0 );
125785 124982         if( iCol<0 ) iCol = pTab->iPKey;
125786 124983         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
125787 124984         if( iCol<0 ){
125788 124985           zCol = "rowid";
125789 124986         }else{
125790 124987           zCol = pTab->aCol[iCol].zName;
................................................................................
125867 125064           pColExpr = pColExpr->pRight;
125868 125065           assert( pColExpr!=0 );
125869 125066         }
125870 125067         assert( pColExpr->op!=TK_AGG_COLUMN );
125871 125068         if( pColExpr->op==TK_COLUMN ){
125872 125069           /* For columns use the column name name */
125873 125070           int iCol = pColExpr->iColumn;
125874         -        Table *pTab = pColExpr->y.pTab;
       125071  +        Table *pTab = pColExpr->pTab;
125875 125072           assert( pTab!=0 );
125876 125073           if( iCol<0 ) iCol = pTab->iPKey;
125877 125074           zName = iCol>=0 ? pTab->aCol[iCol].zName : "rowid";
125878 125075         }else if( pColExpr->op==TK_ID ){
125879 125076           assert( !ExprHasProperty(pColExpr, EP_IntValue) );
125880 125077           zName = pColExpr->u.zToken;
125881 125078         }else{
................................................................................
126221 125418     SelectDest destQueue;         /* SelectDest targetting the Queue table */
126222 125419     int i;                        /* Loop counter */
126223 125420     int rc;                       /* Result code */
126224 125421     ExprList *pOrderBy;           /* The ORDER BY clause */
126225 125422     Expr *pLimit;                 /* Saved LIMIT and OFFSET */
126226 125423     int regLimit, regOffset;      /* Registers used by LIMIT and OFFSET */
126227 125424   
126228         -#ifndef SQLITE_OMIT_WINDOWFUNC
126229         -  if( p->pWin ){
126230         -    sqlite3ErrorMsg(pParse, "cannot use window functions in recursive queries");
126231         -    return;
126232         -  }
126233         -#endif
126234         -
126235 125425     /* Obtain authorization to do a recursive query */
126236 125426     if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
126237 125427   
126238 125428     /* Process the LIMIT and OFFSET clauses, if they exist */
126239 125429     addrBreak = sqlite3VdbeMakeLabel(v);
126240 125430     p->nSelectRow = 320;  /* 4 billion rows */
126241 125431     computeLimitRegisters(pParse, p, addrBreak);
................................................................................
127977 127167   #endif
127978 127168   
127979 127169     return 1;
127980 127170   }
127981 127171   #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
127982 127172   
127983 127173   /*
127984         -** A structure to keep track of all of the column values that are fixed to
       127174  +** A structure to keep track of all of the column values that fixed to
127985 127175   ** a known value due to WHERE clause constraints of the form COLUMN=VALUE.
127986 127176   */
127987 127177   typedef struct WhereConst WhereConst;
127988 127178   struct WhereConst {
127989 127179     Parse *pParse;   /* Parsing context */
127990 127180     int nConst;      /* Number for COLUMN=CONSTANT terms */
127991 127181     int nChng;       /* Number of times a constant is propagated */
127992 127182     Expr **apExpr;   /* [i*2] is COLUMN and [i*2+1] is VALUE */
127993 127183   };
127994 127184   
127995 127185   /*
127996         -** Add a new entry to the pConst object.  Except, do not add duplicate
127997         -** pColumn entires.
       127186  +** Add a new entry to the pConst object
127998 127187   */
127999 127188   static void constInsert(
128000         -  WhereConst *pConst,      /* The WhereConst into which we are inserting */
128001         -  Expr *pColumn,           /* The COLUMN part of the constraint */
128002         -  Expr *pValue             /* The VALUE part of the constraint */
       127189  +  WhereConst *pConst,
       127190  +  Expr *pColumn,
       127191  +  Expr *pValue
128003 127192   ){
128004         -  int i;
128005         -  assert( pColumn->op==TK_COLUMN );
128006         -
128007         -  /* 2018-10-25 ticket [cf5ed20f]
128008         -  ** Make sure the same pColumn is not inserted more than once */
128009         -  for(i=0; i<pConst->nConst; i++){
128010         -    const Expr *pExpr = pConst->apExpr[i*2];
128011         -    assert( pExpr->op==TK_COLUMN );
128012         -    if( pExpr->iTable==pColumn->iTable
128013         -     && pExpr->iColumn==pColumn->iColumn
128014         -    ){
128015         -      return;  /* Already present.  Return without doing anything. */
128016         -    }
128017         -  }
128018 127193   
128019 127194     pConst->nConst++;
128020 127195     pConst->apExpr = sqlite3DbReallocOrFree(pConst->pParse->db, pConst->apExpr,
128021 127196                            pConst->nConst*2*sizeof(Expr*));
128022 127197     if( pConst->apExpr==0 ){
128023 127198       pConst->nConst = 0;
128024 127199     }else{
................................................................................
131992 131167   #ifndef SQLITE_OMIT_FLOATING_POINT
131993 131168     if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
131994 131169       sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
131995 131170     }
131996 131171   #endif
131997 131172   }
131998 131173   
131999         -/*
132000         -** Check to see if column iCol of index pIdx references any of the
132001         -** columns defined by aXRef and chngRowid.  Return true if it does
132002         -** and false if not.  This is an optimization.  False-positives are a
132003         -** performance degradation, but false-negatives can result in a corrupt
132004         -** index and incorrect answers.
132005         -**
132006         -** aXRef[j] will be non-negative if column j of the original table is
132007         -** being updated.  chngRowid will be true if the rowid of the table is
132008         -** being updated.
132009         -*/
132010         -static int indexColumnIsBeingUpdated(
132011         -  Index *pIdx,      /* The index to check */
132012         -  int iCol,         /* Which column of the index to check */
132013         -  int *aXRef,       /* aXRef[j]>=0 if column j is being updated */
132014         -  int chngRowid     /* true if the rowid is being updated */
132015         -){
132016         -  i16 iIdxCol = pIdx->aiColumn[iCol];
132017         -  assert( iIdxCol!=XN_ROWID ); /* Cannot index rowid */
132018         -  if( iIdxCol>=0 ){
132019         -    return aXRef[iIdxCol]>=0;
132020         -  }
132021         -  assert( iIdxCol==XN_EXPR );
132022         -  assert( pIdx->aColExpr!=0 );
132023         -  assert( pIdx->aColExpr->a[iCol].pExpr!=0 );
132024         -  return sqlite3ExprReferencesUpdatedColumn(pIdx->aColExpr->a[iCol].pExpr,
132025         -                                            aXRef,chngRowid);
132026         -}
132027         -
132028         -/*
132029         -** Check to see if index pIdx is a partial index whose conditional
132030         -** expression might change values due to an UPDATE.  Return true if
132031         -** the index is subject to change and false if the index is guaranteed
132032         -** to be unchanged.  This is an optimization.  False-positives are a
132033         -** performance degradation, but false-negatives can result in a corrupt
132034         -** index and incorrect answers.
132035         -**
132036         -** aXRef[j] will be non-negative if column j of the original table is
132037         -** being updated.  chngRowid will be true if the rowid of the table is
132038         -** being updated.
132039         -*/
132040         -static int indexWhereClauseMightChange(
132041         -  Index *pIdx,      /* The index to check */
132042         -  int *aXRef,       /* aXRef[j]>=0 if column j is being updated */
132043         -  int chngRowid     /* true if the rowid is being updated */
132044         -){
132045         -  if( pIdx->pPartIdxWhere==0 ) return 0;
132046         -  return sqlite3ExprReferencesUpdatedColumn(pIdx->pPartIdxWhere,
132047         -                                            aXRef, chngRowid);
132048         -}
132049         -
132050 131174   /*
132051 131175   ** Process an UPDATE statement.
132052 131176   **
132053 131177   **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
132054 131178   **          \_______/ \________/     \______/       \________________/
132055 131179   *            onError   pTabList      pChanges             pWhere
132056 131180   */
................................................................................
132266 131390     pTabList->a[0].colUsed = IsVirtual(pTab) ? ALLBITS : 0;
132267 131391   
132268 131392     hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
132269 131393   
132270 131394     /* There is one entry in the aRegIdx[] array for each index on the table
132271 131395     ** being updated.  Fill in aRegIdx[] with a register number that will hold
132272 131396     ** the key for accessing each index.
       131397  +  **
       131398  +  ** FIXME:  Be smarter about omitting indexes that use expressions.
132273 131399     */
132274 131400     for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
132275 131401       int reg;
132276         -    if( chngKey || hasFK>1 || pIdx==pPk
132277         -     || indexWhereClauseMightChange(pIdx,aXRef,chngRowid)
132278         -    ){
       131402  +    if( chngKey || hasFK>1 || pIdx->pPartIdxWhere || pIdx==pPk ){
132279 131403         reg = ++pParse->nMem;
132280 131404         pParse->nMem += pIdx->nColumn;
132281 131405       }else{
132282 131406         reg = 0;
132283 131407         for(i=0; i<pIdx->nKeyCol; i++){
132284         -        if( indexColumnIsBeingUpdated(pIdx, i, aXRef, chngRowid) ){
       131408  +        i16 iIdxCol = pIdx->aiColumn[i];
       131409  +        if( iIdxCol<0 || aXRef[iIdxCol]>=0 ){
132285 131410             reg = ++pParse->nMem;
132286 131411             pParse->nMem += pIdx->nColumn;
132287 131412             if( (onError==OE_Replace)
132288 131413              || (onError==OE_Default && pIdx->onError==OE_Replace) 
132289 131414             ){
132290 131415               bReplace = 1;
132291 131416             }
................................................................................
132826 131951   
132827 131952     /* Populate the argument registers. */
132828 131953     for(i=0; i<pTab->nCol; i++){
132829 131954       if( aXRef[i]>=0 ){
132830 131955         sqlite3ExprCode(pParse, pChanges->a[aXRef[i]].pExpr, regArg+2+i);
132831 131956       }else{
132832 131957         sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, i, regArg+2+i);
132833         -      sqlite3VdbeChangeP5(v, OPFLAG_NOCHNG);/* Enable sqlite3_vtab_nochange() */
       131958  +      sqlite3VdbeChangeP5(v, 1); /* Enable sqlite3_vtab_nochange() */
132834 131959       }
132835 131960     }
132836 131961     if( HasRowid(pTab) ){
132837 131962       sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg);
132838 131963       if( pRowid ){
132839 131964         sqlite3ExprCode(pParse, pRowid, regArg+1);
132840 131965       }else{
................................................................................
133327 132452     saved_flags = db->flags;
133328 132453     saved_mDbFlags = db->mDbFlags;
133329 132454     saved_nChange = db->nChange;
133330 132455     saved_nTotalChange = db->nTotalChange;
133331 132456     saved_mTrace = db->mTrace;
133332 132457     db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks;
133333 132458     db->mDbFlags |= DBFLAG_PreferBuiltin | DBFLAG_Vacuum;
133334         -  db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder
133335         -                   | SQLITE_Defensive | SQLITE_CountRows);
       132459  +  db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder | SQLITE_CountRows);
133336 132460     db->mTrace = 0;
133337 132461   
133338 132462     zDbMain = db->aDb[iDb].zDbSName;
133339 132463     pMain = db->aDb[iDb].pBt;
133340 132464     isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
133341 132465   
133342 132466     /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
................................................................................
133870 132994   SQLITE_PRIVATE void sqlite3VtabBeginParse(
133871 132995     Parse *pParse,        /* Parsing context */
133872 132996     Token *pName1,        /* Name of new table, or database name */
133873 132997     Token *pName2,        /* Name of new table or NULL */
133874 132998     Token *pModuleName,   /* Name of the module for the virtual table */
133875 132999     int ifNotExists       /* No error if the table already exists */
133876 133000   ){
       133001  +  int iDb;              /* The database the table is being created in */
133877 133002     Table *pTable;        /* The new virtual table */
133878 133003     sqlite3 *db;          /* Database connection */
133879 133004   
133880 133005     sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
133881 133006     pTable = pParse->pNewTable;
133882 133007     if( pTable==0 ) return;
133883 133008     assert( 0==pTable->pIndex );
133884 133009   
133885 133010     db = pParse->db;
       133011  +  iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
       133012  +  assert( iDb>=0 );
133886 133013   
133887 133014     assert( pTable->nModuleArg==0 );
133888 133015     addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
133889 133016     addModuleArgument(db, pTable, 0);
133890 133017     addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
133891 133018     assert( (pParse->sNameToken.z==pName2->z && pName2->z!=0)
133892 133019          || (pParse->sNameToken.z==pName1->z && pName2->z==0)
................................................................................
133898 133025   #ifndef SQLITE_OMIT_AUTHORIZATION
133899 133026     /* Creating a virtual table invokes the authorization callback twice.
133900 133027     ** The first invocation, to obtain permission to INSERT a row into the
133901 133028     ** sqlite_master table, has already been made by sqlite3StartTable().
133902 133029     ** The second call, to obtain permission to create the table, is made now.
133903 133030     */
133904 133031     if( pTable->azModuleArg ){
133905         -    int iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
133906         -    assert( iDb>=0 ); /* The database the table is being created in */
133907 133032       sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName, 
133908 133033               pTable->azModuleArg[0], pParse->db->aDb[iDb].zDbSName);
133909 133034     }
133910 133035   #endif
133911 133036   }
133912 133037   
133913 133038   /*
................................................................................
134594 133719     void *pArg = 0;
134595 133720     FuncDef *pNew;
134596 133721     int rc = 0;
134597 133722   
134598 133723     /* Check to see the left operand is a column in a virtual table */
134599 133724     if( NEVER(pExpr==0) ) return pDef;
134600 133725     if( pExpr->op!=TK_COLUMN ) return pDef;
134601         -  pTab = pExpr->y.pTab;
       133726  +  pTab = pExpr->pTab;
134602 133727     if( pTab==0 ) return pDef;
134603 133728     if( !IsVirtual(pTab) ) return pDef;
134604 133729     pVtab = sqlite3GetVTable(db, pTab)->pVtab;
134605 133730     assert( pVtab!=0 );
134606 133731     assert( pVtab->pModule!=0 );
134607 133732     pMod = (sqlite3_module *)pVtab->pModule;
134608 133733     if( pMod->xFindFunction==0 ) return pDef;
................................................................................
135214 134339     WhereLoop *pNew;          /* Template WhereLoop */
135215 134340     WhereOrSet *pOrSet;       /* Record best loops here, if not NULL */
135216 134341   #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
135217 134342     UnpackedRecord *pRec;     /* Probe for stat4 (if required) */
135218 134343     int nRecValid;            /* Number of valid fields currently in pRec */
135219 134344   #endif
135220 134345     unsigned int bldFlags;    /* SQLITE_BLDF_* flags */
135221         -  unsigned int iPlanLimit;  /* Search limiter */
135222 134346   };
135223 134347   
135224 134348   /* Allowed values for WhereLoopBuider.bldFlags */
135225 134349   #define SQLITE_BLDF_INDEXED  0x0001   /* An index is used */
135226 134350   #define SQLITE_BLDF_UNIQUE   0x0002   /* All keys of a UNIQUE index used */
135227 134351   
135228         -/* The WhereLoopBuilder.iPlanLimit is used to limit the number of
135229         -** index+constraint combinations the query planner will consider for a
135230         -** particular query.  If this parameter is unlimited, then certain
135231         -** pathological queries can spend excess time in the sqlite3WhereBegin()
135232         -** routine.  The limit is high enough that is should not impact real-world
135233         -** queries.
135234         -**
135235         -** SQLITE_QUERY_PLANNER_LIMIT is the baseline limit.  The limit is
135236         -** increased by SQLITE_QUERY_PLANNER_LIMIT_INCR before each term of the FROM
135237         -** clause is processed, so that every table in a join is guaranteed to be
135238         -** able to propose a some index+constraint combinations even if the initial
135239         -** baseline limit was exhausted by prior tables of the join.
135240         -*/
135241         -#ifndef SQLITE_QUERY_PLANNER_LIMIT
135242         -# define SQLITE_QUERY_PLANNER_LIMIT 20000
135243         -#endif
135244         -#ifndef SQLITE_QUERY_PLANNER_LIMIT_INCR
135245         -# define SQLITE_QUERY_PLANNER_LIMIT_INCR 1000
135246         -#endif
135247         -
135248 134352   /*
135249 134353   ** The WHERE clause processing routine has two halves.  The
135250 134354   ** first part does the start of the WHERE loop and the second
135251 134355   ** half does the tail of the WHERE loop.  An instance of
135252 134356   ** this structure is returned by the first half and passed
135253 134357   ** into the second half to give some continuity.
135254 134358   **
................................................................................
135802 134906       ExprList *pLhs = 0;         /* New LHS after mods */
135803 134907       int i;                      /* Loop counter */
135804 134908       Select *pSelect;            /* Pointer to the SELECT on the RHS */
135805 134909   
135806 134910       for(i=iEq; i<pLoop->nLTerm; i++){
135807 134911         if( pLoop->aLTerm[i]->pExpr==pX ){
135808 134912           int iField = pLoop->aLTerm[i]->iField - 1;
135809         -        if( pOrigRhs->a[iField].pExpr==0 ) continue; /* Duplicate PK column */
       134913  +        assert( pOrigRhs->a[iField].pExpr!=0 );
135810 134914           pRhs = sqlite3ExprListAppend(pParse, pRhs, pOrigRhs->a[iField].pExpr);
135811 134915           pOrigRhs->a[iField].pExpr = 0;
135812 134916           assert( pOrigLhs->a[iField].pExpr!=0 );
135813 134917           pLhs = sqlite3ExprListAppend(pParse, pLhs, pOrigLhs->a[iField].pExpr);
135814 134918           pOrigLhs->a[iField].pExpr = 0;
135815 134919         }
135816 134920       }
................................................................................
136494 135598   */
136495 135599   static int whereIndexExprTransNode(Walker *p, Expr *pExpr){
136496 135600     IdxExprTrans *pX = p->u.pIdxTrans;
136497 135601     if( sqlite3ExprCompare(0, pExpr, pX->pIdxExpr, pX->iTabCur)==0 ){
136498 135602       pExpr->op = TK_COLUMN;
136499 135603       pExpr->iTable = pX->iIdxCur;
136500 135604       pExpr->iColumn = pX->iIdxCol;
136501         -    pExpr->y.pTab = 0;
       135605  +    pExpr->pTab = 0;
136502 135606       return WRC_Prune;
136503 135607     }else{
136504 135608       return WRC_Continue;
136505 135609     }
136506 135610   }
136507 135611   
136508 135612   /*
................................................................................
137894 136998           */
137895 136999           if( sqlite3Isdigit(zNew[0])
137896 137000            || zNew[0]=='-'
137897 137001            || (zNew[0]+1=='0' && iTo==1)
137898 137002           ){
137899 137003             if( pLeft->op!=TK_COLUMN 
137900 137004              || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT 
137901         -           || IsVirtual(pLeft->y.pTab)  /* Value might be numeric */
       137005  +           || IsVirtual(pLeft->pTab)  /* Value might be numeric */
137902 137006             ){
137903 137007               sqlite3ExprDelete(db, pPrefix);
137904 137008               sqlite3ValueFree(pVal);
137905 137009               return 0;
137906 137010             }
137907 137011           }
137908 137012         }
................................................................................
137995 137099       ** virtual table on their second argument, which is the same as
137996 137100       ** the left-hand side operand in their in-fix form.
137997 137101       **
137998 137102       **       vtab_column MATCH expression
137999 137103       **       MATCH(expression,vtab_column)
138000 137104       */
138001 137105       pCol = pList->a[1].pExpr;
138002         -    if( pCol->op==TK_COLUMN && IsVirtual(pCol->y.pTab) ){
       137106  +    if( pCol->op==TK_COLUMN && IsVirtual(pCol->pTab) ){
138003 137107         for(i=0; i<ArraySize(aOp); i++){
138004 137108           if( sqlite3StrICmp(pExpr->u.zToken, aOp[i].zOp)==0 ){
138005 137109             *peOp2 = aOp[i].eOp2;
138006 137110             *ppRight = pList->a[0].pExpr;
138007 137111             *ppLeft = pCol;
138008 137112             return 1;
138009 137113           }
................................................................................
138017 137121       **      OVERLOADED(vtab_column,expression)
138018 137122       **
138019 137123       ** Historically, xFindFunction expected to see lower-case function
138020 137124       ** names.  But for this use case, xFindFunction is expected to deal
138021 137125       ** with function names in an arbitrary case.
138022 137126       */
138023 137127       pCol = pList->a[0].pExpr;
138024         -    if( pCol->op==TK_COLUMN && IsVirtual(pCol->y.pTab) ){
       137128  +    if( pCol->op==TK_COLUMN && IsVirtual(pCol->pTab) ){
138025 137129         sqlite3_vtab *pVtab;
138026 137130         sqlite3_module *pMod;
138027 137131         void (*xNotUsed)(sqlite3_context*,int,sqlite3_value**);
138028 137132         void *pNotUsed;
138029         -      pVtab = sqlite3GetVTable(db, pCol->y.pTab)->pVtab;
       137133  +      pVtab = sqlite3GetVTable(db, pCol->pTab)->pVtab;
138030 137134         assert( pVtab!=0 );
138031 137135         assert( pVtab->pModule!=0 );
138032 137136         pMod = (sqlite3_module *)pVtab->pModule;
138033 137137         if( pMod->xFindFunction!=0 ){
138034 137138           i = pMod->xFindFunction(pVtab,2, pExpr->u.zToken, &xNotUsed, &pNotUsed);
138035 137139           if( i>=SQLITE_INDEX_CONSTRAINT_FUNCTION ){
138036 137140             *peOp2 = i;
................................................................................
138040 137144           }
138041 137145         }
138042 137146       }
138043 137147     }else if( pExpr->op==TK_NE || pExpr->op==TK_ISNOT || pExpr->op==TK_NOTNULL ){
138044 137148       int res = 0;
138045 137149       Expr *pLeft = pExpr->pLeft;
138046 137150       Expr *pRight = pExpr->pRight;
138047         -    if( pLeft->op==TK_COLUMN && IsVirtual(pLeft->y.pTab) ){
       137151  +    if( pLeft->op==TK_COLUMN && IsVirtual(pLeft->pTab) ){
138048 137152         res++;
138049 137153       }
138050         -    if( pRight && pRight->op==TK_COLUMN && IsVirtual(pRight->y.pTab) ){
       137154  +    if( pRight && pRight->op==TK_COLUMN && IsVirtual(pRight->pTab) ){
138051 137155         res++;
138052 137156         SWAP(Expr*, pLeft, pRight);
138053 137157       }
138054 137158       *ppLeft = pLeft;
138055 137159       *ppRight = pRight;
138056 137160       if( pExpr->op==TK_NE ) *peOp2 = SQLITE_INDEX_CONSTRAINT_NE;
138057 137161       if( pExpr->op==TK_ISNOT ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOT;
................................................................................
138995 138099     ** virtual term of that form.
138996 138100     **
138997 138101     ** Note that the virtual term must be tagged with TERM_VNULL.
138998 138102     */
138999 138103     if( pExpr->op==TK_NOTNULL
139000 138104      && pExpr->pLeft->op==TK_COLUMN
139001 138105      && pExpr->pLeft->iColumn>=0
139002         -   && !ExprHasProperty(pExpr, EP_FromJoin)
139003 138106      && OptimizationEnabled(db, SQLITE_Stat34)
139004 138107     ){
139005 138108       Expr *pNewExpr;
139006 138109       Expr *pLeft = pExpr->pLeft;
139007 138110       int idxNew;
139008 138111       WhereTerm *pNewTerm;
139009 138112   
................................................................................
139187 138290     Expr *pTerm;
139188 138291     if( pItem->fg.isTabFunc==0 ) return;
139189 138292     pTab = pItem->pTab;
139190 138293     assert( pTab!=0 );
139191 138294     pArgs = pItem->u1.pFuncArg;
139192 138295     if( pArgs==0 ) return;
139193 138296     for(j=k=0; j<pArgs->nExpr; j++){
139194         -    Expr *pRhs;
139195 138297       while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){k++;}
139196 138298       if( k>=pTab->nCol ){
139197 138299         sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d",
139198 138300                         pTab->zName, j);
139199 138301         return;
139200 138302       }
139201 138303       pColRef = sqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0);
139202 138304       if( pColRef==0 ) return;
139203 138305       pColRef->iTable = pItem->iCursor;
139204 138306       pColRef->iColumn = k++;
139205         -    pColRef->y.pTab = pTab;
139206         -    pRhs = sqlite3PExpr(pParse, TK_UPLUS, 
139207         -        sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0), 0);
139208         -    pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef, pRhs);
       138307  +    pColRef->pTab = pTab;
       138308  +    pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef,
       138309  +                         sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0));
139209 138310       whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);
139210 138311     }
139211 138312   }
139212 138313   
139213 138314   /************** End of whereexpr.c *******************************************/
139214 138315   /************** Begin file where.c *******************************************/
139215 138316   /*
................................................................................
140064 139165     if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
140065 139166     if( pTabItem->fg.viaCoroutine ){
140066 139167       sqlite3VdbeChangeP2(v, addrCounter, regBase+n);
140067 139168       testcase( pParse->db->mallocFailed );
140068 139169       translateColumnToCopy(pParse, addrTop, pLevel->iTabCur,
140069 139170                             pTabItem->regResult, 1);
140070 139171       sqlite3VdbeGoto(v, addrTop);
       139172  +    pTabItem->fg.viaCoroutine = 0;
140071 139173     }else{
140072 139174       sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
140073 139175     }
140074 139176     sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
140075 139177     sqlite3VdbeJumpHere(v, addrTop);
140076 139178     sqlite3ReleaseTempReg(pParse, regRecord);
140077 139179     
................................................................................
140241 139343   
140242 139344   /*
140243 139345   ** The table object reference passed as the second argument to this function
140244 139346   ** must represent a virtual table. This function invokes the xBestIndex()
140245 139347   ** method of the virtual table with the sqlite3_index_info object that
140246 139348   ** comes in as the 3rd argument to this function.
140247 139349   **
140248         -** If an error occurs, pParse is populated with an error message and an
140249         -** appropriate error code is returned.  A return of SQLITE_CONSTRAINT from
140250         -** xBestIndex is not considered an error.  SQLITE_CONSTRAINT indicates that
140251         -** the current configuration of "unusable" flags in sqlite3_index_info can
140252         -** not result in a valid plan.
       139350  +** If an error occurs, pParse is populated with an error message and a
       139351  +** non-zero value is returned. Otherwise, 0 is returned and the output
       139352  +** part of the sqlite3_index_info structure is left populated.
140253 139353   **
140254 139354   ** Whether or not an error is returned, it is the responsibility of the
140255 139355   ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
140256 139356   ** that this is required.
140257 139357   */
140258 139358   static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
140259 139359     sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
140260 139360     int rc;
140261 139361   
140262 139362     TRACE_IDX_INPUTS(p);
140263 139363     rc = pVtab->pModule->xBestIndex(pVtab, p);
140264 139364     TRACE_IDX_OUTPUTS(p);
140265 139365   
140266         -  if( rc!=SQLITE_OK && rc!=SQLITE_CONSTRAINT ){
       139366  +  if( rc!=SQLITE_OK ){
140267 139367       if( rc==SQLITE_NOMEM ){
140268 139368         sqlite3OomFault(pParse->db);
140269 139369       }else if( !pVtab->zErrMsg ){
140270 139370         sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
140271 139371       }else{
140272 139372         sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
140273 139373       }
140274 139374     }
140275 139375     sqlite3_free(pVtab->zErrMsg);
140276 139376     pVtab->zErrMsg = 0;
140277         -  return rc;
       139377  +
       139378  +#if 0
       139379  +  /* This error is now caught by the caller.
       139380  +  ** Search for "xBestIndex malfunction" below */
       139381  +  for(i=0; i<p->nConstraint; i++){
       139382  +    if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
       139383  +      sqlite3ErrorMsg(pParse, 
       139384  +          "table %s: xBestIndex returned an invalid plan", pTab->zName);
       139385  +    }
       139386  +  }
       139387  +#endif
       139388  +
       139389  +  return pParse->nErr;
140278 139390   }
140279 139391   #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
140280 139392   
140281 139393   #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
140282 139394   /*
140283 139395   ** Estimate the location of a particular key among all keys in an
140284 139396   ** index.  Store the results in aStat as follows:
................................................................................
141325 140437   */
141326 140438   static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
141327 140439     WhereLoop **ppPrev, *p;
141328 140440     WhereInfo *pWInfo = pBuilder->pWInfo;
141329 140441     sqlite3 *db = pWInfo->pParse->db;
141330 140442     int rc;
141331 140443   
141332         -  /* Stop the search once we hit the query planner search limit */
141333         -  if( pBuilder->iPlanLimit==0 ){
141334         -    WHERETRACE(0xffffffff,("=== query planner search limit reached ===\n"));
141335         -    if( pBuilder->pOrSet ) pBuilder->pOrSet->n = 0;
141336         -    return SQLITE_DONE;
141337         -  }
141338         -  pBuilder->iPlanLimit--;
141339         -
141340 140444     /* If pBuilder->pOrSet is defined, then only keep track of the costs
141341 140445     ** and prereqs.
141342 140446     */
141343 140447     if( pBuilder->pOrSet!=0 ){
141344 140448       if( pTemplate->nLTerm ){
141345 140449   #if WHERETRACE_ENABLED
141346 140450         u16 n = pBuilder->pOrSet->n;
................................................................................
142343 141447     pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
142344 141448     pIdxInfo->estimatedRows = 25;
142345 141449     pIdxInfo->idxFlags = 0;
142346 141450     pIdxInfo->colUsed = (sqlite3_int64)pSrc->colUsed;
142347 141451   
142348 141452     /* Invoke the virtual table xBestIndex() method */
142349 141453     rc = vtabBestIndex(pParse, pSrc->pTab, pIdxInfo);
142350         -  if( rc ){
142351         -    if( rc==SQLITE_CONSTRAINT ){
142352         -      /* If the xBestIndex method returns SQLITE_CONSTRAINT, that means
142353         -      ** that the particular combination of parameters provided is unusable.
142354         -      ** Make no entries in the loop table.
142355         -      */
142356         -      WHERETRACE(0xffff, ("  ^^^^--- non-viable plan rejected!\n"));
142357         -      return SQLITE_OK;
142358         -    }
142359         -    return rc;
142360         -  }
       141454  +  if( rc ) return rc;
142361 141455   
142362 141456     mxTerm = -1;
142363 141457     assert( pNew->nLSlot>=nConstraint );
142364 141458     for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
142365 141459     pNew->u.vtab.omitMask = 0;
142366 141460     pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
142367 141461     for(i=0; i<nConstraint; i++, pIdxCons++){
................................................................................
142749 141843     int rc = SQLITE_OK;
142750 141844     WhereLoop *pNew;
142751 141845     u8 priorJointype = 0;
142752 141846   
142753 141847     /* Loop over the tables in the join, from left to right */
142754 141848     pNew = pBuilder->pNew;
142755 141849     whereLoopInit(pNew);
142756         -  pBuilder->iPlanLimit = SQLITE_QUERY_PLANNER_LIMIT;
142757 141850     for(iTab=0, pItem=pTabList->a; pItem<pEnd; iTab++, pItem++){
142758 141851       Bitmask mUnusable = 0;
142759 141852       pNew->iTab = iTab;
142760         -    pBuilder->iPlanLimit += SQLITE_QUERY_PLANNER_LIMIT_INCR;
142761 141853       pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor);
142762 141854       if( ((pItem->fg.jointype|priorJointype) & (JT_LEFT|JT_CROSS))!=0 ){
142763 141855         /* This condition is true when pItem is the FROM clause term on the
142764 141856         ** right-hand-side of a LEFT or CROSS JOIN.  */
142765 141857         mPrereq = mPrior;
142766 141858       }
142767 141859       priorJointype = pItem->fg.jointype;
................................................................................
142779 141871       {
142780 141872         rc = whereLoopAddBtree(pBuilder, mPrereq);
142781 141873       }
142782 141874       if( rc==SQLITE_OK && pBuilder->pWC->hasOr ){
142783 141875         rc = whereLoopAddOr(pBuilder, mPrereq, mUnusable);
142784 141876       }
142785 141877       mPrior |= pNew->maskSelf;
142786         -    if( rc || db->mallocFailed ){
142787         -      if( rc==SQLITE_DONE ){
142788         -        /* We hit the query planner search limit set by iPlanLimit */
142789         -        sqlite3_log(SQLITE_WARNING, "abbreviated query algorithm search");
142790         -        rc = SQLITE_OK;
142791         -      }else{
142792         -        break;
142793         -      }
142794         -    }
       141878  +    if( rc || db->mallocFailed ) break;
142795 141879     }
142796 141880   
142797 141881     whereLoopClear(db, pNew);
142798 141882     return rc;
142799 141883   }
142800 141884   
142801 141885   /*
................................................................................
145169 144253         if( i==nSrc ) return WRC_Continue;
145170 144254       }
145171 144255     }
145172 144256   
145173 144257     switch( pExpr->op ){
145174 144258   
145175 144259       case TK_FUNCTION:
145176         -      if( !ExprHasProperty(pExpr, EP_WinFunc) ){
       144260  +      if( pExpr->pWin==0 ){
145177 144261           break;
145178 144262         }else{
145179 144263           Window *pWin;
145180 144264           for(pWin=p->pWin; pWin; pWin=pWin->pNextWin){
145181         -          if( pExpr->y.pWin==pWin ){
       144265  +          if( pExpr->pWin==pWin ){
145182 144266               assert( pWin->pOwner==pExpr );
145183 144267               return WRC_Prune;
145184 144268             }
145185 144269           }
145186 144270         }
145187 144271         /* Fall through.  */
145188 144272   
................................................................................
145291 144375   ** any SQL window functions, this function is a no-op. Otherwise, it 
145292 144376   ** rewrites the SELECT statement so that window function xStep functions
145293 144377   ** are invoked in the correct order as described under "SELECT REWRITING"
145294 144378   ** at the top of this file.
145295 144379   */
145296 144380   SQLITE_PRIVATE int sqlite3WindowRewrite(Parse *pParse, Select *p){
145297 144381     int rc = SQLITE_OK;
145298         -  if( p->pWin && p->pPrior==0 ){
       144382  +  if( p->pWin ){
145299 144383       Vdbe *v = sqlite3GetVdbe(pParse);
145300 144384       sqlite3 *db = pParse->db;
145301 144385       Select *pSub = 0;             /* The subquery */
145302 144386       SrcList *pSrc = p->pSrc;
145303 144387       Expr *pWhere = p->pWhere;
145304 144388       ExprList *pGroupBy = p->pGroupBy;
145305 144389       Expr *pHaving = p->pHaving;
................................................................................
145504 144588   }
145505 144589   
145506 144590   /*
145507 144591   ** Attach window object pWin to expression p.
145508 144592   */
145509 144593   SQLITE_PRIVATE void sqlite3WindowAttach(Parse *pParse, Expr *p, Window *pWin){
145510 144594     if( p ){
145511         -    assert( p->op==TK_FUNCTION );
145512 144595       /* This routine is only called for the parser.  If pWin was not
145513 144596       ** allocated due to an OOM, then the parser would fail before ever
145514 144597       ** invoking this routine */
145515 144598       if( ALWAYS(pWin) ){
145516         -      p->y.pWin = pWin;
145517         -      ExprSetProperty(p, EP_WinFunc);
       144599  +      p->pWin = pWin;
145518 144600         pWin->pOwner = p;
145519 144601         if( p->flags & EP_Distinct ){
145520 144602           sqlite3ErrorMsg(pParse,
145521 144603              "DISTINCT is not supported for window functions");
145522 144604         }
145523 144605       }
145524 144606     }else{
................................................................................
146673 145755   /*
146674 145756   ** Allocate and return a duplicate of the Window object indicated by the
146675 145757   ** third argument. Set the Window.pOwner field of the new object to
146676 145758   ** pOwner.
146677 145759   */
146678 145760   SQLITE_PRIVATE Window *sqlite3WindowDup(sqlite3 *db, Expr *pOwner, Window *p){
146679 145761     Window *pNew = 0;
146680         -  if( ALWAYS(p) ){
       145762  +  if( p ){
146681 145763       pNew = sqlite3DbMallocZero(db, sizeof(Window));
146682 145764       if( pNew ){
146683 145765         pNew->zName = sqlite3DbStrDup(db, p->zName);
146684 145766         pNew->pFilter = sqlite3ExprDup(db, p->pFilter, 0);
146685 145767         pNew->pPartition = sqlite3ExprListDup(db, p->pPartition, 0);
146686 145768         pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, 0);
146687 145769         pNew->eType = p->eType;
................................................................................
146825 145907   ** of this template is copied straight through into the generate parser
146826 145908   ** source file.
146827 145909   **
146828 145910   ** The following is the concatenation of all %include directives from the
146829 145911   ** input grammar file:
146830 145912   */
146831 145913   /* #include <stdio.h> */
146832         -/* #include <assert.h> */
146833 145914   /************ Begin %include sections from the grammar ************************/
146834 145915   
146835 145916   /* #include "sqliteInt.h" */
146836 145917   
146837 145918   /*
146838 145919   ** Disable all error recovery processing in the parser push-down
146839 145920   ** automaton.
................................................................................
146927 146008         p->op = (u8)op;
146928 146009         p->affinity = 0;
146929 146010         p->flags = EP_Leaf;
146930 146011         p->iAgg = -1;
146931 146012         p->pLeft = p->pRight = 0;
146932 146013         p->x.pList = 0;
146933 146014         p->pAggInfo = 0;
146934         -      p->y.pTab = 0;
       146015  +      p->pTab = 0;
146935 146016         p->op2 = 0;
146936 146017         p->iTable = 0;
146937 146018         p->iColumn = 0;
       146019  +#ifndef SQLITE_OMIT_WINDOWFUNC
       146020  +      p->pWin = 0;
       146021  +#endif
146938 146022         p->u.zToken = (char*)&p[1];
146939 146023         memcpy(p->u.zToken, t.z, t.n);
146940 146024         p->u.zToken[t.n] = 0;
146941 146025         if( sqlite3Isquote(p->u.zToken[0]) ){
146942 146026           if( p->u.zToken[0]=='"' ) p->flags |= EP_DblQuoted;
146943 146027           sqlite3Dequote(p->u.zToken);
146944 146028         }
................................................................................
151122 150206                yyTracePrompt,yyTokenName[yymajor]);
151123 150207           }
151124 150208   #endif
151125 150209           yy_destructor(yypParser, (YYCODETYPE)yymajor, &yyminorunion);
151126 150210           yymajor = YYNOCODE;
151127 150211         }else{
151128 150212           while( yypParser->yytos >= yypParser->yystack
       150213  +            && yymx != YYERRORSYMBOL
151129 150214               && (yyact = yy_find_reduce_action(
151130 150215                           yypParser->yytos->stateno,
151131         -                        YYERRORSYMBOL)) > YY_MAX_SHIFTREDUCE
       150216  +                        YYERRORSYMBOL)) >= YY_MIN_REDUCE
151132 150217           ){
151133 150218             yy_pop_parser_stack(yypParser);
151134 150219           }
151135 150220           if( yypParser->yytos < yypParser->yystack || yymajor==0 ){
151136 150221             yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
151137 150222             yy_parse_failed(yypParser);
151138 150223   #ifndef YYNOERRORRECOVERY
................................................................................
152091 151176       }
152092 151177     }
152093 151178     while( IdChar(z[i]) ){ i++; }
152094 151179     *tokenType = TK_ID;
152095 151180     return i;
152096 151181   }
152097 151182   
152098         -#ifdef SQLITE_ENABLE_NORMALIZE
152099         -/*
152100         -** Return the length (in bytes) of the token that begins at z[0].
152101         -** Store the token type in *tokenType before returning.  If flags has
152102         -** SQLITE_TOKEN_NORMALIZE flag enabled, use the identifier token type
152103         -** for keywords.  Add SQLITE_TOKEN_QUOTED to flags if the token was
152104         -** actually a quoted identifier.  Add SQLITE_TOKEN_KEYWORD to flags
152105         -** if the token was recognized as a keyword; this is useful when the
152106         -** SQLITE_TOKEN_NORMALIZE flag is used, because it enables the caller
152107         -** to differentiate between a keyword being treated as an identifier
152108         -** (for normalization purposes) and an actual identifier.
152109         -*/
152110         -SQLITE_PRIVATE int sqlite3GetTokenNormalized(
152111         -  const unsigned char *z,
152112         -  int *tokenType,
152113         -  int *flags
152114         -){
152115         -  int n;
152116         -  unsigned char iClass = aiClass[*z];
152117         -  if( iClass==CC_KYWD ){
152118         -    int i;
152119         -    for(i=1; aiClass[z[i]]<=CC_KYWD; i++){}
152120         -    if( IdChar(z[i]) ){
152121         -      /* This token started out using characters that can appear in keywords,
152122         -      ** but z[i] is a character not allowed within keywords, so this must
152123         -      ** be an identifier instead */
152124         -      i++;
152125         -      while( IdChar(z[i]) ){ i++; }
152126         -      *tokenType = TK_ID;
152127         -      return i;
152128         -    }
152129         -    *tokenType = TK_ID;
152130         -    n = keywordCode((char*)z, i, tokenType);
152131         -    /* If the token is no longer considered to be an identifier, then it is a
152132         -    ** keyword of some kind.  Make the token back into an identifier and then
152133         -    ** set the SQLITE_TOKEN_KEYWORD flag.  Several non-identifier tokens are
152134         -    ** used verbatim, including IN, IS, NOT, and NULL. */
152135         -    switch( *tokenType ){
152136         -      case TK_ID: {
152137         -        /* do nothing, handled by caller */
152138         -        break;
152139         -      }
152140         -      case TK_IN:
152141         -      case TK_IS:
152142         -      case TK_NOT:
152143         -      case TK_NULL: {
152144         -        *flags |= SQLITE_TOKEN_KEYWORD;
152145         -        break;
152146         -      }
152147         -      default: {
152148         -        *tokenType = TK_ID;
152149         -        *flags |= SQLITE_TOKEN_KEYWORD;
152150         -        break;
152151         -      }
152152         -    }
152153         -  }else{
152154         -    n = sqlite3GetToken(z, tokenType);
152155         -    /* If the token is considered to be an identifier and the character class
152156         -    ** of the first character is a quote, set the SQLITE_TOKEN_QUOTED flag. */
152157         -    if( *tokenType==TK_ID && (iClass==CC_QUOTE || iClass==CC_QUOTE2) ){
152158         -      *flags |= SQLITE_TOKEN_QUOTED;
152159         -    }
152160         -  }
152161         -  return n;
152162         -}
152163         -#endif /* SQLITE_ENABLE_NORMALIZE */
152164         -
152165 151183   /*
152166 151184   ** Run the parser on the given SQL string.  The parser structure is
152167 151185   ** passed in.  An SQLITE_ status code is returned.  If an error occurs
152168 151186   ** then an and attempt is made to write an error message into 
152169 151187   ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
152170 151188   ** error message.
152171 151189   */
................................................................................
153555 152573           { SQLITE_DBCONFIG_ENABLE_TRIGGER,        SQLITE_EnableTrigger  },
153556 152574           { SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, SQLITE_Fts3Tokenizer  },
153557 152575           { SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, SQLITE_LoadExtension  },
153558 152576           { SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE,      SQLITE_NoCkptOnClose  },
153559 152577           { SQLITE_DBCONFIG_ENABLE_QPSG,           SQLITE_EnableQPSG     },
153560 152578           { SQLITE_DBCONFIG_TRIGGER_EQP,           SQLITE_TriggerEQP     },
153561 152579           { SQLITE_DBCONFIG_RESET_DATABASE,        SQLITE_ResetDatabase  },
153562         -        { SQLITE_DBCONFIG_DEFENSIVE,             SQLITE_Defensive      },
153563 152580         };
153564 152581         unsigned int i;
153565 152582         rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
153566 152583         for(i=0; i<ArraySize(aFlagOp); i++){
153567 152584           if( aFlagOp[i].op==op ){
153568 152585             int onoff = va_arg(ap, int);
153569 152586             int *pRes = va_arg(ap, int*);
................................................................................
155742 154759       }
155743 154760     }
155744 154761     sqlite3_mutex_enter(db->mutex);
155745 154762     db->errMask = 0xff;
155746 154763     db->nDb = 2;
155747 154764     db->magic = SQLITE_MAGIC_BUSY;
155748 154765     db->aDb = db->aDbStatic;
155749         -  db->lookaside.bDisable = 1;
155750 154766   
155751 154767     assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
155752 154768     memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
155753 154769     db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
155754 154770     db->autoCommit = 1;
155755 154771     db->nextAutovac = -1;
155756 154772     db->szMmap = sqlite3GlobalConfig.szMmap;
................................................................................
155783 154799   #endif
155784 154800   #if defined(SQLITE_ENABLE_FTS3_TOKENIZER)
155785 154801                    | SQLITE_Fts3Tokenizer
155786 154802   #endif
155787 154803   #if defined(SQLITE_ENABLE_QPSG)
155788 154804                    | SQLITE_EnableQPSG
155789 154805   #endif
155790         -#if defined(SQLITE_DEFAULT_DEFENSIVE)
155791         -                 | SQLITE_Defensive
155792         -#endif
155793 154806         ;
155794 154807     sqlite3HashInit(&db->aCollSeq);
155795 154808   #ifndef SQLITE_OMIT_VIRTUALTABLE
155796 154809     sqlite3HashInit(&db->aModule);
155797 154810   #endif
155798 154811   
155799 154812     /* Add the default collation sequence BINARY. BINARY works for both UTF-8
................................................................................
156673 155686         sqlite3 *db = va_arg(ap, sqlite3*);
156674 155687         db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
156675 155688         break;
156676 155689       }
156677 155690   
156678 155691       /*   sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
156679 155692       **
156680         -    ** If parameter onoff is non-zero, subsequent calls to localtime()
156681         -    ** and its variants fail. If onoff is zero, undo this setting.
       155693  +    ** If parameter onoff is non-zero, configure the wrappers so that all
       155694  +    ** subsequent calls to localtime() and variants fail. If onoff is zero,
       155695  +    ** undo this setting.
156682 155696       */
156683 155697       case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
156684 155698         sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
156685 155699         break;
156686 155700       }
156687 155701   
156688         -    /*   sqlite3_test_control(SQLITE_TESTCTRL_INTERNAL_FUNCS, int onoff);
156689         -    **
156690         -    ** If parameter onoff is non-zero, internal-use-only SQL functions
156691         -    ** are visible to ordinary SQL.  This is useful for testing but is
156692         -    ** unsafe because invalid parameters to those internal-use-only functions
156693         -    ** can result in crashes or segfaults.
156694         -    */
156695         -    case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS: {
156696         -      sqlite3GlobalConfig.bInternalFunctions = va_arg(ap, int);
156697         -      break;
156698         -    }
156699         -
156700 155702       /*   sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
156701 155703       **
156702 155704       ** Set or clear a flag that indicates that the database file is always well-
156703 155705       ** formed and never corrupt.  This flag is clear by default, indicating that
156704 155706       ** database files might have arbitrary corruption.  Setting the flag during
156705 155707       ** testing causes certain assert() statements in the code to be activated
156706 155708       ** that demonstrat invariants on well-formed database files.
................................................................................
160135 159137     sqlite3_int64 *piFirst,         /* OUT: Selected child node */
160136 159138     sqlite3_int64 *piLast           /* OUT: Selected child node */
160137 159139   ){
160138 159140     int rc = SQLITE_OK;             /* Return code */
160139 159141     const char *zCsr = zNode;       /* Cursor to iterate through node */
160140 159142     const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
160141 159143     char *zBuffer = 0;              /* Buffer to load terms into */
160142         -  i64 nAlloc = 0;                 /* Size of allocated buffer */
       159144  +  int nAlloc = 0;                 /* Size of allocated buffer */
160143 159145     int isFirstTerm = 1;            /* True when processing first term on page */
160144 159146     sqlite3_int64 iChild;           /* Block id of child node to descend to */
160145 159147   
160146 159148     /* Skip over the 'height' varint that occurs at the start of every 
160147 159149     ** interior node. Then load the blockid of the left-child of the b-tree
160148 159150     ** node into variable iChild.  
160149 159151     **
................................................................................
160173 159175       if( !isFirstTerm ){
160174 159176         zCsr += fts3GetVarint32(zCsr, &nPrefix);
160175 159177       }
160176 159178       isFirstTerm = 0;
160177 159179       zCsr += fts3GetVarint32(zCsr, &nSuffix);
160178 159180       
160179 159181       assert( nPrefix>=0 && nSuffix>=0 );
160180         -    if( nPrefix>zCsr-zNode || nSuffix>zEnd-zCsr ){
       159182  +    if( &zCsr[nSuffix]>zEnd ){
160181 159183         rc = FTS_CORRUPT_VTAB;
160182 159184         goto finish_scan;
160183 159185       }
160184         -    if( (i64)nPrefix+nSuffix>nAlloc ){
       159186  +    if( nPrefix+nSuffix>nAlloc ){
160185 159187         char *zNew;
160186         -      nAlloc = ((i64)nPrefix+nSuffix) * 2;
160187         -      zNew = (char *)sqlite3_realloc64(zBuffer, nAlloc);
       159188  +      nAlloc = (nPrefix+nSuffix) * 2;
       159189  +      zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
160188 159190         if( !zNew ){
160189 159191           rc = SQLITE_NOMEM;
160190 159192           goto finish_scan;
160191 159193         }
160192 159194         zBuffer = zNew;
160193 159195       }
160194 159196       assert( zBuffer );
................................................................................
162160 161162     assert( p->inTransaction );
162161 161163     assert( p->mxSavepoint >= iSavepoint );
162162 161164     TESTONLY( p->mxSavepoint = iSavepoint );
162163 161165     sqlite3Fts3PendingTermsClear(p);
162164 161166     return SQLITE_OK;
162165 161167   }
162166 161168   
162167         -/*
162168         -** Return true if zName is the extension on one of the shadow tables used
162169         -** by this module.
162170         -*/
162171         -static int fts3ShadowName(const char *zName){
162172         -  static const char *azName[] = {
162173         -    "content", "docsize", "segdir", "segments", "stat", 
162174         -  };
162175         -  unsigned int i;
162176         -  for(i=0; i<sizeof(azName)/sizeof(azName[0]); i++){
162177         -    if( sqlite3_stricmp(zName, azName[i])==0 ) return 1;
162178         -  }
162179         -  return 0;
162180         -}
162181         -
162182 161169   static const sqlite3_module fts3Module = {
162183         -  /* iVersion      */ 3,
       161170  +  /* iVersion      */ 2,
162184 161171     /* xCreate       */ fts3CreateMethod,
162185 161172     /* xConnect      */ fts3ConnectMethod,
162186 161173     /* xBestIndex    */ fts3BestIndexMethod,
162187 161174     /* xDisconnect   */ fts3DisconnectMethod,
162188 161175     /* xDestroy      */ fts3DestroyMethod,
162189 161176     /* xOpen         */ fts3OpenMethod,
162190 161177     /* xClose        */ fts3CloseMethod,
................................................................................
162199 161186     /* xCommit       */ fts3CommitMethod,
162200 161187     /* xRollback     */ fts3RollbackMethod,
162201 161188     /* xFindFunction */ fts3FindFunctionMethod,
162202 161189     /* xRename */       fts3RenameMethod,
162203 161190     /* xSavepoint    */ fts3SavepointMethod,
162204 161191     /* xRelease      */ fts3ReleaseMethod,
162205 161192     /* xRollbackTo   */ fts3RollbackToMethod,
162206         -  /* xShadowName   */ fts3ShadowName,
162207 161193   };
162208 161194   
162209 161195   /*
162210 161196   ** This function is registered as the module destructor (called when an
162211 161197   ** FTS3 enabled database connection is closed). It frees the memory
162212 161198   ** allocated for the tokenizer hash table.
162213 161199   */
................................................................................
162480 161466       }
162481 161467       assert( pToken->pSegcsr==0 );
162482 161468     }
162483 161469   
162484 161470     return rc;
162485 161471   }
162486 161472   
162487         -#ifndef SQLITE_DISABLE_FTS4_DEFERRED
162488 161473   /*
162489 161474   ** This function is called on each phrase after the position lists for
162490 161475   ** any deferred tokens have been loaded into memory. It updates the phrases
162491 161476   ** current position list to include only those positions that are really
162492 161477   ** instances of the phrase (after considering deferred tokens). If this
162493 161478   ** means that the phrase does not appear in the current row, doclist.pList
162494 161479   ** and doclist.nList are both zeroed.
................................................................................
162584 161569         }
162585 161570         sqlite3_free(aPoslist);
162586 161571       }
162587 161572     }
162588 161573   
162589 161574     return SQLITE_OK;
162590 161575   }
162591         -#endif /* SQLITE_DISABLE_FTS4_DEFERRED */
162592 161576   
162593 161577   /*
162594 161578   ** Maximum number of tokens a phrase may have to be considered for the
162595 161579   ** incremental doclists strategy.
162596 161580   */
162597 161581   #define MAX_INCR_PHRASE_TOKENS 4
162598 161582   
................................................................................
164833 163817        0,                           /* xSync         */
164834 163818        0,                           /* xCommit       */
164835 163819        0,                           /* xRollback     */
164836 163820        0,                           /* xFindFunction */
164837 163821        0,                           /* xRename       */
164838 163822        0,                           /* xSavepoint    */
164839 163823        0,                           /* xRelease      */
164840         -     0,                           /* xRollbackTo   */
164841         -     0                            /* xShadowName   */
       163824  +     0                            /* xRollbackTo   */
164842 163825     };
164843 163826     int rc;                         /* Return code */
164844 163827   
164845 163828     rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
164846 163829     return rc;
164847 163830   }
164848 163831   
................................................................................
168393 167376        0,                           /* xSync         */
168394 167377        0,                           /* xCommit       */
168395 167378        0,                           /* xRollback     */
168396 167379        0,                           /* xFindFunction */
168397 167380        0,                           /* xRename       */
168398 167381        0,                           /* xSavepoint    */
168399 167382        0,                           /* xRelease      */
168400         -     0,                           /* xRollbackTo   */
168401         -     0                            /* xShadowName   */
       167383  +     0                            /* xRollbackTo   */
168402 167384     };
168403 167385     int rc;                         /* Return code */
168404 167386   
168405 167387     rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
168406 167388     return rc;
168407 167389   }
168408 167390   
................................................................................
169782 168764     rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
169783 168765     if( rc!=SQLITE_OK ) return rc;
169784 168766     
169785 168767     /* Because of the FTS3_NODE_PADDING bytes of padding, the following is 
169786 168768     ** safe (no risk of overread) even if the node data is corrupted. */
169787 168769     pNext += fts3GetVarint32(pNext, &nPrefix);
169788 168770     pNext += fts3GetVarint32(pNext, &nSuffix);
169789         -  if( nSuffix<=0 
169790         -   || (&pReader->aNode[pReader->nNode] - pNext)<nSuffix
169791         -   || nPrefix>pReader->nTermAlloc
       168771  +  if( nPrefix<0 || nSuffix<=0 
       168772  +   || &pNext[nSuffix]>&pReader->aNode[pReader->nNode] 
169792 168773     ){
169793 168774       return FTS_CORRUPT_VTAB;
169794 168775     }
169795 168776   
169796         -  /* Both nPrefix and nSuffix were read by fts3GetVarint32() and so are
169797         -  ** between 0 and 0x7FFFFFFF. But the sum of the two may cause integer
169798         -  ** overflow - hence the (i64) casts.  */
169799         -  if( (i64)nPrefix+nSuffix>(i64)pReader->nTermAlloc ){
169800         -    i64 nNew = ((i64)nPrefix+nSuffix)*2;
169801         -    char *zNew = sqlite3_realloc64(pReader->zTerm, nNew);
       168777  +  if( nPrefix+nSuffix>pReader->nTermAlloc ){
       168778  +    int nNew = (nPrefix+nSuffix)*2;
       168779  +    char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
169802 168780       if( !zNew ){
169803 168781         return SQLITE_NOMEM;
169804 168782       }
169805 168783       pReader->zTerm = zNew;
169806 168784       pReader->nTermAlloc = nNew;
169807 168785     }
169808 168786   
................................................................................
169816 168794     pReader->aDoclist = pNext;
169817 168795     pReader->pOffsetList = 0;
169818 168796   
169819 168797     /* Check that the doclist does not appear to extend past the end of the
169820 168798     ** b-tree node. And that the final byte of the doclist is 0x00. If either 
169821 168799     ** of these statements is untrue, then the data structure is corrupt.
169822 168800     */
169823         -  if( (&pReader->aNode[pReader->nNode] - pReader->aDoclist)<pReader->nDoclist
       168801  +  if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode] 
169824 168802      || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
169825 168803     ){
169826 168804       return FTS_CORRUPT_VTAB;
169827 168805     }
169828 168806     return SQLITE_OK;
169829 168807   }
169830 168808   
................................................................................
172142 171120       p->aNode = 0;
172143 171121     }else{
172144 171122       if( bFirst==0 ){
172145 171123         p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
172146 171124       }
172147 171125       p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
172148 171126   
172149         -    if( nPrefix>p->iOff || nSuffix>p->nNode-p->iOff ){
172150         -      return SQLITE_CORRUPT_VTAB;
172151         -    }
172152 171127       blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
172153 171128       if( rc==SQLITE_OK ){
172154 171129         memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
172155 171130         p->term.n = nPrefix+nSuffix;
172156 171131         p->iOff += nSuffix;
172157 171132         if( p->iChild==0 ){
172158 171133           p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
172159         -        if( (p->nNode-p->iOff)<p->nDoclist ){
172160         -          return SQLITE_CORRUPT_VTAB;
172161         -        }
172162 171134           p->aDoclist = &p->aNode[p->iOff];
172163 171135           p->iOff += p->nDoclist;
172164 171136         }
172165 171137       }
172166 171138     }
172167 171139   
172168 171140     assert( p->iOff<=p->nNode );
       171141  +
172169 171142     return rc;
172170 171143   }
172171 171144   
172172 171145   /*
172173 171146   ** Release all dynamic resources held by node-reader object *p.
172174 171147   */
172175 171148   static void nodeReaderRelease(NodeReader *p){
................................................................................
178571 177544   #define JEACH_VALUE   1
178572 177545   #define JEACH_TYPE    2
178573 177546   #define JEACH_ATOM    3
178574 177547   #define JEACH_ID      4
178575 177548   #define JEACH_PARENT  5
178576 177549   #define JEACH_FULLKEY 6
178577 177550   #define JEACH_PATH    7
178578         -/* The xBestIndex method assumes that the JSON and ROOT columns are
178579         -** the last two columns in the table.  Should this ever changes, be
178580         -** sure to update the xBestIndex method. */
178581 177551   #define JEACH_JSON    8
178582 177552   #define JEACH_ROOT    9
178583 177553   
178584 177554     UNUSED_PARAM(pzErr);
178585 177555     UNUSED_PARAM(argv);
178586 177556     UNUSED_PARAM(argc);
178587 177557     UNUSED_PARAM(pAux);
................................................................................
178831 177801   ** 1 if the constraint is found, 3 if the constraint and zRoot are found,
178832 177802   ** and 0 otherwise.
178833 177803   */
178834 177804   static int jsonEachBestIndex(
178835 177805     sqlite3_vtab *tab,
178836 177806     sqlite3_index_info *pIdxInfo
178837 177807   ){
178838         -  int i;                     /* Loop counter or computed array index */
178839         -  int aIdx[2];               /* Index of constraints for JSON and ROOT */
178840         -  int unusableMask = 0;      /* Mask of unusable JSON and ROOT constraints */
178841         -  int idxMask = 0;           /* Mask of usable == constraints JSON and ROOT */
       177808  +  int i;
       177809  +  int jsonIdx = -1;
       177810  +  int rootIdx = -1;
178842 177811     const struct sqlite3_index_constraint *pConstraint;
178843 177812   
178844         -  /* This implementation assumes that JSON and ROOT are the last two
178845         -  ** columns in the table */
178846         -  assert( JEACH_ROOT == JEACH_JSON+1 );
178847 177813     UNUSED_PARAM(tab);
178848         -  aIdx[0] = aIdx[1] = -1;
178849 177814     pConstraint = pIdxInfo->aConstraint;
178850 177815     for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
178851         -    int iCol;
178852         -    int iMask;
178853         -    if( pConstraint->iColumn < JEACH_JSON ) continue;
178854         -    iCol = pConstraint->iColumn - JEACH_JSON;
178855         -    assert( iCol==0 || iCol==1 );
178856         -    iMask = 1 << iCol;
178857         -    if( pConstraint->usable==0 ){
178858         -      unusableMask |= iMask;
178859         -    }else if( pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
178860         -      aIdx[iCol] = i;
178861         -      idxMask |= iMask;
       177816  +    if( pConstraint->usable==0 ) continue;
       177817  +    if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
       177818  +    switch( pConstraint->iColumn ){
       177819  +      case JEACH_JSON:   jsonIdx = i;    break;
       177820  +      case JEACH_ROOT:   rootIdx = i;    break;
       177821  +      default:           /* no-op */     break;
178862 177822       }
178863 177823     }
178864         -  if( (unusableMask & ~idxMask)!=0 ){
178865         -    /* If there are any unusable constraints on JSON or ROOT, then reject
178866         -    ** this entire plan */
178867         -    return SQLITE_CONSTRAINT;
178868         -  }
178869         -  if( aIdx[0]<0 ){
178870         -    /* No JSON input.  Leave estimatedCost at the huge value that it was
178871         -    ** initialized to to discourage the query planner from selecting this
178872         -    ** plan. */
       177824  +  if( jsonIdx<0 ){
178873 177825       pIdxInfo->idxNum = 0;
       177826  +    pIdxInfo->estimatedCost = 1e99;
178874 177827     }else{
178875 177828       pIdxInfo->estimatedCost = 1.0;
178876         -    i = aIdx[0];
178877         -    pIdxInfo->aConstraintUsage[i].argvIndex = 1;
178878         -    pIdxInfo->aConstraintUsage[i].omit = 1;
178879         -    if( aIdx[1]<0 ){
178880         -      pIdxInfo->idxNum = 1;  /* Only JSON supplied.  Plan 1 */
       177829  +    pIdxInfo->aConstraintUsage[jsonIdx].argvIndex = 1;
       177830  +    pIdxInfo->aConstraintUsage[jsonIdx].omit = 1;
       177831  +    if( rootIdx<0 ){
       177832  +      pIdxInfo->idxNum = 1;
178881 177833       }else{
178882         -      i = aIdx[1];
178883         -      pIdxInfo->aConstraintUsage[i].argvIndex = 2;
178884         -      pIdxInfo->aConstraintUsage[i].omit = 1;
178885         -      pIdxInfo->idxNum = 3;  /* Both JSON and ROOT are supplied.  Plan 3 */
       177834  +      pIdxInfo->aConstraintUsage[rootIdx].argvIndex = 2;
       177835  +      pIdxInfo->aConstraintUsage[rootIdx].omit = 1;
       177836  +      pIdxInfo->idxNum = 3;
178886 177837       }
178887 177838     }
178888 177839     return SQLITE_OK;
178889 177840   }
178890 177841   
178891 177842   /* Start a search on a new JSON string */
178892 177843   static int jsonEachFilter(
................................................................................
178987 177938     0,                         /* xSync */
178988 177939     0,                         /* xCommit */
178989 177940     0,                         /* xRollback */
178990 177941     0,                         /* xFindMethod */
178991 177942     0,                         /* xRename */
178992 177943     0,                         /* xSavepoint */
178993 177944     0,                         /* xRelease */
178994         -  0,                         /* xRollbackTo */
178995         -  0                          /* xShadowName */
       177945  +  0                          /* xRollbackTo */
178996 177946   };
178997 177947   
178998 177948   /* The methods of the json_tree virtual table. */
178999 177949   static sqlite3_module jsonTreeModule = {
179000 177950     0,                         /* iVersion */
179001 177951     0,                         /* xCreate */
179002 177952     jsonEachConnect,           /* xConnect */
................................................................................
179015 177965     0,                         /* xSync */
179016 177966     0,                         /* xCommit */
179017 177967     0,                         /* xRollback */
179018 177968     0,                         /* xFindMethod */
179019 177969     0,                         /* xRename */
179020 177970     0,                         /* xSavepoint */