/ Check-in [a608fd1d]
Login
SQLite training in Houston TX on 2019-11-05 (details)
Part of the 2019 Tcl Conference

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

Overview
Comment:Merge the pre-3.8.6 changes into the threads branch.
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | threads
Files: files | file ages | folders
SHA1: a608fd1d52606a009c3acc7f1d184b86a7df3c82
User & Date: drh 2014-08-14 14:02:48
Context
2014-08-15
15:46
Merge the 3.8.6 release into the threads branch. check-in: 05807c41 user: drh tags: threads
2014-08-14
14:02
Merge the pre-3.8.6 changes into the threads branch. check-in: a608fd1d user: drh tags: threads
13:06
Fix typos in comments used to help generate documentation. No changes to code. check-in: 13a2d90a user: drh tags: trunk
2014-08-06
02:03
Merge all recent changes from trunk. check-in: a353a851 user: drh tags: threads
Changes
Hide Diffs Side-by-Side Diffs Ignore Whitespace Patch

Changes to ext/fts3/fts3_unicode.c.

   314    314     int *pnToken,                   /* OUT: Number of bytes at *paToken */
   315    315     int *piStart,                   /* OUT: Starting offset of token */
   316    316     int *piEnd,                     /* OUT: Ending offset of token */
   317    317     int *piPos                      /* OUT: Position integer of token */
   318    318   ){
   319    319     unicode_cursor *pCsr = (unicode_cursor *)pC;
   320    320     unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
   321         -  int iCode;
          321  +  int iCode = 0;
   322    322     char *zOut;
   323    323     const unsigned char *z = &pCsr->aInput[pCsr->iOff];
   324    324     const unsigned char *zStart = z;
   325    325     const unsigned char *zEnd;
   326    326     const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
   327    327   
   328    328     /* Scan past any delimiter characters before the start of the next token.

Changes to ext/fts3/fts3_unicode2.c.

    35     35     ** The most significant 22 bits in each 32-bit value contain the first 
    36     36     ** codepoint in the range. The least significant 10 bits are used to store
    37     37     ** the size of the range (always at least 1). In other words, the value 
    38     38     ** ((C<<22) + N) represents a range of N codepoints starting with codepoint 
    39     39     ** C. It is not possible to represent a range larger than 1023 codepoints 
    40     40     ** using this format.
    41     41     */
    42         -  const static unsigned int aEntry[] = {
           42  +  static const unsigned int aEntry[] = {
    43     43       0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
    44     44       0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
    45     45       0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
    46     46       0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
    47     47       0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
    48     48       0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
    49     49       0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
................................................................................
   127    127       0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
   128    128     };
   129    129   
   130    130     if( c<128 ){
   131    131       return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
   132    132     }else if( c<(1<<22) ){
   133    133       unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
   134         -    int iRes;
          134  +    int iRes = 0;
   135    135       int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
   136    136       int iLo = 0;
   137    137       while( iHi>=iLo ){
   138    138         int iTest = (iHi + iLo) / 2;
   139    139         if( key >= aEntry[iTest] ){
   140    140           iRes = iTest;
   141    141           iLo = iTest+1;
................................................................................
   198    198         iLo = iTest+1;
   199    199       }else{
   200    200         iHi = iTest-1;
   201    201       }
   202    202     }
   203    203     assert( key>=aDia[iRes] );
   204    204     return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
   205         -};
          205  +}
   206    206   
   207    207   
   208    208   /*
   209    209   ** Return true if the argument interpreted as a unicode codepoint
   210    210   ** is a diacritical modifier character.
   211    211   */
   212    212   int sqlite3FtsUnicodeIsdiacritic(int c){

Changes to ext/fts3/unicode/mkunicode.tcl.

   156    156         iLo = iTest+1;
   157    157       }else{
   158    158         iHi = iTest-1;
   159    159       }
   160    160     }
   161    161     assert( key>=aDia[iRes] );
   162    162     return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);}
   163         -  puts "\};"
          163  +  puts "\}"
   164    164   }
   165    165   
   166    166   proc print_isdiacritic {zFunc map} {
   167    167   
   168    168     set lCode [list]
   169    169     foreach m $map {
   170    170       foreach {code char} $m {}
................................................................................
   294    294     ** codepoint in the range. The least significant 10 bits are used to store
   295    295     ** the size of the range (always at least 1). In other words, the value 
   296    296     ** ((C<<22) + N) represents a range of N codepoints starting with codepoint 
   297    297     ** C. It is not possible to represent a range larger than 1023 codepoints 
   298    298     ** using this format.
   299    299     */
   300    300     }]
   301         -  puts -nonewline "  const static unsigned int aEntry\[\] = \{"
          301  +  puts -nonewline "  static const unsigned int aEntry\[\] = \{"
   302    302     set i 0
   303    303     foreach range $lRange {
   304    304       foreach {iFirst nRange} $range {}
   305    305       set u32 [format "0x%08X" [expr ($iFirst<<10) + $nRange]]
   306    306   
   307    307       if {($i % 5)==0} {puts "" ; puts -nonewline "   "}
   308    308       puts -nonewline " $u32,"
................................................................................
   345    345     an_print_range_array $lRange
   346    346     an_print_ascii_bitmap $lRange
   347    347     puts {
   348    348     if( c<128 ){
   349    349       return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
   350    350     }else if( c<(1<<22) ){
   351    351       unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
   352         -    int iRes;
          352  +    int iRes = 0;
   353    353       int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
   354    354       int iLo = 0;
   355    355       while( iHi>=iLo ){
   356    356         int iTest = (iHi + iLo) / 2;
   357    357         if( key >= aEntry[iTest] ){
   358    358           iRes = iTest;
   359    359           iLo = iTest+1;
................................................................................
   728    728   */
   729    729   
   730    730   /*
   731    731   ** DO NOT EDIT THIS MACHINE GENERATED FILE.
   732    732   */
   733    733     }]
   734    734     puts ""
   735         -  puts "#if defined(SQLITE_ENABLE_FTS4_UNICODE61)"
          735  +  puts "#ifndef SQLITE_DISABLE_FTS3_UNICODE"
   736    736     puts "#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)"
   737    737     puts ""
   738    738     puts "#include <assert.h>"
   739    739     puts ""
   740    740   }
   741    741   
   742    742   proc print_test_main {} {
................................................................................
   804    804   if {$::generate_test_code} {
   805    805     print_test_isalnum sqlite3FtsUnicodeIsalnum $lRange
   806    806     print_fold_test sqlite3FtsUnicodeFold $mappings
   807    807     print_test_main 
   808    808   }
   809    809   
   810    810   puts "#endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */"
   811         -puts "#endif /* !defined(SQLITE_ENABLE_FTS4_UNICODE61) */"
          811  +puts "#endif /* !defined(SQLITE_DISABLE_FTS3_UNICODE) */"

Changes to ext/misc/fileio.c.

    57     57   static void writefileFunc(
    58     58     sqlite3_context *context,
    59     59     int argc,
    60     60     sqlite3_value **argv
    61     61   ){
    62     62     FILE *out;
    63     63     const char *z;
    64         -  int n;
    65     64     sqlite3_int64 rc;
    66     65     const char *zFile;
    67     66   
    68     67     zFile = (const char*)sqlite3_value_text(argv[0]);
    69     68     if( zFile==0 ) return;
    70     69     out = fopen(zFile, "wb");
    71     70     if( out==0 ) return;
    72     71     z = (const char*)sqlite3_value_blob(argv[1]);
    73     72     if( z==0 ){
    74         -    n = 0;
    75     73       rc = 0;
    76     74     }else{
    77         -    n = sqlite3_value_bytes(argv[1]);
    78         -    rc = fwrite(z, 1, n, out);
           75  +    rc = fwrite(z, 1, sqlite3_value_bytes(argv[1]), out);
    79     76     }
    80     77     fclose(out);
    81     78     sqlite3_result_int64(context, rc);
    82     79   }
    83     80   
    84     81   
    85     82   #ifdef _WIN32

Changes to src/func.c.

     5      5   ** a legal notice, here is a blessing:
     6      6   **
     7      7   **    May you do good and not evil.
     8      8   **    May you find forgiveness for yourself and forgive others.
     9      9   **    May you share freely, never taking more than you give.
    10     10   **
    11     11   *************************************************************************
    12         -** This file contains the C functions that implement various SQL
    13         -** functions of SQLite.  
    14         -**
    15         -** There is only one exported symbol in this file - the function
    16         -** sqliteRegisterBuildinFunctions() found at the bottom of the file.
    17         -** All other code has file scope.
           12  +** This file contains the C-language implementions for many of the SQL
           13  +** functions of SQLite.  (Some function, and in particular the date and
           14  +** time functions, are implemented separately.)
    18     15   */
    19     16   #include "sqliteInt.h"
    20     17   #include <stdlib.h>
    21     18   #include <assert.h>
    22     19   #include "vdbeInt.h"
    23     20   
    24     21   /*

Changes to src/legacy.c.

    92     92               if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
    93     93                 db->mallocFailed = 1;
    94     94                 goto exec_out;
    95     95               }
    96     96             }
    97     97           }
    98     98           if( xCallback(pArg, nCol, azVals, azCols) ){
           99  +          /* EVIDENCE-OF: R-38229-40159 If the callback function to
          100  +          ** sqlite3_exec() returns non-zero, then sqlite3_exec() will
          101  +          ** return SQLITE_ABORT. */
    99    102             rc = SQLITE_ABORT;
   100    103             sqlite3VdbeFinalize((Vdbe *)pStmt);
   101    104             pStmt = 0;
   102    105             sqlite3Error(db, SQLITE_ABORT, 0);
   103    106             goto exec_out;
   104    107           }
   105    108         }

Changes to src/main.c.

   832    832   }
   833    833   
   834    834   /*
   835    835   ** Close an existing SQLite database
   836    836   */
   837    837   static int sqlite3Close(sqlite3 *db, int forceZombie){
   838    838     if( !db ){
          839  +    /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
          840  +    ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
   839    841       return SQLITE_OK;
   840    842     }
   841    843     if( !sqlite3SafetyCheckSickOrOk(db) ){
   842    844       return SQLITE_MISUSE_BKPT;
   843    845     }
   844    846     sqlite3_mutex_enter(db->mutex);
   845    847   
................................................................................
  1061   1063     }
  1062   1064   }
  1063   1065   
  1064   1066   /*
  1065   1067   ** Return a static string containing the name corresponding to the error code
  1066   1068   ** specified in the argument.
  1067   1069   */
  1068         -#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
         1070  +#if (defined(SQLITE_DEBUG) && SQLITE_OS_WIN) || defined(SQLITE_TEST)
  1069   1071   const char *sqlite3ErrName(int rc){
  1070   1072     const char *zName = 0;
  1071   1073     int i, origRc = rc;
  1072   1074     for(i=0; i<2 && zName==0; i++, rc &= 0xff){
  1073   1075       switch( rc ){
  1074   1076         case SQLITE_OK:                 zName = "SQLITE_OK";                break;
  1075   1077         case SQLITE_ERROR:              zName = "SQLITE_ERROR";             break;
................................................................................
  1096   1098         case SQLITE_IOERR_FSYNC:        zName = "SQLITE_IOERR_FSYNC";       break;
  1097   1099         case SQLITE_IOERR_DIR_FSYNC:    zName = "SQLITE_IOERR_DIR_FSYNC";   break;
  1098   1100         case SQLITE_IOERR_TRUNCATE:     zName = "SQLITE_IOERR_TRUNCATE";    break;
  1099   1101         case SQLITE_IOERR_FSTAT:        zName = "SQLITE_IOERR_FSTAT";       break;
  1100   1102         case SQLITE_IOERR_UNLOCK:       zName = "SQLITE_IOERR_UNLOCK";      break;
  1101   1103         case SQLITE_IOERR_RDLOCK:       zName = "SQLITE_IOERR_RDLOCK";      break;
  1102   1104         case SQLITE_IOERR_DELETE:       zName = "SQLITE_IOERR_DELETE";      break;
  1103         -      case SQLITE_IOERR_BLOCKED:      zName = "SQLITE_IOERR_BLOCKED";     break;
  1104   1105         case SQLITE_IOERR_NOMEM:        zName = "SQLITE_IOERR_NOMEM";       break;
  1105   1106         case SQLITE_IOERR_ACCESS:       zName = "SQLITE_IOERR_ACCESS";      break;
  1106   1107         case SQLITE_IOERR_CHECKRESERVEDLOCK:
  1107   1108                                   zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
  1108   1109         case SQLITE_IOERR_LOCK:         zName = "SQLITE_IOERR_LOCK";        break;
  1109   1110         case SQLITE_IOERR_CLOSE:        zName = "SQLITE_IOERR_CLOSE";       break;
  1110   1111         case SQLITE_IOERR_DIR_CLOSE:    zName = "SQLITE_IOERR_DIR_CLOSE";   break;
................................................................................
  2081   2082     SQLITE_MAX_COLUMN,
  2082   2083     SQLITE_MAX_EXPR_DEPTH,
  2083   2084     SQLITE_MAX_COMPOUND_SELECT,
  2084   2085     SQLITE_MAX_VDBE_OP,
  2085   2086     SQLITE_MAX_FUNCTION_ARG,
  2086   2087     SQLITE_MAX_ATTACHED,
  2087   2088     SQLITE_MAX_LIKE_PATTERN_LENGTH,
  2088         -  SQLITE_MAX_VARIABLE_NUMBER,
         2089  +  SQLITE_MAX_VARIABLE_NUMBER,      /* IMP: R-38091-32352 */
  2089   2090     SQLITE_MAX_TRIGGER_DEPTH,
  2090   2091   };
  2091   2092   
  2092   2093   /*
  2093   2094   ** Make sure the hard limits are set to reasonable values
  2094   2095   */
  2095   2096   #if SQLITE_MAX_LENGTH<100

Changes to src/os_unix.c.

    90     90   #include <sys/stat.h>
    91     91   #include <fcntl.h>
    92     92   #include <unistd.h>
    93     93   #include <time.h>
    94     94   #include <sys/time.h>
    95     95   #include <errno.h>
    96     96   #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
    97         -#include <sys/mman.h>
           97  +# include <sys/mman.h>
    98     98   #endif
    99     99   
   100         -
   101         -#if SQLITE_ENABLE_LOCKING_STYLE
          100  +#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
   102    101   # include <sys/ioctl.h>
   103    102   # if OS_VXWORKS
   104    103   #  include <semaphore.h>
   105    104   #  include <limits.h>
   106    105   # else
   107    106   #  include <sys/file.h>
   108    107   #  include <sys/param.h>
................................................................................
   314    313   
   315    314   /*
   316    315   ** On some systems, calls to fchown() will trigger a message in a security
   317    316   ** log if they come from non-root processes.  So avoid calling fchown() if
   318    317   ** we are not running as root.
   319    318   */
   320    319   static int posixFchown(int fd, uid_t uid, gid_t gid){
          320  +#if OS_VXWORKS
          321  +  return 0;
          322  +#else
   321    323     return geteuid() ? 0 : fchown(fd,uid,gid);
          324  +#endif
   322    325   }
   323    326   
   324    327   /* Forward reference */
   325    328   static int openDirectory(const char*, int*);
   326    329   static int unixGetpagesize(void);
   327    330   
   328    331   /*
................................................................................
   370    373   
   371    374     { "fcntl",        (sqlite3_syscall_ptr)fcntl,      0  },
   372    375   #define osFcntl     ((int(*)(int,int,...))aSyscall[7].pCurrent)
   373    376   
   374    377     { "read",         (sqlite3_syscall_ptr)read,       0  },
   375    378   #define osRead      ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
   376    379   
   377         -#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
          380  +#if defined(USE_PREAD) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
   378    381     { "pread",        (sqlite3_syscall_ptr)pread,      0  },
   379    382   #else
   380    383     { "pread",        (sqlite3_syscall_ptr)0,          0  },
   381    384   #endif
   382    385   #define osPread     ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
   383    386   
   384    387   #if defined(USE_PREAD64)
................................................................................
   387    390     { "pread64",      (sqlite3_syscall_ptr)0,          0  },
   388    391   #endif
   389    392   #define osPread64   ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
   390    393   
   391    394     { "write",        (sqlite3_syscall_ptr)write,      0  },
   392    395   #define osWrite     ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
   393    396   
   394         -#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
          397  +#if defined(USE_PREAD) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
   395    398     { "pwrite",       (sqlite3_syscall_ptr)pwrite,     0  },
   396    399   #else
   397    400     { "pwrite",       (sqlite3_syscall_ptr)0,          0  },
   398    401   #endif
   399    402   #define osPwrite    ((ssize_t(*)(int,const void*,size_t,off_t))\
   400    403                       aSyscall[12].pCurrent)
   401    404   
................................................................................
   757    760           (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
   758    761         return SQLITE_BUSY;
   759    762       }
   760    763       /* else fall through */
   761    764     case EPERM: 
   762    765       return SQLITE_PERM;
   763    766       
   764         -  /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
   765         -  ** this module never makes such a call. And the code in SQLite itself 
   766         -  ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
   767         -  ** this case is also commented out. If the system does set errno to EDEADLK,
   768         -  ** the default SQLITE_IOERR_XXX code will be returned. */
   769         -#if 0
   770         -  case EDEADLK:
   771         -    return SQLITE_IOERR_BLOCKED;
   772         -#endif
   773         -    
   774    767   #if EOPNOTSUPP!=ENOTSUP
   775    768     case EOPNOTSUPP: 
   776    769       /* something went terribly awry, unless during file system support 
   777    770        * introspection, in which it actually means what it says */
   778    771   #endif
   779    772   #ifdef ENOTSUP
   780    773     case ENOTSUP: 
................................................................................
  1299   1292     return SQLITE_OK;
  1300   1293   }
  1301   1294   
  1302   1295   /*
  1303   1296   ** Return TRUE if pFile has been renamed or unlinked since it was first opened.
  1304   1297   */
  1305   1298   static int fileHasMoved(unixFile *pFile){
         1299  +#if OS_VXWORKS
         1300  +  return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
         1301  +#else
  1306   1302     struct stat buf;
  1307   1303     return pFile->pInode!=0 &&
  1308         -         (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
         1304  +      (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
         1305  +#endif
  1309   1306   }
  1310   1307   
  1311   1308   
  1312   1309   /*
  1313   1310   ** Check a unixFile that is a database.  Verify the following:
  1314   1311   **
  1315   1312   ** (1) There is exactly one hard link on the file
................................................................................
  2444   2441     if( pFile->eFileLock>SHARED_LOCK ){
  2445   2442       reserved = 1;
  2446   2443     }
  2447   2444     
  2448   2445     /* Otherwise see if some other process holds it. */
  2449   2446     if( !reserved ){
  2450   2447       sem_t *pSem = pFile->pInode->pSem;
  2451         -    struct stat statBuf;
  2452   2448   
  2453   2449       if( sem_trywait(pSem)==-1 ){
  2454   2450         int tErrno = errno;
  2455   2451         if( EAGAIN != tErrno ){
  2456   2452           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
  2457   2453           pFile->lastErrno = tErrno;
  2458   2454         } else {
................................................................................
  2497   2493   ** access the file.
  2498   2494   **
  2499   2495   ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
  2500   2496   ** routine to lower a locking level.
  2501   2497   */
  2502   2498   static int semLock(sqlite3_file *id, int eFileLock) {
  2503   2499     unixFile *pFile = (unixFile*)id;
  2504         -  int fd;
  2505   2500     sem_t *pSem = pFile->pInode->pSem;
  2506   2501     int rc = SQLITE_OK;
  2507   2502   
  2508   2503     /* if we already have a lock, it is exclusive.  
  2509   2504     ** Just adjust level and punt on outta here. */
  2510   2505     if (pFile->eFileLock > NO_LOCK) {
  2511   2506       pFile->eFileLock = eFileLock;
................................................................................
  5884   5879     const char *zPath,        /* Name of file to be deleted */
  5885   5880     int dirSync               /* If true, fsync() directory after deleting file */
  5886   5881   ){
  5887   5882     int rc = SQLITE_OK;
  5888   5883     UNUSED_PARAMETER(NotUsed);
  5889   5884     SimulateIOError(return SQLITE_IOERR_DELETE);
  5890   5885     if( osUnlink(zPath)==(-1) ){
  5891         -    if( errno==ENOENT ){
         5886  +    if( errno==ENOENT
         5887  +#if OS_VXWORKS
         5888  +        || errno==0x380003
         5889  +#endif
         5890  +    ){
  5892   5891         rc = SQLITE_IOERR_DELETE_NOENT;
  5893   5892       }else{
  5894   5893         rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
  5895   5894       }
  5896   5895       return rc;
  5897   5896     }
  5898   5897   #ifndef SQLITE_DISABLE_DIRSYNC

Changes to src/os_win.c.

    68     68   #endif
    69     69   
    70     70   #ifndef NTDDI_WINBLUE
    71     71   #  define NTDDI_WINBLUE                     0x06030000
    72     72   #endif
    73     73   
    74     74   /*
    75         -** Check if the GetVersionEx[AW] functions should be considered deprecated
    76         -** and avoid using them in that case.  It should be noted here that if the
    77         -** value of the SQLITE_WIN32_GETVERSIONEX pre-processor macro is zero
    78         -** (whether via this block or via being manually specified), that implies
    79         -** the underlying operating system will always be based on the Windows NT
    80         -** Kernel.
           75  +** Check to see if the GetVersionEx[AW] functions are deprecated on the
           76  +** target system.  GetVersionEx was first deprecated in Win8.1.
    81     77   */
    82     78   #ifndef SQLITE_WIN32_GETVERSIONEX
    83     79   #  if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE
    84         -#    define SQLITE_WIN32_GETVERSIONEX   0
           80  +#    define SQLITE_WIN32_GETVERSIONEX   0   /* GetVersionEx() is deprecated */
    85     81   #  else
    86         -#    define SQLITE_WIN32_GETVERSIONEX   1
           82  +#    define SQLITE_WIN32_GETVERSIONEX   1   /* GetVersionEx() is current */
    87     83   #  endif
    88     84   #endif
    89     85   
    90     86   /*
    91     87   ** This constant should already be defined (in the "WinDef.h" SDK file).
    92     88   */
    93     89   #ifndef MAX_PATH
................................................................................
   151    147   #endif
   152    148   
   153    149   /*
   154    150   ** This macro is used when a local variable is set to a value that is
   155    151   ** [sometimes] not used by the code (e.g. via conditional compilation).
   156    152   */
   157    153   #ifndef UNUSED_VARIABLE_VALUE
   158         -#  define UNUSED_VARIABLE_VALUE(x) (void)(x)
          154  +#  define UNUSED_VARIABLE_VALUE(x)      (void)(x)
   159    155   #endif
   160    156   
   161    157   /*
   162    158   ** Returns the character that should be used as the directory separator.
   163    159   */
   164    160   #ifndef winGetDirSep
   165    161   #  define winGetDirSep()                '\\'
................................................................................
   200    196   WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
   201    197   #endif /* SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL) */
   202    198   
   203    199   /*
   204    200   ** Some Microsoft compilers lack this definition.
   205    201   */
   206    202   #ifndef INVALID_FILE_ATTRIBUTES
   207         -# define INVALID_FILE_ATTRIBUTES ((DWORD)-1) 
          203  +# define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
   208    204   #endif
   209    205   
   210    206   #ifndef FILE_FLAG_MASK
   211    207   # define FILE_FLAG_MASK          (0xFF3C0000)
   212    208   #endif
   213    209   
   214    210   #ifndef FILE_ATTRIBUTE_MASK
................................................................................
   250    246   #ifndef SQLITE_OMIT_WAL
   251    247     winShm *pShm;           /* Instance of shared memory on this file */
   252    248   #endif
   253    249     const char *zPath;      /* Full pathname of this file */
   254    250     int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
   255    251   #if SQLITE_OS_WINCE
   256    252     LPWSTR zDeleteOnClose;  /* Name of file to delete when closing */
   257         -  HANDLE hMutex;          /* Mutex used to control access to shared lock */  
          253  +  HANDLE hMutex;          /* Mutex used to control access to shared lock */
   258    254     HANDLE hShared;         /* Shared memory segment used for locking */
   259    255     winceLock local;        /* Locks obtained by this instance of winFile */
   260    256     winceLock *shared;      /* Global shared lock memory for the file  */
   261    257   #endif
   262    258   #if SQLITE_MAX_MMAP_SIZE>0
   263    259     int nFetchOut;                /* Number of outstanding xFetch references */
   264    260     HANDLE hMap;                  /* Handle for accessing memory mapping */
................................................................................
  1039   1035   #else
  1040   1036     { "CreateFileMappingFromApp", (SYSCALL)0,                      0 },
  1041   1037   #endif
  1042   1038   
  1043   1039   #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
  1044   1040           LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
  1045   1041   
         1042  +/*
         1043  +** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
         1044  +**       is really just a macro that uses a compiler intrinsic (e.g. x64).
         1045  +**       So do not try to make this is into a redefinable interface.
         1046  +*/
         1047  +#if defined(InterlockedCompareExchange)
         1048  +  { "InterlockedCompareExchange", (SYSCALL)0,                    0 },
         1049  +
         1050  +#define osInterlockedCompareExchange InterlockedCompareExchange
         1051  +#else
  1046   1052     { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 },
  1047   1053   
  1048   1054   #define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG volatile*, \
  1049   1055           LONG,LONG))aSyscall[76].pCurrent)
         1056  +#endif /* defined(InterlockedCompareExchange) */
  1050   1057   
  1051   1058   }; /* End of the overrideable system calls */
  1052   1059   
  1053   1060   /*
  1054   1061   ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  1055   1062   ** "win32" VFSes.  Return SQLITE_OK opon successfully updating the
  1056   1063   ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
................................................................................
  1309   1316   #endif
  1310   1317   
  1311   1318   /*
  1312   1319   ** This function determines if the machine is running a version of Windows
  1313   1320   ** based on the NT kernel.
  1314   1321   */
  1315   1322   int sqlite3_win32_is_nt(void){
         1323  +#if defined(SQLITE_WIN32_GETVERSIONEX) && SQLITE_WIN32_GETVERSIONEX
  1316   1324     if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){
  1317         -#if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WIN8
         1325  +#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
         1326  +        defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WIN8
  1318   1327       OSVERSIONINFOW sInfo;
  1319   1328       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  1320   1329       osGetVersionExW(&sInfo);
  1321         -#else
         1330  +    osInterlockedCompareExchange(&sqlite3_os_type,
         1331  +        (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
         1332  +#elif defined(SQLITE_WIN32_HAS_ANSI)
  1322   1333       OSVERSIONINFOA sInfo;
  1323   1334       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  1324   1335       osGetVersionExA(&sInfo);
  1325         -#endif
  1326   1336       osInterlockedCompareExchange(&sqlite3_os_type,
  1327   1337           (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
         1338  +#endif
  1328   1339     }
         1340  +  return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
         1341  +#elif SQLITE_TEST
  1329   1342     return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
         1343  +#else
         1344  +  return 1;
         1345  +#endif
  1330   1346   }
  1331   1347   
  1332   1348   #ifdef SQLITE_WIN32_MALLOC
  1333   1349   /*
  1334   1350   ** Allocate nBytes of memory.
  1335   1351   */
  1336   1352   static void *winMemMalloc(int nBytes){
................................................................................
  1531   1547   
  1532   1548   void sqlite3MemSetDefault(void){
  1533   1549     sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
  1534   1550   }
  1535   1551   #endif /* SQLITE_WIN32_MALLOC */
  1536   1552   
  1537   1553   /*
  1538         -** Convert a UTF-8 string to Microsoft Unicode (UTF-16?). 
         1554  +** Convert a UTF-8 string to Microsoft Unicode (UTF-16?).
  1539   1555   **
  1540   1556   ** Space to hold the returned string is obtained from malloc.
  1541   1557   */
  1542   1558   static LPWSTR winUtf8ToUnicode(const char *zFilename){
  1543   1559     int nChar;
  1544   1560     LPWSTR zWideFilename;
  1545   1561   
................................................................................
  1584   1600     }
  1585   1601     return zFilename;
  1586   1602   }
  1587   1603   
  1588   1604   /*
  1589   1605   ** Convert an ANSI string to Microsoft Unicode, based on the
  1590   1606   ** current codepage settings for file apis.
  1591         -** 
         1607  +**
  1592   1608   ** Space to hold the returned string is obtained
  1593   1609   ** from sqlite3_malloc.
  1594   1610   */
  1595   1611   static LPWSTR winMbcsToUnicode(const char *zFilename){
  1596   1612     int nByte;
  1597   1613     LPWSTR zMbcsFilename;
  1598   1614     int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
................................................................................
  1658   1674     }
  1659   1675     zFilenameUtf8 = winUnicodeToUtf8(zTmpWide);
  1660   1676     sqlite3_free(zTmpWide);
  1661   1677     return zFilenameUtf8;
  1662   1678   }
  1663   1679   
  1664   1680   /*
  1665         -** Convert UTF-8 to multibyte character string.  Space to hold the 
         1681  +** Convert UTF-8 to multibyte character string.  Space to hold the
  1666   1682   ** returned string is obtained from sqlite3_malloc().
  1667   1683   */
  1668   1684   char *sqlite3_win32_utf8_to_mbcs(const char *zFilename){
  1669   1685     char *zFilenameMbcs;
  1670   1686     LPWSTR zTmpWide;
  1671   1687   
  1672   1688     zTmpWide = winUtf8ToUnicode(zFilename);
................................................................................
  1798   1814   /*
  1799   1815   **
  1800   1816   ** This function - winLogErrorAtLine() - is only ever called via the macro
  1801   1817   ** winLogError().
  1802   1818   **
  1803   1819   ** This routine is invoked after an error occurs in an OS function.
  1804   1820   ** It logs a message using sqlite3_log() containing the current value of
  1805         -** error code and, if possible, the human-readable equivalent from 
         1821  +** error code and, if possible, the human-readable equivalent from
  1806   1822   ** FormatMessage.
  1807   1823   **
  1808   1824   ** The first argument passed to the macro should be the error code that
  1809         -** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN). 
         1825  +** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  1810   1826   ** The two subsequent arguments should be the name of the OS function that
  1811   1827   ** failed and the associated file-system path, if any.
  1812   1828   */
  1813   1829   #define winLogError(a,b,c,d)   winLogErrorAtLine(a,b,c,d,__LINE__)
  1814   1830   static int winLogErrorAtLine(
  1815   1831     int errcode,                    /* SQLite error code */
  1816   1832     DWORD lastErrno,                /* Win32 last error */
................................................................................
  1833   1849     );
  1834   1850   
  1835   1851     return errcode;
  1836   1852   }
  1837   1853   
  1838   1854   /*
  1839   1855   ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
  1840         -** will be retried following a locking error - probably caused by 
         1856  +** will be retried following a locking error - probably caused by
  1841   1857   ** antivirus software.  Also the initial delay before the first retry.
  1842   1858   ** The delay increases linearly with each retry.
  1843   1859   */
  1844   1860   #ifndef SQLITE_WIN32_IOERR_RETRY
  1845   1861   # define SQLITE_WIN32_IOERR_RETRY 10
  1846   1862   #endif
  1847   1863   #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
................................................................................
  1908   1924   }
  1909   1925   
  1910   1926   /*
  1911   1927   ** Log a I/O error retry episode.
  1912   1928   */
  1913   1929   static void winLogIoerr(int nRetry){
  1914   1930     if( nRetry ){
  1915         -    sqlite3_log(SQLITE_IOERR, 
         1931  +    sqlite3_log(SQLITE_IOERR,
  1916   1932         "delayed %dms for lock/sharing conflict",
  1917   1933         winIoerrRetryDelay*nRetry*(nRetry+1)/2
  1918   1934       );
  1919   1935     }
  1920   1936   }
  1921   1937   
  1922   1938   #if SQLITE_OS_WINCE
................................................................................
  2002   2018       sqlite3_free(zName);
  2003   2019       return winLogError(SQLITE_IOERR, pFile->lastErrno,
  2004   2020                          "winceCreateLock1", zFilename);
  2005   2021     }
  2006   2022   
  2007   2023     /* Acquire the mutex before continuing */
  2008   2024     winceMutexAcquire(pFile->hMutex);
  2009         -  
  2010         -  /* Since the names of named mutexes, semaphores, file mappings etc are 
         2025  +
         2026  +  /* Since the names of named mutexes, semaphores, file mappings etc are
  2011   2027     ** case-sensitive, take advantage of that by uppercasing the mutex name
  2012   2028     ** and using that as the shared filemapping name.
  2013   2029     */
  2014   2030     osCharUpperW(zName);
  2015   2031     pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
  2016   2032                                           PAGE_READWRITE, 0, sizeof(winceLock),
  2017         -                                        zName);  
         2033  +                                        zName);
  2018   2034   
  2019         -  /* Set a flag that indicates we're the first to create the memory so it 
         2035  +  /* Set a flag that indicates we're the first to create the memory so it
  2020   2036     ** must be zero-initialized */
  2021   2037     lastErrno = osGetLastError();
  2022   2038     if (lastErrno == ERROR_ALREADY_EXISTS){
  2023   2039       bInit = FALSE;
  2024   2040     }
  2025   2041   
  2026   2042     sqlite3_free(zName);
  2027   2043   
  2028   2044     /* If we succeeded in making the shared memory handle, map it. */
  2029   2045     if( pFile->hShared ){
  2030         -    pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared, 
         2046  +    pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
  2031   2047                FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
  2032   2048       /* If mapping failed, close the shared memory handle and erase it */
  2033   2049       if( !pFile->shared ){
  2034   2050         pFile->lastErrno = osGetLastError();
  2035   2051         winLogError(SQLITE_IOERR, pFile->lastErrno,
  2036   2052                     "winceCreateLock2", zFilename);
  2037   2053         bLogged = TRUE;
................................................................................
  2049   2065         bLogged = TRUE;
  2050   2066       }
  2051   2067       winceMutexRelease(pFile->hMutex);
  2052   2068       osCloseHandle(pFile->hMutex);
  2053   2069       pFile->hMutex = NULL;
  2054   2070       return SQLITE_IOERR;
  2055   2071     }
  2056         -  
         2072  +
  2057   2073     /* Initialize the shared memory if we're supposed to */
  2058   2074     if( bInit ){
  2059   2075       memset(pFile->shared, 0, sizeof(winceLock));
  2060   2076     }
  2061   2077   
  2062   2078     winceMutexRelease(pFile->hMutex);
  2063   2079     return SQLITE_OK;
................................................................................
  2087   2103       }
  2088   2104   
  2089   2105       /* De-reference and close our copy of the shared memory handle */
  2090   2106       osUnmapViewOfFile(pFile->shared);
  2091   2107       osCloseHandle(pFile->hShared);
  2092   2108   
  2093   2109       /* Done with the mutex */
  2094         -    winceMutexRelease(pFile->hMutex);    
         2110  +    winceMutexRelease(pFile->hMutex);
  2095   2111       osCloseHandle(pFile->hMutex);
  2096   2112       pFile->hMutex = NULL;
  2097   2113     }
  2098   2114   }
  2099   2115   
  2100         -/* 
         2116  +/*
  2101   2117   ** An implementation of the LockFile() API of Windows for CE
  2102   2118   */
  2103   2119   static BOOL winceLockFile(
  2104   2120     LPHANDLE phFile,
  2105   2121     DWORD dwFileOffsetLow,
  2106   2122     DWORD dwFileOffsetHigh,
  2107   2123     DWORD nNumberOfBytesToLockLow,
................................................................................
  2304   2320   ** Some Microsoft compilers lack this definition.
  2305   2321   */
  2306   2322   #ifndef INVALID_SET_FILE_POINTER
  2307   2323   # define INVALID_SET_FILE_POINTER ((DWORD)-1)
  2308   2324   #endif
  2309   2325   
  2310   2326   /*
  2311         -** Move the current position of the file handle passed as the first 
  2312         -** argument to offset iOffset within the file. If successful, return 0. 
         2327  +** Move the current position of the file handle passed as the first
         2328  +** argument to offset iOffset within the file. If successful, return 0.
  2313   2329   ** Otherwise, set pFile->lastErrno and return non-zero.
  2314   2330   */
  2315   2331   static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
  2316   2332   #if !SQLITE_OS_WINRT
  2317   2333     LONG upperBits;                 /* Most sig. 32 bits of new offset */
  2318   2334     LONG lowerBits;                 /* Least sig. 32 bits of new offset */
  2319   2335     DWORD dwRet;                    /* Value returned by SetFilePointer() */
................................................................................
  2320   2336     DWORD lastErrno;                /* Value returned by GetLastError() */
  2321   2337   
  2322   2338     OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
  2323   2339   
  2324   2340     upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
  2325   2341     lowerBits = (LONG)(iOffset & 0xffffffff);
  2326   2342   
  2327         -  /* API oddity: If successful, SetFilePointer() returns a dword 
         2343  +  /* API oddity: If successful, SetFilePointer() returns a dword
  2328   2344     ** containing the lower 32-bits of the new file-offset. Or, if it fails,
  2329         -  ** it returns INVALID_SET_FILE_POINTER. However according to MSDN, 
  2330         -  ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine 
  2331         -  ** whether an error has actually occurred, it is also necessary to call 
         2345  +  ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
         2346  +  ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
         2347  +  ** whether an error has actually occurred, it is also necessary to call
  2332   2348     ** GetLastError().
  2333   2349     */
  2334   2350     dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
  2335   2351   
  2336   2352     if( (dwRet==INVALID_SET_FILE_POINTER
  2337   2353         && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
  2338   2354       pFile->lastErrno = lastErrno;
................................................................................
  2407   2423   #if SQLITE_OS_WINCE
  2408   2424   #define WINCE_DELETION_ATTEMPTS 3
  2409   2425     winceDestroyLock(pFile);
  2410   2426     if( pFile->zDeleteOnClose ){
  2411   2427       int cnt = 0;
  2412   2428       while(
  2413   2429              osDeleteFileW(pFile->zDeleteOnClose)==0
  2414         -        && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff 
         2430  +        && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
  2415   2431           && cnt++ < WINCE_DELETION_ATTEMPTS
  2416   2432       ){
  2417   2433          sqlite3_win32_sleep(100);  /* Wait a little before trying again */
  2418   2434       }
  2419   2435       sqlite3_free(pFile->zDeleteOnClose);
  2420   2436     }
  2421   2437   #endif
................................................................................
  3255   3271   */
  3256   3272   static int winDeviceCharacteristics(sqlite3_file *id){
  3257   3273     winFile *p = (winFile*)id;
  3258   3274     return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
  3259   3275            ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
  3260   3276   }
  3261   3277   
  3262         -/* 
         3278  +/*
  3263   3279   ** Windows will only let you create file view mappings
  3264   3280   ** on allocation size granularity boundaries.
  3265   3281   ** During sqlite3_os_init() we do a GetSystemInfo()
  3266   3282   ** to get the granularity size.
  3267   3283   */
  3268   3284   static SYSTEM_INFO winSysInfo;
  3269   3285   
  3270   3286   #ifndef SQLITE_OMIT_WAL
  3271   3287   
  3272   3288   /*
  3273   3289   ** Helper functions to obtain and relinquish the global mutex. The
  3274         -** global mutex is used to protect the winLockInfo objects used by 
         3290  +** global mutex is used to protect the winLockInfo objects used by
  3275   3291   ** this file, all of which may be shared by multiple threads.
  3276   3292   **
  3277         -** Function winShmMutexHeld() is used to assert() that the global mutex 
  3278         -** is held when required. This function is only used as part of assert() 
         3293  +** Function winShmMutexHeld() is used to assert() that the global mutex
         3294  +** is held when required. This function is only used as part of assert()
  3279   3295   ** statements. e.g.
  3280   3296   **
  3281   3297   **   winShmEnterMutex()
  3282   3298   **     assert( winShmMutexHeld() );
  3283   3299   **   winShmLeaveMutex()
  3284   3300   */
  3285   3301   static void winShmEnterMutex(void){
................................................................................
  3301   3317   ** point to a single instance of this object.  In other words, each
  3302   3318   ** log-summary is opened only once per process.
  3303   3319   **
  3304   3320   ** winShmMutexHeld() must be true when creating or destroying
  3305   3321   ** this object or while reading or writing the following fields:
  3306   3322   **
  3307   3323   **      nRef
  3308         -**      pNext 
         3324  +**      pNext
  3309   3325   **
  3310   3326   ** The following fields are read-only after the object is created:
  3311         -** 
         3327  +**
  3312   3328   **      fid
  3313   3329   **      zFilename
  3314   3330   **
  3315   3331   ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
  3316   3332   ** winShmMutexHeld() is true when reading or writing any other field
  3317   3333   ** in this structure.
  3318   3334   **
................................................................................
  3400   3416       rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
  3401   3417     }else{
  3402   3418       /* Initialize the locking parameters */
  3403   3419       DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
  3404   3420       if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
  3405   3421       rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
  3406   3422     }
  3407         -  
         3423  +
  3408   3424     if( rc!= 0 ){
  3409   3425       rc = SQLITE_OK;
  3410   3426     }else{
  3411   3427       pFile->lastErrno =  osGetLastError();
  3412   3428       rc = SQLITE_BUSY;
  3413   3429     }
  3414   3430   
................................................................................
  3496   3512     pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
  3497   3513     if( pNew==0 ){
  3498   3514       sqlite3_free(p);
  3499   3515       return SQLITE_IOERR_NOMEM;
  3500   3516     }
  3501   3517     pNew->zFilename = (char*)&pNew[1];
  3502   3518     sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
  3503         -  sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename); 
         3519  +  sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
  3504   3520   
  3505   3521     /* Look to see if there is an existing winShmNode that can be used.
  3506   3522     ** If no matching winShmNode currently exists, create a new one.
  3507   3523     */
  3508   3524     winShmEnterMutex();
  3509   3525     for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
  3510   3526       /* TBD need to come up with better match here.  Perhaps
................................................................................
  3533   3549                    SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
  3534   3550                    0);
  3535   3551       if( SQLITE_OK!=rc ){
  3536   3552         goto shm_open_err;
  3537   3553       }
  3538   3554   
  3539   3555       /* Check to see if another process is holding the dead-man switch.
  3540         -    ** If not, truncate the file to zero length. 
         3556  +    ** If not, truncate the file to zero length.
  3541   3557       */
  3542   3558       if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
  3543   3559         rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
  3544   3560         if( rc!=SQLITE_OK ){
  3545   3561           rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
  3546   3562                            "winOpenShm", pDbFd->zPath);
  3547   3563         }
................................................................................
  3562   3578     pDbFd->pShm = p;
  3563   3579     winShmLeaveMutex();
  3564   3580   
  3565   3581     /* The reference count on pShmNode has already been incremented under
  3566   3582     ** the cover of the winShmEnterMutex() mutex and the pointer from the
  3567   3583     ** new (struct winShm) object to the pShmNode has been set. All that is
  3568   3584     ** left to do is to link the new object into the linked list starting
  3569         -  ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex 
         3585  +  ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
  3570   3586     ** mutex.
  3571   3587     */
  3572   3588     sqlite3_mutex_enter(pShmNode->mutex);
  3573   3589     p->pNext = pShmNode->pFirst;
  3574   3590     pShmNode->pFirst = p;
  3575   3591     sqlite3_mutex_leave(pShmNode->mutex);
  3576   3592     return SQLITE_OK;
................................................................................
  3582   3598     sqlite3_free(p);
  3583   3599     sqlite3_free(pNew);
  3584   3600     winShmLeaveMutex();
  3585   3601     return rc;
  3586   3602   }
  3587   3603   
  3588   3604   /*
  3589         -** Close a connection to shared-memory.  Delete the underlying 
         3605  +** Close a connection to shared-memory.  Delete the underlying
  3590   3606   ** storage if deleteFlag is true.
  3591   3607   */
  3592   3608   static int winShmUnmap(
  3593   3609     sqlite3_file *fd,          /* Database holding shared memory */
  3594   3610     int deleteFlag             /* Delete after closing if true */
  3595   3611   ){
  3596   3612     winFile *pDbFd;       /* Database holding shared-memory */
................................................................................
  3671   3687         rc = SQLITE_OK;
  3672   3688       }
  3673   3689   
  3674   3690       /* Undo the local locks */
  3675   3691       if( rc==SQLITE_OK ){
  3676   3692         p->exclMask &= ~mask;
  3677   3693         p->sharedMask &= ~mask;
  3678         -    } 
         3694  +    }
  3679   3695     }else if( flags & SQLITE_SHM_SHARED ){
  3680   3696       u16 allShared = 0;  /* Union of locks held by connections other than "p" */
  3681   3697   
  3682   3698       /* Find out which shared locks are already held by sibling connections.
  3683   3699       ** If any sibling already holds an exclusive lock, go ahead and return
  3684   3700       ** SQLITE_BUSY.
  3685   3701       */
................................................................................
  3710   3726       */
  3711   3727       for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  3712   3728         if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  3713   3729           rc = SQLITE_BUSY;
  3714   3730           break;
  3715   3731         }
  3716   3732       }
  3717         -  
         3733  +
  3718   3734       /* Get the exclusive locks at the system level.  Then if successful
  3719   3735       ** also mark the local connection as being locked.
  3720   3736       */
  3721   3737       if( rc==SQLITE_OK ){
  3722   3738         rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
  3723   3739         if( rc==SQLITE_OK ){
  3724   3740           assert( (p->sharedMask & mask)==0 );
................................................................................
  3730   3746     OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
  3731   3747              osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
  3732   3748              sqlite3ErrName(rc)));
  3733   3749     return rc;
  3734   3750   }
  3735   3751   
  3736   3752   /*
  3737         -** Implement a memory barrier or memory fence on shared memory.  
         3753  +** Implement a memory barrier or memory fence on shared memory.
  3738   3754   **
  3739   3755   ** All loads and stores begun before the barrier must complete before
  3740   3756   ** any load or store begun after the barrier.
  3741   3757   */
  3742   3758   static void winShmBarrier(
  3743   3759     sqlite3_file *fd          /* Database holding the shared memory */
  3744   3760   ){
................................................................................
  3745   3761     UNUSED_PARAMETER(fd);
  3746   3762     /* MemoryBarrier(); // does not work -- do not know why not */
  3747   3763     winShmEnterMutex();
  3748   3764     winShmLeaveMutex();
  3749   3765   }
  3750   3766   
  3751   3767   /*
  3752         -** This function is called to obtain a pointer to region iRegion of the 
  3753         -** shared-memory associated with the database file fd. Shared-memory regions 
  3754         -** are numbered starting from zero. Each shared-memory region is szRegion 
         3768  +** This function is called to obtain a pointer to region iRegion of the
         3769  +** shared-memory associated with the database file fd. Shared-memory regions
         3770  +** are numbered starting from zero. Each shared-memory region is szRegion
  3755   3771   ** bytes in size.
  3756   3772   **
  3757   3773   ** If an error occurs, an error code is returned and *pp is set to NULL.
  3758   3774   **
  3759   3775   ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
  3760   3776   ** region has not been allocated (by any client, including one running in a
  3761         -** separate process), then *pp is set to NULL and SQLITE_OK returned. If 
  3762         -** isWrite is non-zero and the requested shared-memory region has not yet 
         3777  +** separate process), then *pp is set to NULL and SQLITE_OK returned. If
         3778  +** isWrite is non-zero and the requested shared-memory region has not yet
  3763   3779   ** been allocated, it is allocated by this function.
  3764   3780   **
  3765   3781   ** If the shared-memory region has already been allocated or is allocated by
  3766         -** this call as described above, then it is mapped into this processes 
  3767         -** address space (if it is not already), *pp is set to point to the mapped 
         3782  +** this call as described above, then it is mapped into this processes
         3783  +** address space (if it is not already), *pp is set to point to the mapped
  3768   3784   ** memory and SQLITE_OK returned.
  3769   3785   */
  3770   3786   static int winShmMap(
  3771   3787     sqlite3_file *fd,               /* Handle open on database file */
  3772   3788     int iRegion,                    /* Region to retrieve */
  3773   3789     int szRegion,                   /* Size of regions */
  3774   3790     int isWrite,                    /* True to extend file if necessary */
................................................................................
  3832   3848         goto shmpage_out;
  3833   3849       }
  3834   3850       pShmNode->aRegion = apNew;
  3835   3851   
  3836   3852       while( pShmNode->nRegion<=iRegion ){
  3837   3853         HANDLE hMap = NULL;         /* file-mapping handle */
  3838   3854         void *pMap = 0;             /* Mapped memory region */
  3839         -     
         3855  +
  3840   3856   #if SQLITE_OS_WINRT
  3841   3857         hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
  3842   3858             NULL, PAGE_READWRITE, nByte, NULL
  3843   3859         );
  3844   3860   #elif defined(SQLITE_WIN32_HAS_WIDE)
  3845         -      hMap = osCreateFileMappingW(pShmNode->hFile.h, 
         3861  +      hMap = osCreateFileMappingW(pShmNode->hFile.h,
  3846   3862             NULL, PAGE_READWRITE, 0, nByte, NULL
  3847   3863         );
  3848   3864   #elif defined(SQLITE_WIN32_HAS_ANSI)
  3849         -      hMap = osCreateFileMappingA(pShmNode->hFile.h, 
         3865  +      hMap = osCreateFileMappingA(pShmNode->hFile.h,
  3850   3866             NULL, PAGE_READWRITE, 0, nByte, NULL
  3851   3867         );
  3852   3868   #endif
  3853   3869         OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
  3854   3870                  osGetCurrentProcessId(), pShmNode->nRegion, nByte,
  3855   3871                  hMap ? "ok" : "failed"));
  3856   3872         if( hMap ){
................................................................................
  3939   3955     OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  3940   3956              osGetCurrentProcessId(), pFile));
  3941   3957     return SQLITE_OK;
  3942   3958   }
  3943   3959   
  3944   3960   /*
  3945   3961   ** Memory map or remap the file opened by file-descriptor pFd (if the file
  3946         -** is already mapped, the existing mapping is replaced by the new). Or, if 
  3947         -** there already exists a mapping for this file, and there are still 
         3962  +** is already mapped, the existing mapping is replaced by the new). Or, if
         3963  +** there already exists a mapping for this file, and there are still
  3948   3964   ** outstanding xFetch() references to it, this function is a no-op.
  3949   3965   **
  3950         -** If parameter nByte is non-negative, then it is the requested size of 
  3951         -** the mapping to create. Otherwise, if nByte is less than zero, then the 
         3966  +** If parameter nByte is non-negative, then it is the requested size of
         3967  +** the mapping to create. Otherwise, if nByte is less than zero, then the
  3952   3968   ** requested size is the size of the file on disk. The actual size of the
  3953         -** created mapping is either the requested size or the value configured 
         3969  +** created mapping is either the requested size or the value configured
  3954   3970   ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
  3955   3971   **
  3956   3972   ** SQLITE_OK is returned if no error occurs (even if the mapping is not
  3957   3973   ** recreated as a result of outstanding references) or an SQLite error
  3958   3974   ** code otherwise.
  3959   3975   */
  3960   3976   static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
................................................................................
  3975   3991         return SQLITE_IOERR_FSTAT;
  3976   3992       }
  3977   3993     }
  3978   3994     if( nMap>pFd->mmapSizeMax ){
  3979   3995       nMap = pFd->mmapSizeMax;
  3980   3996     }
  3981   3997     nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
  3982         - 
         3998  +
  3983   3999     if( nMap==0 && pFd->mmapSize>0 ){
  3984   4000       winUnmapfile(pFd);
  3985   4001     }
  3986   4002     if( nMap!=pFd->mmapSize ){
  3987   4003       void *pNew = 0;
  3988   4004       DWORD protect = PAGE_READONLY;
  3989   4005       DWORD flags = FILE_MAP_READ;
................................................................................
  4047   4063   ** iOff. The mapping must be valid for at least nAmt bytes.
  4048   4064   **
  4049   4065   ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  4050   4066   ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  4051   4067   ** Finally, if an error does occur, return an SQLite error code. The final
  4052   4068   ** value of *pp is undefined in this case.
  4053   4069   **
  4054         -** If this function does return a pointer, the caller must eventually 
         4070  +** If this function does return a pointer, the caller must eventually
  4055   4071   ** release the reference by calling winUnfetch().
  4056   4072   */
  4057   4073   static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  4058   4074   #if SQLITE_MAX_MMAP_SIZE>0
  4059   4075     winFile *pFd = (winFile*)fd;   /* The underlying database file */
  4060   4076   #endif
  4061   4077     *pp = 0;
................................................................................
  4082   4098   
  4083   4099     OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
  4084   4100              osGetCurrentProcessId(), fd, pp, *pp));
  4085   4101     return SQLITE_OK;
  4086   4102   }
  4087   4103   
  4088   4104   /*
  4089         -** If the third argument is non-NULL, then this function releases a 
         4105  +** If the third argument is non-NULL, then this function releases a
  4090   4106   ** reference obtained by an earlier call to winFetch(). The second
  4091   4107   ** argument passed to this function must be the same as the corresponding
  4092         -** argument that was passed to the winFetch() invocation. 
         4108  +** argument that was passed to the winFetch() invocation.
  4093   4109   **
  4094         -** Or, if the third argument is NULL, then this function is being called 
  4095         -** to inform the VFS layer that, according to POSIX, any existing mapping 
         4110  +** Or, if the third argument is NULL, then this function is being called
         4111  +** to inform the VFS layer that, according to POSIX, any existing mapping
  4096   4112   ** may now be invalid and should be unmapped.
  4097   4113   */
  4098   4114   static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  4099   4115   #if SQLITE_MAX_MMAP_SIZE>0
  4100   4116     winFile *pFd = (winFile*)fd;   /* The underlying database file */
  4101   4117   
  4102         -  /* If p==0 (unmap the entire file) then there must be no outstanding 
         4118  +  /* If p==0 (unmap the entire file) then there must be no outstanding
  4103   4119     ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
  4104   4120     ** then there must be at least one outstanding.  */
  4105   4121     assert( (p==0)==(pFd->nFetchOut==0) );
  4106   4122   
  4107   4123     /* If p!=0, it must match the iOff value. */
  4108   4124     assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
  4109   4125   
................................................................................
  4241   4257     size_t i, j;
  4242   4258     int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX);
  4243   4259     int nMax, nBuf, nDir, nLen;
  4244   4260     char *zBuf;
  4245   4261   
  4246   4262     /* It's odd to simulate an io-error here, but really this is just
  4247   4263     ** using the io-error infrastructure to test that SQLite handles this
  4248         -  ** function failing. 
         4264  +  ** function failing.
  4249   4265     */
  4250   4266     SimulateIOError( return SQLITE_IOERR );
  4251   4267   
  4252   4268     /* Allocate a temporary buffer to store the fully qualified file
  4253   4269     ** name for the temporary file.  If this fails, we cannot continue.
  4254   4270     */
  4255   4271     nMax = pVfs->mxPathname; nBuf = nMax + 2;
................................................................................
  4423   4439     if( !winMakeEndInDirSep(nDir+1, zBuf) ){
  4424   4440       sqlite3_free(zBuf);
  4425   4441       OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  4426   4442       return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0);
  4427   4443     }
  4428   4444   
  4429   4445     /*
  4430         -  ** Check that the output buffer is large enough for the temporary file 
         4446  +  ** Check that the output buffer is large enough for the temporary file
  4431   4447     ** name in the following format:
  4432   4448     **
  4433   4449     **   "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
  4434   4450     **
  4435   4451     ** If not, return SQLITE_ERROR.  The number 17 is used here in order to
  4436   4452     ** account for the space used by the 15 character random suffix and the
  4437   4453     ** two trailing NUL characters.  The final directory separator character
................................................................................
  4526   4542     int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
  4527   4543     int isCreate     = (flags & SQLITE_OPEN_CREATE);
  4528   4544     int isReadonly   = (flags & SQLITE_OPEN_READONLY);
  4529   4545     int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
  4530   4546   
  4531   4547   #ifndef NDEBUG
  4532   4548     int isOpenJournal = (isCreate && (
  4533         -        eType==SQLITE_OPEN_MASTER_JOURNAL 
  4534         -     || eType==SQLITE_OPEN_MAIN_JOURNAL 
         4549  +        eType==SQLITE_OPEN_MASTER_JOURNAL
         4550  +     || eType==SQLITE_OPEN_MAIN_JOURNAL
  4535   4551        || eType==SQLITE_OPEN_WAL
  4536   4552     ));
  4537   4553   #endif
  4538   4554   
  4539   4555     OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
  4540   4556              zUtf8Name, id, flags, pOutFlags));
  4541   4557   
  4542         -  /* Check the following statements are true: 
         4558  +  /* Check the following statements are true:
  4543   4559     **
  4544         -  **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
         4560  +  **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
  4545   4561     **   (b) if CREATE is set, then READWRITE must also be set, and
  4546   4562     **   (c) if EXCLUSIVE is set, then CREATE must also be set.
  4547   4563     **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
  4548   4564     */
  4549   4565     assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  4550   4566     assert(isCreate==0 || isReadWrite);
  4551   4567     assert(isExclusive==0 || isCreate);
  4552   4568     assert(isDelete==0 || isCreate);
  4553   4569   
  4554         -  /* The main DB, main journal, WAL file and master journal are never 
         4570  +  /* The main DB, main journal, WAL file and master journal are never
  4555   4571     ** automatically deleted. Nor are they ever temporary files.  */
  4556   4572     assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  4557   4573     assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  4558   4574     assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  4559   4575     assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  4560   4576   
  4561   4577     /* Assert that the upper layer has set one of the "file-type" flags. */
  4562         -  assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
  4563         -       || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
  4564         -       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
         4578  +  assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
         4579  +       || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
         4580  +       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
  4565   4581          || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  4566   4582     );
  4567   4583   
  4568   4584     assert( pFile!=0 );
  4569   4585     memset(pFile, 0, sizeof(winFile));
  4570   4586     pFile->h = INVALID_HANDLE_VALUE;
  4571   4587   
................................................................................
  4572   4588   #if SQLITE_OS_WINRT
  4573   4589     if( !zUtf8Name && !sqlite3_temp_directory ){
  4574   4590       sqlite3_log(SQLITE_ERROR,
  4575   4591           "sqlite3_temp_directory variable should be set for WinRT");
  4576   4592     }
  4577   4593   #endif
  4578   4594   
  4579         -  /* If the second argument to this function is NULL, generate a 
  4580         -  ** temporary file name to use 
         4595  +  /* If the second argument to this function is NULL, generate a
         4596  +  ** temporary file name to use
  4581   4597     */
  4582   4598     if( !zUtf8Name ){
  4583   4599       assert( isDelete && !isOpenJournal );
  4584   4600       rc = winGetTempname(pVfs, &zTmpname);
  4585   4601       if( rc!=SQLITE_OK ){
  4586   4602         OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
  4587   4603         return rc;
................................................................................
  4613   4629   
  4614   4630     if( isReadWrite ){
  4615   4631       dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
  4616   4632     }else{
  4617   4633       dwDesiredAccess = GENERIC_READ;
  4618   4634     }
  4619   4635   
  4620         -  /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is 
  4621         -  ** created. SQLite doesn't use it to indicate "exclusive access" 
         4636  +  /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
         4637  +  ** created. SQLite doesn't use it to indicate "exclusive access"
  4622   4638     ** as it is usually understood.
  4623   4639     */
  4624   4640     if( isExclusive ){
  4625   4641       /* Creates a new file, only if it does not already exist. */
  4626   4642       /* If the file exists, it fails. */
  4627   4643       dwCreationDisposition = CREATE_NEW;
  4628   4644     }else if( isCreate ){
................................................................................
  4703   4719   
  4704   4720     if( h==INVALID_HANDLE_VALUE ){
  4705   4721       pFile->lastErrno = lastErrno;
  4706   4722       winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
  4707   4723       sqlite3_free(zConverted);
  4708   4724       sqlite3_free(zTmpname);
  4709   4725       if( isReadWrite && !isExclusive ){
  4710         -      return winOpen(pVfs, zName, id, 
         4726  +      return winOpen(pVfs, zName, id,
  4711   4727            ((flags|SQLITE_OPEN_READONLY) &
  4712   4728                        ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
  4713   4729            pOutFlags);
  4714   4730       }else{
  4715   4731         return SQLITE_CANTOPEN_BKPT;
  4716   4732       }
  4717   4733     }
................................................................................
  4912   4928       return SQLITE_IOERR_NOMEM;
  4913   4929     }
  4914   4930     if( osIsNT() ){
  4915   4931       int cnt = 0;
  4916   4932       WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  4917   4933       memset(&sAttrData, 0, sizeof(sAttrData));
  4918   4934       while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
  4919         -                             GetFileExInfoStandard, 
         4935  +                             GetFileExInfoStandard,
  4920   4936                                &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
  4921   4937       if( rc ){
  4922   4938         /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
  4923   4939         ** as if it does not exist.
  4924   4940         */
  4925   4941         if(    flags==SQLITE_ACCESS_EXISTS
  4926         -          && sAttrData.nFileSizeHigh==0 
         4942  +          && sAttrData.nFileSizeHigh==0
  4927   4943             && sAttrData.nFileSizeLow==0 ){
  4928   4944           attr = INVALID_FILE_ATTRIBUTES;
  4929   4945         }else{
  4930   4946           attr = sAttrData.dwFileAttributes;
  4931   4947         }
  4932   4948       }else{
  4933   4949         winLogIoerr(cnt);
................................................................................
  5018   5034   */
  5019   5035   static int winFullPathname(
  5020   5036     sqlite3_vfs *pVfs,            /* Pointer to vfs object */
  5021   5037     const char *zRelative,        /* Possibly relative input path */
  5022   5038     int nFull,                    /* Size of output buffer in bytes */
  5023   5039     char *zFull                   /* Output buffer */
  5024   5040   ){
  5025         -  
         5041  +
  5026   5042   #if defined(__CYGWIN__)
  5027   5043     SimulateIOError( return SQLITE_ERROR );
  5028   5044     UNUSED_PARAMETER(nFull);
  5029   5045     assert( nFull>=pVfs->mxPathname );
  5030   5046     if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  5031   5047       /*
  5032   5048       ** NOTE: We are dealing with a relative path name and the data
................................................................................
  5331   5347   /*
  5332   5348   ** Find the current time (in Universal Coordinated Time).  Write into *piNow
  5333   5349   ** the current time and date as a Julian Day number times 86_400_000.  In
  5334   5350   ** other words, write into *piNow the number of milliseconds since the Julian
  5335   5351   ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  5336   5352   ** proleptic Gregorian calendar.
  5337   5353   **
  5338         -** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date 
         5354  +** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date
  5339   5355   ** cannot be found.
  5340   5356   */
  5341   5357   static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
  5342         -  /* FILETIME structure is a 64-bit value representing the number of 
  5343         -     100-nanosecond intervals since January 1, 1601 (= JD 2305813.5). 
         5358  +  /* FILETIME structure is a 64-bit value representing the number of
         5359  +     100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
  5344   5360     */
  5345   5361     FILETIME ft;
  5346   5362     static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
  5347   5363   #ifdef SQLITE_TEST
  5348   5364     static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  5349   5365   #endif
  5350   5366     /* 2^32 - to avoid use of LL and warnings in gcc */
  5351         -  static const sqlite3_int64 max32BitValue = 
         5367  +  static const sqlite3_int64 max32BitValue =
  5352   5368         (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
  5353   5369         (sqlite3_int64)294967296;
  5354   5370   
  5355   5371   #if SQLITE_OS_WINCE
  5356   5372     SYSTEMTIME time;
  5357   5373     osGetSystemTime(&time);
  5358   5374     /* if SystemTimeToFileTime() fails, it returns zero. */
................................................................................
  5360   5376       return SQLITE_ERROR;
  5361   5377     }
  5362   5378   #else
  5363   5379     osGetSystemTimeAsFileTime( &ft );
  5364   5380   #endif
  5365   5381   
  5366   5382     *piNow = winFiletimeEpoch +
  5367         -            ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) + 
         5383  +            ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
  5368   5384                  (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
  5369   5385   
  5370   5386   #ifdef SQLITE_TEST
  5371   5387     if( sqlite3_current_time ){
  5372   5388       *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  5373   5389     }
  5374   5390   #endif
................................................................................
  5497   5513   
  5498   5514     sqlite3_vfs_register(&winVfs, 1);
  5499   5515   
  5500   5516   #if defined(SQLITE_WIN32_HAS_WIDE)
  5501   5517     sqlite3_vfs_register(&winLongPathVfs, 0);
  5502   5518   #endif
  5503   5519   
  5504         -  return SQLITE_OK; 
         5520  +  return SQLITE_OK;
  5505   5521   }
  5506   5522   
  5507         -int sqlite3_os_end(void){ 
         5523  +int sqlite3_os_end(void){
  5508   5524   #if SQLITE_OS_WINRT
  5509   5525     if( sleepObj!=NULL ){
  5510   5526       osCloseHandle(sleepObj);
  5511   5527       sleepObj = NULL;
  5512   5528     }
  5513   5529   #endif
  5514   5530     return SQLITE_OK;
  5515   5531   }
  5516   5532   
  5517   5533   #endif /* SQLITE_OS_WIN */

Changes to src/resolve.c.

   350    350               if( iCol==pTab->iPKey ){
   351    351                 iCol = -1;
   352    352               }
   353    353               break;
   354    354             }
   355    355           }
   356    356           if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && HasRowid(pTab) ){
   357         -          /* IMP: R-24309-18625 */
          357  +          /* IMP: R-51414-32910 */
   358    358             /* IMP: R-44911-55124 */
   359    359             iCol = -1;
   360    360           }
   361    361           if( iCol<pTab->nCol ){
   362    362             cnt++;
   363    363             if( iCol<0 ){
   364    364               pExpr->affinity = SQLITE_AFF_INTEGER;
................................................................................
   706    706                                         "constant between 0.0 and 1.0");
   707    707                 pNC->nErr++;
   708    708               }
   709    709             }else{
   710    710               /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is equivalent to
   711    711               ** likelihood(X, 0.0625).
   712    712               ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is short-hand for
   713         -            ** likelihood(X,0.0625). */
          713  +            ** likelihood(X,0.0625).
          714  +            ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand for
          715  +            ** likelihood(X,0.9375).
          716  +            ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent to
          717  +            ** likelihood(X,0.9375). */
   714    718               /* TUNING: unlikely() probability is 0.0625.  likely() is 0.9375 */
   715    719               pExpr->iTable = pDef->zName[0]=='u' ? 62 : 938;
   716    720             }             
   717    721           }
   718    722         }
   719    723   #ifndef SQLITE_OMIT_AUTHORIZATION
   720    724         if( pDef ){

Changes to src/select.c.

   728    728             }else{
   729    729               sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
   730    730               VdbeCoverage(v);
   731    731              }
   732    732             sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
   733    733             sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
   734    734           }
   735         -        assert( sqlite3VdbeCurrentAddr(v)==iJump );
          735  +        assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
   736    736           sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
   737    737           break;
   738    738         }
   739    739   
   740    740         case WHERE_DISTINCT_UNIQUE: {
   741    741           sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
   742    742           break;

Changes to src/shell.c.

  1690   1690   static void writefileFunc(
  1691   1691     sqlite3_context *context,
  1692   1692     int argc,
  1693   1693     sqlite3_value **argv
  1694   1694   ){
  1695   1695     FILE *out;
  1696   1696     const char *z;
  1697         -  int n;
  1698   1697     sqlite3_int64 rc;
  1699   1698     const char *zFile;
  1700   1699   
  1701   1700     zFile = (const char*)sqlite3_value_text(argv[0]);
  1702   1701     if( zFile==0 ) return;
  1703   1702     out = fopen(zFile, "wb");
  1704   1703     if( out==0 ) return;
  1705   1704     z = (const char*)sqlite3_value_blob(argv[1]);
  1706   1705     if( z==0 ){
  1707         -    n = 0;
  1708   1706       rc = 0;
  1709   1707     }else{
  1710         -    n = sqlite3_value_bytes(argv[1]);
  1711         -    rc = fwrite(z, 1, n, out);
         1708  +    rc = fwrite(z, 1, sqlite3_value_bytes(argv[1]), out);
  1712   1709     }
  1713   1710     fclose(out);
  1714   1711     sqlite3_result_int64(context, rc);
  1715   1712   }
  1716   1713   
  1717   1714   /*
  1718   1715   ** Make sure the database is open.  If it is not, then open it.  If
................................................................................
  3122   3119       }
  3123   3120     }else
  3124   3121   
  3125   3122     if( c=='s'
  3126   3123      && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
  3127   3124     ){
  3128   3125       char *zCmd;
  3129         -    int i;
         3126  +    int i, x;
  3130   3127       if( nArg<2 ){
  3131   3128         fprintf(stderr, "Usage: .system COMMAND\n");
  3132   3129         rc = 1;
  3133   3130         goto meta_command_exit;
  3134   3131       }
  3135   3132       zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
  3136   3133       for(i=2; i<nArg; i++){
  3137   3134         zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
  3138   3135                                zCmd, azArg[i]);
  3139   3136       }
  3140         -    (void)system(zCmd);
         3137  +    x = system(zCmd);
  3141   3138       sqlite3_free(zCmd);
         3139  +    if( x ) fprintf(stderr, "System command returns %d\n", x);
  3142   3140     }else
  3143   3141   
  3144   3142     if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
  3145   3143       int i;
  3146   3144       if( nArg!=1 ){
  3147   3145         fprintf(stderr, "Usage: .show\n");
  3148   3146         rc = 1;

Changes to src/sqlite.h.in.

   260    260   #endif
   261    261   
   262    262   /*
   263    263   ** CAPI3REF: Closing A Database Connection
   264    264   **
   265    265   ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
   266    266   ** for the [sqlite3] object.
   267         -** ^Calls to sqlite3_close() and sqlite3_close_v2() return SQLITE_OK if
          267  +** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if
   268    268   ** the [sqlite3] object is successfully destroyed and all associated
   269    269   ** resources are deallocated.
   270    270   **
   271    271   ** ^If the database connection is associated with unfinalized prepared
   272    272   ** statements or unfinished sqlite3_backup objects then sqlite3_close()
   273    273   ** will leave the database connection open and return [SQLITE_BUSY].
   274    274   ** ^If sqlite3_close_v2() is called with unfinalized prepared statements
   275         -** and unfinished sqlite3_backups, then the database connection becomes
          275  +** and/or unfinished sqlite3_backups, then the database connection becomes
   276    276   ** an unusable "zombie" which will automatically be deallocated when the
   277    277   ** last prepared statement is finalized or the last sqlite3_backup is
   278    278   ** finished.  The sqlite3_close_v2() interface is intended for use with
   279    279   ** host languages that are garbage collected, and where the order in which
   280    280   ** destructors are called is arbitrary.
   281    281   **
   282    282   ** Applications should [sqlite3_finalize | finalize] all [prepared statements],
   283    283   ** [sqlite3_blob_close | close] all [BLOB handles], and 
   284    284   ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
   285    285   ** with the [sqlite3] object prior to attempting to close the object.  ^If
   286    286   ** sqlite3_close_v2() is called on a [database connection] that still has
   287    287   ** outstanding [prepared statements], [BLOB handles], and/or
   288         -** [sqlite3_backup] objects then it returns SQLITE_OK but the deallocation
          288  +** [sqlite3_backup] objects then it returns [SQLITE_OK] and the deallocation
   289    289   ** of resources is deferred until all [prepared statements], [BLOB handles],
   290    290   ** and [sqlite3_backup] objects are also destroyed.
   291    291   **
   292    292   ** ^If an [sqlite3] object is destroyed while a transaction is open,
   293    293   ** the transaction is automatically rolled back.
   294    294   **
   295    295   ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
................................................................................
   377    377     int (*callback)(void*,int,char**,char**),  /* Callback function */
   378    378     void *,                                    /* 1st argument to callback */
   379    379     char **errmsg                              /* Error msg written here */
   380    380   );
   381    381   
   382    382   /*
   383    383   ** CAPI3REF: Result Codes
   384         -** KEYWORDS: SQLITE_OK {error code} {error codes}
   385         -** KEYWORDS: {result code} {result codes}
          384  +** KEYWORDS: {result code definitions}
   386    385   **
   387    386   ** Many SQLite functions return an integer result code from the set shown
   388    387   ** here in order to indicate success or failure.
   389    388   **
   390    389   ** New error codes may be added in future versions of SQLite.
   391    390   **
   392         -** See also: [SQLITE_IOERR_READ | extended result codes],
   393         -** [sqlite3_vtab_on_conflict()] [SQLITE_ROLLBACK | result codes].
          391  +** See also: [extended result code definitions]
   394    392   */
   395    393   #define SQLITE_OK           0   /* Successful result */
   396    394   /* beginning-of-error-codes */
   397    395   #define SQLITE_ERROR        1   /* SQL error or missing database */
   398    396   #define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
   399    397   #define SQLITE_PERM         3   /* Access permission denied */
   400    398   #define SQLITE_ABORT        4   /* Callback routine requested an abort */
................................................................................
   424    422   #define SQLITE_WARNING     28   /* Warnings from sqlite3_log() */
   425    423   #define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
   426    424   #define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
   427    425   /* end-of-error-codes */
   428    426   
   429    427   /*
   430    428   ** CAPI3REF: Extended Result Codes
   431         -** KEYWORDS: {extended error code} {extended error codes}
   432         -** KEYWORDS: {extended result code} {extended result codes}
          429  +** KEYWORDS: {extended result code definitions}
   433    430   **
   434         -** In its default configuration, SQLite API routines return one of 26 integer
   435         -** [SQLITE_OK | result codes].  However, experience has shown that many of
          431  +** In its default configuration, SQLite API routines return one of 30 integer
          432  +** [result codes].  However, experience has shown that many of
   436    433   ** these result codes are too coarse-grained.  They do not provide as
   437    434   ** much information about problems as programmers might like.  In an effort to
   438    435   ** address this, newer versions of SQLite (version 3.3.8 and later) include
   439    436   ** support for additional result codes that provide more detailed information
   440         -** about errors. The extended result codes are enabled or disabled
          437  +** about errors. These [extended result codes] are enabled or disabled
   441    438   ** on a per database connection basis using the
   442         -** [sqlite3_extended_result_codes()] API.
   443         -**
   444         -** Some of the available extended result codes are listed here.
   445         -** One may expect the number of extended result codes will increase
   446         -** over time.  Software that uses extended result codes should expect
   447         -** to see new result codes in future releases of SQLite.
   448         -**
   449         -** The SQLITE_OK result code will never be extended.  It will always
   450         -** be exactly zero.
          439  +** [sqlite3_extended_result_codes()] API.  Or, the extended code for
          440  +** the most recent error can be obtained using
          441  +** [sqlite3_extended_errcode()].
   451    442   */
   452    443   #define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
   453    444   #define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
   454    445   #define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
   455    446   #define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
   456    447   #define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
   457    448   #define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
................................................................................
   676    667   ** integer opcode.  The third argument is a generic pointer intended to
   677    668   ** point to a structure that may contain arguments or space in which to
   678    669   ** write return values.  Potential uses for xFileControl() might be
   679    670   ** functions to enable blocking locks with timeouts, to change the
   680    671   ** locking strategy (for example to use dot-file locks), to inquire
   681    672   ** about the status of a lock, or to break stale locks.  The SQLite
   682    673   ** core reserves all opcodes less than 100 for its own use.
   683         -** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
          674  +** A [file control opcodes | list of opcodes] less than 100 is available.
   684    675   ** Applications that define a custom xFileControl method should use opcodes
   685    676   ** greater than 100 to avoid conflicts.  VFS implementations should
   686    677   ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
   687    678   ** recognize.
   688    679   **
   689    680   ** The xSectorSize() method returns the sector size of the
   690    681   ** device that underlies the file.  The sector size is the
................................................................................
   749    740     int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
   750    741     /* Methods above are valid for version 3 */
   751    742     /* Additional methods may be added in future releases */
   752    743   };
   753    744   
   754    745   /*
   755    746   ** CAPI3REF: Standard File Control Opcodes
          747  +** KEYWORDS: {file control opcodes} {file control opcode}
   756    748   **
   757    749   ** These integer constants are opcodes for the xFileControl method
   758    750   ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
   759    751   ** interface.
   760    752   **
   761    753   ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
   762    754   ** opcode causes the xFileControl method to write the current state of
................................................................................
  2047   2039   ** that might be invoked with argument P whenever
  2048   2040   ** an attempt is made to access a database table associated with
  2049   2041   ** [database connection] D when another thread
  2050   2042   ** or process has the table locked.
  2051   2043   ** The sqlite3_busy_handler() interface is used to implement
  2052   2044   ** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout].
  2053   2045   **
  2054         -** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
         2046  +** ^If the busy callback is NULL, then [SQLITE_BUSY]
  2055   2047   ** is returned immediately upon encountering the lock.  ^If the busy callback
  2056   2048   ** is not NULL, then the callback might be invoked with two arguments.
  2057   2049   **
  2058   2050   ** ^The first argument to the busy handler is a copy of the void* pointer which
  2059   2051   ** is the third argument to sqlite3_busy_handler().  ^The second argument to
  2060   2052   ** the busy handler callback is the number of times that the busy handler has
  2061   2053   ** been invoked for the same locking event.  ^If the
  2062   2054   ** busy callback returns 0, then no additional attempts are made to
  2063         -** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned
         2055  +** access the database and [SQLITE_BUSY] is returned
  2064   2056   ** to the application.
  2065   2057   ** ^If the callback returns non-zero, then another attempt
  2066   2058   ** is made to access the database and the cycle repeats.
  2067   2059   **
  2068   2060   ** The presence of a busy handler does not guarantee that it will be invoked
  2069   2061   ** when there is lock contention. ^If SQLite determines that invoking the busy
  2070   2062   ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
  2071         -** or [SQLITE_IOERR_BLOCKED] to the application instead of invoking the 
         2063  +** to the application instead of invoking the 
  2072   2064   ** busy handler.
  2073   2065   ** Consider a scenario where one process is holding a read lock that
  2074   2066   ** it is trying to promote to a reserved lock and
  2075   2067   ** a second process is holding a reserved lock that it is trying
  2076   2068   ** to promote to an exclusive lock.  The first process cannot proceed
  2077   2069   ** because it is blocked by the second and the second process cannot
  2078   2070   ** proceed because it is blocked by the first.  If both processes
................................................................................
  2079   2071   ** invoke the busy handlers, neither will make any progress.  Therefore,
  2080   2072   ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
  2081   2073   ** will induce the first process to release its read lock and allow
  2082   2074   ** the second process to proceed.
  2083   2075   **
  2084   2076   ** ^The default busy callback is NULL.
  2085   2077   **
  2086         -** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
  2087         -** when SQLite is in the middle of a large transaction where all the
  2088         -** changes will not fit into the in-memory cache.  SQLite will
  2089         -** already hold a RESERVED lock on the database file, but it needs
  2090         -** to promote this lock to EXCLUSIVE so that it can spill cache
  2091         -** pages into the database file without harm to concurrent
  2092         -** readers.  ^If it is unable to promote the lock, then the in-memory
  2093         -** cache will be left in an inconsistent state and so the error
  2094         -** code is promoted from the relatively benign [SQLITE_BUSY] to
  2095         -** the more severe [SQLITE_IOERR_BLOCKED].  ^This error code promotion
  2096         -** forces an automatic rollback of the changes.  See the
  2097         -** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
  2098         -** CorruptionFollowingBusyError</a> wiki page for a discussion of why
  2099         -** this is important.
  2100         -**
  2101   2078   ** ^(There can only be a single busy handler defined for each
  2102   2079   ** [database connection].  Setting a new busy handler clears any
  2103   2080   ** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
  2104   2081   ** or evaluating [PRAGMA busy_timeout=N] will change the
  2105   2082   ** busy handler and thus clear any previously set busy handler.
  2106   2083   **
  2107   2084   ** The busy callback should not take any actions which modify the
................................................................................
  2118   2095   ** CAPI3REF: Set A Busy Timeout
  2119   2096   **
  2120   2097   ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
  2121   2098   ** for a specified amount of time when a table is locked.  ^The handler
  2122   2099   ** will sleep multiple times until at least "ms" milliseconds of sleeping
  2123   2100   ** have accumulated.  ^After at least "ms" milliseconds of sleeping,
  2124   2101   ** the handler returns 0 which causes [sqlite3_step()] to return
  2125         -** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
         2102  +** [SQLITE_BUSY].
  2126   2103   **
  2127   2104   ** ^Calling this routine with an argument less than or equal to zero
  2128   2105   ** turns off all busy handlers.
  2129   2106   **
  2130   2107   ** ^(There can only be a single busy handler for a particular
  2131   2108   ** [database connection] any any given moment.  If another busy handler
  2132   2109   ** was defined  (using [sqlite3_busy_handler()]) prior to calling
................................................................................
  2530   2507   **
  2531   2508   ** The [sqlite3_set_authorizer | authorizer callback function] must
  2532   2509   ** return either [SQLITE_OK] or one of these two constants in order
  2533   2510   ** to signal SQLite whether or not the action is permitted.  See the
  2534   2511   ** [sqlite3_set_authorizer | authorizer documentation] for additional
  2535   2512   ** information.
  2536   2513   **
  2537         -** Note that SQLITE_IGNORE is also used as a [SQLITE_ROLLBACK | return code]
  2538         -** from the [sqlite3_vtab_on_conflict()] interface.
         2514  +** Note that SQLITE_IGNORE is also used as a [conflict resolution mode]
         2515  +** returned from the [sqlite3_vtab_on_conflict()] interface.
  2539   2516   */
  2540   2517   #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
  2541   2518   #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
  2542   2519   
  2543   2520   /*
  2544   2521   ** CAPI3REF: Authorizer Action Codes
  2545   2522   **
................................................................................
  7372   7349   ** of the SQL statement that triggered the call to the [xUpdate] method of the
  7373   7350   ** [virtual table].
  7374   7351   */
  7375   7352   int sqlite3_vtab_on_conflict(sqlite3 *);
  7376   7353   
  7377   7354   /*
  7378   7355   ** CAPI3REF: Conflict resolution modes
         7356  +** KEYWORDS: {conflict resolution mode}
  7379   7357   **
  7380   7358   ** These constants are returned by [sqlite3_vtab_on_conflict()] to
  7381   7359   ** inform a [virtual table] implementation what the [ON CONFLICT] mode
  7382   7360   ** is for the SQL statement being evaluated.
  7383   7361   **
  7384   7362   ** Note that the [SQLITE_IGNORE] constant is also used as a potential
  7385   7363   ** return value from the [sqlite3_set_authorizer()] callback and that

Changes to src/sqlite3.rc.

    31     31    */
    32     32   
    33     33   #if defined(_WIN32)
    34     34   LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
    35     35   #pragma code_page(1252)
    36     36   #endif /* defined(_WIN32) */
    37     37   
           38  +/*
           39  + * Icon
           40  + */
           41  +
           42  +#define IDI_SQLITE 101
           43  +
           44  +IDI_SQLITE ICON "..\\art\\sqlite370.ico"
           45  +
    38     46   /*
    39     47    * Version
    40     48    */
    41     49   
    42     50   VS_VERSION_INFO VERSIONINFO
    43     51     FILEVERSION SQLITE_RESOURCE_VERSION
    44     52     PRODUCTVERSION SQLITE_RESOURCE_VERSION

Changes to src/vdbe.c.

  3262   3262   */
  3263   3263   case OP_ReopenIdx: {
  3264   3264     VdbeCursor *pCur;
  3265   3265   
  3266   3266     assert( pOp->p5==0 );
  3267   3267     assert( pOp->p4type==P4_KEYINFO );
  3268   3268     pCur = p->apCsr[pOp->p1];
  3269         -  if( pCur && pCur->pgnoRoot==pOp->p2 ){
         3269  +  if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
  3270   3270       assert( pCur->iDb==pOp->p3 );      /* Guaranteed by the code generator */
  3271   3271       break;
  3272   3272     }
  3273   3273     /* If the cursor is not currently open or is open on a different
  3274   3274     ** index, then fall through into OP_OpenRead to force a reopen */
  3275   3275   }
  3276   3276   case OP_OpenRead:
................................................................................
  3549   3549   ** that are used as an unpacked index key. 
  3550   3550   **
  3551   3551   ** Reposition cursor P1 so that  it points to the smallest entry that 
  3552   3552   ** is greater than the key value. If there are no records greater than 
  3553   3553   ** the key and P2 is not zero, then jump to P2.
  3554   3554   **
  3555   3555   ** This opcode leaves the cursor configured to move in forward order,
  3556         -** from the begining toward the end.  In other words, the cursor is
         3556  +** from the beginning toward the end.  In other words, the cursor is
  3557   3557   ** configured to use Next, not Prev.
  3558   3558   **
  3559   3559   ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
  3560   3560   */
  3561   3561   /* Opcode: SeekLT P1 P2 P3 P4 * 
  3562   3562   ** Synopsis: key=r[P3@P4]
  3563   3563   **
................................................................................
  4567   4567   ** The next use of the Rowid or Column or Next instruction for P1 
  4568   4568   ** will refer to the first entry in the database table or index.
  4569   4569   ** If the table or index is empty and P2>0, then jump immediately to P2.
  4570   4570   ** If P2 is 0 or if the table or index is not empty, fall through
  4571   4571   ** to the following instruction.
  4572   4572   **
  4573   4573   ** This opcode leaves the cursor configured to move in forward order,
  4574         -** from the begining toward the end.  In other words, the cursor is
         4574  +** from the beginning toward the end.  In other words, the cursor is
  4575   4575   ** configured to use Next, not Prev.
  4576   4576   */
  4577   4577   case OP_Rewind: {        /* jump */
  4578   4578     VdbeCursor *pC;
  4579   4579     BtCursor *pCrsr;
  4580   4580     int res;
  4581   4581   

Changes to src/vdbeaux.c.

    80     80     zTmp = pA->zSql;
    81     81     pA->zSql = pB->zSql;
    82     82     pB->zSql = zTmp;
    83     83     pB->isPrepareV2 = pA->isPrepareV2;
    84     84   }
    85     85   
    86     86   /*
    87         -** Resize the Vdbe.aOp array so that it is at least one op larger than 
    88         -** it was.
           87  +** Resize the Vdbe.aOp array so that it is at least nOp elements larger 
           88  +** than its current size. nOp is guaranteed to be less than or equal
           89  +** to 1024/sizeof(Op).
    89     90   **
    90     91   ** If an out-of-memory error occurs while resizing the array, return
    91         -** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain 
           92  +** SQLITE_NOMEM. In this case Vdbe.aOp and Parse.nOpAlloc remain 
    92     93   ** unchanged (this is so that any opcodes already allocated can be 
    93     94   ** correctly deallocated along with the rest of the Vdbe).
    94     95   */
    95         -static int growOpArray(Vdbe *v){
           96  +static int growOpArray(Vdbe *v, int nOp){
    96     97     VdbeOp *pNew;
    97     98     Parse *p = v->pParse;
           99  +
          100  +  /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
          101  +  ** more frequent reallocs and hence provide more opportunities for 
          102  +  ** simulated OOM faults.  SQLITE_TEST_REALLOC_STRESS is generally used
          103  +  ** during testing only.  With SQLITE_TEST_REALLOC_STRESS grow the op array
          104  +  ** by the minimum* amount required until the size reaches 512.  Normal
          105  +  ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
          106  +  ** size of the op array or add 1KB of space, whichever is smaller. */
          107  +#ifdef SQLITE_TEST_REALLOC_STRESS
          108  +  int nNew = (p->nOpAlloc>=512 ? p->nOpAlloc*2 : p->nOpAlloc+nOp);
          109  +#else
    98    110     int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
          111  +  UNUSED_PARAMETER(nOp);
          112  +#endif
          113  +
          114  +  assert( nOp<=(1024/sizeof(Op)) );
          115  +  assert( nNew>=(p->nOpAlloc+nOp) );
    99    116     pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
   100    117     if( pNew ){
   101    118       p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
   102    119       v->aOp = pNew;
   103    120     }
   104    121     return (pNew ? SQLITE_OK : SQLITE_NOMEM);
   105    122   }
................................................................................
   135    152     int i;
   136    153     VdbeOp *pOp;
   137    154   
   138    155     i = p->nOp;
   139    156     assert( p->magic==VDBE_MAGIC_INIT );
   140    157     assert( op>0 && op<0xff );
   141    158     if( p->pParse->nOpAlloc<=i ){
   142         -    if( growOpArray(p) ){
          159  +    if( growOpArray(p, 1) ){
   143    160         return 1;
   144    161       }
   145    162     }
   146    163     p->nOp++;
   147    164     pOp = &p->aOp[i];
   148    165     pOp->opcode = (u8)op;
   149    166     pOp->p5 = 0;
................................................................................
   537    554   /*
   538    555   ** Add a whole list of operations to the operation stack.  Return the
   539    556   ** address of the first operation added.
   540    557   */
   541    558   int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp, int iLineno){
   542    559     int addr;
   543    560     assert( p->magic==VDBE_MAGIC_INIT );
   544         -  if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p) ){
          561  +  if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p, nOp) ){
   545    562       return 0;
   546    563     }
   547    564     addr = p->nOp;
   548    565     if( ALWAYS(nOp>0) ){
   549    566       int i;
   550    567       VdbeOpList const *pIn = aOp;
   551    568       for(i=0; i<nOp; i++, pIn++){
................................................................................
   722    739     pVdbe->pProgram = p;
   723    740   }
   724    741   
   725    742   /*
   726    743   ** Change the opcode at addr into OP_Noop
   727    744   */
   728    745   void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
   729         -  if( p->aOp ){
          746  +  if( addr<p->nOp ){
   730    747       VdbeOp *pOp = &p->aOp[addr];
   731    748       sqlite3 *db = p->db;
   732    749       freeP4(db, pOp->p4type, pOp->p4.p);
   733    750       memset(pOp, 0, sizeof(pOp[0]));
   734    751       pOp->opcode = OP_Noop;
   735    752       if( addr==p->nOp-1 ) p->nOp--;
   736    753     }
................................................................................
  2297   2314       int isSpecialError;            /* Set to true if a 'special' error */
  2298   2315   
  2299   2316       /* Lock all btrees used by the statement */
  2300   2317       sqlite3VdbeEnter(p);
  2301   2318   
  2302   2319       /* Check for one of the special errors */
  2303   2320       mrc = p->rc & 0xff;
  2304         -    assert( p->rc!=SQLITE_IOERR_BLOCKED );  /* This error no longer exists */
  2305   2321       isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
  2306   2322                        || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
  2307   2323       if( isSpecialError ){
  2308   2324         /* If the query was read-only and the error code is SQLITE_INTERRUPT, 
  2309   2325         ** no rollback is necessary. Otherwise, at least a savepoint 
  2310   2326         ** transaction must be rolled back to restore the database to a 
  2311   2327         ** consistent state.

Changes to src/where.c.

  5395   5395     int i;
  5396   5396     for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
  5397   5397     if( pLast ) zName[i++] = pLast->cId;
  5398   5398     zName[i] = 0;
  5399   5399     return zName;
  5400   5400   }
  5401   5401   #endif
         5402  +
         5403  +/*
         5404  +** Return the cost of sorting nRow rows, assuming that the keys have 
         5405  +** nOrderby columns and that the first nSorted columns are already in
         5406  +** order.
         5407  +*/
         5408  +static LogEst whereSortingCost(
         5409  +  WhereInfo *pWInfo,
         5410  +  LogEst nRow,
         5411  +  int nOrderBy,
         5412  +  int nSorted
         5413  +){
         5414  +  /* TUNING: Estimated cost of a full external sort, where N is 
         5415  +  ** the number of rows to sort is:
         5416  +  **
         5417  +  **   cost = (3.0 * N * log(N)).
         5418  +  ** 
         5419  +  ** Or, if the order-by clause has X terms but only the last Y 
         5420  +  ** terms are out of order, then block-sorting will reduce the 
         5421  +  ** sorting cost to:
         5422  +  **
         5423  +  **   cost = (3.0 * N * log(N)) * (Y/X)
         5424  +  **
         5425  +  ** The (Y/X) term is implemented using stack variable rScale
         5426  +  ** below.  */
         5427  +  LogEst rScale, rSortCost;
         5428  +  assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
         5429  +  rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
         5430  +  rSortCost = nRow + estLog(nRow) + rScale + 16;
         5431  +
         5432  +  /* TUNING: The cost of implementing DISTINCT using a B-TREE is
         5433  +  ** similar but with a larger constant of proportionality. 
         5434  +  ** Multiply by an additional factor of 3.0.  */
         5435  +  if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
         5436  +    rSortCost += 16;
         5437  +  }
         5438  +
         5439  +  return rSortCost;
         5440  +}
  5402   5441   
  5403   5442   /*
  5404   5443   ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
  5405   5444   ** attempts to find the lowest cost path that visits each WhereLoop
  5406   5445   ** once.  This path is then loaded into the pWInfo->a[].pWLoop fields.
  5407   5446   **
  5408   5447   ** Assume that the total number of output rows that will need to be sorted
................................................................................
  5417   5456     int nLoop;                /* Number of terms in the join */
  5418   5457     Parse *pParse;            /* Parsing context */
  5419   5458     sqlite3 *db;              /* The database connection */
  5420   5459     int iLoop;                /* Loop counter over the terms of the join */
  5421   5460     int ii, jj;               /* Loop counters */
  5422   5461     int mxI = 0;              /* Index of next entry to replace */
  5423   5462     int nOrderBy;             /* Number of ORDER BY clause terms */
  5424         -  LogEst rCost;             /* Cost of a path */
  5425         -  LogEst nOut;              /* Number of outputs */
  5426   5463     LogEst mxCost = 0;        /* Maximum cost of a set of paths */
         5464  +  LogEst mxUnsorted = 0;    /* Maximum unsorted cost of a set of path */
  5427   5465     int nTo, nFrom;           /* Number of valid entries in aTo[] and aFrom[] */
  5428   5466     WherePath *aFrom;         /* All nFrom paths at the previous level */
  5429   5467     WherePath *aTo;           /* The nTo best paths at the current level */
  5430   5468     WherePath *pFrom;         /* An element of aFrom[] that we are working on */
  5431   5469     WherePath *pTo;           /* An element of aTo[] that we are working on */
  5432   5470     WhereLoop *pWLoop;        /* One of the WhereLoop objects */
  5433   5471     WhereLoop **pX;           /* Used to divy up the pSpace memory */
         5472  +  LogEst *aSortCost = 0;    /* Sorting and partial sorting costs */
  5434   5473     char *pSpace;             /* Temporary memory used by this routine */
         5474  +  int nSpace;               /* Bytes of space allocated at pSpace */
  5435   5475   
  5436   5476     pParse = pWInfo->pParse;
  5437   5477     db = pParse->db;
  5438   5478     nLoop = pWInfo->nLevel;
  5439   5479     /* TUNING: For simple queries, only the best path is tracked.
  5440   5480     ** For 2-way joins, the 5 best paths are followed.
  5441   5481     ** For joins of 3 or more tables, track the 10 best paths */
  5442   5482     mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
  5443   5483     assert( nLoop<=pWInfo->pTabList->nSrc );
  5444         -  WHERETRACE(0x002, ("---- begin solver\n"));
         5484  +  WHERETRACE(0x002, ("---- begin solver.  (nRowEst=%d)\n", nRowEst));
  5445   5485   
  5446         -  /* Allocate and initialize space for aTo and aFrom */
  5447         -  ii = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
  5448         -  pSpace = sqlite3DbMallocRaw(db, ii);
         5486  +  /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
         5487  +  ** case the purpose of this call is to estimate the number of rows returned
         5488  +  ** by the overall query. Once this estimate has been obtained, the caller
         5489  +  ** will invoke this function a second time, passing the estimate as the
         5490  +  ** nRowEst parameter.  */
         5491  +  if( pWInfo->pOrderBy==0 || nRowEst==0 ){
         5492  +    nOrderBy = 0;
         5493  +  }else{
         5494  +    nOrderBy = pWInfo->pOrderBy->nExpr;
         5495  +  }
         5496  +
         5497  +  /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
         5498  +  nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
         5499  +  nSpace += sizeof(LogEst) * nOrderBy;
         5500  +  pSpace = sqlite3DbMallocRaw(db, nSpace);
  5449   5501     if( pSpace==0 ) return SQLITE_NOMEM;
  5450   5502     aTo = (WherePath*)pSpace;
  5451   5503     aFrom = aTo+mxChoice;
  5452   5504     memset(aFrom, 0, sizeof(aFrom[0]));
  5453   5505     pX = (WhereLoop**)(aFrom+mxChoice);
  5454   5506     for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
  5455   5507       pFrom->aLoop = pX;
  5456   5508     }
         5509  +  if( nOrderBy ){
         5510  +    /* If there is an ORDER BY clause and it is not being ignored, set up
         5511  +    ** space for the aSortCost[] array. Each element of the aSortCost array
         5512  +    ** is either zero - meaning it has not yet been initialized - or the
         5513  +    ** cost of sorting nRowEst rows of data where the first X terms of
         5514  +    ** the ORDER BY clause are already in order, where X is the array 
         5515  +    ** index.  */
         5516  +    aSortCost = (LogEst*)pX;
         5517  +    memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
         5518  +  }
         5519  +  assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
         5520  +  assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
  5457   5521   
  5458   5522     /* Seed the search with a single WherePath containing zero WhereLoops.
  5459   5523     **
  5460   5524     ** TUNING: Do not let the number of iterations go above 25.  If the cost
  5461   5525     ** of computing an automatic index is not paid back within the first 25
  5462   5526     ** rows, then do not use the automatic index. */
  5463   5527     aFrom[0].nRow = MIN(pParse->nQueryLoop, 46);  assert( 46==sqlite3LogEst(25) );
  5464   5528     nFrom = 1;
  5465         -
  5466         -  /* Precompute the cost of sorting the final result set, if the caller
  5467         -  ** to sqlite3WhereBegin() was concerned about sorting */
  5468         -  if( pWInfo->pOrderBy==0 || nRowEst==0 ){
  5469         -    aFrom[0].isOrdered = 0;
  5470         -    nOrderBy = 0;
  5471         -  }else{
  5472         -    aFrom[0].isOrdered = nLoop>0 ? -1 : 1;
  5473         -    nOrderBy = pWInfo->pOrderBy->nExpr;
         5529  +  assert( aFrom[0].isOrdered==0 );
         5530  +  if( nOrderBy ){
         5531  +    /* If nLoop is zero, then there are no FROM terms in the query. Since
         5532  +    ** in this case the query may return a maximum of one row, the results
         5533  +    ** are already in the requested order. Set isOrdered to nOrderBy to
         5534  +    ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
         5535  +    ** -1, indicating that the result set may or may not be ordered, 
         5536  +    ** depending on the loops added to the current plan.  */
         5537  +    aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
  5474   5538     }
  5475   5539   
  5476   5540     /* Compute successively longer WherePaths using the previous generation
  5477   5541     ** of WherePaths as the basis for the next.  Keep track of the mxChoice
  5478   5542     ** best paths at each generation */
  5479   5543     for(iLoop=0; iLoop<nLoop; iLoop++){
  5480   5544       nTo = 0;
  5481   5545       for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
  5482   5546         for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
  5483         -        Bitmask maskNew;
  5484         -        Bitmask revMask = 0;
  5485         -        i8 isOrdered = pFrom->isOrdered;
         5547  +        LogEst nOut;                      /* Rows visited by (pFrom+pWLoop) */
         5548  +        LogEst rCost;                     /* Cost of path (pFrom+pWLoop) */
         5549  +        LogEst rUnsorted;                 /* Unsorted cost of (pFrom+pWLoop) */
         5550  +        i8 isOrdered = pFrom->isOrdered;  /* isOrdered for (pFrom+pWLoop) */
         5551  +        Bitmask maskNew;                  /* Mask of src visited by (..) */
         5552  +        Bitmask revMask = 0;              /* Mask of rev-order loops for (..) */
         5553  +
  5486   5554           if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
  5487   5555           if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
  5488   5556           /* At this point, pWLoop is a candidate to be the next loop. 
  5489   5557           ** Compute its cost */
  5490         -        rCost = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
  5491         -        rCost = sqlite3LogEstAdd(rCost, pFrom->rCost);
         5558  +        rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
         5559  +        rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
  5492   5560           nOut = pFrom->nRow + pWLoop->nOut;
  5493   5561           maskNew = pFrom->maskLoop | pWLoop->maskSelf;
  5494   5562           if( isOrdered<0 ){
  5495   5563             isOrdered = wherePathSatisfiesOrderBy(pWInfo,
  5496   5564                          pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
  5497   5565                          iLoop, pWLoop, &revMask);
  5498         -          if( isOrdered>=0 && isOrdered<nOrderBy ){
  5499         -            /* TUNING: Estimated cost of a full external sort, where N is 
  5500         -            ** the number of rows to sort is:
  5501         -            **
  5502         -            **   cost = (3.0 * N * log(N)).
  5503         -            ** 
  5504         -            ** Or, if the order-by clause has X terms but only the last Y 
  5505         -            ** terms are out of order, then block-sorting will reduce the 
  5506         -            ** sorting cost to:
  5507         -            **
  5508         -            **   cost = (3.0 * N * log(N)) * (Y/X)
  5509         -            **
  5510         -            ** The (Y/X) term is implemented using stack variable rScale
  5511         -            ** below.  */
  5512         -            LogEst rScale, rSortCost;
  5513         -            assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
  5514         -            rScale = sqlite3LogEst((nOrderBy-isOrdered)*100/nOrderBy) - 66;
  5515         -            rSortCost = nRowEst + estLog(nRowEst) + rScale + 16;
  5516         -
  5517         -            /* TUNING: The cost of implementing DISTINCT using a B-TREE is
  5518         -            ** similar but with a larger constant of proportionality. 
  5519         -            ** Multiply by an additional factor of 3.0.  */
  5520         -            if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
  5521         -              rSortCost += 16;
  5522         -            }
  5523         -            WHERETRACE(0x002,
  5524         -               ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
  5525         -                rSortCost, (nOrderBy-isOrdered), nOrderBy, rCost,
  5526         -                sqlite3LogEstAdd(rCost,rSortCost)));
  5527         -            rCost = sqlite3LogEstAdd(rCost, rSortCost);
  5528         -          }
  5529   5566           }else{
  5530   5567             revMask = pFrom->revLoop;
  5531   5568           }
  5532         -        /* Check to see if pWLoop should be added to the mxChoice best so far */
         5569  +        if( isOrdered>=0 && isOrdered<nOrderBy ){
         5570  +          if( aSortCost[isOrdered]==0 ){
         5571  +            aSortCost[isOrdered] = whereSortingCost(
         5572  +                pWInfo, nRowEst, nOrderBy, isOrdered
         5573  +            );
         5574  +          }
         5575  +          rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]);
         5576  +
         5577  +          WHERETRACE(0x002,
         5578  +              ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
         5579  +               aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy, 
         5580  +               rUnsorted, rCost));
         5581  +        }else{
         5582  +          rCost = rUnsorted;
         5583  +        }
         5584  +
         5585  +        /* Check to see if pWLoop should be added to the set of
         5586  +        ** mxChoice best-so-far paths.
         5587  +        **
         5588  +        ** First look for an existing path among best-so-far paths
         5589  +        ** that covers the same set of loops and has the same isOrdered
         5590  +        ** setting as the current path candidate.
         5591  +        **
         5592  +        ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
         5593  +        ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
         5594  +        ** of legal values for isOrdered, -1..64.
         5595  +        */
  5533   5596           for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
  5534   5597             if( pTo->maskLoop==maskNew
  5535         -           && ((pTo->isOrdered^isOrdered)&80)==0
         5598  +           && ((pTo->isOrdered^isOrdered)&0x80)==0
  5536   5599             ){
  5537   5600               testcase( jj==nTo-1 );
  5538   5601               break;
  5539   5602             }
  5540   5603           }
  5541   5604           if( jj>=nTo ){
  5542         -          if( nTo>=mxChoice && rCost>=mxCost ){
         5605  +          /* None of the existing best-so-far paths match the candidate. */
         5606  +          if( nTo>=mxChoice
         5607  +           && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
         5608  +          ){
         5609  +            /* The current candidate is no better than any of the mxChoice
         5610  +            ** paths currently in the best-so-far buffer.  So discard
         5611  +            ** this candidate as not viable. */
  5543   5612   #ifdef WHERETRACE_ENABLED /* 0x4 */
  5544   5613               if( sqlite3WhereTrace&0x4 ){
  5545   5614                 sqlite3DebugPrintf("Skip   %s cost=%-3d,%3d order=%c\n",
  5546   5615                     wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  5547   5616                     isOrdered>=0 ? isOrdered+'0' : '?');
  5548   5617               }
  5549   5618   #endif
  5550   5619               continue;
  5551   5620             }
  5552         -          /* Add a new Path to the aTo[] set */
         5621  +          /* If we reach this points it means that the new candidate path
         5622  +          ** needs to be added to the set of best-so-far paths. */
  5553   5623             if( nTo<mxChoice ){
  5554   5624               /* Increase the size of the aTo set by one */
  5555   5625               jj = nTo++;
  5556   5626             }else{
  5557   5627               /* New path replaces the prior worst to keep count below mxChoice */
  5558   5628               jj = mxI;
  5559   5629             }
................................................................................
  5562   5632             if( sqlite3WhereTrace&0x4 ){
  5563   5633               sqlite3DebugPrintf("New    %s cost=%-3d,%3d order=%c\n",
  5564   5634                   wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  5565   5635                   isOrdered>=0 ? isOrdered+'0' : '?');
  5566   5636             }
  5567   5637   #endif
  5568   5638           }else{
  5569         -          if( pTo->rCost<=rCost ){
         5639  +          /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
         5640  +          ** same set of loops and has the sam isOrdered setting as the
         5641  +          ** candidate path.  Check to see if the candidate should replace
         5642  +          ** pTo or if the candidate should be skipped */
         5643  +          if( pTo->rCost<rCost || (pTo->rCost==rCost && pTo->nRow<=nOut) ){
  5570   5644   #ifdef WHERETRACE_ENABLED /* 0x4 */
  5571   5645               if( sqlite3WhereTrace&0x4 ){
  5572   5646                 sqlite3DebugPrintf(
  5573   5647                     "Skip   %s cost=%-3d,%3d order=%c",
  5574   5648                     wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  5575   5649                     isOrdered>=0 ? isOrdered+'0' : '?');
  5576   5650                 sqlite3DebugPrintf("   vs %s cost=%-3d,%d order=%c\n",
  5577   5651                     wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  5578   5652                     pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
  5579   5653               }
  5580   5654   #endif
         5655  +            /* Discard the candidate path from further consideration */
  5581   5656               testcase( pTo->rCost==rCost );
  5582   5657               continue;
  5583   5658             }
  5584   5659             testcase( pTo->rCost==rCost+1 );
  5585         -          /* A new and better score for a previously created equivalent path */
         5660  +          /* Control reaches here if the candidate path is better than the
         5661  +          ** pTo path.  Replace pTo with the candidate. */
  5586   5662   #ifdef WHERETRACE_ENABLED /* 0x4 */
  5587   5663             if( sqlite3WhereTrace&0x4 ){
  5588   5664               sqlite3DebugPrintf(
  5589   5665                   "Update %s cost=%-3d,%3d order=%c",
  5590   5666                   wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  5591   5667                   isOrdered>=0 ? isOrdered+'0' : '?');
  5592   5668               sqlite3DebugPrintf("  was %s cost=%-3d,%3d order=%c\n",
................................................................................
  5596   5672   #endif
  5597   5673           }
  5598   5674           /* pWLoop is a winner.  Add it to the set of best so far */
  5599   5675           pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
  5600   5676           pTo->revLoop = revMask;
  5601   5677           pTo->nRow = nOut;
  5602   5678           pTo->rCost = rCost;
         5679  +        pTo->rUnsorted = rUnsorted;
  5603   5680           pTo->isOrdered = isOrdered;
  5604   5681           memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
  5605   5682           pTo->aLoop[iLoop] = pWLoop;
  5606   5683           if( nTo>=mxChoice ){
  5607   5684             mxI = 0;
  5608   5685             mxCost = aTo[0].rCost;
         5686  +          mxUnsorted = aTo[0].nRow;
  5609   5687             for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
  5610         -            if( pTo->rCost>mxCost ){
         5688  +            if( pTo->rCost>mxCost 
         5689  +             || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted) 
         5690  +            ){
  5611   5691                 mxCost = pTo->rCost;
         5692  +              mxUnsorted = pTo->rUnsorted;
  5612   5693                 mxI = jj;
  5613   5694               }
  5614   5695             }
  5615   5696           }
  5616   5697         }
  5617   5698       }
  5618   5699   

Changes to src/whereInt.h.

   179    179   ** at the end is the choosen query plan.
   180    180   */
   181    181   struct WherePath {
   182    182     Bitmask maskLoop;     /* Bitmask of all WhereLoop objects in this path */
   183    183     Bitmask revLoop;      /* aLoop[]s that should be reversed for ORDER BY */
   184    184     LogEst nRow;          /* Estimated number of rows generated by this path */
   185    185     LogEst rCost;         /* Total cost of this path */
          186  +  LogEst rUnsorted;     /* Total cost of this path ignoring sorting costs */
   186    187     i8 isOrdered;         /* No. of ORDER BY terms satisfied. -1 for unknown */
   187    188     WhereLoop **aLoop;    /* Array of WhereLoop objects implementing this path */
   188    189   };
   189    190   
   190    191   /*
   191    192   ** The query generator uses an array of instances of this structure to
   192    193   ** help it analyze the subexpressions of the WHERE clause.  Each WHERE

Changes to test/e_createtable.test.

  1171   1171     2.2    "CREATE TABLE t5(a, b, c, PRIMARY KEY(c,b,a))"       {a b c}
  1172   1172     2.3    "CREATE TABLE t5(a, b INTEGER PRIMARY KEY, c)"       {b}
  1173   1173   }
  1174   1174   
  1175   1175   # EVIDENCE-OF: R-59124-61339 Each row in a table with a primary key must
  1176   1176   # have a unique combination of values in its primary key columns.
  1177   1177   #
  1178         -# EVIDENCE-OF: R-39102-06737 If an INSERT or UPDATE statement attempts
  1179         -# to modify the table content so that two or more rows feature identical
  1180         -# primary key values, it is a constraint violation.
         1178  +# EVIDENCE-OF: R-06471-16287 If an INSERT or UPDATE statement attempts
         1179  +# to modify the table content so that two or more rows have identical
         1180  +# primary key values, that is a constraint violation.
  1181   1181   #
  1182   1182   drop_all_tables
  1183   1183   do_execsql_test 4.3.0 {
  1184   1184     CREATE TABLE t1(x PRIMARY KEY, y);
  1185   1185     INSERT INTO t1 VALUES(0,          'zero');
  1186   1186     INSERT INTO t1 VALUES(45.5,       'one');
  1187   1187     INSERT INTO t1 VALUES('brambles', 'two');

Changes to test/e_expr.test.

   446    446   do_execsql_test e_expr-10.3.3 { SELECT 'isn''t' }         {isn't}
   447    447   do_execsql_test e_expr-10.3.4 { SELECT typeof('isn''t') } {text}
   448    448   
   449    449   # EVIDENCE-OF: R-09593-03321 BLOB literals are string literals
   450    450   # containing hexadecimal data and preceded by a single "x" or "X"
   451    451   # character.
   452    452   #
   453         -# EVIDENCE-OF: R-39344-59787 For example: X'53514C697465'
          453  +# EVIDENCE-OF: R-19836-11244 Example: X'53514C697465'
   454    454   #
   455    455   do_execsql_test e_expr-10.4.1 { SELECT typeof(X'0123456789ABCDEF') } blob
   456    456   do_execsql_test e_expr-10.4.2 { SELECT typeof(x'0123456789ABCDEF') } blob
   457    457   do_execsql_test e_expr-10.4.3 { SELECT typeof(X'0123456789abcdef') } blob
   458    458   do_execsql_test e_expr-10.4.4 { SELECT typeof(x'0123456789abcdef') } blob
   459    459   do_execsql_test e_expr-10.4.5 { SELECT typeof(X'53514C697465')     } blob
   460    460   
................................................................................
  1591   1591   
  1592   1592   # EVIDENCE-OF: R-43164-44276 If there is no prefix that can be
  1593   1593   # interpreted as an integer number, the result of the conversion is 0.
  1594   1594   #
  1595   1595   do_expr_test e_expr-30.4.1 { CAST('' AS INTEGER) } integer 0
  1596   1596   do_expr_test e_expr-30.4.2 { CAST('not a number' AS INTEGER) } integer 0
  1597   1597   do_expr_test e_expr-30.4.3 { CAST('XXI' AS INTEGER) } integer 0
         1598  +
         1599  +# EVIDENCE-OF: R-08980-53124 The CAST operator understands decimal
         1600  +# integers only &mdash; conversion of hexadecimal integers stops at
         1601  +# the "x" in the "0x" prefix of the hexadecimal integer string and thus
         1602  +# result of the CAST is always zero.
         1603  +do_expr_test e_expr-30.5.1 { CAST('0x1234' AS INTEGER) } integer 0
         1604  +do_expr_test e_expr-30.5.2 { CAST('0X1234' AS INTEGER) } integer 0
  1598   1605   
  1599   1606   # EVIDENCE-OF: R-02752-50091 A cast of a REAL value into an INTEGER
  1600   1607   # results in the integer between the REAL value and zero that is closest
  1601   1608   # to the REAL value.
  1602   1609   #
  1603   1610   do_expr_test e_expr-31.1.1 { CAST(3.14159 AS INTEGER) } integer 3
  1604   1611   do_expr_test e_expr-31.1.2 { CAST(1.99999 AS INTEGER) } integer 1

Changes to test/func3.test.

   149    149   # the code generator optimizes away so that it consumes no CPU cycles at
   150    150   # run-time (that is, during calls to sqlite3_step()).
   151    151   #
   152    152   do_test func3-5.39 {
   153    153     db eval {EXPLAIN SELECT unlikely(min(1.0+'2.0',4*11))}
   154    154   } [db eval {EXPLAIN SELECT min(1.0+'2.0',4*11)}]
   155    155   
   156         -do_execsql_test func3-5.40 {
          156  +
          157  +# EVIDENCE-OF: R-23735-03107 The likely(X) function returns the argument
          158  +# X unchanged.
          159  +#
          160  +do_execsql_test func3-5.50 {
   157    161     SELECT likely(9223372036854775807);
   158    162   } {9223372036854775807}
   159         -do_execsql_test func3-5.41 {
          163  +do_execsql_test func3-5.51 {
   160    164     SELECT likely(-9223372036854775808);
   161    165   } {-9223372036854775808}
   162         -do_execsql_test func3-5.42 {
          166  +do_execsql_test func3-5.52 {
   163    167     SELECT likely(14.125);
   164    168   } {14.125}
   165         -do_execsql_test func3-5.43 {
          169  +do_execsql_test func3-5.53 {
   166    170     SELECT likely(NULL);
   167    171   } {{}}
   168         -do_execsql_test func3-5.44 {
          172  +do_execsql_test func3-5.54 {
   169    173     SELECT likely('test-string');
   170    174   } {test-string}
   171         -do_execsql_test func3-5.45 {
          175  +do_execsql_test func3-5.55 {
   172    176     SELECT quote(likely(x'010203000405'));
   173    177   } {X'010203000405'}
   174         -do_test func3-5.49 {
          178  +
          179  +# EVIDENCE-OF: R-43464-09689 The likely(X) function is a no-op that the
          180  +# code generator optimizes away so that it consumes no CPU cycles at
          181  +# run-time (that is, during calls to sqlite3_step()).
          182  +#
          183  +do_test func3-5.59 {
   175    184     db eval {EXPLAIN SELECT likely(min(1.0+'2.0',4*11))}
   176    185   } [db eval {EXPLAIN SELECT min(1.0+'2.0',4*11)}]
          186  +
   177    187   
   178    188   
   179    189   
   180    190   finish_test

Changes to test/incrblob_err.test.

    10     10   #***********************************************************************
    11     11   #
    12     12   # $Id: incrblob_err.test,v 1.14 2008/07/18 17:16:27 drh Exp $
    13     13   #
    14     14   
    15     15   set testdir [file dirname $argv0]
    16     16   source $testdir/tester.tcl
           17  +set ::testprefix incrblob_err
    17     18   
    18     19   ifcapable {!incrblob  || !memdebug || !tclvar} {
    19     20     finish_test
    20     21     return
    21     22   }
    22     23   
    23     24   source $testdir/malloc_common.tcl

Changes to test/malloc.test.

    16     16   # to see what happens in the library if a malloc were to really fail
    17     17   # due to an out-of-memory situation.
    18     18   #
    19     19   # $Id: malloc.test,v 1.81 2009/06/24 13:13:45 drh Exp $
    20     20   
    21     21   set testdir [file dirname $argv0]
    22     22   source $testdir/tester.tcl
           23  +set ::testprefix malloc
    23     24   
    24     25   
    25     26   # Only run these tests if memory debugging is turned on.
    26     27   #
    27     28   source $testdir/malloc_common.tcl
    28     29   if {!$MEMDEBUG} {
    29     30      puts "Skipping malloc tests: not compiled with -DSQLITE_MEMDEBUG..."

Added test/mallocL.test.

            1  +# 2014 August 12
            2  +#
            3  +# The author disclaims copyright to this source code.  In place of
            4  +# a legal notice, here is a blessing:
            5  +#
            6  +#    May you do good and not evil.
            7  +#    May you find forgiveness for yourself and forgive others.
            8  +#    May you share freely, never taking more than you give.
            9  +#
           10  +#***********************************************************************
           11  +#
           12  +# This test script is designed to show that the assert() fix at 
           13  +# [f1cb48f412] really is required.
           14  +# 
           15  +
           16  +set testdir [file dirname $argv0]
           17  +source $testdir/tester.tcl
           18  +source $testdir/malloc_common.tcl
           19  +set testprefix mallocL
           20  +
           21  +do_test 1.0 {
           22  +  for {set i 0} {$i < 40} {incr i} { 
           23  +    lappend cols "c$i" 
           24  +    lappend vals $i
           25  +  }
           26  +
           27  +  execsql "CREATE TABLE t1([join $cols ,])"
           28  +  execsql "CREATE INDEX i1 ON t1([join $cols ,])"
           29  +  execsql "INSERT INTO t1 VALUES([join $vals ,])"
           30  +} {}
           31  +
           32  +for {set j 1} {$j < 40} {incr j} {
           33  +  set ::sql "SELECT DISTINCT [join [lrange $cols 0 $j] ,] FROM t1"
           34  +  do_faultsim_test 1.$j -faults oom* -body {
           35  +    execsql $::sql
           36  +  } -test {
           37  +    faultsim_test_result [list 0 [lrange $::vals 0 $::j]]
           38  +  }
           39  +}
           40  +
           41  +
           42  +finish_test
           43  +

Changes to test/malloc_common.tcl.

   405    405   #
   406    406   proc do_malloc_test {tn args} {
   407    407     array unset ::mallocopts 
   408    408     array set ::mallocopts $args
   409    409   
   410    410     if {[string is integer $tn]} {
   411    411       set tn malloc-$tn
          412  +    catch { set tn $::testprefix-$tn }
   412    413     }
   413    414     if {[info exists ::mallocopts(-start)]} {
   414    415       set start $::mallocopts(-start)
   415    416     } else {
   416    417       set start 0
   417    418     }
   418    419     if {[info exists ::mallocopts(-end)]} {

Changes to test/releasetest.tcl.

   172    172       -DSQLITE_MAX_ATTACHED=30
   173    173       -DSQLITE_ENABLE_COLUMN_METADATA
   174    174       -DSQLITE_ENABLE_FTS4
   175    175       -DSQLITE_ENABLE_FTS4_PARENTHESIS
   176    176       -DSQLITE_DISABLE_FTS4_DEFERRED
   177    177       -DSQLITE_ENABLE_RTREE
   178    178     }
          179  +
          180  +  "No-lookaside" {
          181  +    -DSQLITE_TEST_REALLOC_STRESS=1
          182  +    -DSQLITE_OMIT_LOOKASIDE=1
          183  +    -DHAVE_USLEEP=1
          184  +  }
   179    185   }
   180    186   
   181    187   array set ::Platforms {
   182    188     Linux-x86_64 {
   183    189       "Check-Symbols"           checksymbols
   184    190       "Debug-One"               test
   185    191       "Secure-Delete"           test
   186    192       "Unlock-Notify"           "QUICKTEST_INCLUDE=notify2.test test"
   187    193       "Update-Delete-Limit"     test
   188    194       "Extra-Robustness"        test
   189    195       "Device-Two"              test
   190    196       "Ftrapv"                  test
          197  +    "No-lookaside"            test
   191    198       "Default"                 "threadtest test"
   192    199       "Device-One"              fulltest
   193    200     }
   194    201     Linux-i686 {
   195    202       "Devkit"                  test
   196    203       "Unlock-Notify"           "QUICKTEST_INCLUDE=notify2.test test"
   197    204       "Device-One"              test

Changes to test/where9.test.

   777    777     catchsql {
   778    778       UPDATE t1 INDEXED BY t1b SET a=a+100
   779    779        WHERE (+b IS NULL AND c NOT NULL AND d NOT NULL)
   780    780           OR (b NOT NULL AND c IS NULL AND d NOT NULL)
   781    781           OR (b NOT NULL AND c NOT NULL AND d IS NULL)
   782    782     }
   783    783   } {1 {no query solution}}
          784  +
          785  +set solution_possible 0
   784    786   ifcapable stat4||stat3 {
          787  +  if {[permutation] != "no_optimization"} { set solution_possible 1 }
          788  +}
          789  +if $solution_possible {
   785    790     # When STAT3 is enabled, the "b NOT NULL" terms get translated
   786    791     # into b>NULL, which can be satified by the index t1b.  It is a very
   787    792     # expensive way to do the query, but it works, and so a solution is possible.
   788    793     do_test where9-6.8.3-stat4 {
   789    794       catchsql {
   790    795         UPDATE t1 INDEXED BY t1b SET a=a+100
   791    796          WHERE (b IS NULL AND c NOT NULL AND d NOT NULL)

Changes to test/whereJ.test.

     5      5   #
     6      6   #    May you do good and not evil.
     7      7   #    May you find forgiveness for yourself and forgive others.
     8      8   #    May you share freely, never taking more than you give.
     9      9   #
    10     10   #***********************************************************************
    11     11   # 
    12         -# This file implements a single regression test for a complex
           12  +# This file implements regression tests for a complex
    13     13   # query planning case.
    14     14   #
    15     15   
    16     16   set testdir [file dirname $argv0]
    17     17   source $testdir/tester.tcl
    18     18   set ::testprefix whereJ
    19     19   
................................................................................
   323    323     SELECT aid, sid, MAX(edate) edate
   324    324       FROM tx1
   325    325      WHERE cid = 115790
   326    326        AND sid = 9100
   327    327        AND edate <= 20140430 AND edate >= 20120429
   328    328      GROUP BY aid;
   329    329   } {/B-TREE/}
          330  +
          331  +############################################################################
          332  +# Ensure that the sorting cost does not swamp the loop costs and cause
          333  +# distinctions between individual loop costs to get lost, and hence for
          334  +# sub-optimal loops to be chosen.
          335  +#
          336  +do_execsql_test whereJ-2.1 {
          337  +  CREATE TABLE tab(
          338  +    id INTEGER PRIMARY KEY,
          339  +    minChild INTEGER REFERENCES t1,
          340  +    maxChild INTEGER REFERENCES t1,
          341  +    x INTEGER
          342  +  );
          343  +  EXPLAIN QUERY PLAN
          344  +  SELECT t4.x
          345  +    FROM tab AS t0, tab AS t1, tab AS t2, tab AS t3, tab AS t4
          346  +   WHERE t0.id=0
          347  +     AND t1.id BETWEEN t0.minChild AND t0.maxChild
          348  +     AND t2.id BETWEEN t1.minChild AND t1.maxChild
          349  +     AND t3.id BETWEEN t2.minChild AND t2.maxChild
          350  +     AND t4.id BETWEEN t3.minChild AND t3.maxChild
          351  +  ORDER BY t4.x;
          352  +} {~/SCAN/}
          353  +do_execsql_test whereJ-2.2 {
          354  +  EXPLAIN QUERY PLAN
          355  +  SELECT t4.x
          356  +    FROM tab AS t0a, tab AS t0b,
          357  +         tab AS t1a, tab AS t1b,
          358  +         tab AS t2a, tab AS t2b,
          359  +         tab AS t3a, tab AS t3b,
          360  +         tab AS t4
          361  +   WHERE 1
          362  +     AND t0a.id=1
          363  +     AND t1a.id BETWEEN t0a.minChild AND t0a.maxChild
          364  +     AND t2a.id BETWEEN t1a.minChild AND t1a.maxChild
          365  +     AND t3a.id BETWEEN t2a.minChild AND t2a.maxChild
          366  +     AND t0b.id=2
          367  +     AND t1b.id BETWEEN t0b.minChild AND t0b.maxChild
          368  +     AND t2b.id BETWEEN t1b.minChild AND t1b.maxChild
          369  +     AND t3b.id BETWEEN t2b.minChild AND t2b.maxChild
          370  +     AND t4.id BETWEEN t3a.minChild AND t3b.maxChild
          371  +  ORDER BY t4.x;
          372  +} {~/SCAN/}
          373  +
   330    374   
   331    375   finish_test