Attachment #467601: sqlite 3.7.1 snapshot+ some printfs for bug #581606

View | Details | Raw Unified | Return to bug 581606
Collapse All | Expand All

(-)a/db/sqlite3/src/sqlite3.c (-11677 / +18831 lines)
Line     Link Here 
 Lines 1-6    Link Here 
1
/******************************************************************************
1
/******************************************************************************
2
** This file is an amalgamation of many separate C source files from SQLite
2
** This file is an amalgamation of many separate C source files from SQLite
3
** version 3.6.23.1.  By combining all the individual C code files into this 
3
** version 3.7.1.  By combining all the individual C code files into this 
4
** single large file, the entire code can be compiled as a one translation
4
** single large file, the entire code can be compiled as a one translation
5
** unit.  This allows many compilers to do optimizations that would not be
5
** unit.  This allows many compilers to do optimizations that would not be
6
** possible if the files were compiled separately.  Performance improvements
6
** possible if the files were compiled separately.  Performance improvements
 Lines 191-196    Link Here 
191
#endif
191
#endif
192
192
193
/*
193
/*
194
** The default number of frames to accumulate in the log file before
195
** checkpointing the database in WAL mode.
196
*/
197
#ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
198
# define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT  1000
199
#endif
200
201
/*
194
** The maximum number of attached databases.  This must be between 0
202
** The maximum number of attached databases.  This must be between 0
195
** and 30.  The upper bound on 30 is because a 32-bit integer bitmap
203
** and 30.  The upper bound on 30 is because a 32-bit integer bitmap
196
** is used internally to track attached databases.
204
** is used internally to track attached databases.
 Lines 207-226    Link Here 
207
# define SQLITE_MAX_VARIABLE_NUMBER 999
215
# define SQLITE_MAX_VARIABLE_NUMBER 999
208
#endif
216
#endif
209
217
210
/* Maximum page size.  The upper bound on this value is 32768.  This a limit
218
/* Maximum page size.  The upper bound on this value is 65536.  This a limit
211
** imposed by the necessity of storing the value in a 2-byte unsigned integer
219
** imposed by the use of 16-bit offsets within each page.
212
** and the fact that the page size must be a power of 2.
220
**
213
**
221
** Earlier versions of SQLite allowed the user to change this value at
214
** If this limit is changed, then the compiled library is technically
222
** compile time. This is no longer permitted, on the grounds that it creates
215
** incompatible with an SQLite library compiled with a different limit. If
223
** a library that is technically incompatible with an SQLite library 
216
** a process operating on a database with a page-size of 65536 bytes 
224
** compiled with a different limit. If a process operating on a database 
217
** crashes, then an instance of SQLite compiled with the default page-size 
225
** with a page-size of 65536 bytes crashes, then an instance of SQLite 
218
** limit will not be able to rollback the aborted transaction. This could
226
** compiled with the default page-size limit will not be able to rollback 
219
** lead to database corruption.
227
** the aborted transaction. This could lead to database corruption.
220
*/
228
*/
221
#ifndef SQLITE_MAX_PAGE_SIZE
229
#ifdef SQLITE_MAX_PAGE_SIZE
222
# define SQLITE_MAX_PAGE_SIZE 32768
230
# undef SQLITE_MAX_PAGE_SIZE
223
#endif
231
#endif
232
#define SQLITE_MAX_PAGE_SIZE 65536
224
233
225
234
226
/*
235
/*
 Lines 323-329    Link Here 
323
** The correct "ANSI" way to do this is to use the intptr_t type. 
332
** The correct "ANSI" way to do this is to use the intptr_t type. 
324
** Unfortunately, that typedef is not available on all compilers, or
333
** Unfortunately, that typedef is not available on all compilers, or
325
** if it is available, it requires an #include of specific headers
334
** if it is available, it requires an #include of specific headers
326
** that very from one machine to the next.
335
** that vary from one machine to the next.
327
**
336
**
328
** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
337
** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
329
** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
338
** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
 Lines 504-509   SQLITE_PRIVATE void sqlite3Coverage(in Link Here 
504
#endif
513
#endif
505
514
506
/*
515
/*
516
** Return true (non-zero) if the input is a integer that is too large
517
** to fit in 32-bits.  This macro is used inside of various testcase()
518
** macros to verify that we have tested SQLite for large-file support.
519
*/
520
#define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)
521
522
/*
507
** The macro unlikely() is a hint that surrounds a boolean
523
** The macro unlikely() is a hint that surrounds a boolean
508
** expression that is usually false.  Macro likely() surrounds
524
** expression that is usually false.  Macro likely() surrounds
509
** a boolean expression that is usually true.  GCC is able to
525
** a boolean expression that is usually true.  GCC is able to
 Lines 618-624   extern "C" { Link Here 
618
**
634
**
619
** Since version 3.6.18, SQLite source code has been stored in the
635
** Since version 3.6.18, SQLite source code has been stored in the
620
** <a href="http://www.fossil-scm.org/">Fossil configuration management
636
** <a href="http://www.fossil-scm.org/">Fossil configuration management
621
** system</a>.  ^The SQLITE_SOURCE_ID macro evalutes to
637
** system</a>.  ^The SQLITE_SOURCE_ID macro evaluates to
622
** a string which identifies a particular check-in of SQLite
638
** a string which identifies a particular check-in of SQLite
623
** within its configuration management system.  ^The SQLITE_SOURCE_ID
639
** within its configuration management system.  ^The SQLITE_SOURCE_ID
624
** string contains the date and time of the check-in (UTC) and an SHA1
640
** string contains the date and time of the check-in (UTC) and an SHA1
 Lines 628-636   extern "C" { Link Here 
628
** [sqlite3_libversion_number()], [sqlite3_sourceid()],
644
** [sqlite3_libversion_number()], [sqlite3_sourceid()],
629
** [sqlite_version()] and [sqlite_source_id()].
645
** [sqlite_version()] and [sqlite_source_id()].
630
*/
646
*/
631
#define SQLITE_VERSION        "3.6.23.1"
647
#define SQLITE_VERSION        "3.7.1"
632
#define SQLITE_VERSION_NUMBER 3006023
648
#define SQLITE_VERSION_NUMBER 3007001
633
#define SQLITE_SOURCE_ID      "2010-03-26 22:28:06 b078b588d617e07886ad156e9f54ade6d823568e"
649
#define SQLITE_SOURCE_ID      "2010-08-19 15:12:55 b03091fc3592896fcf1ec563ae9682a8e0a05baa"
634
650
635
/*
651
/*
636
** CAPI3REF: Run-Time Library Version Numbers
652
** CAPI3REF: Run-Time Library Version Numbers
 Lines 667-673   SQLITE_API const char *sqlite3_libversio Link Here 
667
SQLITE_API const char *sqlite3_sourceid(void);
683
SQLITE_API const char *sqlite3_sourceid(void);
668
SQLITE_API int sqlite3_libversion_number(void);
684
SQLITE_API int sqlite3_libversion_number(void);
669
685
670
#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
671
/*
686
/*
672
** CAPI3REF: Run-Time Library Compilation Options Diagnostics
687
** CAPI3REF: Run-Time Library Compilation Options Diagnostics
673
**
688
**
 Lines 676-682   SQLITE_API int sqlite3_libversion_number Link Here 
676
** compile time.  ^The SQLITE_ prefix may be omitted from the 
691
** compile time.  ^The SQLITE_ prefix may be omitted from the 
677
** option name passed to sqlite3_compileoption_used().  
692
** option name passed to sqlite3_compileoption_used().  
678
**
693
**
679
** ^The sqlite3_compileoption_get() function allows interating
694
** ^The sqlite3_compileoption_get() function allows iterating
680
** over the list of options that were defined at compile time by
695
** over the list of options that were defined at compile time by
681
** returning the N-th compile time option string.  ^If N is out of range,
696
** returning the N-th compile time option string.  ^If N is out of range,
682
** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_ 
697
** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_ 
 Lines 684-698   SQLITE_API int sqlite3_libversion_number Link Here 
684
** sqlite3_compileoption_get().
699
** sqlite3_compileoption_get().
685
**
700
**
686
** ^Support for the diagnostic functions sqlite3_compileoption_used()
701
** ^Support for the diagnostic functions sqlite3_compileoption_used()
687
** and sqlite3_compileoption_get() may be omitted by specifing the 
702
** and sqlite3_compileoption_get() may be omitted by specifying the 
688
** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
703
** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
689
**
704
**
690
** See also: SQL functions [sqlite_compileoption_used()] and
705
** See also: SQL functions [sqlite_compileoption_used()] and
691
** [sqlite_compileoption_get()] and the [compile_options pragma].
706
** [sqlite_compileoption_get()] and the [compile_options pragma].
692
*/
707
*/
708
#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
693
SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
709
SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
694
SQLITE_API const char *sqlite3_compileoption_get(int N);
710
SQLITE_API const char *sqlite3_compileoption_get(int N);
695
#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
711
#endif
696
712
697
/*
713
/*
698
** CAPI3REF: Test To See If The Library Is Threadsafe
714
** CAPI3REF: Test To See If The Library Is Threadsafe
 Lines 789-795   typedef sqlite_uint64 sqlite3_uint64; Link Here 
789
**
805
**
790
** ^The sqlite3_close() routine is the destructor for the [sqlite3] object.
806
** ^The sqlite3_close() routine is the destructor for the [sqlite3] object.
791
** ^Calls to sqlite3_close() return SQLITE_OK if the [sqlite3] object is
807
** ^Calls to sqlite3_close() return SQLITE_OK if the [sqlite3] object is
792
** successfullly destroyed and all associated resources are deallocated.
808
** successfully destroyed and all associated resources are deallocated.
793
**
809
**
794
** Applications must [sqlite3_finalize | finalize] all [prepared statements]
810
** Applications must [sqlite3_finalize | finalize] all [prepared statements]
795
** and [sqlite3_blob_close | close] all [BLOB handles] associated with
811
** and [sqlite3_blob_close | close] all [BLOB handles] associated with
 Lines 914-920   SQLITE_API int sqlite3_exec( Link Here 
914
#define SQLITE_NOTFOUND    12   /* NOT USED. Table or record not found */
930
#define SQLITE_NOTFOUND    12   /* NOT USED. Table or record not found */
915
#define SQLITE_FULL        13   /* Insertion failed because database is full */
931
#define SQLITE_FULL        13   /* Insertion failed because database is full */
916
#define SQLITE_CANTOPEN    14   /* Unable to open the database file */
932
#define SQLITE_CANTOPEN    14   /* Unable to open the database file */
917
#define SQLITE_PROTOCOL    15   /* NOT USED. Database lock protocol error */
933
#define SQLITE_PROTOCOL    15   /* Database lock protocol error */
918
#define SQLITE_EMPTY       16   /* Database is empty */
934
#define SQLITE_EMPTY       16   /* Database is empty */
919
#define SQLITE_SCHEMA      17   /* The database schema changed */
935
#define SQLITE_SCHEMA      17   /* The database schema changed */
920
#define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
936
#define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
 Lines 970-976   SQLITE_API int sqlite3_exec( Link Here 
970
#define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
986
#define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
971
#define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
987
#define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
972
#define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
988
#define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
973
#define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED | (1<<8) )
989
#define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))
990
#define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))
991
#define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))
992
#define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))
993
#define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))
994
#define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
974
995
975
/*
996
/*
976
** CAPI3REF: Flags For File Open Operations
997
** CAPI3REF: Flags For File Open Operations
 Lines 997-1007   SQLITE_API int sqlite3_exec( Link Here 
997
#define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
1018
#define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
998
#define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
1019
#define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
999
#define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
1020
#define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
1021
#define SQLITE_OPEN_WAL              0x00080000  /* VFS only */
1000
1022
1001
/*
1023
/*
1002
** CAPI3REF: Device Characteristics
1024
** CAPI3REF: Device Characteristics
1003
**
1025
**
1004
** The xDeviceCapabilities method of the [sqlite3_io_methods]
1026
** The xDeviceCharacteristics method of the [sqlite3_io_methods]
1005
** object returns an integer which is a vector of the these
1027
** object returns an integer which is a vector of the these
1006
** bit values expressing I/O characteristics of the mass storage
1028
** bit values expressing I/O characteristics of the mass storage
1007
** device that holds the file that the [sqlite3_io_methods]
1029
** device that holds the file that the [sqlite3_io_methods]
 Lines 1018-1034   SQLITE_API int sqlite3_exec( Link Here 
1018
** information is written to disk in the same order as calls
1040
** information is written to disk in the same order as calls
1019
** to xWrite().
1041
** to xWrite().
1020
*/
1042
*/
1021
#define SQLITE_IOCAP_ATOMIC          0x00000001
1043
#define SQLITE_IOCAP_ATOMIC                 0x00000001
1022
#define SQLITE_IOCAP_ATOMIC512       0x00000002
1044
#define SQLITE_IOCAP_ATOMIC512              0x00000002
1023
#define SQLITE_IOCAP_ATOMIC1K        0x00000004
1045
#define SQLITE_IOCAP_ATOMIC1K               0x00000004
1024
#define SQLITE_IOCAP_ATOMIC2K        0x00000008
1046
#define SQLITE_IOCAP_ATOMIC2K               0x00000008
1025
#define SQLITE_IOCAP_ATOMIC4K        0x00000010
1047
#define SQLITE_IOCAP_ATOMIC4K               0x00000010
1026
#define SQLITE_IOCAP_ATOMIC8K        0x00000020
1048
#define SQLITE_IOCAP_ATOMIC8K               0x00000020
1027
#define SQLITE_IOCAP_ATOMIC16K       0x00000040
1049
#define SQLITE_IOCAP_ATOMIC16K              0x00000040
1028
#define SQLITE_IOCAP_ATOMIC32K       0x00000080
1050
#define SQLITE_IOCAP_ATOMIC32K              0x00000080
1029
#define SQLITE_IOCAP_ATOMIC64K       0x00000100
1051
#define SQLITE_IOCAP_ATOMIC64K              0x00000100
1030
#define SQLITE_IOCAP_SAFE_APPEND     0x00000200
1052
#define SQLITE_IOCAP_SAFE_APPEND            0x00000200
1031
#define SQLITE_IOCAP_SEQUENTIAL      0x00000400
1053
#define SQLITE_IOCAP_SEQUENTIAL             0x00000400
1054
#define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800
1032
1055
1033
/*
1056
/*
1034
** CAPI3REF: File Locking Levels
1057
** CAPI3REF: File Locking Levels
 Lines 1179-1184   struct sqlite3_io_methods { Link Here 
1179
  int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1202
  int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1180
  int (*xSectorSize)(sqlite3_file*);
1203
  int (*xSectorSize)(sqlite3_file*);
1181
  int (*xDeviceCharacteristics)(sqlite3_file*);
1204
  int (*xDeviceCharacteristics)(sqlite3_file*);
1205
  /* Methods above are valid for version 1 */
1206
  int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
1207
  int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
1208
  void (*xShmBarrier)(sqlite3_file*);
1209
  int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
1210
  /* Methods above are valid for version 2 */
1182
  /* Additional methods may be added in future releases */
1211
  /* Additional methods may be added in future releases */
1183
};
1212
};
1184
1213
 Lines 1196-1206   struct sqlite3_io_methods { Link Here 
1196
** into an integer that the pArg argument points to. This capability
1225
** into an integer that the pArg argument points to. This capability
1197
** is used during testing and only needs to be supported when SQLITE_TEST
1226
** is used during testing and only needs to be supported when SQLITE_TEST
1198
** is defined.
1227
** is defined.
1228
**
1229
** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
1230
** layer a hint of how large the database file will grow to be during the
1231
** current transaction.  This hint is not guaranteed to be accurate but it
1232
** is often close.  The underlying VFS might choose to preallocate database
1233
** file space based on this hint in order to help writes to the database
1234
** file run faster.
1235
**
1236
** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
1237
** extends and truncates the database file in chunks of a size specified
1238
** by the user. The fourth argument to [sqlite3_file_control()] should 
1239
** point to an integer (type int) containing the new chunk-size to use
1240
** for the nominated database. Allocating database file space in large
1241
** chunks (say 1MB at a time), may reduce file-system fragmentation and
1242
** improve performance on some systems.
1199
*/
1243
*/
1200
#define SQLITE_FCNTL_LOCKSTATE        1
1244
#define SQLITE_FCNTL_LOCKSTATE        1
1201
#define SQLITE_GET_LOCKPROXYFILE      2
1245
#define SQLITE_GET_LOCKPROXYFILE      2
1202
#define SQLITE_SET_LOCKPROXYFILE      3
1246
#define SQLITE_SET_LOCKPROXYFILE      3
1203
#define SQLITE_LAST_ERRNO             4
1247
#define SQLITE_LAST_ERRNO             4
1248
#define SQLITE_FCNTL_SIZE_HINT        5
1249
#define SQLITE_FCNTL_CHUNK_SIZE       6
1204
1250
1205
/*
1251
/*
1206
** CAPI3REF: Mutex Handle
1252
** CAPI3REF: Mutex Handle
 Lines 1332-1351   typedef struct sqlite3_mutex sqlite3_mut Link Here 
1332
** handled as a fatal error by SQLite, vfs implementations should endeavor
1378
** handled as a fatal error by SQLite, vfs implementations should endeavor
1333
** to prevent this by setting mxPathname to a sufficiently large value.
1379
** to prevent this by setting mxPathname to a sufficiently large value.
1334
**
1380
**
1335
** The xRandomness(), xSleep(), and xCurrentTime() interfaces
1381
** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
1336
** are not strictly a part of the filesystem, but they are
1382
** interfaces are not strictly a part of the filesystem, but they are
1337
** included in the VFS structure for completeness.
1383
** included in the VFS structure for completeness.
1338
** The xRandomness() function attempts to return nBytes bytes
1384
** The xRandomness() function attempts to return nBytes bytes
1339
** of good-quality randomness into zOut.  The return value is
1385
** of good-quality randomness into zOut.  The return value is
1340
** the actual number of bytes of randomness obtained.
1386
** the actual number of bytes of randomness obtained.
1341
** The xSleep() method causes the calling thread to sleep for at
1387
** The xSleep() method causes the calling thread to sleep for at
1342
** least the number of microseconds given.  The xCurrentTime()
1388
** least the number of microseconds given.  The xCurrentTime()
1343
** method returns a Julian Day Number for the current date and time.
1389
** method returns a Julian Day Number for the current date and time as
1344
**
1390
** a floating point value.
1391
** The xCurrentTimeInt64() method returns, as an integer, the Julian
1392
** Day Number multipled by 86400000 (the number of milliseconds in 
1393
** a 24-hour day).  
1394
** ^SQLite will use the xCurrentTimeInt64() method to get the current
1395
** date and time if that method is available (if iVersion is 2 or 
1396
** greater and the function pointer is not NULL) and will fall back
1397
** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
1345
*/
1398
*/
1346
typedef struct sqlite3_vfs sqlite3_vfs;
1399
typedef struct sqlite3_vfs sqlite3_vfs;
1347
struct sqlite3_vfs {
1400
struct sqlite3_vfs {
1348
  int iVersion;            /* Structure version number */
1401
  int iVersion;            /* Structure version number (currently 2) */
1349
  int szOsFile;            /* Size of subclassed sqlite3_file */
1402
  int szOsFile;            /* Size of subclassed sqlite3_file */
1350
  int mxPathname;          /* Maximum file pathname length */
1403
  int mxPathname;          /* Maximum file pathname length */
1351
  sqlite3_vfs *pNext;      /* Next registered VFS */
1404
  sqlite3_vfs *pNext;      /* Next registered VFS */
 Lines 1364-1371   struct sqlite3_vfs { Link Here 
1364
  int (*xSleep)(sqlite3_vfs*, int microseconds);
1417
  int (*xSleep)(sqlite3_vfs*, int microseconds);
1365
  int (*xCurrentTime)(sqlite3_vfs*, double*);
1418
  int (*xCurrentTime)(sqlite3_vfs*, double*);
1366
  int (*xGetLastError)(sqlite3_vfs*, int, char *);
1419
  int (*xGetLastError)(sqlite3_vfs*, int, char *);
1367
  /* New fields may be appended in figure versions.  The iVersion
1420
  /*
1368
  ** value will increment whenever this happens. */
1421
  ** The methods above are in version 1 of the sqlite_vfs object
1422
  ** definition.  Those that follow are added in version 2 or later
1423
  */
1424
  int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
1425
  /*
1426
  ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
1427
  ** New fields may be appended in figure versions.  The iVersion
1428
  ** value will increment whenever this happens. 
1429
  */
1369
};
1430
};
1370
1431
1371
/*
1432
/*
 Lines 1377-1389   struct sqlite3_vfs { Link Here 
1377
** With SQLITE_ACCESS_EXISTS, the xAccess method
1438
** With SQLITE_ACCESS_EXISTS, the xAccess method
1378
** simply checks whether the file exists.
1439
** simply checks whether the file exists.
1379
** With SQLITE_ACCESS_READWRITE, the xAccess method
1440
** With SQLITE_ACCESS_READWRITE, the xAccess method
1380
** checks whether the file is both readable and writable.
1441
** checks whether the named directory is both readable and writable
1442
** (in other words, if files can be added, removed, and renamed within
1443
** the directory).
1444
** The SQLITE_ACCESS_READWRITE constant is currently used only by the
1445
** [temp_store_directory pragma], though this could change in a future
1446
** release of SQLite.
1381
** With SQLITE_ACCESS_READ, the xAccess method
1447
** With SQLITE_ACCESS_READ, the xAccess method
1382
** checks whether the file is readable.
1448
** checks whether the file is readable.  The SQLITE_ACCESS_READ constant is
1449
** currently unused, though it might be used in a future release of
1450
** SQLite.
1383
*/
1451
*/
1384
#define SQLITE_ACCESS_EXISTS    0
1452
#define SQLITE_ACCESS_EXISTS    0
1385
#define SQLITE_ACCESS_READWRITE 1
1453
#define SQLITE_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */
1386
#define SQLITE_ACCESS_READ      2
1454
#define SQLITE_ACCESS_READ      2   /* Unused */
1455
1456
/*
1457
** CAPI3REF: Flags for the xShmLock VFS method
1458
**
1459
** These integer constants define the various locking operations
1460
** allowed by the xShmLock method of [sqlite3_io_methods].  The
1461
** following are the only legal combinations of flags to the
1462
** xShmLock method:
1463
**
1464
** <ul>
1465
** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
1466
** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
1467
** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
1468
** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
1469
** </ul>
1470
**
1471
** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
1472
** was given no the corresponding lock.  
1473
**
1474
** The xShmLock method can transition between unlocked and SHARED or
1475
** between unlocked and EXCLUSIVE.  It cannot transition between SHARED
1476
** and EXCLUSIVE.
1477
*/
1478
#define SQLITE_SHM_UNLOCK       1
1479
#define SQLITE_SHM_LOCK         2
1480
#define SQLITE_SHM_SHARED       4
1481
#define SQLITE_SHM_EXCLUSIVE    8
1482
1483
/*
1484
** CAPI3REF: Maximum xShmLock index
1485
**
1486
** The xShmLock method on [sqlite3_io_methods] may use values
1487
** between 0 and this upper bound as its "offset" argument.
1488
** The SQLite core will never attempt to acquire or release a
1489
** lock outside of this range
1490
*/
1491
#define SQLITE_SHM_NLOCK        8
1492
1387
1493
1388
/*
1494
/*
1389
** CAPI3REF: Initialize The SQLite Library
1495
** CAPI3REF: Initialize The SQLite Library
 Lines 1494-1504   SQLITE_API int sqlite3_os_end(void); Link Here 
1494
** ^If the option is unknown or SQLite is unable to set the option
1600
** ^If the option is unknown or SQLite is unable to set the option
1495
** then this routine returns a non-zero [error code].
1601
** then this routine returns a non-zero [error code].
1496
*/
1602
*/
1497
SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_config(int, ...);
1603
SQLITE_API int sqlite3_config(int, ...);
1498
1604
1499
/*
1605
/*
1500
** CAPI3REF: Configure database connections
1606
** CAPI3REF: Configure database connections
1501
** EXPERIMENTAL
1502
**
1607
**
1503
** The sqlite3_db_config() interface is used to make configuration
1608
** The sqlite3_db_config() interface is used to make configuration
1504
** changes to a [database connection].  The interface is similar to
1609
** changes to a [database connection].  The interface is similar to
 Lines 1518-1528   SQLITE_API SQLITE_EXPERIMENTAL int sqlit Link Here 
1518
** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1623
** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1519
** the call is considered successful.
1624
** the call is considered successful.
1520
*/
1625
*/
1521
SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_db_config(sqlite3*, int op, ...);
1626
SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
1522
1627
1523
/*
1628
/*
1524
** CAPI3REF: Memory Allocation Routines
1629
** CAPI3REF: Memory Allocation Routines
1525
** EXPERIMENTAL
1526
**
1630
**
1527
** An instance of this object defines the interface between SQLite
1631
** An instance of this object defines the interface between SQLite
1528
** and low-level memory allocation routines.
1632
** and low-level memory allocation routines.
 Lines 1604-1610   struct sqlite3_mem_methods { Link Here 
1604
1708
1605
/*
1709
/*
1606
** CAPI3REF: Configuration Options
1710
** CAPI3REF: Configuration Options
1607
** EXPERIMENTAL
1608
**
1711
**
1609
** These constants are the available integer configuration options that
1712
** These constants are the available integer configuration options that
1610
** can be passed as the first argument to the [sqlite3_config()] interface.
1713
** can be passed as the first argument to the [sqlite3_config()] interface.
 Lines 1790-1795   struct sqlite3_mem_methods { Link Here 
1790
** [sqlite3_pcache_methods] object.  SQLite copies of the current
1893
** [sqlite3_pcache_methods] object.  SQLite copies of the current
1791
** page cache implementation into that object.)^ </dd>
1894
** page cache implementation into that object.)^ </dd>
1792
**
1895
**
1896
** <dt>SQLITE_CONFIG_LOG</dt>
1897
** <dd> ^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
1898
** function with a call signature of void(*)(void*,int,const char*), 
1899
** and a pointer to void. ^If the function pointer is not NULL, it is
1900
** invoked by [sqlite3_log()] to process each logging event.  ^If the
1901
** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
1902
** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
1903
** passed through as the first parameter to the application-defined logger
1904
** function whenever that function is invoked.  ^The second parameter to
1905
** the logger function is a copy of the first parameter to the corresponding
1906
** [sqlite3_log()] call and is intended to be a [result code] or an
1907
** [extended result code].  ^The third parameter passed to the logger is
1908
** log message after formatting via [sqlite3_snprintf()].
1909
** The SQLite logging interface is not reentrant; the logger function
1910
** supplied by the application must not invoke any SQLite interface.
1911
** In a multi-threaded application, the application-defined logger
1912
** function must be threadsafe. </dd>
1913
**
1793
** </dl>
1914
** </dl>
1794
*/
1915
*/
1795
#define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
1916
#define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
 Lines 1810-1817   struct sqlite3_mem_methods { Link Here 
1810
#define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
1931
#define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
1811
1932
1812
/*
1933
/*
1813
** CAPI3REF: Configuration Options
1934
** CAPI3REF: Database Connection Configuration Options
1814
** EXPERIMENTAL
1815
**
1935
**
1816
** These constants are the available integer configuration options that
1936
** These constants are the available integer configuration options that
1817
** can be passed as the second argument to the [sqlite3_db_config()] interface.
1937
** can be passed as the second argument to the [sqlite3_db_config()] interface.
 Lines 2587-2593   SQLITE_API int sqlite3_set_authorizer( Link Here 
2587
2707
2588
/*
2708
/*
2589
** CAPI3REF: Tracing And Profiling Functions
2709
** CAPI3REF: Tracing And Profiling Functions
2590
** EXPERIMENTAL
2591
**
2710
**
2592
** These routines register callback functions that can be used for
2711
** These routines register callback functions that can be used for
2593
** tracing and profiling the execution of SQL statements.
2712
** tracing and profiling the execution of SQL statements.
 Lines 2603-2611   SQLITE_API int sqlite3_set_authorizer( Link Here 
2603
** ^The callback function registered by sqlite3_profile() is invoked
2722
** ^The callback function registered by sqlite3_profile() is invoked
2604
** as each SQL statement finishes.  ^The profile callback contains
2723
** as each SQL statement finishes.  ^The profile callback contains
2605
** the original statement text and an estimate of wall-clock time
2724
** the original statement text and an estimate of wall-clock time
2606
** of how long that statement took to run.
2725
** of how long that statement took to run.  ^The profile callback
2607
*/
2726
** time is in units of nanoseconds, however the current implementation
2608
SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
2727
** is only capable of millisecond resolution so the six least significant
2728
** digits in the time are meaningless.  Future versions of SQLite
2729
** might provide greater resolution on the profiler callback.  The
2730
** sqlite3_profile() function is considered experimental and is
2731
** subject to change in future versions of SQLite.
2732
*/
2733
SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
2609
SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
2734
SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
2610
   void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
2735
   void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
2611
2736
 Lines 3084-3090   typedef struct sqlite3_context sqlite3_c Link Here 
3084
** </ul>
3209
** </ul>
3085
**
3210
**
3086
** In the templates above, NNN represents an integer literal,
3211
** In the templates above, NNN represents an integer literal,
3087
** and VVV represents an alphanumeric identifer.)^  ^The values of these
3212
** and VVV represents an alphanumeric identifier.)^  ^The values of these
3088
** parameters (also called "host parameter names" or "SQL parameters")
3213
** parameters (also called "host parameter names" or "SQL parameters")
3089
** can be set using the sqlite3_bind_*() routines defined here.
3214
** can be set using the sqlite3_bind_*() routines defined here.
3090
**
3215
**
 Lines 3398-3403   SQLITE_API const void *sqlite3_column_de Link Here 
3398
** be the case that the same database connection is being used by two or
3523
** be the case that the same database connection is being used by two or
3399
** more threads at the same moment in time.
3524
** more threads at the same moment in time.
3400
**
3525
**
3526
** For all versions of SQLite up to and including 3.6.23.1, it was required
3527
** after sqlite3_step() returned anything other than [SQLITE_ROW] that
3528
** [sqlite3_reset()] be called before any subsequent invocation of
3529
** sqlite3_step().  Failure to invoke [sqlite3_reset()] in this way would
3530
** result in an [SQLITE_MISUSE] return from sqlite3_step().  But after
3531
** version 3.6.23.1, sqlite3_step() began calling [sqlite3_reset()] 
3532
** automatically in this circumstance rather than returning [SQLITE_MISUSE].  
3533
**
3401
** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
3534
** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
3402
** API always returns a generic error code, [SQLITE_ERROR], following any
3535
** API always returns a generic error code, [SQLITE_ERROR], following any
3403
** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
3536
** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
 Lines 3855-3861   SQLITE_API int sqlite3_value_numeric_typ Link Here 
3855
/*
3988
/*
3856
** CAPI3REF: Obtain Aggregate Function Context
3989
** CAPI3REF: Obtain Aggregate Function Context
3857
**
3990
**
3858
** Implementions of aggregate SQL functions use this
3991
** Implementations of aggregate SQL functions use this
3859
** routine to allocate memory for storing their state.
3992
** routine to allocate memory for storing their state.
3860
**
3993
**
3861
** ^The first time the sqlite3_aggregate_context(C,N) routine is called 
3994
** ^The first time the sqlite3_aggregate_context(C,N) routine is called 
 Lines 4127-4133   SQLITE_API void sqlite3_result_zeroblob( Link Here 
4127
**
4260
**
4128
** A pointer to the user supplied routine must be passed as the fifth
4261
** A pointer to the user supplied routine must be passed as the fifth
4129
** argument.  ^If it is NULL, this is the same as deleting the collation
4262
** argument.  ^If it is NULL, this is the same as deleting the collation
4130
** sequence (so that SQLite cannot call it anymore).
4263
** sequence (so that SQLite cannot call it any more).
4131
** ^Each time the application supplied function is invoked, it is passed
4264
** ^Each time the application supplied function is invoked, it is passed
4132
** as its first parameter a copy of the void* passed as the fourth argument
4265
** as its first parameter a copy of the void* passed as the fourth argument
4133
** to sqlite3_create_collation() or sqlite3_create_collation16().
4266
** to sqlite3_create_collation() or sqlite3_create_collation16().
 Lines 4210-4216   SQLITE_API int sqlite3_collation_needed1 Link Here 
4210
  void(*)(void*,sqlite3*,int eTextRep,const void*)
4343
  void(*)(void*,sqlite3*,int eTextRep,const void*)
4211
);
4344
);
4212
4345
4213
#if SQLITE_HAS_CODEC
4346
#ifdef SQLITE_HAS_CODEC
4214
/*
4347
/*
4215
** Specify the key for an encrypted database.  This routine should be
4348
** Specify the key for an encrypted database.  This routine should be
4216
** called right after sqlite3_open().
4349
** called right after sqlite3_open().
 Lines 4393-4400   SQLITE_API sqlite3_stmt *sqlite3_next_st Link Here 
4393
** an error or constraint causes an implicit rollback to occur.
4526
** an error or constraint causes an implicit rollback to occur.
4394
** ^The rollback callback is not invoked if a transaction is
4527
** ^The rollback callback is not invoked if a transaction is
4395
** automatically rolled back because the database connection is closed.
4528
** automatically rolled back because the database connection is closed.
4396
** ^The rollback callback is not invoked if a transaction is
4397
** rolled back because a commit callback returned non-zero.
4398
**
4529
**
4399
** See also the [sqlite3_update_hook()] interface.
4530
** See also the [sqlite3_update_hook()] interface.
4400
*/
4531
*/
 Lines 4680-4687   SQLITE_API int sqlite3_auto_extension(vo Link Here 
4680
SQLITE_API void sqlite3_reset_auto_extension(void);
4811
SQLITE_API void sqlite3_reset_auto_extension(void);
4681
4812
4682
/*
4813
/*
4683
****** EXPERIMENTAL - subject to change without notice **************
4684
**
4685
** The interface to the virtual-table mechanism is currently considered
4814
** The interface to the virtual-table mechanism is currently considered
4686
** to be experimental.  The interface might change in incompatible ways.
4815
** to be experimental.  The interface might change in incompatible ways.
4687
** If this is a problem for you, do not use the interface at this time.
4816
** If this is a problem for you, do not use the interface at this time.
 Lines 4701-4707   typedef struct sqlite3_module sqlite3_mo Link Here 
4701
/*
4830
/*
4702
** CAPI3REF: Virtual Table Object
4831
** CAPI3REF: Virtual Table Object
4703
** KEYWORDS: sqlite3_module {virtual table module}
4832
** KEYWORDS: sqlite3_module {virtual table module}
4704
** EXPERIMENTAL
4705
**
4833
**
4706
** This structure, sometimes called a a "virtual table module", 
4834
** This structure, sometimes called a a "virtual table module", 
4707
** defines the implementation of a [virtual tables].  
4835
** defines the implementation of a [virtual tables].  
 Lines 4748-4756   struct sqlite3_module { Link Here 
4748
/*
4876
/*
4749
** CAPI3REF: Virtual Table Indexing Information
4877
** CAPI3REF: Virtual Table Indexing Information
4750
** KEYWORDS: sqlite3_index_info
4878
** KEYWORDS: sqlite3_index_info
4751
** EXPERIMENTAL
4879
**
4752
**
4880
** The sqlite3_index_info structure and its substructures is used as part
4753
** The sqlite3_index_info structure and its substructures is used to
4881
** of the [virtual table] interface to
4754
** pass information into and receive the reply from the [xBestIndex]
4882
** pass information into and receive the reply from the [xBestIndex]
4755
** method of a [virtual table module].  The fields under **Inputs** are the
4883
** method of a [virtual table module].  The fields under **Inputs** are the
4756
** inputs to xBestIndex and are read-only.  xBestIndex inserts its
4884
** inputs to xBestIndex and are read-only.  xBestIndex inserts its
 Lines 4758-4767   struct sqlite3_module { Link Here 
4758
**
4886
**
4759
** ^(The aConstraint[] array records WHERE clause constraints of the form:
4887
** ^(The aConstraint[] array records WHERE clause constraints of the form:
4760
**
4888
**
4761
** <pre>column OP expr</pre>
4889
** <blockquote>column OP expr</blockquote>
4762
**
4890
**
4763
** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
4891
** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
4764
** stored in aConstraint[].op.)^  ^(The index of the column is stored in
4892
** stored in aConstraint[].op using one of the
4893
** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
4894
** ^(The index of the column is stored in
4765
** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
4895
** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
4766
** expr on the right-hand side can be evaluated (and thus the constraint
4896
** expr on the right-hand side can be evaluated (and thus the constraint
4767
** is usable) and false if it cannot.)^
4897
** is usable) and false if it cannot.)^
 Lines 4821-4826   struct sqlite3_index_info { Link Here 
4821
  int orderByConsumed;       /* True if output is already ordered */
4951
  int orderByConsumed;       /* True if output is already ordered */
4822
  double estimatedCost;      /* Estimated cost of using this index */
4952
  double estimatedCost;      /* Estimated cost of using this index */
4823
};
4953
};
4954
4955
/*
4956
** CAPI3REF: Virtual Table Constraint Operator Codes
4957
**
4958
** These macros defined the allowed values for the
4959
** [sqlite3_index_info].aConstraint[].op field.  Each value represents
4960
** an operator that is part of a constraint term in the wHERE clause of
4961
** a query that uses a [virtual table].
4962
*/
4824
#define SQLITE_INDEX_CONSTRAINT_EQ    2
4963
#define SQLITE_INDEX_CONSTRAINT_EQ    2
4825
#define SQLITE_INDEX_CONSTRAINT_GT    4
4964
#define SQLITE_INDEX_CONSTRAINT_GT    4
4826
#define SQLITE_INDEX_CONSTRAINT_LE    8
4965
#define SQLITE_INDEX_CONSTRAINT_LE    8
 Lines 4830-4836   struct sqlite3_index_info { Link Here 
4830
4969
4831
/*
4970
/*
4832
** CAPI3REF: Register A Virtual Table Implementation
4971
** CAPI3REF: Register A Virtual Table Implementation
4833
** EXPERIMENTAL
4834
**
4972
**
4835
** ^These routines are used to register a new [virtual table module] name.
4973
** ^These routines are used to register a new [virtual table module] name.
4836
** ^Module names must be registered before
4974
** ^Module names must be registered before
 Lines 4852-4864   struct sqlite3_index_info { Link Here 
4852
** interface is equivalent to sqlite3_create_module_v2() with a NULL
4990
** interface is equivalent to sqlite3_create_module_v2() with a NULL
4853
** destructor.
4991
** destructor.
4854
*/
4992
*/
4855
SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_create_module(
4993
SQLITE_API int sqlite3_create_module(
4856
  sqlite3 *db,               /* SQLite connection to register module with */
4994
  sqlite3 *db,               /* SQLite connection to register module with */
4857
  const char *zName,         /* Name of the module */
4995
  const char *zName,         /* Name of the module */
4858
  const sqlite3_module *p,   /* Methods for the module */
4996
  const sqlite3_module *p,   /* Methods for the module */
4859
  void *pClientData          /* Client data for xCreate/xConnect */
4997
  void *pClientData          /* Client data for xCreate/xConnect */
4860
);
4998
);
4861
SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_create_module_v2(
4999
SQLITE_API int sqlite3_create_module_v2(
4862
  sqlite3 *db,               /* SQLite connection to register module with */
5000
  sqlite3 *db,               /* SQLite connection to register module with */
4863
  const char *zName,         /* Name of the module */
5001
  const char *zName,         /* Name of the module */
4864
  const sqlite3_module *p,   /* Methods for the module */
5002
  const sqlite3_module *p,   /* Methods for the module */
 Lines 4869-4875   SQLITE_API SQLITE_EXPERIMENTAL int sqlit Link Here 
4869
/*
5007
/*
4870
** CAPI3REF: Virtual Table Instance Object
5008
** CAPI3REF: Virtual Table Instance Object
4871
** KEYWORDS: sqlite3_vtab
5009
** KEYWORDS: sqlite3_vtab
4872
** EXPERIMENTAL
4873
**
5010
**
4874
** Every [virtual table module] implementation uses a subclass
5011
** Every [virtual table module] implementation uses a subclass
4875
** of this object to describe a particular instance
5012
** of this object to describe a particular instance
 Lines 4895-4901   struct sqlite3_vtab { Link Here 
4895
/*
5032
/*
4896
** CAPI3REF: Virtual Table Cursor Object
5033
** CAPI3REF: Virtual Table Cursor Object
4897
** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
5034
** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
4898
** EXPERIMENTAL
4899
**
5035
**
4900
** Every [virtual table module] implementation uses a subclass of the
5036
** Every [virtual table module] implementation uses a subclass of the
4901
** following structure to describe cursors that point into the
5037
** following structure to describe cursors that point into the
 Lines 4917-4934   struct sqlite3_vtab_cursor { Link Here 
4917
5053
4918
/*
5054
/*
4919
** CAPI3REF: Declare The Schema Of A Virtual Table
5055
** CAPI3REF: Declare The Schema Of A Virtual Table
4920
** EXPERIMENTAL
4921
**
5056
**
4922
** ^The [xCreate] and [xConnect] methods of a
5057
** ^The [xCreate] and [xConnect] methods of a
4923
** [virtual table module] call this interface
5058
** [virtual table module] call this interface
4924
** to declare the format (the names and datatypes of the columns) of
5059
** to declare the format (the names and datatypes of the columns) of
4925
** the virtual tables they implement.
5060
** the virtual tables they implement.
4926
*/
5061
*/
4927
SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
5062
SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
4928
5063
4929
/*
5064
/*
4930
** CAPI3REF: Overload A Function For A Virtual Table
5065
** CAPI3REF: Overload A Function For A Virtual Table
4931
** EXPERIMENTAL
4932
**
5066
**
4933
** ^(Virtual tables can provide alternative implementations of functions
5067
** ^(Virtual tables can provide alternative implementations of functions
4934
** using the [xFindFunction] method of the [virtual table module].  
5068
** using the [xFindFunction] method of the [virtual table module].  
 Lines 4943-4949   SQLITE_API SQLITE_EXPERIMENTAL int sqlit Link Here 
4943
** purpose is to be a placeholder function that can be overloaded
5077
** purpose is to be a placeholder function that can be overloaded
4944
** by a [virtual table].
5078
** by a [virtual table].
4945
*/
5079
*/
4946
SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
5080
SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
4947
5081
4948
/*
5082
/*
4949
** The interface to the virtual-table mechanism defined above (back up
5083
** The interface to the virtual-table mechanism defined above (back up
 Lines 4953-4960   SQLITE_API SQLITE_EXPERIMENTAL int sqlit Link Here 
4953
**
5087
**
4954
** When the virtual-table mechanism stabilizes, we will declare the
5088
** When the virtual-table mechanism stabilizes, we will declare the
4955
** interface fixed, support it indefinitely, and remove this comment.
5089
** interface fixed, support it indefinitely, and remove this comment.
4956
**
4957
****** EXPERIMENTAL - subject to change without notice **************
4958
*/
5090
*/
4959
5091
4960
/*
5092
/*
 Lines 5297-5303   SQLITE_API void sqlite3_mutex_leave(sqli Link Here 
5297
5429
5298
/*
5430
/*
5299
** CAPI3REF: Mutex Methods Object
5431
** CAPI3REF: Mutex Methods Object
5300
** EXPERIMENTAL
5301
**
5432
**
5302
** An instance of this structure defines the low-level routines
5433
** An instance of this structure defines the low-level routines
5303
** used to allocate and use mutexes.
5434
** used to allocate and use mutexes.
 Lines 5347-5353   SQLITE_API void sqlite3_mutex_leave(sqli Link Here 
5347
** it is passed a NULL pointer).
5478
** it is passed a NULL pointer).
5348
**
5479
**
5349
** The xMutexInit() method must be threadsafe.  ^It must be harmless to
5480
** The xMutexInit() method must be threadsafe.  ^It must be harmless to
5350
** invoke xMutexInit() mutiple times within the same process and without
5481
** invoke xMutexInit() multiple times within the same process and without
5351
** intervening calls to xMutexEnd().  Second and subsequent calls to
5482
** intervening calls to xMutexEnd().  Second and subsequent calls to
5352
** xMutexInit() must be no-ops.
5483
** xMutexInit() must be no-ops.
5353
**
5484
**
 Lines 5510-5523   SQLITE_API int sqlite3_test_control(int Link Here 
5510
#define SQLITE_TESTCTRL_RESERVE                 14
5641
#define SQLITE_TESTCTRL_RESERVE                 14
5511
#define SQLITE_TESTCTRL_OPTIMIZATIONS           15
5642
#define SQLITE_TESTCTRL_OPTIMIZATIONS           15
5512
#define SQLITE_TESTCTRL_ISKEYWORD               16
5643
#define SQLITE_TESTCTRL_ISKEYWORD               16
5513
#define SQLITE_TESTCTRL_LAST                    16
5644
#define SQLITE_TESTCTRL_PGHDRSZ                 17
5645
#define SQLITE_TESTCTRL_LAST                    17
5514
5646
5515
/*
5647
/*
5516
** CAPI3REF: SQLite Runtime Status
5648
** CAPI3REF: SQLite Runtime Status
5517
** EXPERIMENTAL
5518
**
5649
**
5519
** ^This interface is used to retrieve runtime status information
5650
** ^This interface is used to retrieve runtime status information
5520
** about the preformance of SQLite, and optionally to reset various
5651
** about the performance of SQLite, and optionally to reset various
5521
** highwater marks.  ^The first argument is an integer code for
5652
** highwater marks.  ^The first argument is an integer code for
5522
** the specific parameter to measure.  ^(Recognized integer codes
5653
** the specific parameter to measure.  ^(Recognized integer codes
5523
** are of the form [SQLITE_STATUS_MEMORY_USED | SQLITE_STATUS_...].)^
5654
** are of the form [SQLITE_STATUS_MEMORY_USED | SQLITE_STATUS_...].)^
 Lines 5542-5553   SQLITE_API int sqlite3_test_control(int Link Here 
5542
**
5673
**
5543
** See also: [sqlite3_db_status()]
5674
** See also: [sqlite3_db_status()]
5544
*/
5675
*/
5545
SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
5676
SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
5546
5677
5547
5678
5548
/*
5679
/*
5549
** CAPI3REF: Status Parameters
5680
** CAPI3REF: Status Parameters
5550
** EXPERIMENTAL
5551
**
5681
**
5552
** These integer constants designate various run-time status parameters
5682
** These integer constants designate various run-time status parameters
5553
** that can be returned by [sqlite3_status()].
5683
** that can be returned by [sqlite3_status()].
 Lines 5570-5575   SQLITE_API SQLITE_EXPERIMENTAL int sqlit Link Here 
5570
** *pHighwater parameter to [sqlite3_status()] is of interest.  
5700
** *pHighwater parameter to [sqlite3_status()] is of interest.  
5571
** The value written into the *pCurrent parameter is undefined.</dd>)^
5701
** The value written into the *pCurrent parameter is undefined.</dd>)^
5572
**
5702
**
5703
** ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
5704
** <dd>This parameter records the number of separate memory allocations.</dd>)^
5705
**
5573
** ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
5706
** ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
5574
** <dd>This parameter returns the number of pages used out of the
5707
** <dd>This parameter returns the number of pages used out of the
5575
** [pagecache memory allocator] that was configured using 
5708
** [pagecache memory allocator] that was configured using 
 Lines 5631-5647   SQLITE_API SQLITE_EXPERIMENTAL int sqlit Link Here 
5631
#define SQLITE_STATUS_PARSER_STACK         6
5764
#define SQLITE_STATUS_PARSER_STACK         6
5632
#define SQLITE_STATUS_PAGECACHE_SIZE       7
5765
#define SQLITE_STATUS_PAGECACHE_SIZE       7
5633
#define SQLITE_STATUS_SCRATCH_SIZE         8
5766
#define SQLITE_STATUS_SCRATCH_SIZE         8
5767
#define SQLITE_STATUS_MALLOC_COUNT         9
5634
5768
5635
/*
5769
/*
5636
** CAPI3REF: Database Connection Status
5770
** CAPI3REF: Database Connection Status
5637
** EXPERIMENTAL
5638
**
5771
**
5639
** ^This interface is used to retrieve runtime status information 
5772
** ^This interface is used to retrieve runtime status information 
5640
** about a single [database connection].  ^The first argument is the
5773
** about a single [database connection].  ^The first argument is the
5641
** database connection object to be interrogated.  ^The second argument
5774
** database connection object to be interrogated.  ^The second argument
5642
** is the parameter to interrogate.  ^Currently, the only allowed value
5775
** is an integer constant, taken from the set of
5643
** for the second parameter is [SQLITE_DBSTATUS_LOOKASIDE_USED].
5776
** [SQLITE_DBSTATUS_LOOKASIDE_USED | SQLITE_DBSTATUS_*] macros, that
5644
** Additional options will likely appear in future releases of SQLite.
5777
** determines the parameter to interrogate.  The set of 
5778
** [SQLITE_DBSTATUS_LOOKASIDE_USED | SQLITE_DBSTATUS_*] macros is likely
5779
** to grow in future releases of SQLite.
5645
**
5780
**
5646
** ^The current value of the requested parameter is written into *pCur
5781
** ^The current value of the requested parameter is written into *pCur
5647
** and the highest instantaneous value is written into *pHiwtr.  ^If
5782
** and the highest instantaneous value is written into *pHiwtr.  ^If
 Lines 5650-5660   SQLITE_API SQLITE_EXPERIMENTAL int sqlit Link Here 
5650
**
5785
**
5651
** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
5786
** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
5652
*/
5787
*/
5653
SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
5788
SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
5654
5789
5655
/*
5790
/*
5656
** CAPI3REF: Status Parameters for database connections
5791
** CAPI3REF: Status Parameters for database connections
5657
** EXPERIMENTAL
5658
**
5792
**
5659
** These constants are the available integer "verbs" that can be passed as
5793
** These constants are the available integer "verbs" that can be passed as
5660
** the second argument to the [sqlite3_db_status()] interface.
5794
** the second argument to the [sqlite3_db_status()] interface.
 Lines 5669-5682   SQLITE_API SQLITE_EXPERIMENTAL int sqlit Link Here 
5669
** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
5803
** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
5670
** <dd>This parameter returns the number of lookaside memory slots currently
5804
** <dd>This parameter returns the number of lookaside memory slots currently
5671
** checked out.</dd>)^
5805
** checked out.</dd>)^
5806
**
5807
** ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
5808
** <dd>This parameter returns the approximate number of of bytes of heap
5809
** memory used by all pager caches associated with the database connection.)^
5810
** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
5811
**
5812
** ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
5813
** <dd>This parameter returns the approximate number of of bytes of heap
5814
** memory used to store the schema for all databases associated
5815
** with the connection - main, temp, and any [ATTACH]-ed databases.)^ 
5816
** ^The full amount of memory used by the schemas is reported, even if the
5817
** schema memory is shared with other database connections due to
5818
** [shared cache mode] being enabled.
5819
** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
5820
**
5821
** ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
5822
** <dd>This parameter returns the approximate number of of bytes of heap
5823
** and lookaside memory used by all prepared statements associated with
5824
** the database connection.)^
5825
** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
5826
** </dd>
5672
** </dl>
5827
** </dl>
5673
*/
5828
*/
5674
#define SQLITE_DBSTATUS_LOOKASIDE_USED     0
5829
#define SQLITE_DBSTATUS_LOOKASIDE_USED     0
5830
#define SQLITE_DBSTATUS_CACHE_USED         1
5831
#define SQLITE_DBSTATUS_SCHEMA_USED        2
5832
#define SQLITE_DBSTATUS_STMT_USED          3
5833
#define SQLITE_DBSTATUS_MAX                3   /* Largest defined DBSTATUS */
5675
5834
5676
5835
5677
/*
5836
/*
5678
** CAPI3REF: Prepared Statement Status
5837
** CAPI3REF: Prepared Statement Status
5679
** EXPERIMENTAL
5680
**
5838
**
5681
** ^(Each prepared statement maintains various
5839
** ^(Each prepared statement maintains various
5682
** [SQLITE_STMTSTATUS_SORT | counters] that measure the number
5840
** [SQLITE_STMTSTATUS_SORT | counters] that measure the number
 Lines 5698-5708   SQLITE_API SQLITE_EXPERIMENTAL int sqlit Link Here 
5698
**
5856
**
5699
** See also: [sqlite3_status()] and [sqlite3_db_status()].
5857
** See also: [sqlite3_status()] and [sqlite3_db_status()].
5700
*/
5858
*/
5701
SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
5859
SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
5702
5860
5703
/*
5861
/*
5704
** CAPI3REF: Status Parameters for prepared statements
5862
** CAPI3REF: Status Parameters for prepared statements
5705
** EXPERIMENTAL
5706
**
5863
**
5707
** These preprocessor macros define integer codes that name counter
5864
** These preprocessor macros define integer codes that name counter
5708
** values associated with the [sqlite3_stmt_status()] interface.
5865
** values associated with the [sqlite3_stmt_status()] interface.
 Lines 5720-5733   SQLITE_API SQLITE_EXPERIMENTAL int sqlit Link Here 
5720
** A non-zero value in this counter may indicate an opportunity to
5877
** A non-zero value in this counter may indicate an opportunity to
5721
** improvement performance through careful use of indices.</dd>
5878
** improvement performance through careful use of indices.</dd>
5722
**
5879
**
5880
** <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
5881
** <dd>^This is the number of rows inserted into transient indices that
5882
** were created automatically in order to help joins run faster.
5883
** A non-zero value in this counter may indicate an opportunity to
5884
** improvement performance by adding permanent indices that do not
5885
** need to be reinitialized each time the statement is run.</dd>
5886
**
5723
** </dl>
5887
** </dl>
5724
*/
5888
*/
5725
#define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
5889
#define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
5726
#define SQLITE_STMTSTATUS_SORT              2
5890
#define SQLITE_STMTSTATUS_SORT              2
5891
#define SQLITE_STMTSTATUS_AUTOINDEX         3
5727
5892
5728
/*
5893
/*
5729
** CAPI3REF: Custom Page Cache Object
5894
** CAPI3REF: Custom Page Cache Object
5730
** EXPERIMENTAL
5731
**
5895
**
5732
** The sqlite3_pcache type is opaque.  It is implemented by
5896
** The sqlite3_pcache type is opaque.  It is implemented by
5733
** the pluggable module.  The SQLite core has no knowledge of
5897
** the pluggable module.  The SQLite core has no knowledge of
 Lines 5742-5748   typedef struct sqlite3_pcache sqlite3_pc Link Here 
5742
/*
5906
/*
5743
** CAPI3REF: Application Defined Page Cache.
5907
** CAPI3REF: Application Defined Page Cache.
5744
** KEYWORDS: {page cache}
5908
** KEYWORDS: {page cache}
5745
** EXPERIMENTAL
5746
**
5909
**
5747
** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE], ...) interface can
5910
** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE], ...) interface can
5748
** register an alternative page cache implementation by passing in an 
5911
** register an alternative page cache implementation by passing in an 
 Lines 5884-5890   struct sqlite3_pcache_methods { Link Here 
5884
6047
5885
/*
6048
/*
5886
** CAPI3REF: Online Backup Object
6049
** CAPI3REF: Online Backup Object
5887
** EXPERIMENTAL
5888
**
6050
**
5889
** The sqlite3_backup object records state information about an ongoing
6051
** The sqlite3_backup object records state information about an ongoing
5890
** online backup operation.  ^The sqlite3_backup object is created by
6052
** online backup operation.  ^The sqlite3_backup object is created by
 Lines 5897-5903   typedef struct sqlite3_backup sqlite3_ba Link Here 
5897
6059
5898
/*
6060
/*
5899
** CAPI3REF: Online Backup API.
6061
** CAPI3REF: Online Backup API.
5900
** EXPERIMENTAL
5901
**
6062
**
5902
** The backup API copies the content of one database into another.
6063
** The backup API copies the content of one database into another.
5903
** It is useful either for creating backups of databases or
6064
** It is useful either for creating backups of databases or
 Lines 5966-5975   typedef struct sqlite3_backup sqlite3_ba Link Here 
5966
** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
6127
** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
5967
** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
6128
** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
5968
**
6129
**
5969
** ^The sqlite3_backup_step() might return [SQLITE_READONLY] if the destination
6130
** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
5970
** database was opened read-only or if
6131
** <ol>
5971
** the destination is an in-memory database with a different page size
6132
** <li> the destination database was opened read-only, or
5972
** from the source database.
6133
** <li> the destination database is using write-ahead-log journaling
6134
** and the destination and source page sizes differ, or
6135
** <li> The destination database is an in-memory database and the
6136
** destination and source page sizes differ.
6137
** </ol>)^
5973
**
6138
**
5974
** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
6139
** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
5975
** the [sqlite3_busy_handler | busy-handler function]
6140
** the [sqlite3_busy_handler | busy-handler function]
 Lines 6031-6037   typedef struct sqlite3_backup sqlite3_ba Link Here 
6031
**
6196
**
6032
** ^Each call to sqlite3_backup_step() sets two values inside
6197
** ^Each call to sqlite3_backup_step() sets two values inside
6033
** the [sqlite3_backup] object: the number of pages still to be backed
6198
** the [sqlite3_backup] object: the number of pages still to be backed
6034
** up and the total number of pages in the source databae file.
6199
** up and the total number of pages in the source database file.
6035
** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
6200
** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
6036
** retrieve these two values, respectively.
6201
** retrieve these two values, respectively.
6037
**
6202
**
 Lines 6085-6091   SQLITE_API int sqlite3_backup_pagecount( Link Here 
6085
6250
6086
/*
6251
/*
6087
** CAPI3REF: Unlock Notification
6252
** CAPI3REF: Unlock Notification
6088
** EXPERIMENTAL
6089
**
6253
**
6090
** ^When running in shared-cache mode, a database operation may fail with
6254
** ^When running in shared-cache mode, a database operation may fail with
6091
** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
6255
** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
 Lines 6128-6134   SQLITE_API int sqlite3_backup_pagecount( Link Here 
6128
** blocked connection already has a registered unlock-notify callback,
6292
** blocked connection already has a registered unlock-notify callback,
6129
** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
6293
** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
6130
** called with a NULL pointer as its second argument, then any existing
6294
** called with a NULL pointer as its second argument, then any existing
6131
** unlock-notify callback is cancelled. ^The blocked connections 
6295
** unlock-notify callback is canceled. ^The blocked connections 
6132
** unlock-notify callback may also be canceled by closing the blocked
6296
** unlock-notify callback may also be canceled by closing the blocked
6133
** connection using [sqlite3_close()].
6297
** connection using [sqlite3_close()].
6134
**
6298
**
 Lines 6207-6229   SQLITE_API int sqlite3_unlock_notify( Link Here 
6207
6371
6208
/*
6372
/*
6209
** CAPI3REF: String Comparison
6373
** CAPI3REF: String Comparison
6210
** EXPERIMENTAL
6211
**
6374
**
6212
** ^The [sqlite3_strnicmp()] API allows applications and extensions to
6375
** ^The [sqlite3_strnicmp()] API allows applications and extensions to
6213
** compare the contents of two buffers containing UTF-8 strings in a
6376
** compare the contents of two buffers containing UTF-8 strings in a
6214
** case-indendent fashion, using the same definition of case independence 
6377
** case-independent fashion, using the same definition of case independence 
6215
** that SQLite uses internally when comparing identifiers.
6378
** that SQLite uses internally when comparing identifiers.
6216
*/
6379
*/
6217
SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
6380
SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
6218
6381
6219
/*
6382
/*
6220
** CAPI3REF: Error Logging Interface
6383
** CAPI3REF: Error Logging Interface
6221
** EXPERIMENTAL
6222
**
6384
**
6223
** ^The [sqlite3_log()] interface writes a message into the error log
6385
** ^The [sqlite3_log()] interface writes a message into the error log
6224
** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
6386
** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
6225
** ^If logging is enabled, the zFormat string and subsequent arguments are
6387
** ^If logging is enabled, the zFormat string and subsequent arguments are
6226
** passed through to [sqlite3_vmprintf()] to generate the final output string.
6388
** used with [sqlite3_snprintf()] to generate the final output string.
6227
**
6389
**
6228
** The sqlite3_log() interface is intended for use by extensions such as
6390
** The sqlite3_log() interface is intended for use by extensions such as
6229
** virtual tables, collating functions, and SQL functions.  While there is
6391
** virtual tables, collating functions, and SQL functions.  While there is
 Lines 6241-6246   SQLITE_API int sqlite3_strnicmp(const ch Link Here 
6241
SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
6403
SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
6242
6404
6243
/*
6405
/*
6406
** CAPI3REF: Write-Ahead Log Commit Hook
6407
**
6408
** ^The [sqlite3_wal_hook()] function is used to register a callback that
6409
** will be invoked each time a database connection commits data to a
6410
** [write-ahead log] (i.e. whenever a transaction is committed in
6411
** [journal_mode | journal_mode=WAL mode]). 
6412
**
6413
** ^The callback is invoked by SQLite after the commit has taken place and 
6414
** the associated write-lock on the database released, so the implementation 
6415
** may read, write or [checkpoint] the database as required.
6416
**
6417
** ^The first parameter passed to the callback function when it is invoked
6418
** is a copy of the third parameter passed to sqlite3_wal_hook() when
6419
** registering the callback. ^The second is a copy of the database handle.
6420
** ^The third parameter is the name of the database that was written to -
6421
** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
6422
** is the number of pages currently in the write-ahead log file,
6423
** including those that were just committed.
6424
**
6425
** The callback function should normally return [SQLITE_OK].  ^If an error
6426
** code is returned, that error will propagate back up through the
6427
** SQLite code base to cause the statement that provoked the callback
6428
** to report an error, though the commit will have still occurred. If the
6429
** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
6430
** that does not correspond to any valid SQLite error code, the results
6431
** are undefined.
6432
**
6433
** A single database handle may have at most a single write-ahead log callback 
6434
** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
6435
** previously registered write-ahead log callback. ^Note that the
6436
** [sqlite3_wal_autocheckpoint()] interface and the
6437
** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
6438
** those overwrite any prior [sqlite3_wal_hook()] settings.
6439
*/
6440
SQLITE_API void *sqlite3_wal_hook(
6441
  sqlite3*, 
6442
  int(*)(void *,sqlite3*,const char*,int),
6443
  void*
6444
);
6445
6446
/*
6447
** CAPI3REF: Configure an auto-checkpoint
6448
**
6449
** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
6450
** [sqlite3_wal_hook()] that causes any database on [database connection] D
6451
** to automatically [checkpoint]
6452
** after committing a transaction if there are N or
6453
** more frames in the [write-ahead log] file.  ^Passing zero or 
6454
** a negative value as the nFrame parameter disables automatic
6455
** checkpoints entirely.
6456
**
6457
** ^The callback registered by this function replaces any existing callback
6458
** registered using [sqlite3_wal_hook()].  ^Likewise, registering a callback
6459
** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
6460
** configured by this function.
6461
**
6462
** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
6463
** from SQL.
6464
**
6465
** ^Every new [database connection] defaults to having the auto-checkpoint
6466
** enabled with a threshold of 1000 pages.  The use of this interface
6467
** is only necessary if the default setting is found to be suboptimal
6468
** for a particular application.
6469
*/
6470
SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
6471
6472
/*
6473
** CAPI3REF: Checkpoint a database
6474
**
6475
** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X
6476
** on [database connection] D to be [checkpointed].  ^If X is NULL or an
6477
** empty string, then a checkpoint is run on all databases of
6478
** connection D.  ^If the database connection D is not in
6479
** [WAL | write-ahead log mode] then this interface is a harmless no-op.
6480
**
6481
** ^The [wal_checkpoint pragma] can be used to invoke this interface
6482
** from SQL.  ^The [sqlite3_wal_autocheckpoint()] interface and the
6483
** [wal_autocheckpoint pragma] can be used to cause this interface to be
6484
** run whenever the WAL reaches a certain size threshold.
6485
*/
6486
SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
6487
6488
/*
6244
** Undo the hack that converts floating point types to integer for
6489
** Undo the hack that converts floating point types to integer for
6245
** builds on processors without floating point support.
6490
** builds on processors without floating point support.
6246
*/
6491
*/
 Lines 6531-6536   SQLITE_PRIVATE void sqlite3HashClear(Has Link Here 
6531
*/
6776
*/
6532
#ifdef SQLITE_OMIT_FLOATING_POINT
6777
#ifdef SQLITE_OMIT_FLOATING_POINT
6533
# define double sqlite_int64
6778
# define double sqlite_int64
6779
# define float sqlite_int64
6534
# define LONGDOUBLE_TYPE sqlite_int64
6780
# define LONGDOUBLE_TYPE sqlite_int64
6535
# ifndef SQLITE_BIG_DBL
6781
# ifndef SQLITE_BIG_DBL
6536
#   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
6782
#   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
 Lines 6942-6947   SQLITE_PRIVATE int sqlite3BtreeSyncDisab Link Here 
6942
SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
7188
SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
6943
SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
7189
SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
6944
SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
7190
SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
7191
SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
6945
SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
7192
SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
6946
SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
7193
SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
6947
SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
7194
SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
 Lines 7046-7051   SQLITE_PRIVATE int sqlite3BtreePutData(B Link Here 
7046
SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
7293
SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
7047
SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
7294
SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
7048
7295
7296
SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
7297
7049
#ifndef NDEBUG
7298
#ifndef NDEBUG
7050
SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
7299
SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
7051
#endif
7300
#endif
 Lines 7059-7064   SQLITE_PRIVATE int sqlite3BtreeCursorInf Link Here 
7059
SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
7308
SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
7060
#endif
7309
#endif
7061
7310
7311
#ifndef SQLITE_OMIT_WAL
7312
SQLITE_PRIVATE   int sqlite3BtreeCheckpoint(Btree*);
7313
#endif
7314
7062
/*
7315
/*
7063
** If we are not using shared cache, then there is no need to
7316
** If we are not using shared cache, then there is no need to
7064
** use mutexes to access the BtShared structures.  So make the
7317
** use mutexes to access the BtShared structures.  So make the
 Lines 7188-7195   struct SubProgram { Link Here 
7188
  int nOp;                      /* Elements in aOp[] */
7441
  int nOp;                      /* Elements in aOp[] */
7189
  int nMem;                     /* Number of memory cells required */
7442
  int nMem;                     /* Number of memory cells required */
7190
  int nCsr;                     /* Number of cursors required */
7443
  int nCsr;                     /* Number of cursors required */
7191
  int nRef;                     /* Number of pointers to this structure */
7192
  void *token;                  /* id that may be used to recursive triggers */
7444
  void *token;                  /* id that may be used to recursive triggers */
7445
  SubProgram *pNext;            /* Next sub-program already visited */
7193
};
7446
};
7194
7447
7195
/*
7448
/*
 Lines 7336-7418   typedef struct VdbeOpList VdbeOpList; Link Here 
7336
#define OP_VerifyCookie                        37
7589
#define OP_VerifyCookie                        37
7337
#define OP_OpenRead                            38
7590
#define OP_OpenRead                            38
7338
#define OP_OpenWrite                           39
7591
#define OP_OpenWrite                           39
7339
#define OP_OpenEphemeral                       40
7592
#define OP_OpenAutoindex                       40
7340
#define OP_OpenPseudo                          41
7593
#define OP_OpenEphemeral                       41
7341
#define OP_Close                               42
7594
#define OP_OpenPseudo                          42
7342
#define OP_SeekLt                              43
7595
#define OP_Close                               43
7343
#define OP_SeekLe                              44
7596
#define OP_SeekLt                              44
7344
#define OP_SeekGe                              45
7597
#define OP_SeekLe                              45
7345
#define OP_SeekGt                              46
7598
#define OP_SeekGe                              46
7346
#define OP_Seek                                47
7599
#define OP_SeekGt                              47
7347
#define OP_NotFound                            48
7600
#define OP_Seek                                48
7348
#define OP_Found                               49
7601
#define OP_NotFound                            49
7349
#define OP_IsUnique                            50
7602
#define OP_Found                               50
7350
#define OP_NotExists                           51
7603
#define OP_IsUnique                            51
7351
#define OP_Sequence                            52
7604
#define OP_NotExists                           52
7352
#define OP_NewRowid                            53
7605
#define OP_Sequence                            53
7353
#define OP_Insert                              54
7606
#define OP_NewRowid                            54
7354
#define OP_InsertInt                           55
7607
#define OP_Insert                              55
7355
#define OP_Delete                              56
7608
#define OP_InsertInt                           56
7356
#define OP_ResetCount                          57
7609
#define OP_Delete                              57
7357
#define OP_RowKey                              58
7610
#define OP_ResetCount                          58
7358
#define OP_RowData                             59
7611
#define OP_RowKey                              59
7359
#define OP_Rowid                               60
7612
#define OP_RowData                             60
7360
#define OP_NullRow                             61
7613
#define OP_Rowid                               61
7361
#define OP_Last                                62
7614
#define OP_NullRow                             62
7362
#define OP_Sort                                63
7615
#define OP_Last                                63
7363
#define OP_Rewind                              64
7616
#define OP_Sort                                64
7364
#define OP_Prev                                65
7617
#define OP_Rewind                              65
7365
#define OP_Next                                66
7618
#define OP_Prev                                66
7366
#define OP_IdxInsert                           67
7619
#define OP_Next                                67
7367
#define OP_IdxDelete                           70
7620
#define OP_IdxInsert                           70
7368
#define OP_IdxRowid                            71
7621
#define OP_IdxDelete                           71
7369
#define OP_IdxLT                               72
7622
#define OP_IdxRowid                            72
7370
#define OP_IdxGE                               81
7623
#define OP_IdxLT                               81
7371
#define OP_Destroy                             92
7624
#define OP_IdxGE                               92
7372
#define OP_Clear                               95
7625
#define OP_Destroy                             95
7373
#define OP_CreateIndex                         96
7626
#define OP_Clear                               96
7374
#define OP_CreateTable                         97
7627
#define OP_CreateIndex                         97
7375
#define OP_ParseSchema                         98
7628
#define OP_CreateTable                         98
7376
#define OP_LoadAnalysis                        99
7629
#define OP_ParseSchema                         99
7377
#define OP_DropTable                          100
7630
#define OP_LoadAnalysis                       100
7378
#define OP_DropIndex                          101
7631
#define OP_DropTable                          101
7379
#define OP_DropTrigger                        102
7632
#define OP_DropIndex                          102
7380
#define OP_IntegrityCk                        103
7633
#define OP_DropTrigger                        103
7381
#define OP_RowSetAdd                          104
7634
#define OP_IntegrityCk                        104
7382
#define OP_RowSetRead                         105
7635
#define OP_RowSetAdd                          105
7383
#define OP_RowSetTest                         106
7636
#define OP_RowSetRead                         106
7384
#define OP_Program                            107
7637
#define OP_RowSetTest                         107
7385
#define OP_Param                              108
7638
#define OP_Program                            108
7386
#define OP_FkCounter                          109
7639
#define OP_Param                              109
7387
#define OP_FkIfZero                           110
7640
#define OP_FkCounter                          110
7388
#define OP_MemMax                             111
7641
#define OP_FkIfZero                           111
7389
#define OP_IfPos                              112
7642
#define OP_MemMax                             112
7390
#define OP_IfNeg                              113
7643
#define OP_IfPos                              113
7391
#define OP_IfZero                             114
7644
#define OP_IfNeg                              114
7392
#define OP_AggStep                            115
7645
#define OP_IfZero                             115
7393
#define OP_AggFinal                           116
7646
#define OP_AggStep                            116
7394
#define OP_Vacuum                             117
7647
#define OP_AggFinal                           117
7395
#define OP_IncrVacuum                         118
7648
#define OP_Checkpoint                         118
7396
#define OP_Expire                             119
7649
#define OP_JournalMode                        119
7397
#define OP_TableLock                          120
7650
#define OP_Vacuum                             120
7398
#define OP_VBegin                             121
7651
#define OP_IncrVacuum                         121
7399
#define OP_VCreate                            122
7652
#define OP_Expire                             122
7400
#define OP_VDestroy                           123
7653
#define OP_TableLock                          123
7401
#define OP_VOpen                              124
7654
#define OP_VBegin                             124
7402
#define OP_VFilter                            125
7655
#define OP_VCreate                            125
7403
#define OP_VColumn                            126
7656
#define OP_VDestroy                           126
7404
#define OP_VNext                              127
7657
#define OP_VOpen                              127
7405
#define OP_VRename                            128
7658
#define OP_VFilter                            128
7406
#define OP_VUpdate                            129
7659
#define OP_VColumn                            129
7407
#define OP_Pagecount                          131
7660
#define OP_VNext                              131
7408
#define OP_Trace                              132
7661
#define OP_VRename                            132
7409
#define OP_Noop                               133
7662
#define OP_VUpdate                            133
7410
#define OP_Explain                            134
7663
#define OP_Pagecount                          134
7664
#define OP_Trace                              135
7665
#define OP_Noop                               136
7666
#define OP_Explain                            137
7411
7667
7412
/* The following opcode values are never used */
7668
/* The following opcode values are never used */
7413
#define OP_NotUsed_135                        135
7414
#define OP_NotUsed_136                        136
7415
#define OP_NotUsed_137                        137
7416
#define OP_NotUsed_138                        138
7669
#define OP_NotUsed_138                        138
7417
#define OP_NotUsed_139                        139
7670
#define OP_NotUsed_139                        139
7418
#define OP_NotUsed_140                        140
7671
#define OP_NotUsed_140                        140
 Lines 7431-7452   typedef struct VdbeOpList VdbeOpList; Link Here 
7431
#define OPFLG_OUT3            0x0040  /* out3:  P3 is an output */
7684
#define OPFLG_OUT3            0x0040  /* out3:  P3 is an output */
7432
#define OPFLG_INITIALIZER {\
7685
#define OPFLG_INITIALIZER {\
7433
/*   0 */ 0x00, 0x01, 0x05, 0x04, 0x04, 0x10, 0x00, 0x02,\
7686
/*   0 */ 0x00, 0x01, 0x05, 0x04, 0x04, 0x10, 0x00, 0x02,\
7434
/*   8 */ 0x02, 0x02, 0x02, 0x02, 0x00, 0x00, 0x24, 0x24,\
7687
/*   8 */ 0x02, 0x02, 0x02, 0x02, 0x02, 0x00, 0x24, 0x24,\
7435
/*  16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\
7688
/*  16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\
7436
/*  24 */ 0x00, 0x01, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\
7689
/*  24 */ 0x00, 0x01, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\
7437
/*  32 */ 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00, 0x00,\
7690
/*  32 */ 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00, 0x00,\
7438
/*  40 */ 0x00, 0x00, 0x00, 0x11, 0x11, 0x11, 0x11, 0x08,\
7691
/*  40 */ 0x00, 0x00, 0x00, 0x00, 0x11, 0x11, 0x11, 0x11,\
7439
/*  48 */ 0x11, 0x11, 0x11, 0x11, 0x02, 0x02, 0x00, 0x00,\
7692
/*  48 */ 0x08, 0x11, 0x11, 0x11, 0x11, 0x02, 0x02, 0x00,\
7440
/*  56 */ 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x01,\
7693
/*  56 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01,\
7441
/*  64 */ 0x01, 0x01, 0x01, 0x08, 0x4c, 0x4c, 0x00, 0x02,\
7694
/*  64 */ 0x01, 0x01, 0x01, 0x01, 0x4c, 0x4c, 0x08, 0x00,\
7442
/*  72 */ 0x01, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
7695
/*  72 */ 0x02, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
7443
/*  80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
7696
/*  80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
7444
/*  88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x02, 0x24, 0x02, 0x00,\
7697
/*  88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x01, 0x24, 0x02, 0x02,\
7445
/*  96 */ 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
7698
/*  96 */ 0x00, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,\
7446
/* 104 */ 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01, 0x08,\
7699
/* 104 */ 0x00, 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01,\
7447
/* 112 */ 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x01, 0x00,\
7700
/* 112 */ 0x08, 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\
7448
/* 120 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01,\
7701
/* 120 */ 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
7449
/* 128 */ 0x00, 0x00, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00,\
7702
/* 128 */ 0x01, 0x00, 0x02, 0x01, 0x00, 0x00, 0x02, 0x00,\
7450
/* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04,\
7703
/* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04,\
7451
/* 144 */ 0x04, 0x04,}
7704
/* 144 */ 0x04, 0x04,}
7452
7705
 Lines 7477-7482   SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp( Link Here 
7477
SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
7730
SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
7478
SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
7731
SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
7479
SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
7732
SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
7733
SQLITE_PRIVATE void sqlite3VdbeDeleteObject(sqlite3*,Vdbe*);
7480
SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int,int,int);
7734
SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int,int,int);
7481
SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
7735
SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
7482
SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
7736
SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
 Lines 7494-7500   SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vd Link Here 
7494
SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
7748
SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
7495
SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
7749
SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
7496
SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
7750
SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
7497
SQLITE_PRIVATE void sqlite3VdbeProgramDelete(sqlite3 *, SubProgram *, int);
7498
SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);
7751
SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);
7499
SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
7752
SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
7500
#ifndef SQLITE_OMIT_TRACE
7753
#ifndef SQLITE_OMIT_TRACE
 Lines 7505-7510   SQLITE_PRIVATE UnpackedRecord *sqlite3Vd Link Here 
7505
SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord*);
7758
SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord*);
7506
SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
7759
SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
7507
7760
7761
#ifndef SQLITE_OMIT_TRIGGER
7762
SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
7763
#endif
7764
7508
7765
7509
#ifndef NDEBUG
7766
#ifndef NDEBUG
7510
SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
7767
SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
 Lines 7592-7605   typedef struct PgHdr DbPage; Link Here 
7592
#define PAGER_LOCKINGMODE_EXCLUSIVE   1
7849
#define PAGER_LOCKINGMODE_EXCLUSIVE   1
7593
7850
7594
/*
7851
/*
7595
** Valid values for the second argument to sqlite3PagerJournalMode().
7852
** Numeric constants that encode the journalmode.  
7596
*/
7853
*/
7597
#define PAGER_JOURNALMODE_QUERY      -1
7854
#define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */
7598
#define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
7855
#define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
7599
#define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
7856
#define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
7600
#define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
7857
#define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
7601
#define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
7858
#define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
7602
#define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
7859
#define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
7860
#define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */
7603
7861
7604
/*
7862
/*
7605
** The remainder of this file contains the declarations of the functions
7863
** The remainder of this file contains the declarations of the functions
 Lines 7622-7633   SQLITE_PRIVATE int sqlite3PagerReadFileh Link Here 
7622
7880
7623
/* Functions used to configure a Pager object. */
7881
/* Functions used to configure a Pager object. */
7624
SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
7882
SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
7625
SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u16*, int);
7883
SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
7626
SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
7884
SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
7627
SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
7885
SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
7628
SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int);
7886
SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int);
7629
SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
7887
SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
7630
SQLITE_PRIVATE int sqlite3PagerJournalMode(Pager *, int);
7888
SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
7889
SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
7890
SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
7631
SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
7891
SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
7632
SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
7892
SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
7633
7893
 Lines 7647-7655   SQLITE_PRIVATE void *sqlite3PagerGetData Link Here 
7647
SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); 
7907
SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); 
7648
7908
7649
/* Functions used to manage pager transactions and savepoints. */
7909
/* Functions used to manage pager transactions and savepoints. */
7650
SQLITE_PRIVATE int sqlite3PagerPagecount(Pager*, int*);
7910
SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
7651
SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
7911
SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
7652
SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
7912
SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
7913
SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
7653
SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
7914
SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
7654
SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
7915
SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
7655
SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
7916
SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
 Lines 7657-7665   SQLITE_PRIVATE int sqlite3PagerOpenSavep Link Here 
7657
SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
7918
SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
7658
SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
7919
SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
7659
7920
7921
SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager);
7922
SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
7923
SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
7924
SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
7925
SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager);
7926
7660
/* Functions used to query pager state and configuration. */
7927
/* Functions used to query pager state and configuration. */
7661
SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
7928
SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
7662
SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
7929
SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
7930
SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
7663
SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*);
7931
SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*);
7664
SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
7932
SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
7665
SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
7933
SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
 Lines 7671-7676   SQLITE_PRIVATE int sqlite3PagerIsMemdb(P Link Here 
7671
/* Functions used to truncate the database file. */
7939
/* Functions used to truncate the database file. */
7672
SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
7940
SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
7673
7941
7942
#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
7943
SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
7944
#endif
7945
7674
/* Functions to support testing and debugging. */
7946
/* Functions to support testing and debugging. */
7675
#if !defined(NDEBUG) || defined(SQLITE_TEST)
7947
#if !defined(NDEBUG) || defined(SQLITE_TEST)
7676
SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
7948
SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
 Lines 8072-8078   SQLITE_PRIVATE void sqlite3PCacheSetDefa Link Here 
8072
** 1GB boundary.
8344
** 1GB boundary.
8073
**
8345
**
8074
*/
8346
*/
8075
#define PENDING_BYTE      sqlite3PendingByte
8347
#ifdef SQLITE_OMIT_WSD
8348
# define PENDING_BYTE     (0x40000000)
8349
#else
8350
# define PENDING_BYTE      sqlite3PendingByte
8351
#endif
8076
#define RESERVED_BYTE     (PENDING_BYTE+1)
8352
#define RESERVED_BYTE     (PENDING_BYTE+1)
8077
#define SHARED_FIRST      (PENDING_BYTE+2)
8353
#define SHARED_FIRST      (PENDING_BYTE+2)
8078
#define SHARED_SIZE       510
8354
#define SHARED_SIZE       510
 Lines 8098-8103   SQLITE_PRIVATE int sqlite3OsFileControl( Link Here 
8098
#define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
8374
#define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
8099
SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
8375
SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
8100
SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
8376
SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
8377
SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
8378
SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
8379
SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
8380
SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
8101
8381
8102
/* 
8382
/* 
8103
** Functions for accessing sqlite3_vfs methods 
8383
** Functions for accessing sqlite3_vfs methods 
 Lines 8114-8120   SQLITE_PRIVATE void sqlite3OsDlClose(sql Link Here 
8114
#endif /* SQLITE_OMIT_LOAD_EXTENSION */
8394
#endif /* SQLITE_OMIT_LOAD_EXTENSION */
8115
SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
8395
SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
8116
SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
8396
SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
8117
SQLITE_PRIVATE int sqlite3OsCurrentTime(sqlite3_vfs *, double*);
8397
SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
8118
8398
8119
/*
8399
/*
8120
** Convenience functions for opening and closing files using 
8400
** Convenience functions for opening and closing files using 
 Lines 8222-8235   struct Db { Link Here 
8222
8502
8223
/*
8503
/*
8224
** An instance of the following structure stores a database schema.
8504
** An instance of the following structure stores a database schema.
8225
**
8226
** If there are no virtual tables configured in this schema, the
8227
** Schema.db variable is set to NULL. After the first virtual table
8228
** has been added, it is set to point to the database connection 
8229
** used to create the connection. Once a virtual table has been
8230
** added to the Schema structure and the Schema.db variable populated, 
8231
** only that database connection may use the Schema to prepare 
8232
** statements.
8233
*/
8505
*/
8234
struct Schema {
8506
struct Schema {
8235
  int schema_cookie;   /* Database schema version number for this file */
8507
  int schema_cookie;   /* Database schema version number for this file */
 Lines 8242-8250   struct Schema { Link Here 
8242
  u8 enc;              /* Text encoding used by this database */
8514
  u8 enc;              /* Text encoding used by this database */
8243
  u16 flags;           /* Flags associated with this schema */
8515
  u16 flags;           /* Flags associated with this schema */
8244
  int cache_size;      /* Number of pages to use in the cache */
8516
  int cache_size;      /* Number of pages to use in the cache */
8245
#ifndef SQLITE_OMIT_VIRTUALTABLE
8246
  sqlite3 *db;         /* "Owner" connection. See comment above */
8247
#endif
8248
};
8517
};
8249
8518
8250
/*
8519
/*
 Lines 8358-8364   struct sqlite3 { Link Here 
8358
  u8 temp_store;                /* 1: file 2: memory 0: default */
8627
  u8 temp_store;                /* 1: file 2: memory 0: default */
8359
  u8 mallocFailed;              /* True if we have seen a malloc failure */
8628
  u8 mallocFailed;              /* True if we have seen a malloc failure */
8360
  u8 dfltLockMode;              /* Default locking-mode for attached dbs */
8629
  u8 dfltLockMode;              /* Default locking-mode for attached dbs */
8361
  u8 dfltJournalMode;           /* Default journal mode for attached dbs */
8362
  signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
8630
  signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
8363
  u8 suppressErr;               /* Do not issue error messages if true */
8631
  u8 suppressErr;               /* Do not issue error messages if true */
8364
  int nextPagesize;             /* Pagesize after VACUUM if >0 */
8632
  int nextPagesize;             /* Pagesize after VACUUM if >0 */
 Lines 8391-8396   struct sqlite3 { Link Here 
8391
  void (*xRollbackCallback)(void*); /* Invoked at every commit. */
8659
  void (*xRollbackCallback)(void*); /* Invoked at every commit. */
8392
  void *pUpdateArg;
8660
  void *pUpdateArg;
8393
  void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
8661
  void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
8662
#ifndef SQLITE_OMIT_WAL
8663
  int (*xWalCallback)(void *, sqlite3 *, const char *, int);
8664
  void *pWalArg;
8665
#endif
8394
  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
8666
  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
8395
  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
8667
  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
8396
  void *pCollNeededArg;
8668
  void *pCollNeededArg;
 Lines 8429-8434   struct sqlite3 { Link Here 
8429
  int nStatement;               /* Number of nested statement-transactions  */
8701
  int nStatement;               /* Number of nested statement-transactions  */
8430
  u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
8702
  u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
8431
  i64 nDeferredCons;            /* Net deferred constraints this transaction. */
8703
  i64 nDeferredCons;            /* Net deferred constraints this transaction. */
8704
  int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
8432
8705
8433
#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
8706
#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
8434
  /* The following variables are all protected by the STATIC_MASTER 
8707
  /* The following variables are all protected by the STATIC_MASTER 
 Lines 8480-8485   struct sqlite3 { Link Here 
8480
#define SQLITE_ReverseOrder   0x01000000  /* Reverse unordered SELECTs */
8753
#define SQLITE_ReverseOrder   0x01000000  /* Reverse unordered SELECTs */
8481
#define SQLITE_RecTriggers    0x02000000  /* Enable recursive triggers */
8754
#define SQLITE_RecTriggers    0x02000000  /* Enable recursive triggers */
8482
#define SQLITE_ForeignKeys    0x04000000  /* Enforce foreign key constraints  */
8755
#define SQLITE_ForeignKeys    0x04000000  /* Enforce foreign key constraints  */
8756
#define SQLITE_AutoIndex      0x08000000  /* Enable automatic indexes */
8757
#define SQLITE_PreferBuiltin  0x10000000  /* Preference to built-in funcs */
8483
8758
8484
/*
8759
/*
8485
** Bits of the sqlite3.flags field that are used by the
8760
** Bits of the sqlite3.flags field that are used by the
 Lines 8491-8497   struct sqlite3 { Link Here 
8491
#define SQLITE_IndexSort      0x04        /* Disable indexes for sorting */
8766
#define SQLITE_IndexSort      0x04        /* Disable indexes for sorting */
8492
#define SQLITE_IndexSearch    0x08        /* Disable indexes for searching */
8767
#define SQLITE_IndexSearch    0x08        /* Disable indexes for searching */
8493
#define SQLITE_IndexCover     0x10        /* Disable index covering table */
8768
#define SQLITE_IndexCover     0x10        /* Disable index covering table */
8494
#define SQLITE_OptMask        0x1f        /* Mask of all disablable opts */
8769
#define SQLITE_GroupByOrder   0x20        /* Disable GROUPBY cover of ORDERBY */
8770
#define SQLITE_OptMask        0xff        /* Mask of all disablable opts */
8495
8771
8496
/*
8772
/*
8497
** Possible values for the sqlite.magic field.
8773
** Possible values for the sqlite.magic field.
 Lines 8783-8789   struct VTable { Link Here 
8783
** of a SELECT statement.
9059
** of a SELECT statement.
8784
*/
9060
*/
8785
struct Table {
9061
struct Table {
8786
  sqlite3 *dbMem;      /* DB connection used for lookaside allocations. */
8787
  char *zName;         /* Name of the table or view */
9062
  char *zName;         /* Name of the table or view */
8788
  int iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
9063
  int iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
8789
  int nCol;            /* Number of columns in this table */
9064
  int nCol;            /* Number of columns in this table */
 Lines 8920-8928   struct FKey { Link Here 
8920
*/
9195
*/
8921
struct KeyInfo {
9196
struct KeyInfo {
8922
  sqlite3 *db;        /* The database connection */
9197
  sqlite3 *db;        /* The database connection */
8923
  u8 enc;             /* Text encoding - one of the TEXT_Utf* values */
9198
  u8 enc;             /* Text encoding - one of the SQLITE_UTF* values */
8924
  u16 nField;         /* Number of entries in aColl[] */
9199
  u16 nField;         /* Number of entries in aColl[] */
8925
  u8 *aSortOrder;     /* If defined an aSortOrder[i] is true, sort DESC */
9200
  u8 *aSortOrder;     /* Sort order for each column.  May be NULL */
8926
  CollSeq *aColl[1];  /* Collating sequence for each term of the key */
9201
  CollSeq *aColl[1];  /* Collating sequence for each term of the key */
8927
};
9202
};
8928
9203
 Lines 9342-9347   typedef u64 Bitmask; Link Here 
9342
** and the next table on the list.  The parser builds the list this way.
9617
** and the next table on the list.  The parser builds the list this way.
9343
** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
9618
** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
9344
** jointype expresses the join between the table and the previous table.
9619
** jointype expresses the join between the table and the previous table.
9620
**
9621
** In the colUsed field, the high-order bit (bit 63) is set if the table
9622
** contains more than 63 columns and the 64-th or later column is used.
9345
*/
9623
*/
9346
struct SrcList {
9624
struct SrcList {
9347
  i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
9625
  i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
 Lines 9453-9459   struct WhereLevel { Link Here 
9453
#define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
9731
#define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
9454
#define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
9732
#define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
9455
#define WHERE_DUPLICATES_OK    0x0008 /* Ok to return a row more than once */
9733
#define WHERE_DUPLICATES_OK    0x0008 /* Ok to return a row more than once */
9456
#define WHERE_OMIT_OPEN        0x0010 /* Table cursor are already open */
9734
#define WHERE_OMIT_OPEN        0x0010 /* Table cursors are already open */
9457
#define WHERE_OMIT_CLOSE       0x0020 /* Omit close of table & index cursors */
9735
#define WHERE_OMIT_CLOSE       0x0020 /* Omit close of table & index cursors */
9458
#define WHERE_FORCE_TABLE      0x0040 /* Do not use an index-only search */
9736
#define WHERE_FORCE_TABLE      0x0040 /* Do not use an index-only search */
9459
#define WHERE_ONETABLE_ONLY    0x0080 /* Only code the 1st table in pTabList */
9737
#define WHERE_ONETABLE_ONLY    0x0080 /* Only code the 1st table in pTabList */
 Lines 9476-9481   struct WhereInfo { Link Here 
9476
  int iBreak;                    /* Jump here to break out of the loop */
9754
  int iBreak;                    /* Jump here to break out of the loop */
9477
  int nLevel;                    /* Number of nested loop */
9755
  int nLevel;                    /* Number of nested loop */
9478
  struct WhereClause *pWC;       /* Decomposition of the WHERE clause */
9756
  struct WhereClause *pWC;       /* Decomposition of the WHERE clause */
9757
  double savedNQueryLoop;        /* pParse->nQueryLoop outside the WHERE loop */
9479
  WhereLevel a[1];               /* Information about each nest loop in WHERE */
9758
  WhereLevel a[1];               /* Information about each nest loop in WHERE */
9480
};
9759
};
9481
9760
 Lines 9717-9722   struct Parse { Link Here 
9717
  u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
9996
  u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
9718
  u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
9997
  u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
9719
  u8 disableTriggers;  /* True to disable triggers */
9998
  u8 disableTriggers;  /* True to disable triggers */
9999
  double nQueryLoop;   /* Estimated number of iterations of a query */
9720
10000
9721
  /* Above is constant between recursions.  Below is reset before and after
10001
  /* Above is constant between recursions.  Below is reset before and after
9722
  ** each recursion */
10002
  ** each recursion */
 Lines 9887-9893   struct StrAccum { Link Here 
9887
  int  nAlloc;         /* Amount of space allocated in zText */
10167
  int  nAlloc;         /* Amount of space allocated in zText */
9888
  int  mxAlloc;        /* Maximum allowed string length */
10168
  int  mxAlloc;        /* Maximum allowed string length */
9889
  u8   mallocFailed;   /* Becomes true if any memory allocation fails */
10169
  u8   mallocFailed;   /* Becomes true if any memory allocation fails */
9890
  u8   useMalloc;      /* True if zText is enlargeable using realloc */
10170
  u8   useMalloc;      /* 0: none,  1: sqlite3DbMalloc,  2: sqlite3_malloc */
9891
  u8   tooBig;         /* Becomes true if string size exceeds limits */
10171
  u8   tooBig;         /* Becomes true if string size exceeds limits */
9892
};
10172
};
9893
10173
 Lines 10092-10098   SQLITE_PRIVATE const sqlite3_mem_methods Link Here 
10092
10372
10093
10373
10094
#ifndef SQLITE_MUTEX_OMIT
10374
#ifndef SQLITE_MUTEX_OMIT
10095
SQLITE_PRIVATE   sqlite3_mutex_methods *sqlite3DefaultMutex(void);
10375
SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
10376
SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3NoopMutex(void);
10096
SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
10377
SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
10097
SQLITE_PRIVATE   int sqlite3MutexInit(void);
10378
SQLITE_PRIVATE   int sqlite3MutexInit(void);
10098
SQLITE_PRIVATE   int sqlite3MutexEnd(void);
10379
SQLITE_PRIVATE   int sqlite3MutexEnd(void);
 Lines 10184-10190   SQLITE_PRIVATE int sqlite3ViewGetColum Link Here 
10184
#endif
10465
#endif
10185
10466
10186
SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
10467
SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
10187
SQLITE_PRIVATE void sqlite3DeleteTable(Table*);
10468
SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
10188
#ifndef SQLITE_OMIT_AUTOINCREMENT
10469
#ifndef SQLITE_OMIT_AUTOINCREMENT
10189
SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
10470
SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
10190
SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
10471
SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
 Lines 10224-10229   SQLITE_PRIVATE void sqlite3Update(Parse* Link Here 
10224
SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**, u16);
10505
SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**, u16);
10225
SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
10506
SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
10226
SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int);
10507
SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int);
10508
SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
10227
SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
10509
SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
10228
SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, int, int, int);
10510
SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, int, int, int);
10229
SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
10511
SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
 Lines 10250-10255   SQLITE_PRIVATE void sqlite3Vacuum(Parse* Link Here 
10250
SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
10532
SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
10251
SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
10533
SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
10252
SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
10534
SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
10535
SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*);
10253
SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
10536
SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
10254
SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
10537
SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
10255
SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
10538
SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
 Lines 10416-10422   SQLITE_PRIVATE int sqlite3ReadSchema(Par Link Here 
10416
SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
10699
SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
10417
SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
10700
SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
10418
SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
10701
SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
10419
SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Parse *pParse, Expr *, Token *);
10702
SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Expr*, CollSeq*);
10703
SQLITE_PRIVATE Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr*, Token*);
10420
SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
10704
SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
10421
SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
10705
SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
10422
SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
10706
SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
 Lines 10437-10449   SQLITE_PRIVATE void sqlite3ValueApplyAff Link Here 
10437
SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
10721
SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
10438
SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
10722
SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
10439
SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
10723
SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
10724
SQLITE_PRIVATE const Token sqlite3IntTokens[];
10440
SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
10725
SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
10441
SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
10726
SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
10727
#ifndef SQLITE_OMIT_WSD
10442
SQLITE_PRIVATE int sqlite3PendingByte;
10728
SQLITE_PRIVATE int sqlite3PendingByte;
10443
#endif
10729
#endif
10730
#endif
10444
SQLITE_PRIVATE void sqlite3RootPageMoved(Db*, int, int);
10731
SQLITE_PRIVATE void sqlite3RootPageMoved(Db*, int, int);
10445
SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
10732
SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
10446
SQLITE_PRIVATE void sqlite3AlterFunctions(sqlite3*);
10733
SQLITE_PRIVATE void sqlite3AlterFunctions(void);
10447
SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
10734
SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
10448
SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
10735
SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
10449
SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
10736
SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
 Lines 10463-10469   SQLITE_PRIVATE int sqlite3InvokeBusyHand Link Here 
10463
SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
10750
SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
10464
SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
10751
SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
10465
SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
10752
SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
10466
SQLITE_PRIVATE void sqlite3DeleteIndexSamples(Index*);
10753
SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
10467
SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
10754
SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
10468
SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
10755
SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
10469
SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
10756
SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
 Lines 10525-10531   SQLITE_PRIVATE int sqlite3Utf8To8(unsi Link Here 
10525
#  define sqlite3VtabUnlock(X)
10812
#  define sqlite3VtabUnlock(X)
10526
#  define sqlite3VtabUnlockList(X)
10813
#  define sqlite3VtabUnlockList(X)
10527
#else
10814
#else
10528
SQLITE_PRIVATE    void sqlite3VtabClear(Table*);
10815
SQLITE_PRIVATE    void sqlite3VtabClear(sqlite3 *db, Table*);
10529
SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, char **);
10816
SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, char **);
10530
SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
10817
SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
10531
SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
10818
SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
 Lines 10552-10557   SQLITE_PRIVATE void sqlite3ExprListCheck Link Here 
10552
SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
10839
SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
10553
SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
10840
SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
10554
SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
10841
SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
10842
SQLITE_PRIVATE const char *sqlite3JournalModename(int);
10843
SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int);
10844
SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
10555
10845
10556
/* Declarations for functions in fkey.c. All of these are replaced by
10846
/* Declarations for functions in fkey.c. All of these are replaced by
10557
** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
10847
** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
 Lines 10575-10583   SQLITE_PRIVATE FKey *sqlite3FkReferenc Link Here 
10575
  #define sqlite3FkRequired(a,b,c,d) 0
10865
  #define sqlite3FkRequired(a,b,c,d) 0
10576
#endif
10866
#endif
10577
#ifndef SQLITE_OMIT_FOREIGN_KEY
10867
#ifndef SQLITE_OMIT_FOREIGN_KEY
10578
SQLITE_PRIVATE   void sqlite3FkDelete(Table*);
10868
SQLITE_PRIVATE   void sqlite3FkDelete(sqlite3 *, Table*);
10579
#else
10869
#else
10580
  #define sqlite3FkDelete(a)
10870
  #define sqlite3FkDelete(a,b)
10581
#endif
10871
#endif
10582
10872
10583
10873
 Lines 10658-10664   SQLITE_PRIVATE void (*sqlite3IoTrace)(co Link Here 
10658
# define sqlite3VdbeIOTraceSql(X)
10948
# define sqlite3VdbeIOTraceSql(X)
10659
#endif
10949
#endif
10660
10950
10661
#endif
10951
/*
10952
** These routines are available for the mem2.c debugging memory allocator
10953
** only.  They are used to verify that different "types" of memory
10954
** allocations are properly tracked by the system.
10955
**
10956
** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
10957
** the MEMTYPE_* macros defined below.  The type must be a bitmask with
10958
** a single bit set.
10959
**
10960
** sqlite3MemdebugHasType() returns true if any of the bits in its second
10961
** argument match the type set by the previous sqlite3MemdebugSetType().
10962
** sqlite3MemdebugHasType() is intended for use inside assert() statements.
10963
**
10964
** sqlite3MemdebugNoType() returns true if none of the bits in its second
10965
** argument match the type set by the previous sqlite3MemdebugSetType().
10966
**
10967
** Perhaps the most important point is the difference between MEMTYPE_HEAP
10968
** and MEMTYPE_LOOKASIDE.  If an allocation is MEMTYPE_LOOKASIDE, that means
10969
** it might have been allocated by lookaside, except the allocation was
10970
** too large or lookaside was already full.  It is important to verify
10971
** that allocations that might have been satisfied by lookaside are not
10972
** passed back to non-lookaside free() routines.  Asserts such as the
10973
** example above are placed on the non-lookaside free() routines to verify
10974
** this constraint. 
10975
**
10976
** All of this is no-op for a production build.  It only comes into
10977
** play when the SQLITE_MEMDEBUG compile-time option is used.
10978
*/
10979
#ifdef SQLITE_MEMDEBUG
10980
SQLITE_PRIVATE   void sqlite3MemdebugSetType(void*,u8);
10981
SQLITE_PRIVATE   int sqlite3MemdebugHasType(void*,u8);
10982
SQLITE_PRIVATE   int sqlite3MemdebugNoType(void*,u8);
10983
#else
10984
# define sqlite3MemdebugSetType(X,Y)  /* no-op */
10985
# define sqlite3MemdebugHasType(X,Y)  1
10986
# define sqlite3MemdebugNoType(X,Y)   1
10987
#endif
10988
#define MEMTYPE_HEAP       0x01  /* General heap allocations */
10989
#define MEMTYPE_LOOKASIDE  0x02  /* Might have been lookaside memory */
10990
#define MEMTYPE_SCRATCH    0x04  /* Scratch allocations */
10991
#define MEMTYPE_PCACHE     0x08  /* Page cache allocations */
10992
#define MEMTYPE_DB         0x10  /* Uses sqlite3DbMalloc, not sqlite_malloc */
10993
10994
#endif /* _SQLITEINT_H_ */
10662
10995
10663
/************** End of sqliteInt.h *******************************************/
10996
/************** End of sqliteInt.h *******************************************/
10664
/************** Begin file global.c ******************************************/
10997
/************** Begin file global.c ******************************************/
 Lines 10840-10845   SQLITE_PRIVATE SQLITE_WSD struct Sqlite3 Link Here 
10840
SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
11173
SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
10841
11174
10842
/*
11175
/*
11176
** Constant tokens for values 0 and 1.
11177
*/
11178
SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
11179
   { "0", 1 },
11180
   { "1", 1 }
11181
};
11182
11183
11184
/*
10843
** The value of the "pending" byte must be 0x40000000 (1 byte past the
11185
** The value of the "pending" byte must be 0x40000000 (1 byte past the
10844
** 1-gibabyte boundary) in a compatible database.  SQLite never uses
11186
** 1-gibabyte boundary) in a compatible database.  SQLite never uses
10845
** the database page that contains the pending byte.  It never attempts
11187
** the database page that contains the pending byte.  It never attempts
 Lines 10857-10863   SQLITE_PRIVATE SQLITE_WSD FuncDefHash sq Link Here 
10857
** Changing the pending byte during operating results in undefined
11199
** Changing the pending byte during operating results in undefined
10858
** and dileterious behavior.
11200
** and dileterious behavior.
10859
*/
11201
*/
11202
#ifndef SQLITE_OMIT_WSD
10860
SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
11203
SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
11204
#endif
10861
11205
10862
/*
11206
/*
10863
** Properties of opcodes.  The OPFLG_INITIALIZER macro is
11207
** Properties of opcodes.  The OPFLG_INITIALIZER macro is
 Lines 11041-11046   static const char * const azCompileOpt[] Link Here 
11041
#ifdef SQLITE_OMIT_AUTOINIT
11385
#ifdef SQLITE_OMIT_AUTOINIT
11042
  "OMIT_AUTOINIT",
11386
  "OMIT_AUTOINIT",
11043
#endif
11387
#endif
11388
#ifdef SQLITE_OMIT_AUTOMATIC_INDEX
11389
  "OMIT_AUTOMATIC_INDEX",
11390
#endif
11044
#ifdef SQLITE_OMIT_AUTOVACUUM
11391
#ifdef SQLITE_OMIT_AUTOVACUUM
11045
  "OMIT_AUTOVACUUM",
11392
  "OMIT_AUTOVACUUM",
11046
#endif
11393
#endif
 Lines 11062-11070   static const char * const azCompileOpt[] Link Here 
11062
#ifdef SQLITE_OMIT_CHECK
11409
#ifdef SQLITE_OMIT_CHECK
11063
  "OMIT_CHECK",
11410
  "OMIT_CHECK",
11064
#endif
11411
#endif
11065
#ifdef SQLITE_OMIT_COMPILEOPTION_DIAGS
11412
/* // redundant
11066
  "OMIT_COMPILEOPTION_DIAGS",
11413
** #ifdef SQLITE_OMIT_COMPILEOPTION_DIAGS
11067
#endif
11414
**   "OMIT_COMPILEOPTION_DIAGS",
11415
** #endif
11416
*/
11068
#ifdef SQLITE_OMIT_COMPLETE
11417
#ifdef SQLITE_OMIT_COMPLETE
11069
  "OMIT_COMPLETE",
11418
  "OMIT_COMPLETE",
11070
#endif
11419
#endif
 Lines 11098-11106   static const char * const azCompileOpt[] Link Here 
11098
#ifdef SQLITE_OMIT_GET_TABLE
11447
#ifdef SQLITE_OMIT_GET_TABLE
11099
  "OMIT_GET_TABLE",
11448
  "OMIT_GET_TABLE",
11100
#endif
11449
#endif
11101
#ifdef SQLITE_OMIT_GLOBALRECOVER
11102
  "OMIT_GLOBALRECOVER",
11103
#endif
11104
#ifdef SQLITE_OMIT_INCRBLOB
11450
#ifdef SQLITE_OMIT_INCRBLOB
11105
  "OMIT_INCRBLOB",
11451
  "OMIT_INCRBLOB",
11106
#endif
11452
#endif
 Lines 11179-11184   static const char * const azCompileOpt[] Link Here 
11179
#ifdef SQLITE_OMIT_VIRTUALTABLE
11525
#ifdef SQLITE_OMIT_VIRTUALTABLE
11180
  "OMIT_VIRTUALTABLE",
11526
  "OMIT_VIRTUALTABLE",
11181
#endif
11527
#endif
11528
#ifdef SQLITE_OMIT_WAL
11529
  "OMIT_WAL",
11530
#endif
11182
#ifdef SQLITE_OMIT_WSD
11531
#ifdef SQLITE_OMIT_WSD
11183
  "OMIT_WSD",
11532
  "OMIT_WSD",
11184
#endif
11533
#endif
 Lines 11271-17998   SQLITE_API const char *sqlite3_compileop Link Here 
11271
** This module implements the sqlite3_status() interface and related
11620
** This module implements the sqlite3_status() interface and related
11272
** functionality.
11621
** functionality.
11273
*/
11622
*/
11274
11623
/************** Include vdbeInt.h in the middle of status.c ******************/
11275
/*
11276
** Variables in which to record status information.
11277
*/
11278
typedef struct sqlite3StatType sqlite3StatType;
11279
static SQLITE_WSD struct sqlite3StatType {
11280
  int nowValue[9];         /* Current value */
11281
  int mxValue[9];          /* Maximum value */
11282
} sqlite3Stat = { {0,}, {0,} };
11283
11284
11285
/* The "wsdStat" macro will resolve to the status information
11286
** state vector.  If writable static data is unsupported on the target,
11287
** we have to locate the state vector at run-time.  In the more common
11288
** case where writable static data is supported, wsdStat can refer directly
11289
** to the "sqlite3Stat" state vector declared above.
11290
*/
11291
#ifdef SQLITE_OMIT_WSD
11292
# define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
11293
# define wsdStat x[0]
11294
#else
11295
# define wsdStatInit
11296
# define wsdStat sqlite3Stat
11297
#endif
11298
11299
/*
11300
** Return the current value of a status parameter.
11301
*/
11302
SQLITE_PRIVATE int sqlite3StatusValue(int op){
11303
  wsdStatInit;
11304
  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
11305
  return wsdStat.nowValue[op];
11306
}
11307
11308
/*
11309
** Add N to the value of a status record.  It is assumed that the
11310
** caller holds appropriate locks.
11311
*/
11312
SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
11313
  wsdStatInit;
11314
  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
11315
  wsdStat.nowValue[op] += N;
11316
  if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
11317
    wsdStat.mxValue[op] = wsdStat.nowValue[op];
11318
  }
11319
}
11320
11321
/*
11322
** Set the value of a status to X.
11323
*/
11324
SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
11325
  wsdStatInit;
11326
  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
11327
  wsdStat.nowValue[op] = X;
11328
  if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
11329
    wsdStat.mxValue[op] = wsdStat.nowValue[op];
11330
  }
11331
}
11332
11333
/*
11334
** Query status information.
11335
**
11336
** This implementation assumes that reading or writing an aligned
11337
** 32-bit integer is an atomic operation.  If that assumption is not true,
11338
** then this routine is not threadsafe.
11339
*/
11340
SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
11341
  wsdStatInit;
11342
  if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
11343
    return SQLITE_MISUSE_BKPT;
11344
  }
11345
  *pCurrent = wsdStat.nowValue[op];
11346
  *pHighwater = wsdStat.mxValue[op];
11347
  if( resetFlag ){
11348
    wsdStat.mxValue[op] = wsdStat.nowValue[op];
11349
  }
11350
  return SQLITE_OK;
11351
}
11352
11353
/*
11354
** Query status information for a single database connection
11355
*/
11356
SQLITE_API int sqlite3_db_status(
11357
  sqlite3 *db,          /* The database connection whose status is desired */
11358
  int op,               /* Status verb */
11359
  int *pCurrent,        /* Write current value here */
11360
  int *pHighwater,      /* Write high-water mark here */
11361
  int resetFlag         /* Reset high-water mark if true */
11362
){
11363
  switch( op ){
11364
    case SQLITE_DBSTATUS_LOOKASIDE_USED: {
11365
      *pCurrent = db->lookaside.nOut;
11366
      *pHighwater = db->lookaside.mxOut;
11367
      if( resetFlag ){
11368
        db->lookaside.mxOut = db->lookaside.nOut;
11369
      }
11370
      break;
11371
    }
11372
    default: {
11373
      return SQLITE_ERROR;
11374
    }
11375
  }
11376
  return SQLITE_OK;
11377
}
11378
11379
/************** End of status.c **********************************************/
11380
/************** Begin file date.c ********************************************/
11381
/*
11382
** 2003 October 31
11383
**
11384
** The author disclaims copyright to this source code.  In place of
11385
** a legal notice, here is a blessing:
11386
**
11387
**    May you do good and not evil.
11388
**    May you find forgiveness for yourself and forgive others.
11389
**    May you share freely, never taking more than you give.
11390
**
11391
*************************************************************************
11392
** This file contains the C functions that implement date and time
11393
** functions for SQLite.  
11394
**
11395
** There is only one exported symbol in this file - the function
11396
** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
11397
** All other code has file scope.
11398
**
11399
** SQLite processes all times and dates as Julian Day numbers.  The
11400
** dates and times are stored as the number of days since noon
11401
** in Greenwich on November 24, 4714 B.C. according to the Gregorian
11402
** calendar system. 
11403
**
11404
** 1970-01-01 00:00:00 is JD 2440587.5
11405
** 2000-01-01 00:00:00 is JD 2451544.5
11406
**
11407
** This implemention requires years to be expressed as a 4-digit number
11408
** which means that only dates between 0000-01-01 and 9999-12-31 can
11409
** be represented, even though julian day numbers allow a much wider
11410
** range of dates.
11411
**
11412
** The Gregorian calendar system is used for all dates and times,
11413
** even those that predate the Gregorian calendar.  Historians usually
11414
** use the Julian calendar for dates prior to 1582-10-15 and for some
11415
** dates afterwards, depending on locale.  Beware of this difference.
11416
**
11417
** The conversion algorithms are implemented based on descriptions
11418
** in the following text:
11419
**
11420
**      Jean Meeus
11421
**      Astronomical Algorithms, 2nd Edition, 1998
11422
**      ISBM 0-943396-61-1
11423
**      Willmann-Bell, Inc
11424
**      Richmond, Virginia (USA)
11425
*/
11426
#include <time.h>
11427
11428
#ifndef SQLITE_OMIT_DATETIME_FUNCS
11429
11430
/*
11431
** On recent Windows platforms, the localtime_s() function is available
11432
** as part of the "Secure CRT". It is essentially equivalent to 
11433
** localtime_r() available under most POSIX platforms, except that the 
11434
** order of the parameters is reversed.
11435
**
11436
** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
11437
**
11438
** If the user has not indicated to use localtime_r() or localtime_s()
11439
** already, check for an MSVC build environment that provides 
11440
** localtime_s().
11441
*/
11442
#if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
11443
     defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
11444
#define HAVE_LOCALTIME_S 1
11445
#endif
11446
11447
/*
11448
** A structure for holding a single date and time.
11449
*/
11450
typedef struct DateTime DateTime;
11451
struct DateTime {
11452
  sqlite3_int64 iJD; /* The julian day number times 86400000 */
11453
  int Y, M, D;       /* Year, month, and day */
11454
  int h, m;          /* Hour and minutes */
11455
  int tz;            /* Timezone offset in minutes */
11456
  double s;          /* Seconds */
11457
  char validYMD;     /* True (1) if Y,M,D are valid */
11458
  char validHMS;     /* True (1) if h,m,s are valid */
11459
  char validJD;      /* True (1) if iJD is valid */
11460
  char validTZ;      /* True (1) if tz is valid */
11461
};
11462
11463
11464
/*
11465
** Convert zDate into one or more integers.  Additional arguments
11466
** come in groups of 5 as follows:
11467
**
11468
**       N       number of digits in the integer
11469
**       min     minimum allowed value of the integer
11470
**       max     maximum allowed value of the integer
11471
**       nextC   first character after the integer
11472
**       pVal    where to write the integers value.
11473
**
11474
** Conversions continue until one with nextC==0 is encountered.
11475
** The function returns the number of successful conversions.
11476
*/
11477
static int getDigits(const char *zDate, ...){
11478
  va_list ap;
11479
  int val;
11480
  int N;
11481
  int min;
11482
  int max;
11483
  int nextC;
11484
  int *pVal;
11485
  int cnt = 0;
11486
  va_start(ap, zDate);
11487
  do{
11488
    N = va_arg(ap, int);
11489
    min = va_arg(ap, int);
11490
    max = va_arg(ap, int);
11491
    nextC = va_arg(ap, int);
11492
    pVal = va_arg(ap, int*);
11493
    val = 0;
11494
    while( N-- ){
11495
      if( !sqlite3Isdigit(*zDate) ){
11496
        goto end_getDigits;
11497
      }
11498
      val = val*10 + *zDate - '0';
11499
      zDate++;
11500
    }
11501
    if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
11502
      goto end_getDigits;
11503
    }
11504
    *pVal = val;
11505
    zDate++;
11506
    cnt++;
11507
  }while( nextC );
11508
end_getDigits:
11509
  va_end(ap);
11510
  return cnt;
11511
}
11512
11513
/*
11514
** Read text from z[] and convert into a floating point number.  Return
11515
** the number of digits converted.
11516
*/
11517
#define getValue sqlite3AtoF
11518
11519
/*
11520
** Parse a timezone extension on the end of a date-time.
11521
** The extension is of the form:
11522
**
11523
**        (+/-)HH:MM
11524
**
11525
** Or the "zulu" notation:
11526
**
11527
**        Z
11528
**
11529
** If the parse is successful, write the number of minutes
11530
** of change in p->tz and return 0.  If a parser error occurs,
11531
** return non-zero.
11532
**
11533
** A missing specifier is not considered an error.
11534
*/
11535
static int parseTimezone(const char *zDate, DateTime *p){
11536
  int sgn = 0;
11537
  int nHr, nMn;
11538
  int c;
11539
  while( sqlite3Isspace(*zDate) ){ zDate++; }
11540
  p->tz = 0;
11541
  c = *zDate;
11542
  if( c=='-' ){
11543
    sgn = -1;
11544
  }else if( c=='+' ){
11545
    sgn = +1;
11546
  }else if( c=='Z' || c=='z' ){
11547
    zDate++;
11548
    goto zulu_time;
11549
  }else{
11550
    return c!=0;
11551
  }
11552
  zDate++;
11553
  if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
11554
    return 1;
11555
  }
11556
  zDate += 5;
11557
  p->tz = sgn*(nMn + nHr*60);
11558
zulu_time:
11559
  while( sqlite3Isspace(*zDate) ){ zDate++; }
11560
  return *zDate!=0;
11561
}
11562
11563
/*
11564
** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
11565
** The HH, MM, and SS must each be exactly 2 digits.  The
11566
** fractional seconds FFFF can be one or more digits.
11567
**
11568
** Return 1 if there is a parsing error and 0 on success.
11569
*/
11570
static int parseHhMmSs(const char *zDate, DateTime *p){
11571
  int h, m, s;
11572
  double ms = 0.0;
11573
  if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
11574
    return 1;
11575
  }
11576
  zDate += 5;
11577
  if( *zDate==':' ){
11578
    zDate++;
11579
    if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
11580
      return 1;
11581
    }
11582
    zDate += 2;
11583
    if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
11584
      double rScale = 1.0;
11585
      zDate++;
11586
      while( sqlite3Isdigit(*zDate) ){
11587
        ms = ms*10.0 + *zDate - '0';
11588
        rScale *= 10.0;
11589
        zDate++;
11590
      }
11591
      ms /= rScale;
11592
    }
11593
  }else{
11594
    s = 0;
11595
  }
11596
  p->validJD = 0;
11597
  p->validHMS = 1;
11598
  p->h = h;
11599
  p->m = m;
11600
  p->s = s + ms;
11601
  if( parseTimezone(zDate, p) ) return 1;
11602
  p->validTZ = (p->tz!=0)?1:0;
11603
  return 0;
11604
}
11605
11606
/*
11607
** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
11608
** that the YYYY-MM-DD is according to the Gregorian calendar.
11609
**
11610
** Reference:  Meeus page 61
11611
*/
11612
static void computeJD(DateTime *p){
11613
  int Y, M, D, A, B, X1, X2;
11614
11615
  if( p->validJD ) return;
11616
  if( p->validYMD ){
11617
    Y = p->Y;
11618
    M = p->M;
11619
    D = p->D;
11620
  }else{
11621
    Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
11622
    M = 1;
11623
    D = 1;
11624
  }
11625
  if( M<=2 ){
11626
    Y--;
11627
    M += 12;
11628
  }
11629
  A = Y/100;
11630
  B = 2 - A + (A/4);
11631
  X1 = 36525*(Y+4716)/100;
11632
  X2 = 306001*(M+1)/10000;
11633
  p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
11634
  p->validJD = 1;
11635
  if( p->validHMS ){
11636
    p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
11637
    if( p->validTZ ){
11638
      p->iJD -= p->tz*60000;
11639
      p->validYMD = 0;
11640
      p->validHMS = 0;
11641
      p->validTZ = 0;
11642
    }
11643
  }
11644
}
11645
11646
/*
11647
** Parse dates of the form
11648
**
11649
**     YYYY-MM-DD HH:MM:SS.FFF
11650
**     YYYY-MM-DD HH:MM:SS
11651
**     YYYY-MM-DD HH:MM
11652
**     YYYY-MM-DD
11653
**
11654
** Write the result into the DateTime structure and return 0
11655
** on success and 1 if the input string is not a well-formed
11656
** date.
11657
*/
11658
static int parseYyyyMmDd(const char *zDate, DateTime *p){
11659
  int Y, M, D, neg;
11660
11661
  if( zDate[0]=='-' ){
11662
    zDate++;
11663
    neg = 1;
11664
  }else{
11665
    neg = 0;
11666
  }
11667
  if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
11668
    return 1;
11669
  }
11670
  zDate += 10;
11671
  while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
11672
  if( parseHhMmSs(zDate, p)==0 ){
11673
    /* We got the time */
11674
  }else if( *zDate==0 ){
11675
    p->validHMS = 0;
11676
  }else{
11677
    return 1;
11678
  }
11679
  p->validJD = 0;
11680
  p->validYMD = 1;
11681
  p->Y = neg ? -Y : Y;
11682
  p->M = M;
11683
  p->D = D;
11684
  if( p->validTZ ){
11685
    computeJD(p);
11686
  }
11687
  return 0;
11688
}
11689
11690
/*
11691
** Set the time to the current time reported by the VFS
11692
*/
11693
static void setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
11694
  double r;
11695
  sqlite3 *db = sqlite3_context_db_handle(context);
11696
  sqlite3OsCurrentTime(db->pVfs, &r);
11697
  p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
11698
  p->validJD = 1;
11699
}
11700
11701
/*
11702
** Attempt to parse the given string into a Julian Day Number.  Return
11703
** the number of errors.
11704
**
11705
** The following are acceptable forms for the input string:
11706
**
11707
**      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
11708
**      DDDD.DD 
11709
**      now
11710
**
11711
** In the first form, the +/-HH:MM is always optional.  The fractional
11712
** seconds extension (the ".FFF") is optional.  The seconds portion
11713
** (":SS.FFF") is option.  The year and date can be omitted as long
11714
** as there is a time string.  The time string can be omitted as long
11715
** as there is a year and date.
11716
*/
11717
static int parseDateOrTime(
11718
  sqlite3_context *context, 
11719
  const char *zDate, 
11720
  DateTime *p
11721
){
11722
  int isRealNum;    /* Return from sqlite3IsNumber().  Not used */
11723
  if( parseYyyyMmDd(zDate,p)==0 ){
11724
    return 0;
11725
  }else if( parseHhMmSs(zDate, p)==0 ){
11726
    return 0;
11727
  }else if( sqlite3StrICmp(zDate,"now")==0){
11728
    setDateTimeToCurrent(context, p);
11729
    return 0;
11730
  }else if( sqlite3IsNumber(zDate, &isRealNum, SQLITE_UTF8) ){
11731
    double r;
11732
    getValue(zDate, &r);
11733
    p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
11734
    p->validJD = 1;
11735
    return 0;
11736
  }
11737
  return 1;
11738
}
11739
11740
/*
11741
** Compute the Year, Month, and Day from the julian day number.
11742
*/
11743
static void computeYMD(DateTime *p){
11744
  int Z, A, B, C, D, E, X1;
11745
  if( p->validYMD ) return;
11746
  if( !p->validJD ){
11747
    p->Y = 2000;
11748
    p->M = 1;
11749
    p->D = 1;
11750
  }else{
11751
    Z = (int)((p->iJD + 43200000)/86400000);
11752
    A = (int)((Z - 1867216.25)/36524.25);
11753
    A = Z + 1 + A - (A/4);
11754
    B = A + 1524;
11755
    C = (int)((B - 122.1)/365.25);
11756
    D = (36525*C)/100;
11757
    E = (int)((B-D)/30.6001);
11758
    X1 = (int)(30.6001*E);
11759
    p->D = B - D - X1;
11760
    p->M = E<14 ? E-1 : E-13;
11761
    p->Y = p->M>2 ? C - 4716 : C - 4715;
11762
  }
11763
  p->validYMD = 1;
11764
}
11765
11766
/*
11767
** Compute the Hour, Minute, and Seconds from the julian day number.
11768
*/
11769
static void computeHMS(DateTime *p){
11770
  int s;
11771
  if( p->validHMS ) return;
11772
  computeJD(p);
11773
  s = (int)((p->iJD + 43200000) % 86400000);
11774
  p->s = s/1000.0;
11775
  s = (int)p->s;
11776
  p->s -= s;
11777
  p->h = s/3600;
11778
  s -= p->h*3600;
11779
  p->m = s/60;
11780
  p->s += s - p->m*60;
11781
  p->validHMS = 1;
11782
}
11783
11784
/*
11785
** Compute both YMD and HMS
11786
*/
11787
static void computeYMD_HMS(DateTime *p){
11788
  computeYMD(p);
11789
  computeHMS(p);
11790
}
11791
11792
/*
11793
** Clear the YMD and HMS and the TZ
11794
*/
11795
static void clearYMD_HMS_TZ(DateTime *p){
11796
  p->validYMD = 0;
11797
  p->validHMS = 0;
11798
  p->validTZ = 0;
11799
}
11800
11801
#ifndef SQLITE_OMIT_LOCALTIME
11802
/*
11803
** Compute the difference (in milliseconds)
11804
** between localtime and UTC (a.k.a. GMT)
11805
** for the time value p where p is in UTC.
11806
*/
11807
static sqlite3_int64 localtimeOffset(DateTime *p){
11808
  DateTime x, y;
11809
  time_t t;
11810
  x = *p;
11811
  computeYMD_HMS(&x);
11812
  if( x.Y<1971 || x.Y>=2038 ){
11813
    x.Y = 2000;
11814
    x.M = 1;
11815
    x.D = 1;
11816
    x.h = 0;
11817
    x.m = 0;
11818
    x.s = 0.0;
11819
  } else {
11820
    int s = (int)(x.s + 0.5);
11821
    x.s = s;
11822
  }
11823
  x.tz = 0;
11824
  x.validJD = 0;
11825
  computeJD(&x);
11826
  t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
11827
#ifdef HAVE_LOCALTIME_R
11828
  {
11829
    struct tm sLocal;
11830
    localtime_r(&t, &sLocal);
11831
    y.Y = sLocal.tm_year + 1900;
11832
    y.M = sLocal.tm_mon + 1;
11833
    y.D = sLocal.tm_mday;
11834
    y.h = sLocal.tm_hour;
11835
    y.m = sLocal.tm_min;
11836
    y.s = sLocal.tm_sec;
11837
  }
11838
#elif defined(HAVE_LOCALTIME_S) && HAVE_LOCALTIME_S
11839
  {
11840
    struct tm sLocal;
11841
    localtime_s(&sLocal, &t);
11842
    y.Y = sLocal.tm_year + 1900;
11843
    y.M = sLocal.tm_mon + 1;
11844
    y.D = sLocal.tm_mday;
11845
    y.h = sLocal.tm_hour;
11846
    y.m = sLocal.tm_min;
11847
    y.s = sLocal.tm_sec;
11848
  }
11849
#else
11850
  {
11851
    struct tm *pTm;
11852
    sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
11853
    pTm = localtime(&t);
11854
    y.Y = pTm->tm_year + 1900;
11855
    y.M = pTm->tm_mon + 1;
11856
    y.D = pTm->tm_mday;
11857
    y.h = pTm->tm_hour;
11858
    y.m = pTm->tm_min;
11859
    y.s = pTm->tm_sec;
11860
    sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
11861
  }
11862
#endif
11863
  y.validYMD = 1;
11864
  y.validHMS = 1;
11865
  y.validJD = 0;
11866
  y.validTZ = 0;
11867
  computeJD(&y);
11868
  return y.iJD - x.iJD;
11869
}
11870
#endif /* SQLITE_OMIT_LOCALTIME */
11871
11872
/*
11873
** Process a modifier to a date-time stamp.  The modifiers are
11874
** as follows:
11875
**
11876
**     NNN days
11877
**     NNN hours
11878
**     NNN minutes
11879
**     NNN.NNNN seconds
11880
**     NNN months
11881
**     NNN years
11882
**     start of month
11883
**     start of year
11884
**     start of week
11885
**     start of day
11886
**     weekday N
11887
**     unixepoch
11888
**     localtime
11889
**     utc
11890
**
11891
** Return 0 on success and 1 if there is any kind of error.
11892
*/
11893
static int parseModifier(const char *zMod, DateTime *p){
11894
  int rc = 1;
11895
  int n;
11896
  double r;
11897
  char *z, zBuf[30];
11898
  z = zBuf;
11899
  for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
11900
    z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
11901
  }
11902
  z[n] = 0;
11903
  switch( z[0] ){
11904
#ifndef SQLITE_OMIT_LOCALTIME
11905
    case 'l': {
11906
      /*    localtime
11907
      **
11908
      ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
11909
      ** show local time.
11910
      */
11911
      if( strcmp(z, "localtime")==0 ){
11912
        computeJD(p);
11913
        p->iJD += localtimeOffset(p);
11914
        clearYMD_HMS_TZ(p);
11915
        rc = 0;
11916
      }
11917
      break;
11918
    }
11919
#endif
11920
    case 'u': {
11921
      /*
11922
      **    unixepoch
11923
      **
11924
      ** Treat the current value of p->iJD as the number of
11925
      ** seconds since 1970.  Convert to a real julian day number.
11926
      */
11927
      if( strcmp(z, "unixepoch")==0 && p->validJD ){
11928
        p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
11929
        clearYMD_HMS_TZ(p);
11930
        rc = 0;
11931
      }
11932
#ifndef SQLITE_OMIT_LOCALTIME
11933
      else if( strcmp(z, "utc")==0 ){
11934
        sqlite3_int64 c1;
11935
        computeJD(p);
11936
        c1 = localtimeOffset(p);
11937
        p->iJD -= c1;
11938
        clearYMD_HMS_TZ(p);
11939
        p->iJD += c1 - localtimeOffset(p);
11940
        rc = 0;
11941
      }
11942
#endif
11943
      break;
11944
    }
11945
    case 'w': {
11946
      /*
11947
      **    weekday N
11948
      **
11949
      ** Move the date to the same time on the next occurrence of
11950
      ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
11951
      ** date is already on the appropriate weekday, this is a no-op.
11952
      */
11953
      if( strncmp(z, "weekday ", 8)==0 && getValue(&z[8],&r)>0
11954
                 && (n=(int)r)==r && n>=0 && r<7 ){
11955
        sqlite3_int64 Z;
11956
        computeYMD_HMS(p);
11957
        p->validTZ = 0;
11958
        p->validJD = 0;
11959
        computeJD(p);
11960
        Z = ((p->iJD + 129600000)/86400000) % 7;
11961
        if( Z>n ) Z -= 7;
11962
        p->iJD += (n - Z)*86400000;
11963
        clearYMD_HMS_TZ(p);
11964
        rc = 0;
11965
      }
11966
      break;
11967
    }
11968
    case 's': {
11969
      /*
11970
      **    start of TTTTT
11971
      **
11972
      ** Move the date backwards to the beginning of the current day,
11973
      ** or month or year.
11974
      */
11975
      if( strncmp(z, "start of ", 9)!=0 ) break;
11976
      z += 9;
11977
      computeYMD(p);
11978
      p->validHMS = 1;
11979
      p->h = p->m = 0;
11980
      p->s = 0.0;
11981
      p->validTZ = 0;
11982
      p->validJD = 0;
11983
      if( strcmp(z,"month")==0 ){
11984
        p->D = 1;
11985
        rc = 0;
11986
      }else if( strcmp(z,"year")==0 ){
11987
        computeYMD(p);
11988
        p->M = 1;
11989
        p->D = 1;
11990
        rc = 0;
11991
      }else if( strcmp(z,"day")==0 ){
11992
        rc = 0;
11993
      }
11994
      break;
11995
    }
11996
    case '+':
11997
    case '-':
11998
    case '0':
11999
    case '1':
12000
    case '2':
12001
    case '3':
12002
    case '4':
12003
    case '5':
12004
    case '6':
12005
    case '7':
12006
    case '8':
12007
    case '9': {
12008
      double rRounder;
12009
      n = getValue(z, &r);
12010
      assert( n>=1 );
12011
      if( z[n]==':' ){
12012
        /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
12013
        ** specified number of hours, minutes, seconds, and fractional seconds
12014
        ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
12015
        ** omitted.
12016
        */
12017
        const char *z2 = z;
12018
        DateTime tx;
12019
        sqlite3_int64 day;
12020
        if( !sqlite3Isdigit(*z2) ) z2++;
12021
        memset(&tx, 0, sizeof(tx));
12022
        if( parseHhMmSs(z2, &tx) ) break;
12023
        computeJD(&tx);
12024
        tx.iJD -= 43200000;
12025
        day = tx.iJD/86400000;
12026
        tx.iJD -= day*86400000;
12027
        if( z[0]=='-' ) tx.iJD = -tx.iJD;
12028
        computeJD(p);
12029
        clearYMD_HMS_TZ(p);
12030
        p->iJD += tx.iJD;
12031
        rc = 0;
12032
        break;
12033
      }
12034
      z += n;
12035
      while( sqlite3Isspace(*z) ) z++;
12036
      n = sqlite3Strlen30(z);
12037
      if( n>10 || n<3 ) break;
12038
      if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
12039
      computeJD(p);
12040
      rc = 0;
12041
      rRounder = r<0 ? -0.5 : +0.5;
12042
      if( n==3 && strcmp(z,"day")==0 ){
12043
        p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
12044
      }else if( n==4 && strcmp(z,"hour")==0 ){
12045
        p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
12046
      }else if( n==6 && strcmp(z,"minute")==0 ){
12047
        p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
12048
      }else if( n==6 && strcmp(z,"second")==0 ){
12049
        p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
12050
      }else if( n==5 && strcmp(z,"month")==0 ){
12051
        int x, y;
12052
        computeYMD_HMS(p);
12053
        p->M += (int)r;
12054
        x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
12055
        p->Y += x;
12056
        p->M -= x*12;
12057
        p->validJD = 0;
12058
        computeJD(p);
12059
        y = (int)r;
12060
        if( y!=r ){
12061
          p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
12062
        }
12063
      }else if( n==4 && strcmp(z,"year")==0 ){
12064
        int y = (int)r;
12065
        computeYMD_HMS(p);
12066
        p->Y += y;
12067
        p->validJD = 0;
12068
        computeJD(p);
12069
        if( y!=r ){
12070
          p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
12071
        }
12072
      }else{
12073
        rc = 1;
12074
      }
12075
      clearYMD_HMS_TZ(p);
12076
      break;
12077
    }
12078
    default: {
12079
      break;
12080
    }
12081
  }
12082
  return rc;
12083
}
12084
12085
/*
12086
** Process time function arguments.  argv[0] is a date-time stamp.
12087
** argv[1] and following are modifiers.  Parse them all and write
12088
** the resulting time into the DateTime structure p.  Return 0
12089
** on success and 1 if there are any errors.
12090
**
12091
** If there are zero parameters (if even argv[0] is undefined)
12092
** then assume a default value of "now" for argv[0].
12093
*/
12094
static int isDate(
12095
  sqlite3_context *context, 
12096
  int argc, 
12097
  sqlite3_value **argv, 
12098
  DateTime *p
12099
){
12100
  int i;
12101
  const unsigned char *z;
12102
  int eType;
12103
  memset(p, 0, sizeof(*p));
12104
  if( argc==0 ){
12105
    setDateTimeToCurrent(context, p);
12106
  }else if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
12107
                   || eType==SQLITE_INTEGER ){
12108
    p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
12109
    p->validJD = 1;
12110
  }else{
12111
    z = sqlite3_value_text(argv[0]);
12112
    if( !z || parseDateOrTime(context, (char*)z, p) ){
12113
      return 1;
12114
    }
12115
  }
12116
  for(i=1; i<argc; i++){
12117
    if( (z = sqlite3_value_text(argv[i]))==0 || parseModifier((char*)z, p) ){
12118
      return 1;
12119
    }
12120
  }
12121
  return 0;
12122
}
12123
12124
12125
/*
12126
** The following routines implement the various date and time functions
12127
** of SQLite.
12128
*/
12129
12130
/*
12131
**    julianday( TIMESTRING, MOD, MOD, ...)
12132
**
12133
** Return the julian day number of the date specified in the arguments
12134
*/
12135
static void juliandayFunc(
12136
  sqlite3_context *context,
12137
  int argc,
12138
  sqlite3_value **argv
12139
){
12140
  DateTime x;
12141
  if( isDate(context, argc, argv, &x)==0 ){
12142
    computeJD(&x);
12143
    sqlite3_result_double(context, x.iJD/86400000.0);
12144
  }
12145
}
12146
12147
/*
12148
**    datetime( TIMESTRING, MOD, MOD, ...)
12149
**
12150
** Return YYYY-MM-DD HH:MM:SS
12151
*/
12152
static void datetimeFunc(
12153
  sqlite3_context *context,
12154
  int argc,
12155
  sqlite3_value **argv
12156
){
12157
  DateTime x;
12158
  if( isDate(context, argc, argv, &x)==0 ){
12159
    char zBuf[100];
12160
    computeYMD_HMS(&x);
12161
    sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
12162
                     x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
12163
    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
12164
  }
12165
}
12166
12167
/*
12168
**    time( TIMESTRING, MOD, MOD, ...)
12169
**
12170
** Return HH:MM:SS
12171
*/
12172
static void timeFunc(
12173
  sqlite3_context *context,
12174
  int argc,
12175
  sqlite3_value **argv
12176
){
12177
  DateTime x;
12178
  if( isDate(context, argc, argv, &x)==0 ){
12179
    char zBuf[100];
12180
    computeHMS(&x);
12181
    sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
12182
    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
12183
  }
12184
}
12185
12186
/*
12187
**    date( TIMESTRING, MOD, MOD, ...)
12188
**
12189
** Return YYYY-MM-DD
12190
*/
12191
static void dateFunc(
12192
  sqlite3_context *context,
12193
  int argc,
12194
  sqlite3_value **argv
12195
){
12196
  DateTime x;
12197
  if( isDate(context, argc, argv, &x)==0 ){
12198
    char zBuf[100];
12199
    computeYMD(&x);
12200
    sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
12201
    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
12202
  }
12203
}
12204
12205
/*
12206
**    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
12207
**
12208
** Return a string described by FORMAT.  Conversions as follows:
12209
**
12210
**   %d  day of month
12211
**   %f  ** fractional seconds  SS.SSS
12212
**   %H  hour 00-24
12213
**   %j  day of year 000-366
12214
**   %J  ** Julian day number
12215
**   %m  month 01-12
12216
**   %M  minute 00-59
12217
**   %s  seconds since 1970-01-01
12218
**   %S  seconds 00-59
12219
**   %w  day of week 0-6  sunday==0
12220
**   %W  week of year 00-53
12221
**   %Y  year 0000-9999
12222
**   %%  %
12223
*/
12224
static void strftimeFunc(
12225
  sqlite3_context *context,
12226
  int argc,
12227
  sqlite3_value **argv
12228
){
12229
  DateTime x;
12230
  u64 n;
12231
  size_t i,j;
12232
  char *z;
12233
  sqlite3 *db;
12234
  const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
12235
  char zBuf[100];
12236
  if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
12237
  db = sqlite3_context_db_handle(context);
12238
  for(i=0, n=1; zFmt[i]; i++, n++){
12239
    if( zFmt[i]=='%' ){
12240
      switch( zFmt[i+1] ){
12241
        case 'd':
12242
        case 'H':
12243
        case 'm':
12244
        case 'M':
12245
        case 'S':
12246
        case 'W':
12247
          n++;
12248
          /* fall thru */
12249
        case 'w':
12250
        case '%':
12251
          break;
12252
        case 'f':
12253
          n += 8;
12254
          break;
12255
        case 'j':
12256
          n += 3;
12257
          break;
12258
        case 'Y':
12259
          n += 8;
12260
          break;
12261
        case 's':
12262
        case 'J':
12263
          n += 50;
12264
          break;
12265
        default:
12266
          return;  /* ERROR.  return a NULL */
12267
      }
12268
      i++;
12269
    }
12270
  }
12271
  testcase( n==sizeof(zBuf)-1 );
12272
  testcase( n==sizeof(zBuf) );
12273
  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
12274
  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
12275
  if( n<sizeof(zBuf) ){
12276
    z = zBuf;
12277
  }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
12278
    sqlite3_result_error_toobig(context);
12279
    return;
12280
  }else{
12281
    z = sqlite3DbMallocRaw(db, (int)n);
12282
    if( z==0 ){
12283
      sqlite3_result_error_nomem(context);
12284
      return;
12285
    }
12286
  }
12287
  computeJD(&x);
12288
  computeYMD_HMS(&x);
12289
  for(i=j=0; zFmt[i]; i++){
12290
    if( zFmt[i]!='%' ){
12291
      z[j++] = zFmt[i];
12292
    }else{
12293
      i++;
12294
      switch( zFmt[i] ){
12295
        case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
12296
        case 'f': {
12297
          double s = x.s;
12298
          if( s>59.999 ) s = 59.999;
12299
          sqlite3_snprintf(7, &z[j],"%06.3f", s);
12300
          j += sqlite3Strlen30(&z[j]);
12301
          break;
12302
        }
12303
        case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
12304
        case 'W': /* Fall thru */
12305
        case 'j': {
12306
          int nDay;             /* Number of days since 1st day of year */
12307
          DateTime y = x;
12308
          y.validJD = 0;
12309
          y.M = 1;
12310
          y.D = 1;
12311
          computeJD(&y);
12312
          nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
12313
          if( zFmt[i]=='W' ){
12314
            int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
12315
            wd = (int)(((x.iJD+43200000)/86400000)%7);
12316
            sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
12317
            j += 2;
12318
          }else{
12319
            sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
12320
            j += 3;
12321
          }
12322
          break;
12323
        }
12324
        case 'J': {
12325
          sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
12326
          j+=sqlite3Strlen30(&z[j]);
12327
          break;
12328
        }
12329
        case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
12330
        case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
12331
        case 's': {
12332
          sqlite3_snprintf(30,&z[j],"%lld",
12333
                           (i64)(x.iJD/1000 - 21086676*(i64)10000));
12334
          j += sqlite3Strlen30(&z[j]);
12335
          break;
12336
        }
12337
        case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
12338
        case 'w': {
12339
          z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
12340
          break;
12341
        }
12342
        case 'Y': {
12343
          sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
12344
          break;
12345
        }
12346
        default:   z[j++] = '%'; break;
12347
      }
12348
    }
12349
  }
12350
  z[j] = 0;
12351
  sqlite3_result_text(context, z, -1,
12352
                      z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
12353
}
12354
12355
/*
12356
** current_time()
12357
**
12358
** This function returns the same value as time('now').
12359
*/
12360
static void ctimeFunc(
12361
  sqlite3_context *context,
12362
  int NotUsed,
12363
  sqlite3_value **NotUsed2
12364
){
12365
  UNUSED_PARAMETER2(NotUsed, NotUsed2);
12366
  timeFunc(context, 0, 0);
12367
}
12368
12369
/*
12370
** current_date()
12371
**
12372
** This function returns the same value as date('now').
12373
*/
12374
static void cdateFunc(
12375
  sqlite3_context *context,
12376
  int NotUsed,
12377
  sqlite3_value **NotUsed2
12378
){
12379
  UNUSED_PARAMETER2(NotUsed, NotUsed2);
12380
  dateFunc(context, 0, 0);
12381
}
12382
12383
/*
12384
** current_timestamp()
12385
**
12386
** This function returns the same value as datetime('now').
12387
*/
12388
static void ctimestampFunc(
12389
  sqlite3_context *context,
12390
  int NotUsed,
12391
  sqlite3_value **NotUsed2
12392
){
12393
  UNUSED_PARAMETER2(NotUsed, NotUsed2);
12394
  datetimeFunc(context, 0, 0);
12395
}
12396
#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
12397
12398
#ifdef SQLITE_OMIT_DATETIME_FUNCS
12399
/*
12400
** If the library is compiled to omit the full-scale date and time
12401
** handling (to get a smaller binary), the following minimal version
12402
** of the functions current_time(), current_date() and current_timestamp()
12403
** are included instead. This is to support column declarations that
12404
** include "DEFAULT CURRENT_TIME" etc.
12405
**
12406
** This function uses the C-library functions time(), gmtime()
12407
** and strftime(). The format string to pass to strftime() is supplied
12408
** as the user-data for the function.
12409
*/
12410
static void currentTimeFunc(
12411
  sqlite3_context *context,
12412
  int argc,
12413
  sqlite3_value **argv
12414
){
12415
  time_t t;
12416
  char *zFormat = (char *)sqlite3_user_data(context);
12417
  sqlite3 *db;
12418
  double rT;
12419
  char zBuf[20];
12420
12421
  UNUSED_PARAMETER(argc);
12422
  UNUSED_PARAMETER(argv);
12423
12424
  db = sqlite3_context_db_handle(context);
12425
  sqlite3OsCurrentTime(db->pVfs, &rT);
12426
#ifndef SQLITE_OMIT_FLOATING_POINT
12427
  t = 86400.0*(rT - 2440587.5) + 0.5;
12428
#else
12429
  /* without floating point support, rT will have
12430
  ** already lost fractional day precision.
12431
  */
12432
  t = 86400 * (rT - 2440587) - 43200;
12433
#endif
12434
#ifdef HAVE_GMTIME_R
12435
  {
12436
    struct tm sNow;
12437
    gmtime_r(&t, &sNow);
12438
    strftime(zBuf, 20, zFormat, &sNow);
12439
  }
12440
#else
12441
  {
12442
    struct tm *pTm;
12443
    sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
12444
    pTm = gmtime(&t);
12445
    strftime(zBuf, 20, zFormat, pTm);
12446
    sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
12447
  }
12448
#endif
12449
12450
  sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
12451
}
12452
#endif
12453
12454
/*
12455
** This function registered all of the above C functions as SQL
12456
** functions.  This should be the only routine in this file with
12457
** external linkage.
12458
*/
12459
SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
12460
  static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
12461
#ifndef SQLITE_OMIT_DATETIME_FUNCS
12462
    FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
12463
    FUNCTION(date,             -1, 0, 0, dateFunc      ),
12464
    FUNCTION(time,             -1, 0, 0, timeFunc      ),
12465
    FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
12466
    FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
12467
    FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
12468
    FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
12469
    FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
12470
#else
12471
    STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
12472
    STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
12473
    STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
12474
#endif
12475
  };
12476
  int i;
12477
  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
12478
  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
12479
12480
  for(i=0; i<ArraySize(aDateTimeFuncs); i++){
12481
    sqlite3FuncDefInsert(pHash, &aFunc[i]);
12482
  }
12483
}
12484
12485
/************** End of date.c ************************************************/
12486
/************** Begin file os.c **********************************************/
12487
/*
12488
** 2005 November 29
12489
**
12490
** The author disclaims copyright to this source code.  In place of
12491
** a legal notice, here is a blessing:
12492
**
12493
**    May you do good and not evil.
12494
**    May you find forgiveness for yourself and forgive others.
12495
**    May you share freely, never taking more than you give.
12496
**
12497
******************************************************************************
12498
**
12499
** This file contains OS interface code that is common to all
12500
** architectures.
12501
*/
12502
#define _SQLITE_OS_C_ 1
12503
#undef _SQLITE_OS_C_
12504
12505
/*
12506
** The default SQLite sqlite3_vfs implementations do not allocate
12507
** memory (actually, os_unix.c allocates a small amount of memory
12508
** from within OsOpen()), but some third-party implementations may.
12509
** So we test the effects of a malloc() failing and the sqlite3OsXXX()
12510
** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
12511
**
12512
** The following functions are instrumented for malloc() failure 
12513
** testing:
12514
**
12515
**     sqlite3OsOpen()
12516
**     sqlite3OsRead()
12517
**     sqlite3OsWrite()
12518
**     sqlite3OsSync()
12519
**     sqlite3OsLock()
12520
**
12521
*/
12522
#if defined(SQLITE_TEST) && (SQLITE_OS_WIN==0)
12523
  #define DO_OS_MALLOC_TEST(x) if (!x || !sqlite3IsMemJournal(x)) {     \
12524
    void *pTstAlloc = sqlite3Malloc(10);                             \
12525
    if (!pTstAlloc) return SQLITE_IOERR_NOMEM;                       \
12526
    sqlite3_free(pTstAlloc);                                         \
12527
  }
12528
#else
12529
  #define DO_OS_MALLOC_TEST(x)
12530
#endif
12531
12532
/*
12533
** The following routines are convenience wrappers around methods
12534
** of the sqlite3_file object.  This is mostly just syntactic sugar. All
12535
** of this would be completely automatic if SQLite were coded using
12536
** C++ instead of plain old C.
12537
*/
12538
SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
12539
  int rc = SQLITE_OK;
12540
  if( pId->pMethods ){
12541
    rc = pId->pMethods->xClose(pId);
12542
    pId->pMethods = 0;
12543
  }
12544
  return rc;
12545
}
12546
SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
12547
  DO_OS_MALLOC_TEST(id);
12548
  return id->pMethods->xRead(id, pBuf, amt, offset);
12549
}
12550
SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
12551
  DO_OS_MALLOC_TEST(id);
12552
  return id->pMethods->xWrite(id, pBuf, amt, offset);
12553
}
12554
SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
12555
  return id->pMethods->xTruncate(id, size);
12556
}
12557
SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
12558
  DO_OS_MALLOC_TEST(id);
12559
  return id->pMethods->xSync(id, flags);
12560
}
12561
SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
12562
  DO_OS_MALLOC_TEST(id);
12563
  return id->pMethods->xFileSize(id, pSize);
12564
}
12565
SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
12566
  DO_OS_MALLOC_TEST(id);
12567
  return id->pMethods->xLock(id, lockType);
12568
}
12569
SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
12570
  return id->pMethods->xUnlock(id, lockType);
12571
}
12572
SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
12573
  DO_OS_MALLOC_TEST(id);
12574
  return id->pMethods->xCheckReservedLock(id, pResOut);
12575
}
12576
SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
12577
  return id->pMethods->xFileControl(id, op, pArg);
12578
}
12579
SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
12580
  int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
12581
  return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
12582
}
12583
SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
12584
  return id->pMethods->xDeviceCharacteristics(id);
12585
}
12586
12587
/*
12588
** The next group of routines are convenience wrappers around the
12589
** VFS methods.
12590
*/
12591
SQLITE_PRIVATE int sqlite3OsOpen(
12592
  sqlite3_vfs *pVfs, 
12593
  const char *zPath, 
12594
  sqlite3_file *pFile, 
12595
  int flags, 
12596
  int *pFlagsOut
12597
){
12598
  int rc;
12599
  DO_OS_MALLOC_TEST(0);
12600
  /* 0x7f3f is a mask of SQLITE_OPEN_ flags that are valid to be passed
12601
  ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
12602
  ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
12603
  ** reaching the VFS. */
12604
  rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x7f3f, pFlagsOut);
12605
  assert( rc==SQLITE_OK || pFile->pMethods==0 );
12606
  return rc;
12607
}
12608
SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
12609
  return pVfs->xDelete(pVfs, zPath, dirSync);
12610
}
12611
SQLITE_PRIVATE int sqlite3OsAccess(
12612
  sqlite3_vfs *pVfs, 
12613
  const char *zPath, 
12614
  int flags, 
12615
  int *pResOut
12616
){
12617
  DO_OS_MALLOC_TEST(0);
12618
  return pVfs->xAccess(pVfs, zPath, flags, pResOut);
12619
}
12620
SQLITE_PRIVATE int sqlite3OsFullPathname(
12621
  sqlite3_vfs *pVfs, 
12622
  const char *zPath, 
12623
  int nPathOut, 
12624
  char *zPathOut
12625
){
12626
  zPathOut[0] = 0;
12627
  return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
12628
}
12629
#ifndef SQLITE_OMIT_LOAD_EXTENSION
12630
SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
12631
  return pVfs->xDlOpen(pVfs, zPath);
12632
}
12633
SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
12634
  pVfs->xDlError(pVfs, nByte, zBufOut);
12635
}
12636
SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
12637
  return pVfs->xDlSym(pVfs, pHdle, zSym);
12638
}
12639
SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
12640
  pVfs->xDlClose(pVfs, pHandle);
12641
}
12642
#endif /* SQLITE_OMIT_LOAD_EXTENSION */
12643
SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
12644
  return pVfs->xRandomness(pVfs, nByte, zBufOut);
12645
}
12646
SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
12647
  return pVfs->xSleep(pVfs, nMicro);
12648
}
12649
SQLITE_PRIVATE int sqlite3OsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
12650
  return pVfs->xCurrentTime(pVfs, pTimeOut);
12651
}
12652
12653
SQLITE_PRIVATE int sqlite3OsOpenMalloc(
12654
  sqlite3_vfs *pVfs, 
12655
  const char *zFile, 
12656
  sqlite3_file **ppFile, 
12657
  int flags,
12658
  int *pOutFlags
12659
){
12660
  int rc = SQLITE_NOMEM;
12661
  sqlite3_file *pFile;
12662
  pFile = (sqlite3_file *)sqlite3Malloc(pVfs->szOsFile);
12663
  if( pFile ){
12664
    rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
12665
    if( rc!=SQLITE_OK ){
12666
      sqlite3_free(pFile);
12667
    }else{
12668
      *ppFile = pFile;
12669
    }
12670
  }
12671
  return rc;
12672
}
12673
SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
12674
  int rc = SQLITE_OK;
12675
  assert( pFile );
12676
  rc = sqlite3OsClose(pFile);
12677
  sqlite3_free(pFile);
12678
  return rc;
12679
}
12680
12681
/*
12682
** This function is a wrapper around the OS specific implementation of
12683
** sqlite3_os_init(). The purpose of the wrapper is to provide the
12684
** ability to simulate a malloc failure, so that the handling of an
12685
** error in sqlite3_os_init() by the upper layers can be tested.
12686
*/
12687
SQLITE_PRIVATE int sqlite3OsInit(void){
12688
  void *p = sqlite3_malloc(10);
12689
  if( p==0 ) return SQLITE_NOMEM;
12690
  sqlite3_free(p);
12691
  return sqlite3_os_init();
12692
}
12693
12694
/*
12695
** The list of all registered VFS implementations.
12696
*/
12697
static sqlite3_vfs * SQLITE_WSD vfsList = 0;
12698
#define vfsList GLOBAL(sqlite3_vfs *, vfsList)
12699
12700
/*
12701
** Locate a VFS by name.  If no name is given, simply return the
12702
** first VFS on the list.
12703
*/
12704
SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
12705
  sqlite3_vfs *pVfs = 0;
12706
#if SQLITE_THREADSAFE
12707
  sqlite3_mutex *mutex;
12708
#endif
12709
#ifndef SQLITE_OMIT_AUTOINIT
12710
  int rc = sqlite3_initialize();
12711
  if( rc ) return 0;
12712
#endif
12713
#if SQLITE_THREADSAFE
12714
  mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
12715
#endif
12716
  sqlite3_mutex_enter(mutex);
12717
  for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
12718
    if( zVfs==0 ) break;
12719
    if( strcmp(zVfs, pVfs->zName)==0 ) break;
12720
  }
12721
  sqlite3_mutex_leave(mutex);
12722
  return pVfs;
12723
}
12724
12725
/*
12726
** Unlink a VFS from the linked list
12727
*/
12728
static void vfsUnlink(sqlite3_vfs *pVfs){
12729
  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
12730
  if( pVfs==0 ){
12731
    /* No-op */
12732
  }else if( vfsList==pVfs ){
12733
    vfsList = pVfs->pNext;
12734
  }else if( vfsList ){
12735
    sqlite3_vfs *p = vfsList;
12736
    while( p->pNext && p->pNext!=pVfs ){
12737
      p = p->pNext;
12738
    }
12739
    if( p->pNext==pVfs ){
12740
      p->pNext = pVfs->pNext;
12741
    }
12742
  }
12743
}
12744
12745
/*
12746
** Register a VFS with the system.  It is harmless to register the same
12747
** VFS multiple times.  The new VFS becomes the default if makeDflt is
12748
** true.
12749
*/
12750
SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
12751
  sqlite3_mutex *mutex = 0;
12752
#ifndef SQLITE_OMIT_AUTOINIT
12753
  int rc = sqlite3_initialize();
12754
  if( rc ) return rc;
12755
#endif
12756
  mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
12757
  sqlite3_mutex_enter(mutex);
12758
  vfsUnlink(pVfs);
12759
  if( makeDflt || vfsList==0 ){
12760
    pVfs->pNext = vfsList;
12761
    vfsList = pVfs;
12762
  }else{
12763
    pVfs->pNext = vfsList->pNext;
12764
    vfsList->pNext = pVfs;
12765
  }
12766
  assert(vfsList);
12767
  sqlite3_mutex_leave(mutex);
12768
  return SQLITE_OK;
12769
}
12770
12771
/*
12772
** Unregister a VFS so that it is no longer accessible.
12773
*/
12774
SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
12775
#if SQLITE_THREADSAFE
12776
  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
12777
#endif
12778
  sqlite3_mutex_enter(mutex);
12779
  vfsUnlink(pVfs);
12780
  sqlite3_mutex_leave(mutex);
12781
  return SQLITE_OK;
12782
}
12783
12784
/************** End of os.c **************************************************/
12785
/************** Begin file fault.c *******************************************/
12786
/*
12787
** 2008 Jan 22
12788
**
12789
** The author disclaims copyright to this source code.  In place of
12790
** a legal notice, here is a blessing:
12791
**
12792
**    May you do good and not evil.
12793
**    May you find forgiveness for yourself and forgive others.
12794
**    May you share freely, never taking more than you give.
12795
**
12796
*************************************************************************
12797
**
12798
** This file contains code to support the concept of "benign" 
12799
** malloc failures (when the xMalloc() or xRealloc() method of the
12800
** sqlite3_mem_methods structure fails to allocate a block of memory
12801
** and returns 0). 
12802
**
12803
** Most malloc failures are non-benign. After they occur, SQLite
12804
** abandons the current operation and returns an error code (usually
12805
** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
12806
** fatal. For example, if a malloc fails while resizing a hash table, this 
12807
** is completely recoverable simply by not carrying out the resize. The 
12808
** hash table will continue to function normally.  So a malloc failure 
12809
** during a hash table resize is a benign fault.
12810
*/
12811
12812
12813
#ifndef SQLITE_OMIT_BUILTIN_TEST
12814
12815
/*
12816
** Global variables.
12817
*/
12818
typedef struct BenignMallocHooks BenignMallocHooks;
12819
static SQLITE_WSD struct BenignMallocHooks {
12820
  void (*xBenignBegin)(void);
12821
  void (*xBenignEnd)(void);
12822
} sqlite3Hooks = { 0, 0 };
12823
12824
/* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
12825
** structure.  If writable static data is unsupported on the target,
12826
** we have to locate the state vector at run-time.  In the more common
12827
** case where writable static data is supported, wsdHooks can refer directly
12828
** to the "sqlite3Hooks" state vector declared above.
12829
*/
12830
#ifdef SQLITE_OMIT_WSD
12831
# define wsdHooksInit \
12832
  BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
12833
# define wsdHooks x[0]
12834
#else
12835
# define wsdHooksInit
12836
# define wsdHooks sqlite3Hooks
12837
#endif
12838
12839
12840
/*
12841
** Register hooks to call when sqlite3BeginBenignMalloc() and
12842
** sqlite3EndBenignMalloc() are called, respectively.
12843
*/
12844
SQLITE_PRIVATE void sqlite3BenignMallocHooks(
12845
  void (*xBenignBegin)(void),
12846
  void (*xBenignEnd)(void)
12847
){
12848
  wsdHooksInit;
12849
  wsdHooks.xBenignBegin = xBenignBegin;
12850
  wsdHooks.xBenignEnd = xBenignEnd;
12851
}
12852
12853
/*
12854
** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
12855
** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
12856
** indicates that subsequent malloc failures are non-benign.
12857
*/
12858
SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
12859
  wsdHooksInit;
12860
  if( wsdHooks.xBenignBegin ){
12861
    wsdHooks.xBenignBegin();
12862
  }
12863
}
12864
SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
12865
  wsdHooksInit;
12866
  if( wsdHooks.xBenignEnd ){
12867
    wsdHooks.xBenignEnd();
12868
  }
12869
}
12870
12871
#endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
12872
12873
/************** End of fault.c ***********************************************/
12874
/************** Begin file mem0.c ********************************************/
12875
/*
12876
** 2008 October 28
12877
**
12878
** The author disclaims copyright to this source code.  In place of
12879
** a legal notice, here is a blessing:
12880
**
12881
**    May you do good and not evil.
12882
**    May you find forgiveness for yourself and forgive others.
12883
**    May you share freely, never taking more than you give.
12884
**
12885
*************************************************************************
12886
**
12887
** This file contains a no-op memory allocation drivers for use when
12888
** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
12889
** here always fail.  SQLite will not operate with these drivers.  These
12890
** are merely placeholders.  Real drivers must be substituted using
12891
** sqlite3_config() before SQLite will operate.
12892
*/
12893
12894
/*
12895
** This version of the memory allocator is the default.  It is
12896
** used when no other memory allocator is specified using compile-time
12897
** macros.
12898
*/
12899
#ifdef SQLITE_ZERO_MALLOC
12900
12901
/*
12902
** No-op versions of all memory allocation routines
12903
*/
12904
static void *sqlite3MemMalloc(int nByte){ return 0; }
12905
static void sqlite3MemFree(void *pPrior){ return; }
12906
static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
12907
static int sqlite3MemSize(void *pPrior){ return 0; }
12908
static int sqlite3MemRoundup(int n){ return n; }
12909
static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
12910
static void sqlite3MemShutdown(void *NotUsed){ return; }
12911
12912
/*
12913
** This routine is the only routine in this file with external linkage.
12914
**
12915
** Populate the low-level memory allocation function pointers in
12916
** sqlite3GlobalConfig.m with pointers to the routines in this file.
12917
*/
12918
SQLITE_PRIVATE void sqlite3MemSetDefault(void){
12919
  static const sqlite3_mem_methods defaultMethods = {
12920
     sqlite3MemMalloc,
12921
     sqlite3MemFree,
12922
     sqlite3MemRealloc,
12923
     sqlite3MemSize,
12924
     sqlite3MemRoundup,
12925
     sqlite3MemInit,
12926
     sqlite3MemShutdown,
12927
     0
12928
  };
12929
  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
12930
}
12931
12932
#endif /* SQLITE_ZERO_MALLOC */
12933
12934
/************** End of mem0.c ************************************************/
12935
/************** Begin file mem1.c ********************************************/
12936
/*
12937
** 2007 August 14
12938
**
12939
** The author disclaims copyright to this source code.  In place of
12940
** a legal notice, here is a blessing:
12941
**
12942
**    May you do good and not evil.
12943
**    May you find forgiveness for yourself and forgive others.
12944
**    May you share freely, never taking more than you give.
12945
**
12946
*************************************************************************
12947
**
12948
** This file contains low-level memory allocation drivers for when
12949
** SQLite will use the standard C-library malloc/realloc/free interface
12950
** to obtain the memory it needs.
12951
**
12952
** This file contains implementations of the low-level memory allocation
12953
** routines specified in the sqlite3_mem_methods object.
12954
*/
12955
12956
/*
12957
** This version of the memory allocator is the default.  It is
12958
** used when no other memory allocator is specified using compile-time
12959
** macros.
12960
*/
12961
#ifdef SQLITE_SYSTEM_MALLOC
12962
12963
/*
12964
** Like malloc(), but remember the size of the allocation
12965
** so that we can find it later using sqlite3MemSize().
12966
**
12967
** For this low-level routine, we are guaranteed that nByte>0 because
12968
** cases of nByte<=0 will be intercepted and dealt with by higher level
12969
** routines.
12970
*/
12971
static void *sqlite3MemMalloc(int nByte){
12972
  sqlite3_int64 *p;
12973
  assert( nByte>0 );
12974
  nByte = ROUND8(nByte);
12975
  p = malloc( nByte+8 );
12976
  if( p ){
12977
    p[0] = nByte;
12978
    p++;
12979
  }else{
12980
    testcase( sqlite3GlobalConfig.xLog!=0 );
12981
    sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
12982
  }
12983
  return (void *)p;
12984
}
12985
12986
/*
12987
** Like free() but works for allocations obtained from sqlite3MemMalloc()
12988
** or sqlite3MemRealloc().
12989
**
12990
** For this low-level routine, we already know that pPrior!=0 since
12991
** cases where pPrior==0 will have been intecepted and dealt with
12992
** by higher-level routines.
12993
*/
12994
static void sqlite3MemFree(void *pPrior){
12995
  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
12996
  assert( pPrior!=0 );
12997
  p--;
12998
  free(p);
12999
}
13000
13001
/*
13002
** Report the allocated size of a prior return from xMalloc()
13003
** or xRealloc().
13004
*/
13005
static int sqlite3MemSize(void *pPrior){
13006
  sqlite3_int64 *p;
13007
  if( pPrior==0 ) return 0;
13008
  p = (sqlite3_int64*)pPrior;
13009
  p--;
13010
  return (int)p[0];
13011
}
13012
13013
/*
13014
** Like realloc().  Resize an allocation previously obtained from
13015
** sqlite3MemMalloc().
13016
**
13017
** For this low-level interface, we know that pPrior!=0.  Cases where
13018
** pPrior==0 while have been intercepted by higher-level routine and
13019
** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
13020
** cases where nByte<=0 will have been intercepted by higher-level
13021
** routines and redirected to xFree.
13022
*/
13023
static void *sqlite3MemRealloc(void *pPrior, int nByte){
13024
  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
13025
  assert( pPrior!=0 && nByte>0 );
13026
  nByte = ROUND8(nByte);
13027
  p--;
13028
  p = realloc(p, nByte+8 );
13029
  if( p ){
13030
    p[0] = nByte;
13031
    p++;
13032
  }else{
13033
    testcase( sqlite3GlobalConfig.xLog!=0 );
13034
    sqlite3_log(SQLITE_NOMEM,
13035
      "failed memory resize %u to %u bytes",
13036
      sqlite3MemSize(pPrior), nByte);
13037
  }
13038
  return (void*)p;
13039
}
13040
13041
/*
13042
** Round up a request size to the next valid allocation size.
13043
*/
13044
static int sqlite3MemRoundup(int n){
13045
  return ROUND8(n);
13046
}
13047
13048
/*
13049
** Initialize this module.
13050
*/
13051
static int sqlite3MemInit(void *NotUsed){
13052
  UNUSED_PARAMETER(NotUsed);
13053
  return SQLITE_OK;
13054
}
13055
13056
/*
13057
** Deinitialize this module.
13058
*/
13059
static void sqlite3MemShutdown(void *NotUsed){
13060
  UNUSED_PARAMETER(NotUsed);
13061
  return;
13062
}
13063
13064
/*
13065
** This routine is the only routine in this file with external linkage.
13066
**
13067
** Populate the low-level memory allocation function pointers in
13068
** sqlite3GlobalConfig.m with pointers to the routines in this file.
13069
*/
13070
SQLITE_PRIVATE void sqlite3MemSetDefault(void){
13071
  static const sqlite3_mem_methods defaultMethods = {
13072
     sqlite3MemMalloc,
13073
     sqlite3MemFree,
13074
     sqlite3MemRealloc,
13075
     sqlite3MemSize,
13076
     sqlite3MemRoundup,
13077
     sqlite3MemInit,
13078
     sqlite3MemShutdown,
13079
     0
13080
  };
13081
  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
13082
}
13083
13084
#endif /* SQLITE_SYSTEM_MALLOC */
13085
13086
/************** End of mem1.c ************************************************/
13087
/************** Begin file mem2.c ********************************************/
13088
/*
13089
** 2007 August 15
13090
**
13091
** The author disclaims copyright to this source code.  In place of
13092
** a legal notice, here is a blessing:
13093
**
13094
**    May you do good and not evil.
13095
**    May you find forgiveness for yourself and forgive others.
13096
**    May you share freely, never taking more than you give.
13097
**
13098
*************************************************************************
13099
**
13100
** This file contains low-level memory allocation drivers for when
13101
** SQLite will use the standard C-library malloc/realloc/free interface
13102
** to obtain the memory it needs while adding lots of additional debugging
13103
** information to each allocation in order to help detect and fix memory
13104
** leaks and memory usage errors.
13105
**
13106
** This file contains implementations of the low-level memory allocation
13107
** routines specified in the sqlite3_mem_methods object.
13108
*/
13109
13110
/*
13111
** This version of the memory allocator is used only if the
13112
** SQLITE_MEMDEBUG macro is defined
13113
*/
13114
#ifdef SQLITE_MEMDEBUG
13115
13116
/*
13117
** The backtrace functionality is only available with GLIBC
13118
*/
13119
#ifdef __GLIBC__
13120
  extern int backtrace(void**,int);
13121
  extern void backtrace_symbols_fd(void*const*,int,int);
13122
#else
13123
# define backtrace(A,B) 1
13124
# define backtrace_symbols_fd(A,B,C)
13125
#endif
13126
13127
/*
13128
** Each memory allocation looks like this:
13129
**
13130
**  ------------------------------------------------------------------------
13131
**  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
13132
**  ------------------------------------------------------------------------
13133
**
13134
** The application code sees only a pointer to the allocation.  We have
13135
** to back up from the allocation pointer to find the MemBlockHdr.  The
13136
** MemBlockHdr tells us the size of the allocation and the number of
13137
** backtrace pointers.  There is also a guard word at the end of the
13138
** MemBlockHdr.
13139
*/
13140
struct MemBlockHdr {
13141
  i64 iSize;                          /* Size of this allocation */
13142
  struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
13143
  char nBacktrace;                    /* Number of backtraces on this alloc */
13144
  char nBacktraceSlots;               /* Available backtrace slots */
13145
  short nTitle;                       /* Bytes of title; includes '\0' */
13146
  int iForeGuard;                     /* Guard word for sanity */
13147
};
13148
13149
/*
13150
** Guard words
13151
*/
13152
#define FOREGUARD 0x80F5E153
13153
#define REARGUARD 0xE4676B53
13154
13155
/*
13156
** Number of malloc size increments to track.
13157
*/
13158
#define NCSIZE  1000
13159
13160
/*
13161
** All of the static variables used by this module are collected
13162
** into a single structure named "mem".  This is to keep the
13163
** static variables organized and to reduce namespace pollution
13164
** when this module is combined with other in the amalgamation.
13165
*/
13166
static struct {
13167
  
13168
  /*
13169
  ** Mutex to control access to the memory allocation subsystem.
13170
  */
13171
  sqlite3_mutex *mutex;
13172
13173
  /*
13174
  ** Head and tail of a linked list of all outstanding allocations
13175
  */
13176
  struct MemBlockHdr *pFirst;
13177
  struct MemBlockHdr *pLast;
13178
  
13179
  /*
13180
  ** The number of levels of backtrace to save in new allocations.
13181
  */
13182
  int nBacktrace;
13183
  void (*xBacktrace)(int, int, void **);
13184
13185
  /*
13186
  ** Title text to insert in front of each block
13187
  */
13188
  int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
13189
  char zTitle[100];  /* The title text */
13190
13191
  /* 
13192
  ** sqlite3MallocDisallow() increments the following counter.
13193
  ** sqlite3MallocAllow() decrements it.
13194
  */
13195
  int disallow; /* Do not allow memory allocation */
13196
13197
  /*
13198
  ** Gather statistics on the sizes of memory allocations.
13199
  ** nAlloc[i] is the number of allocation attempts of i*8
13200
  ** bytes.  i==NCSIZE is the number of allocation attempts for
13201
  ** sizes more than NCSIZE*8 bytes.
13202
  */
13203
  int nAlloc[NCSIZE];      /* Total number of allocations */
13204
  int nCurrent[NCSIZE];    /* Current number of allocations */
13205
  int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
13206
13207
} mem;
13208
13209
13210
/*
13211
** Adjust memory usage statistics
13212
*/
13213
static void adjustStats(int iSize, int increment){
13214
  int i = ROUND8(iSize)/8;
13215
  if( i>NCSIZE-1 ){
13216
    i = NCSIZE - 1;
13217
  }
13218
  if( increment>0 ){
13219
    mem.nAlloc[i]++;
13220
    mem.nCurrent[i]++;
13221
    if( mem.nCurrent[i]>mem.mxCurrent[i] ){
13222
      mem.mxCurrent[i] = mem.nCurrent[i];
13223
    }
13224
  }else{
13225
    mem.nCurrent[i]--;
13226
    assert( mem.nCurrent[i]>=0 );
13227
  }
13228
}
13229
13230
/*
13231
** Given an allocation, find the MemBlockHdr for that allocation.
13232
**
13233
** This routine checks the guards at either end of the allocation and
13234
** if they are incorrect it asserts.
13235
*/
13236
static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
13237
  struct MemBlockHdr *p;
13238
  int *pInt;
13239
  u8 *pU8;
13240
  int nReserve;
13241
13242
  p = (struct MemBlockHdr*)pAllocation;
13243
  p--;
13244
  assert( p->iForeGuard==(int)FOREGUARD );
13245
  nReserve = ROUND8(p->iSize);
13246
  pInt = (int*)pAllocation;
13247
  pU8 = (u8*)pAllocation;
13248
  assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
13249
  /* This checks any of the "extra" bytes allocated due
13250
  ** to rounding up to an 8 byte boundary to ensure 
13251
  ** they haven't been overwritten.
13252
  */
13253
  while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
13254
  return p;
13255
}
13256
13257
/*
13258
** Return the number of bytes currently allocated at address p.
13259
*/
13260
static int sqlite3MemSize(void *p){
13261
  struct MemBlockHdr *pHdr;
13262
  if( !p ){
13263
    return 0;
13264
  }
13265
  pHdr = sqlite3MemsysGetHeader(p);
13266
  return pHdr->iSize;
13267
}
13268
13269
/*
13270
** Initialize the memory allocation subsystem.
13271
*/
13272
static int sqlite3MemInit(void *NotUsed){
13273
  UNUSED_PARAMETER(NotUsed);
13274
  assert( (sizeof(struct MemBlockHdr)&7) == 0 );
13275
  if( !sqlite3GlobalConfig.bMemstat ){
13276
    /* If memory status is enabled, then the malloc.c wrapper will already
13277
    ** hold the STATIC_MEM mutex when the routines here are invoked. */
13278
    mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
13279
  }
13280
  return SQLITE_OK;
13281
}
13282
13283
/*
13284
** Deinitialize the memory allocation subsystem.
13285
*/
13286
static void sqlite3MemShutdown(void *NotUsed){
13287
  UNUSED_PARAMETER(NotUsed);
13288
  mem.mutex = 0;
13289
}
13290
13291
/*
13292
** Round up a request size to the next valid allocation size.
13293
*/
13294
static int sqlite3MemRoundup(int n){
13295
  return ROUND8(n);
13296
}
13297
13298
/*
13299
** Fill a buffer with pseudo-random bytes.  This is used to preset
13300
** the content of a new memory allocation to unpredictable values and
13301
** to clear the content of a freed allocation to unpredictable values.
13302
*/
13303
static void randomFill(char *pBuf, int nByte){
13304
  unsigned int x, y, r;
13305
  x = SQLITE_PTR_TO_INT(pBuf);
13306
  y = nByte | 1;
13307
  while( nByte >= 4 ){
13308
    x = (x>>1) ^ (-(x&1) & 0xd0000001);
13309
    y = y*1103515245 + 12345;
13310
    r = x ^ y;
13311
    *(int*)pBuf = r;
13312
    pBuf += 4;
13313
    nByte -= 4;
13314
  }
13315
  while( nByte-- > 0 ){
13316
    x = (x>>1) ^ (-(x&1) & 0xd0000001);
13317
    y = y*1103515245 + 12345;
13318
    r = x ^ y;
13319
    *(pBuf++) = r & 0xff;
13320
  }
13321
}
13322
13323
/*
13324
** Allocate nByte bytes of memory.
13325
*/
13326
static void *sqlite3MemMalloc(int nByte){
13327
  struct MemBlockHdr *pHdr;
13328
  void **pBt;
13329
  char *z;
13330
  int *pInt;
13331
  void *p = 0;
13332
  int totalSize;
13333
  int nReserve;
13334
  sqlite3_mutex_enter(mem.mutex);
13335
  assert( mem.disallow==0 );
13336
  nReserve = ROUND8(nByte);
13337
  totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
13338
               mem.nBacktrace*sizeof(void*) + mem.nTitle;
13339
  p = malloc(totalSize);
13340
  if( p ){
13341
    z = p;
13342
    pBt = (void**)&z[mem.nTitle];
13343
    pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
13344
    pHdr->pNext = 0;
13345
    pHdr->pPrev = mem.pLast;
13346
    if( mem.pLast ){
13347
      mem.pLast->pNext = pHdr;
13348
    }else{
13349
      mem.pFirst = pHdr;
13350
    }
13351
    mem.pLast = pHdr;
13352
    pHdr->iForeGuard = FOREGUARD;
13353
    pHdr->nBacktraceSlots = mem.nBacktrace;
13354
    pHdr->nTitle = mem.nTitle;
13355
    if( mem.nBacktrace ){
13356
      void *aAddr[40];
13357
      pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
13358
      memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
13359
      assert(pBt[0]);
13360
      if( mem.xBacktrace ){
13361
        mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
13362
      }
13363
    }else{
13364
      pHdr->nBacktrace = 0;
13365
    }
13366
    if( mem.nTitle ){
13367
      memcpy(z, mem.zTitle, mem.nTitle);
13368
    }
13369
    pHdr->iSize = nByte;
13370
    adjustStats(nByte, +1);
13371
    pInt = (int*)&pHdr[1];
13372
    pInt[nReserve/sizeof(int)] = REARGUARD;
13373
    randomFill((char*)pInt, nByte);
13374
    memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
13375
    p = (void*)pInt;
13376
  }
13377
  sqlite3_mutex_leave(mem.mutex);
13378
  return p; 
13379
}
13380
13381
/*
13382
** Free memory.
13383
*/
13384
static void sqlite3MemFree(void *pPrior){
13385
  struct MemBlockHdr *pHdr;
13386
  void **pBt;
13387
  char *z;
13388
  assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0 
13389
       || mem.mutex!=0 );
13390
  pHdr = sqlite3MemsysGetHeader(pPrior);
13391
  pBt = (void**)pHdr;
13392
  pBt -= pHdr->nBacktraceSlots;
13393
  sqlite3_mutex_enter(mem.mutex);
13394
  if( pHdr->pPrev ){
13395
    assert( pHdr->pPrev->pNext==pHdr );
13396
    pHdr->pPrev->pNext = pHdr->pNext;
13397
  }else{
13398
    assert( mem.pFirst==pHdr );
13399
    mem.pFirst = pHdr->pNext;
13400
  }
13401
  if( pHdr->pNext ){
13402
    assert( pHdr->pNext->pPrev==pHdr );
13403
    pHdr->pNext->pPrev = pHdr->pPrev;
13404
  }else{
13405
    assert( mem.pLast==pHdr );
13406
    mem.pLast = pHdr->pPrev;
13407
  }
13408
  z = (char*)pBt;
13409
  z -= pHdr->nTitle;
13410
  adjustStats(pHdr->iSize, -1);
13411
  randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
13412
                pHdr->iSize + sizeof(int) + pHdr->nTitle);
13413
  free(z);
13414
  sqlite3_mutex_leave(mem.mutex);  
13415
}
13416
13417
/*
13418
** Change the size of an existing memory allocation.
13419
**
13420
** For this debugging implementation, we *always* make a copy of the
13421
** allocation into a new place in memory.  In this way, if the 
13422
** higher level code is using pointer to the old allocation, it is 
13423
** much more likely to break and we are much more liking to find
13424
** the error.
13425
*/
13426
static void *sqlite3MemRealloc(void *pPrior, int nByte){
13427
  struct MemBlockHdr *pOldHdr;
13428
  void *pNew;
13429
  assert( mem.disallow==0 );
13430
  pOldHdr = sqlite3MemsysGetHeader(pPrior);
13431
  pNew = sqlite3MemMalloc(nByte);
13432
  if( pNew ){
13433
    memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
13434
    if( nByte>pOldHdr->iSize ){
13435
      randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
13436
    }
13437
    sqlite3MemFree(pPrior);
13438
  }
13439
  return pNew;
13440
}
13441
13442
/*
13443
** Populate the low-level memory allocation function pointers in
13444
** sqlite3GlobalConfig.m with pointers to the routines in this file.
13445
*/
13446
SQLITE_PRIVATE void sqlite3MemSetDefault(void){
13447
  static const sqlite3_mem_methods defaultMethods = {
13448
     sqlite3MemMalloc,
13449
     sqlite3MemFree,
13450
     sqlite3MemRealloc,
13451
     sqlite3MemSize,
13452
     sqlite3MemRoundup,
13453
     sqlite3MemInit,
13454
     sqlite3MemShutdown,
13455
     0
13456
  };
13457
  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
13458
}
13459
13460
/*
13461
** Set the number of backtrace levels kept for each allocation.
13462
** A value of zero turns off backtracing.  The number is always rounded
13463
** up to a multiple of 2.
13464
*/
13465
SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
13466
  if( depth<0 ){ depth = 0; }
13467
  if( depth>20 ){ depth = 20; }
13468
  depth = (depth+1)&0xfe;
13469
  mem.nBacktrace = depth;
13470
}
13471
13472
SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
13473
  mem.xBacktrace = xBacktrace;
13474
}
13475
13476
/*
13477
** Set the title string for subsequent allocations.
13478
*/
13479
SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
13480
  unsigned int n = sqlite3Strlen30(zTitle) + 1;
13481
  sqlite3_mutex_enter(mem.mutex);
13482
  if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
13483
  memcpy(mem.zTitle, zTitle, n);
13484
  mem.zTitle[n] = 0;
13485
  mem.nTitle = ROUND8(n);
13486
  sqlite3_mutex_leave(mem.mutex);
13487
}
13488
13489
SQLITE_PRIVATE void sqlite3MemdebugSync(){
13490
  struct MemBlockHdr *pHdr;
13491
  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
13492
    void **pBt = (void**)pHdr;
13493
    pBt -= pHdr->nBacktraceSlots;
13494
    mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
13495
  }
13496
}
13497
13498
/*
13499
** Open the file indicated and write a log of all unfreed memory 
13500
** allocations into that log.
13501
*/
13502
SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
13503
  FILE *out;
13504
  struct MemBlockHdr *pHdr;
13505
  void **pBt;
13506
  int i;
13507
  out = fopen(zFilename, "w");
13508
  if( out==0 ){
13509
    fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
13510
                    zFilename);
13511
    return;
13512
  }
13513
  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
13514
    char *z = (char*)pHdr;
13515
    z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
13516
    fprintf(out, "**** %lld bytes at %p from %s ****\n", 
13517
            pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
13518
    if( pHdr->nBacktrace ){
13519
      fflush(out);
13520
      pBt = (void**)pHdr;
13521
      pBt -= pHdr->nBacktraceSlots;
13522
      backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
13523
      fprintf(out, "\n");
13524
    }
13525
  }
13526
  fprintf(out, "COUNTS:\n");
13527
  for(i=0; i<NCSIZE-1; i++){
13528
    if( mem.nAlloc[i] ){
13529
      fprintf(out, "   %5d: %10d %10d %10d\n", 
13530
            i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
13531
    }
13532
  }
13533
  if( mem.nAlloc[NCSIZE-1] ){
13534
    fprintf(out, "   %5d: %10d %10d %10d\n",
13535
             NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
13536
             mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
13537
  }
13538
  fclose(out);
13539
}
13540
13541
/*
13542
** Return the number of times sqlite3MemMalloc() has been called.
13543
*/
13544
SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
13545
  int i;
13546
  int nTotal = 0;
13547
  for(i=0; i<NCSIZE; i++){
13548
    nTotal += mem.nAlloc[i];
13549
  }
13550
  return nTotal;
13551
}
13552
13553
13554
#endif /* SQLITE_MEMDEBUG */
13555
13556
/************** End of mem2.c ************************************************/
13557
/************** Begin file mem3.c ********************************************/
13558
/*
13559
** 2007 October 14
13560
**
13561
** The author disclaims copyright to this source code.  In place of
13562
** a legal notice, here is a blessing:
13563
**
13564
**    May you do good and not evil.
13565
**    May you find forgiveness for yourself and forgive others.
13566
**    May you share freely, never taking more than you give.
13567
**
13568
*************************************************************************
13569
** This file contains the C functions that implement a memory
13570
** allocation subsystem for use by SQLite. 
13571
**
13572
** This version of the memory allocation subsystem omits all
13573
** use of malloc(). The SQLite user supplies a block of memory
13574
** before calling sqlite3_initialize() from which allocations
13575
** are made and returned by the xMalloc() and xRealloc() 
13576
** implementations. Once sqlite3_initialize() has been called,
13577
** the amount of memory available to SQLite is fixed and cannot
13578
** be changed.
13579
**
13580
** This version of the memory allocation subsystem is included
13581
** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
13582
*/
13583
13584
/*
13585
** This version of the memory allocator is only built into the library
13586
** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
13587
** mean that the library will use a memory-pool by default, just that
13588
** it is available. The mempool allocator is activated by calling
13589
** sqlite3_config().
13590
*/
13591
#ifdef SQLITE_ENABLE_MEMSYS3
13592
13593
/*
13594
** Maximum size (in Mem3Blocks) of a "small" chunk.
13595
*/
13596
#define MX_SMALL 10
13597
13598
13599
/*
13600
** Number of freelist hash slots
13601
*/
13602
#define N_HASH  61
13603
13604
/*
13605
** A memory allocation (also called a "chunk") consists of two or 
13606
** more blocks where each block is 8 bytes.  The first 8 bytes are 
13607
** a header that is not returned to the user.
13608
**
13609
** A chunk is two or more blocks that is either checked out or
13610
** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
13611
** size of the allocation in blocks if the allocation is free.
13612
** The u.hdr.size4x&1 bit is true if the chunk is checked out and
13613
** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
13614
** is true if the previous chunk is checked out and false if the
13615
** previous chunk is free.  The u.hdr.prevSize field is the size of
13616
** the previous chunk in blocks if the previous chunk is on the
13617
** freelist. If the previous chunk is checked out, then
13618
** u.hdr.prevSize can be part of the data for that chunk and should
13619
** not be read or written.
13620
**
13621
** We often identify a chunk by its index in mem3.aPool[].  When
13622
** this is done, the chunk index refers to the second block of
13623
** the chunk.  In this way, the first chunk has an index of 1.
13624
** A chunk index of 0 means "no such chunk" and is the equivalent
13625
** of a NULL pointer.
13626
**
13627
** The second block of free chunks is of the form u.list.  The
13628
** two fields form a double-linked list of chunks of related sizes.
13629
** Pointers to the head of the list are stored in mem3.aiSmall[] 
13630
** for smaller chunks and mem3.aiHash[] for larger chunks.
13631
**
13632
** The second block of a chunk is user data if the chunk is checked 
13633
** out.  If a chunk is checked out, the user data may extend into
13634
** the u.hdr.prevSize value of the following chunk.
13635
*/
13636
typedef struct Mem3Block Mem3Block;
13637
struct Mem3Block {
13638
  union {
13639
    struct {
13640
      u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
13641
      u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
13642
    } hdr;
13643
    struct {
13644
      u32 next;       /* Index in mem3.aPool[] of next free chunk */
13645
      u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
13646
    } list;
13647
  } u;
13648
};
13649
13650
/*
13651
** All of the static variables used by this module are collected
13652
** into a single structure named "mem3".  This is to keep the
13653
** static variables organized and to reduce namespace pollution
13654
** when this module is combined with other in the amalgamation.
13655
*/
13656
static SQLITE_WSD struct Mem3Global {
13657
  /*
13658
  ** Memory available for allocation. nPool is the size of the array
13659
  ** (in Mem3Blocks) pointed to by aPool less 2.
13660
  */
13661
  u32 nPool;
13662
  Mem3Block *aPool;
13663
13664
  /*
13665
  ** True if we are evaluating an out-of-memory callback.
13666
  */
13667
  int alarmBusy;
13668
  
13669
  /*
13670
  ** Mutex to control access to the memory allocation subsystem.
13671
  */
13672
  sqlite3_mutex *mutex;
13673
  
13674
  /*
13675
  ** The minimum amount of free space that we have seen.
13676
  */
13677
  u32 mnMaster;
13678
13679
  /*
13680
  ** iMaster is the index of the master chunk.  Most new allocations
13681
  ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
13682
  ** of the current master.  iMaster is 0 if there is not master chunk.
13683
  ** The master chunk is not in either the aiHash[] or aiSmall[].
13684
  */
13685
  u32 iMaster;
13686
  u32 szMaster;
13687
13688
  /*
13689
  ** Array of lists of free blocks according to the block size 
13690
  ** for smaller chunks, or a hash on the block size for larger
13691
  ** chunks.
13692
  */
13693
  u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
13694
  u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
13695
} mem3 = { 97535575 };
13696
13697
#define mem3 GLOBAL(struct Mem3Global, mem3)
13698
13699
/*
13700
** Unlink the chunk at mem3.aPool[i] from list it is currently
13701
** on.  *pRoot is the list that i is a member of.
13702
*/
13703
static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
13704
  u32 next = mem3.aPool[i].u.list.next;
13705
  u32 prev = mem3.aPool[i].u.list.prev;
13706
  assert( sqlite3_mutex_held(mem3.mutex) );
13707
  if( prev==0 ){
13708
    *pRoot = next;
13709
  }else{
13710
    mem3.aPool[prev].u.list.next = next;
13711
  }
13712
  if( next ){
13713
    mem3.aPool[next].u.list.prev = prev;
13714
  }
13715
  mem3.aPool[i].u.list.next = 0;
13716
  mem3.aPool[i].u.list.prev = 0;
13717
}
13718
13719
/*
13720
** Unlink the chunk at index i from 
13721
** whatever list is currently a member of.
13722
*/
13723
static void memsys3Unlink(u32 i){
13724
  u32 size, hash;
13725
  assert( sqlite3_mutex_held(mem3.mutex) );
13726
  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
13727
  assert( i>=1 );
13728
  size = mem3.aPool[i-1].u.hdr.size4x/4;
13729
  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
13730
  assert( size>=2 );
13731
  if( size <= MX_SMALL ){
13732
    memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
13733
  }else{
13734
    hash = size % N_HASH;
13735
    memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
13736
  }
13737
}
13738
13739
/*
13740
** Link the chunk at mem3.aPool[i] so that is on the list rooted
13741
** at *pRoot.
13742
*/
13743
static void memsys3LinkIntoList(u32 i, u32 *pRoot){
13744
  assert( sqlite3_mutex_held(mem3.mutex) );
13745
  mem3.aPool[i].u.list.next = *pRoot;
13746
  mem3.aPool[i].u.list.prev = 0;
13747
  if( *pRoot ){
13748
    mem3.aPool[*pRoot].u.list.prev = i;
13749
  }
13750
  *pRoot = i;
13751
}
13752
13753
/*
13754
** Link the chunk at index i into either the appropriate
13755
** small chunk list, or into the large chunk hash table.
13756
*/
13757
static void memsys3Link(u32 i){
13758
  u32 size, hash;
13759
  assert( sqlite3_mutex_held(mem3.mutex) );
13760
  assert( i>=1 );
13761
  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
13762
  size = mem3.aPool[i-1].u.hdr.size4x/4;
13763
  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
13764
  assert( size>=2 );
13765
  if( size <= MX_SMALL ){
13766
    memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
13767
  }else{
13768
    hash = size % N_HASH;
13769
    memsys3LinkIntoList(i, &mem3.aiHash[hash]);
13770
  }
13771
}
13772
13773
/*
13774
** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
13775
** will already be held (obtained by code in malloc.c) if
13776
** sqlite3GlobalConfig.bMemStat is true.
13777
*/
13778
static void memsys3Enter(void){
13779
  if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
13780
    mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
13781
  }
13782
  sqlite3_mutex_enter(mem3.mutex);
13783
}
13784
static void memsys3Leave(void){
13785
  sqlite3_mutex_leave(mem3.mutex);
13786
}
13787
13788
/*
13789
** Called when we are unable to satisfy an allocation of nBytes.
13790
*/
13791
static void memsys3OutOfMemory(int nByte){
13792
  if( !mem3.alarmBusy ){
13793
    mem3.alarmBusy = 1;
13794
    assert( sqlite3_mutex_held(mem3.mutex) );
13795
    sqlite3_mutex_leave(mem3.mutex);
13796
    sqlite3_release_memory(nByte);
13797
    sqlite3_mutex_enter(mem3.mutex);
13798
    mem3.alarmBusy = 0;
13799
  }
13800
}
13801
13802
13803
/*
13804
** Chunk i is a free chunk that has been unlinked.  Adjust its 
13805
** size parameters for check-out and return a pointer to the 
13806
** user portion of the chunk.
13807
*/
13808
static void *memsys3Checkout(u32 i, u32 nBlock){
13809
  u32 x;
13810
  assert( sqlite3_mutex_held(mem3.mutex) );
13811
  assert( i>=1 );
13812
  assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
13813
  assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
13814
  x = mem3.aPool[i-1].u.hdr.size4x;
13815
  mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
13816
  mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
13817
  mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
13818
  return &mem3.aPool[i];
13819
}
13820
13821
/*
13822
** Carve a piece off of the end of the mem3.iMaster free chunk.
13823
** Return a pointer to the new allocation.  Or, if the master chunk
13824
** is not large enough, return 0.
13825
*/
13826
static void *memsys3FromMaster(u32 nBlock){
13827
  assert( sqlite3_mutex_held(mem3.mutex) );
13828
  assert( mem3.szMaster>=nBlock );
13829
  if( nBlock>=mem3.szMaster-1 ){
13830
    /* Use the entire master */
13831
    void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
13832
    mem3.iMaster = 0;
13833
    mem3.szMaster = 0;
13834
    mem3.mnMaster = 0;
13835
    return p;
13836
  }else{
13837
    /* Split the master block.  Return the tail. */
13838
    u32 newi, x;
13839
    newi = mem3.iMaster + mem3.szMaster - nBlock;
13840
    assert( newi > mem3.iMaster+1 );
13841
    mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
13842
    mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
13843
    mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
13844
    mem3.szMaster -= nBlock;
13845
    mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
13846
    x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
13847
    mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
13848
    if( mem3.szMaster < mem3.mnMaster ){
13849
      mem3.mnMaster = mem3.szMaster;
13850
    }
13851
    return (void*)&mem3.aPool[newi];
13852
  }
13853
}
13854
13855
/*
13856
** *pRoot is the head of a list of free chunks of the same size
13857
** or same size hash.  In other words, *pRoot is an entry in either
13858
** mem3.aiSmall[] or mem3.aiHash[].  
13859
**
13860
** This routine examines all entries on the given list and tries
13861
** to coalesce each entries with adjacent free chunks.  
13862
**
13863
** If it sees a chunk that is larger than mem3.iMaster, it replaces 
13864
** the current mem3.iMaster with the new larger chunk.  In order for
13865
** this mem3.iMaster replacement to work, the master chunk must be
13866
** linked into the hash tables.  That is not the normal state of
13867
** affairs, of course.  The calling routine must link the master
13868
** chunk before invoking this routine, then must unlink the (possibly
13869
** changed) master chunk once this routine has finished.
13870
*/
13871
static void memsys3Merge(u32 *pRoot){
13872
  u32 iNext, prev, size, i, x;
13873
13874
  assert( sqlite3_mutex_held(mem3.mutex) );
13875
  for(i=*pRoot; i>0; i=iNext){
13876
    iNext = mem3.aPool[i].u.list.next;
13877
    size = mem3.aPool[i-1].u.hdr.size4x;
13878
    assert( (size&1)==0 );
13879
    if( (size&2)==0 ){
13880
      memsys3UnlinkFromList(i, pRoot);
13881
      assert( i > mem3.aPool[i-1].u.hdr.prevSize );
13882
      prev = i - mem3.aPool[i-1].u.hdr.prevSize;
13883
      if( prev==iNext ){
13884
        iNext = mem3.aPool[prev].u.list.next;
13885
      }
13886
      memsys3Unlink(prev);
13887
      size = i + size/4 - prev;
13888
      x = mem3.aPool[prev-1].u.hdr.size4x & 2;
13889
      mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
13890
      mem3.aPool[prev+size-1].u.hdr.prevSize = size;
13891
      memsys3Link(prev);
13892
      i = prev;
13893
    }else{
13894
      size /= 4;
13895
    }
13896
    if( size>mem3.szMaster ){
13897
      mem3.iMaster = i;
13898
      mem3.szMaster = size;
13899
    }
13900
  }
13901
}
13902
13903
/*
13904
** Return a block of memory of at least nBytes in size.
13905
** Return NULL if unable.
13906
**
13907
** This function assumes that the necessary mutexes, if any, are
13908
** already held by the caller. Hence "Unsafe".
13909
*/
13910
static void *memsys3MallocUnsafe(int nByte){
13911
  u32 i;
13912
  u32 nBlock;
13913
  u32 toFree;
13914
13915
  assert( sqlite3_mutex_held(mem3.mutex) );
13916
  assert( sizeof(Mem3Block)==8 );
13917
  if( nByte<=12 ){
13918
    nBlock = 2;
13919
  }else{
13920
    nBlock = (nByte + 11)/8;
13921
  }
13922
  assert( nBlock>=2 );
13923
13924
  /* STEP 1:
13925
  ** Look for an entry of the correct size in either the small
13926
  ** chunk table or in the large chunk hash table.  This is
13927
  ** successful most of the time (about 9 times out of 10).
13928
  */
13929
  if( nBlock <= MX_SMALL ){
13930
    i = mem3.aiSmall[nBlock-2];
13931
    if( i>0 ){
13932
      memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
13933
      return memsys3Checkout(i, nBlock);
13934
    }
13935
  }else{
13936
    int hash = nBlock % N_HASH;
13937
    for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
13938
      if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
13939
        memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
13940
        return memsys3Checkout(i, nBlock);
13941
      }
13942
    }
13943
  }
13944
13945
  /* STEP 2:
13946
  ** Try to satisfy the allocation by carving a piece off of the end
13947
  ** of the master chunk.  This step usually works if step 1 fails.
13948
  */
13949
  if( mem3.szMaster>=nBlock ){
13950
    return memsys3FromMaster(nBlock);
13951
  }
13952
13953
13954
  /* STEP 3:  
13955
  ** Loop through the entire memory pool.  Coalesce adjacent free
13956
  ** chunks.  Recompute the master chunk as the largest free chunk.
13957
  ** Then try again to satisfy the allocation by carving a piece off
13958
  ** of the end of the master chunk.  This step happens very
13959
  ** rarely (we hope!)
13960
  */
13961
  for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
13962
    memsys3OutOfMemory(toFree);
13963
    if( mem3.iMaster ){
13964
      memsys3Link(mem3.iMaster);
13965
      mem3.iMaster = 0;
13966
      mem3.szMaster = 0;
13967
    }
13968
    for(i=0; i<N_HASH; i++){
13969
      memsys3Merge(&mem3.aiHash[i]);
13970
    }
13971
    for(i=0; i<MX_SMALL-1; i++){
13972
      memsys3Merge(&mem3.aiSmall[i]);
13973
    }
13974
    if( mem3.szMaster ){
13975
      memsys3Unlink(mem3.iMaster);
13976
      if( mem3.szMaster>=nBlock ){
13977
        return memsys3FromMaster(nBlock);
13978
      }
13979
    }
13980
  }
13981
13982
  /* If none of the above worked, then we fail. */
13983
  return 0;
13984
}
13985
13986
/*
13987
** Free an outstanding memory allocation.
13988
**
13989
** This function assumes that the necessary mutexes, if any, are
13990
** already held by the caller. Hence "Unsafe".
13991
*/
13992
void memsys3FreeUnsafe(void *pOld){
13993
  Mem3Block *p = (Mem3Block*)pOld;
13994
  int i;
13995
  u32 size, x;
13996
  assert( sqlite3_mutex_held(mem3.mutex) );
13997
  assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
13998
  i = p - mem3.aPool;
13999
  assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
14000
  size = mem3.aPool[i-1].u.hdr.size4x/4;
14001
  assert( i+size<=mem3.nPool+1 );
14002
  mem3.aPool[i-1].u.hdr.size4x &= ~1;
14003
  mem3.aPool[i+size-1].u.hdr.prevSize = size;
14004
  mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
14005
  memsys3Link(i);
14006
14007
  /* Try to expand the master using the newly freed chunk */
14008
  if( mem3.iMaster ){
14009
    while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
14010
      size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
14011
      mem3.iMaster -= size;
14012
      mem3.szMaster += size;
14013
      memsys3Unlink(mem3.iMaster);
14014
      x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
14015
      mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
14016
      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
14017
    }
14018
    x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
14019
    while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
14020
      memsys3Unlink(mem3.iMaster+mem3.szMaster);
14021
      mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
14022
      mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
14023
      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
14024
    }
14025
  }
14026
}
14027
14028
/*
14029
** Return the size of an outstanding allocation, in bytes.  The
14030
** size returned omits the 8-byte header overhead.  This only
14031
** works for chunks that are currently checked out.
14032
*/
14033
static int memsys3Size(void *p){
14034
  Mem3Block *pBlock;
14035
  if( p==0 ) return 0;
14036
  pBlock = (Mem3Block*)p;
14037
  assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
14038
  return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
14039
}
14040
14041
/*
14042
** Round up a request size to the next valid allocation size.
14043
*/
14044
static int memsys3Roundup(int n){
14045
  if( n<=12 ){
14046
    return 12;
14047
  }else{
14048
    return ((n+11)&~7) - 4;
14049
  }
14050
}
14051
14052
/*
14053
** Allocate nBytes of memory.
14054
*/
14055
static void *memsys3Malloc(int nBytes){
14056
  sqlite3_int64 *p;
14057
  assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
14058
  memsys3Enter();
14059
  p = memsys3MallocUnsafe(nBytes);
14060
  memsys3Leave();
14061
  return (void*)p; 
14062
}
14063
14064
/*
14065
** Free memory.
14066
*/
14067
void memsys3Free(void *pPrior){
14068
  assert( pPrior );
14069
  memsys3Enter();
14070
  memsys3FreeUnsafe(pPrior);
14071
  memsys3Leave();
14072
}
14073
14074
/*
14075
** Change the size of an existing memory allocation
14076
*/
14077
void *memsys3Realloc(void *pPrior, int nBytes){
14078
  int nOld;
14079
  void *p;
14080
  if( pPrior==0 ){
14081
    return sqlite3_malloc(nBytes);
14082
  }
14083
  if( nBytes<=0 ){
14084
    sqlite3_free(pPrior);
14085
    return 0;
14086
  }
14087
  nOld = memsys3Size(pPrior);
14088
  if( nBytes<=nOld && nBytes>=nOld-128 ){
14089
    return pPrior;
14090
  }
14091
  memsys3Enter();
14092
  p = memsys3MallocUnsafe(nBytes);
14093
  if( p ){
14094
    if( nOld<nBytes ){
14095
      memcpy(p, pPrior, nOld);
14096
    }else{
14097
      memcpy(p, pPrior, nBytes);
14098
    }
14099
    memsys3FreeUnsafe(pPrior);
14100
  }
14101
  memsys3Leave();
14102
  return p;
14103
}
14104
14105
/*
14106
** Initialize this module.
14107
*/
14108
static int memsys3Init(void *NotUsed){
14109
  UNUSED_PARAMETER(NotUsed);
14110
  if( !sqlite3GlobalConfig.pHeap ){
14111
    return SQLITE_ERROR;
14112
  }
14113
14114
  /* Store a pointer to the memory block in global structure mem3. */
14115
  assert( sizeof(Mem3Block)==8 );
14116
  mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
14117
  mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
14118
14119
  /* Initialize the master block. */
14120
  mem3.szMaster = mem3.nPool;
14121
  mem3.mnMaster = mem3.szMaster;
14122
  mem3.iMaster = 1;
14123
  mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
14124
  mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
14125
  mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
14126
14127
  return SQLITE_OK;
14128
}
14129
14130
/*
14131
** Deinitialize this module.
14132
*/
14133
static void memsys3Shutdown(void *NotUsed){
14134
  UNUSED_PARAMETER(NotUsed);
14135
  mem3.mutex = 0;
14136
  return;
14137
}
14138
14139
14140
14141
/*
14142
** Open the file indicated and write a log of all unfreed memory 
14143
** allocations into that log.
14144
*/
14145
SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
14146
#ifdef SQLITE_DEBUG
14147
  FILE *out;
14148
  u32 i, j;
14149
  u32 size;
14150
  if( zFilename==0 || zFilename[0]==0 ){
14151
    out = stdout;
14152
  }else{
14153
    out = fopen(zFilename, "w");
14154
    if( out==0 ){
14155
      fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
14156
                      zFilename);
14157
      return;
14158
    }
14159
  }
14160
  memsys3Enter();
14161
  fprintf(out, "CHUNKS:\n");
14162
  for(i=1; i<=mem3.nPool; i+=size/4){
14163
    size = mem3.aPool[i-1].u.hdr.size4x;
14164
    if( size/4<=1 ){
14165
      fprintf(out, "%p size error\n", &mem3.aPool[i]);
14166
      assert( 0 );
14167
      break;
14168
    }
14169
    if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
14170
      fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
14171
      assert( 0 );
14172
      break;
14173
    }
14174
    if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
14175
      fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
14176
      assert( 0 );
14177
      break;
14178
    }
14179
    if( size&1 ){
14180
      fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
14181
    }else{
14182
      fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
14183
                  i==mem3.iMaster ? " **master**" : "");
14184
    }
14185
  }
14186
  for(i=0; i<MX_SMALL-1; i++){
14187
    if( mem3.aiSmall[i]==0 ) continue;
14188
    fprintf(out, "small(%2d):", i);
14189
    for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
14190
      fprintf(out, " %p(%d)", &mem3.aPool[j],
14191
              (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
14192
    }
14193
    fprintf(out, "\n"); 
14194
  }
14195
  for(i=0; i<N_HASH; i++){
14196
    if( mem3.aiHash[i]==0 ) continue;
14197
    fprintf(out, "hash(%2d):", i);
14198
    for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
14199
      fprintf(out, " %p(%d)", &mem3.aPool[j],
14200
              (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
14201
    }
14202
    fprintf(out, "\n"); 
14203
  }
14204
  fprintf(out, "master=%d\n", mem3.iMaster);
14205
  fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
14206
  fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
14207
  sqlite3_mutex_leave(mem3.mutex);
14208
  if( out==stdout ){
14209
    fflush(stdout);
14210
  }else{
14211
    fclose(out);
14212
  }
14213
#else
14214
  UNUSED_PARAMETER(zFilename);
14215
#endif
14216
}
14217
14218
/*
14219
** This routine is the only routine in this file with external 
14220
** linkage.
14221
**
14222
** Populate the low-level memory allocation function pointers in
14223
** sqlite3GlobalConfig.m with pointers to the routines in this file. The
14224
** arguments specify the block of memory to manage.
14225
**
14226
** This routine is only called by sqlite3_config(), and therefore
14227
** is not required to be threadsafe (it is not).
14228
*/
14229
SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
14230
  static const sqlite3_mem_methods mempoolMethods = {
14231
     memsys3Malloc,
14232
     memsys3Free,
14233
     memsys3Realloc,
14234
     memsys3Size,
14235
     memsys3Roundup,
14236
     memsys3Init,
14237
     memsys3Shutdown,
14238
     0
14239
  };
14240
  return &mempoolMethods;
14241
}
14242
14243
#endif /* SQLITE_ENABLE_MEMSYS3 */
14244
14245
/************** End of mem3.c ************************************************/
14246
/************** Begin file mem5.c ********************************************/
14247
/*
14248
** 2007 October 14
14249
**
14250
** The author disclaims copyright to this source code.  In place of
14251
** a legal notice, here is a blessing:
14252
**
14253
**    May you do good and not evil.
14254
**    May you find forgiveness for yourself and forgive others.
14255
**    May you share freely, never taking more than you give.
14256
**
14257
*************************************************************************
14258
** This file contains the C functions that implement a memory
14259
** allocation subsystem for use by SQLite. 
14260
**
14261
** This version of the memory allocation subsystem omits all
14262
** use of malloc(). The application gives SQLite a block of memory
14263
** before calling sqlite3_initialize() from which allocations
14264
** are made and returned by the xMalloc() and xRealloc() 
14265
** implementations. Once sqlite3_initialize() has been called,
14266
** the amount of memory available to SQLite is fixed and cannot
14267
** be changed.
14268
**
14269
** This version of the memory allocation subsystem is included
14270
** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
14271
**
14272
** This memory allocator uses the following algorithm:
14273
**
14274
**   1.  All memory allocations sizes are rounded up to a power of 2.
14275
**
14276
**   2.  If two adjacent free blocks are the halves of a larger block,
14277
**       then the two blocks are coalesed into the single larger block.
14278
**
14279
**   3.  New memory is allocated from the first available free block.
14280
**
14281
** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
14282
** Concerning Dynamic Storage Allocation". Journal of the Association for
14283
** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
14284
** 
14285
** Let n be the size of the largest allocation divided by the minimum
14286
** allocation size (after rounding all sizes up to a power of 2.)  Let M
14287
** be the maximum amount of memory ever outstanding at one time.  Let
14288
** N be the total amount of memory available for allocation.  Robson
14289
** proved that this memory allocator will never breakdown due to 
14290
** fragmentation as long as the following constraint holds:
14291
**
14292
**      N >=  M*(1 + log2(n)/2) - n + 1
14293
**
14294
** The sqlite3_status() logic tracks the maximum values of n and M so
14295
** that an application can, at any time, verify this constraint.
14296
*/
14297
14298
/*
14299
** This version of the memory allocator is used only when 
14300
** SQLITE_ENABLE_MEMSYS5 is defined.
14301
*/
14302
#ifdef SQLITE_ENABLE_MEMSYS5
14303
14304
/*
14305
** A minimum allocation is an instance of the following structure.
14306
** Larger allocations are an array of these structures where the
14307
** size of the array is a power of 2.
14308
**
14309
** The size of this object must be a power of two.  That fact is
14310
** verified in memsys5Init().
14311
*/
14312
typedef struct Mem5Link Mem5Link;
14313
struct Mem5Link {
14314
  int next;       /* Index of next free chunk */
14315
  int prev;       /* Index of previous free chunk */
14316
};
14317
14318
/*
14319
** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
14320
** mem5.szAtom is always at least 8 and 32-bit integers are used,
14321
** it is not actually possible to reach this limit.
14322
*/
14323
#define LOGMAX 30
14324
14325
/*
14326
** Masks used for mem5.aCtrl[] elements.
14327
*/
14328
#define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
14329
#define CTRL_FREE     0x20    /* True if not checked out */
14330
14331
/*
14332
** All of the static variables used by this module are collected
14333
** into a single structure named "mem5".  This is to keep the
14334
** static variables organized and to reduce namespace pollution
14335
** when this module is combined with other in the amalgamation.
14336
*/
14337
static SQLITE_WSD struct Mem5Global {
14338
  /*
14339
  ** Memory available for allocation
14340
  */
14341
  int szAtom;      /* Smallest possible allocation in bytes */
14342
  int nBlock;      /* Number of szAtom sized blocks in zPool */
14343
  u8 *zPool;       /* Memory available to be allocated */
14344
  
14345
  /*
14346
  ** Mutex to control access to the memory allocation subsystem.
14347
  */
14348
  sqlite3_mutex *mutex;
14349
14350
  /*
14351
  ** Performance statistics
14352
  */
14353
  u64 nAlloc;         /* Total number of calls to malloc */
14354
  u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
14355
  u64 totalExcess;    /* Total internal fragmentation */
14356
  u32 currentOut;     /* Current checkout, including internal fragmentation */
14357
  u32 currentCount;   /* Current number of distinct checkouts */
14358
  u32 maxOut;         /* Maximum instantaneous currentOut */
14359
  u32 maxCount;       /* Maximum instantaneous currentCount */
14360
  u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
14361
  
14362
  /*
14363
  ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
14364
  ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
14365
  ** and so forth.
14366
  */
14367
  int aiFreelist[LOGMAX+1];
14368
14369
  /*
14370
  ** Space for tracking which blocks are checked out and the size
14371
  ** of each block.  One byte per block.
14372
  */
14373
  u8 *aCtrl;
14374
14375
} mem5 = { 0 };
14376
14377
/*
14378
** Access the static variable through a macro for SQLITE_OMIT_WSD
14379
*/
14380
#define mem5 GLOBAL(struct Mem5Global, mem5)
14381
14382
/*
14383
** Assuming mem5.zPool is divided up into an array of Mem5Link
14384
** structures, return a pointer to the idx-th such lik.
14385
*/
14386
#define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
14387
14388
/*
14389
** Unlink the chunk at mem5.aPool[i] from list it is currently
14390
** on.  It should be found on mem5.aiFreelist[iLogsize].
14391
*/
14392
static void memsys5Unlink(int i, int iLogsize){
14393
  int next, prev;
14394
  assert( i>=0 && i<mem5.nBlock );
14395
  assert( iLogsize>=0 && iLogsize<=LOGMAX );
14396
  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
14397
14398
  next = MEM5LINK(i)->next;
14399
  prev = MEM5LINK(i)->prev;
14400
  if( prev<0 ){
14401
    mem5.aiFreelist[iLogsize] = next;
14402
  }else{
14403
    MEM5LINK(prev)->next = next;
14404
  }
14405
  if( next>=0 ){
14406
    MEM5LINK(next)->prev = prev;
14407
  }
14408
}
14409
14410
/*
14411
** Link the chunk at mem5.aPool[i] so that is on the iLogsize
14412
** free list.
14413
*/
14414
static void memsys5Link(int i, int iLogsize){
14415
  int x;
14416
  assert( sqlite3_mutex_held(mem5.mutex) );
14417
  assert( i>=0 && i<mem5.nBlock );
14418
  assert( iLogsize>=0 && iLogsize<=LOGMAX );
14419
  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
14420
14421
  x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
14422
  MEM5LINK(i)->prev = -1;
14423
  if( x>=0 ){
14424
    assert( x<mem5.nBlock );
14425
    MEM5LINK(x)->prev = i;
14426
  }
14427
  mem5.aiFreelist[iLogsize] = i;
14428
}
14429
14430
/*
14431
** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
14432
** will already be held (obtained by code in malloc.c) if
14433
** sqlite3GlobalConfig.bMemStat is true.
14434
*/
14435
static void memsys5Enter(void){
14436
  sqlite3_mutex_enter(mem5.mutex);
14437
}
14438
static void memsys5Leave(void){
14439
  sqlite3_mutex_leave(mem5.mutex);
14440
}
14441
14442
/*
14443
** Return the size of an outstanding allocation, in bytes.  The
14444
** size returned omits the 8-byte header overhead.  This only
14445
** works for chunks that are currently checked out.
14446
*/
14447
static int memsys5Size(void *p){
14448
  int iSize = 0;
14449
  if( p ){
14450
    int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
14451
    assert( i>=0 && i<mem5.nBlock );
14452
    iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
14453
  }
14454
  return iSize;
14455
}
14456
14457
/*
14458
** Find the first entry on the freelist iLogsize.  Unlink that
14459
** entry and return its index. 
14460
*/
14461
static int memsys5UnlinkFirst(int iLogsize){
14462
  int i;
14463
  int iFirst;
14464
14465
  assert( iLogsize>=0 && iLogsize<=LOGMAX );
14466
  i = iFirst = mem5.aiFreelist[iLogsize];
14467
  assert( iFirst>=0 );
14468
  while( i>0 ){
14469
    if( i<iFirst ) iFirst = i;
14470
    i = MEM5LINK(i)->next;
14471
  }
14472
  memsys5Unlink(iFirst, iLogsize);
14473
  return iFirst;
14474
}
14475
14476
/*
14477
** Return a block of memory of at least nBytes in size.
14478
** Return NULL if unable.  Return NULL if nBytes==0.
14479
**
14480
** The caller guarantees that nByte positive.
14481
**
14482
** The caller has obtained a mutex prior to invoking this
14483
** routine so there is never any chance that two or more
14484
** threads can be in this routine at the same time.
14485
*/
14486
static void *memsys5MallocUnsafe(int nByte){
14487
  int i;           /* Index of a mem5.aPool[] slot */
14488
  int iBin;        /* Index into mem5.aiFreelist[] */
14489
  int iFullSz;     /* Size of allocation rounded up to power of 2 */
14490
  int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
14491
14492
  /* nByte must be a positive */
14493
  assert( nByte>0 );
14494
14495
  /* Keep track of the maximum allocation request.  Even unfulfilled
14496
  ** requests are counted */
14497
  if( (u32)nByte>mem5.maxRequest ){
14498
    mem5.maxRequest = nByte;
14499
  }
14500
14501
  /* Abort if the requested allocation size is larger than the largest
14502
  ** power of two that we can represent using 32-bit signed integers.
14503
  */
14504
  if( nByte > 0x40000000 ){
14505
    return 0;
14506
  }
14507
14508
  /* Round nByte up to the next valid power of two */
14509
  for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
14510
14511
  /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
14512
  ** block.  If not, then split a block of the next larger power of
14513
  ** two in order to create a new free block of size iLogsize.
14514
  */
14515
  for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
14516
  if( iBin>LOGMAX ){
14517
    testcase( sqlite3GlobalConfig.xLog!=0 );
14518
    sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
14519
    return 0;
14520
  }
14521
  i = memsys5UnlinkFirst(iBin);
14522
  while( iBin>iLogsize ){
14523
    int newSize;
14524
14525
    iBin--;
14526
    newSize = 1 << iBin;
14527
    mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
14528
    memsys5Link(i+newSize, iBin);
14529
  }
14530
  mem5.aCtrl[i] = iLogsize;
14531
14532
  /* Update allocator performance statistics. */
14533
  mem5.nAlloc++;
14534
  mem5.totalAlloc += iFullSz;
14535
  mem5.totalExcess += iFullSz - nByte;
14536
  mem5.currentCount++;
14537
  mem5.currentOut += iFullSz;
14538
  if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
14539
  if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
14540
14541
  /* Return a pointer to the allocated memory. */
14542
  return (void*)&mem5.zPool[i*mem5.szAtom];
14543
}
14544
14545
/*
14546
** Free an outstanding memory allocation.
14547
*/
14548
static void memsys5FreeUnsafe(void *pOld){
14549
  u32 size, iLogsize;
14550
  int iBlock;
14551
14552
  /* Set iBlock to the index of the block pointed to by pOld in 
14553
  ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
14554
  */
14555
  iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
14556
14557
  /* Check that the pointer pOld points to a valid, non-free block. */
14558
  assert( iBlock>=0 && iBlock<mem5.nBlock );
14559
  assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
14560
  assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
14561
14562
  iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
14563
  size = 1<<iLogsize;
14564
  assert( iBlock+size-1<(u32)mem5.nBlock );
14565
14566
  mem5.aCtrl[iBlock] |= CTRL_FREE;
14567
  mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
14568
  assert( mem5.currentCount>0 );
14569
  assert( mem5.currentOut>=(size*mem5.szAtom) );
14570
  mem5.currentCount--;
14571
  mem5.currentOut -= size*mem5.szAtom;
14572
  assert( mem5.currentOut>0 || mem5.currentCount==0 );
14573
  assert( mem5.currentCount>0 || mem5.currentOut==0 );
14574
14575
  mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
14576
  while( ALWAYS(iLogsize<LOGMAX) ){
14577
    int iBuddy;
14578
    if( (iBlock>>iLogsize) & 1 ){
14579
      iBuddy = iBlock - size;
14580
    }else{
14581
      iBuddy = iBlock + size;
14582
    }
14583
    assert( iBuddy>=0 );
14584
    if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
14585
    if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
14586
    memsys5Unlink(iBuddy, iLogsize);
14587
    iLogsize++;
14588
    if( iBuddy<iBlock ){
14589
      mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
14590
      mem5.aCtrl[iBlock] = 0;
14591
      iBlock = iBuddy;
14592
    }else{
14593
      mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
14594
      mem5.aCtrl[iBuddy] = 0;
14595
    }
14596
    size *= 2;
14597
  }
14598
  memsys5Link(iBlock, iLogsize);
14599
}
14600
14601
/*
14602
** Allocate nBytes of memory
14603
*/
14604
static void *memsys5Malloc(int nBytes){
14605
  sqlite3_int64 *p = 0;
14606
  if( nBytes>0 ){
14607
    memsys5Enter();
14608
    p = memsys5MallocUnsafe(nBytes);
14609
    memsys5Leave();
14610
  }
14611
  return (void*)p; 
14612
}
14613
14614
/*
14615
** Free memory.
14616
**
14617
** The outer layer memory allocator prevents this routine from
14618
** being called with pPrior==0.
14619
*/
14620
static void memsys5Free(void *pPrior){
14621
  assert( pPrior!=0 );
14622
  memsys5Enter();
14623
  memsys5FreeUnsafe(pPrior);
14624
  memsys5Leave();  
14625
}
14626
14627
/*
14628
** Change the size of an existing memory allocation.
14629
**
14630
** The outer layer memory allocator prevents this routine from
14631
** being called with pPrior==0.  
14632
**
14633
** nBytes is always a value obtained from a prior call to
14634
** memsys5Round().  Hence nBytes is always a non-negative power
14635
** of two.  If nBytes==0 that means that an oversize allocation
14636
** (an allocation larger than 0x40000000) was requested and this
14637
** routine should return 0 without freeing pPrior.
14638
*/
14639
static void *memsys5Realloc(void *pPrior, int nBytes){
14640
  int nOld;
14641
  void *p;
14642
  assert( pPrior!=0 );
14643
  assert( (nBytes&(nBytes-1))==0 );
14644
  assert( nBytes>=0 );
14645
  if( nBytes==0 ){
14646
    return 0;
14647
  }
14648
  nOld = memsys5Size(pPrior);
14649
  if( nBytes<=nOld ){
14650
    return pPrior;
14651
  }
14652
  memsys5Enter();
14653
  p = memsys5MallocUnsafe(nBytes);
14654
  if( p ){
14655
    memcpy(p, pPrior, nOld);
14656
    memsys5FreeUnsafe(pPrior);
14657
  }
14658
  memsys5Leave();
14659
  return p;
14660
}
14661
14662
/*
14663
** Round up a request size to the next valid allocation size.  If
14664
** the allocation is too large to be handled by this allocation system,
14665
** return 0.
14666
**
14667
** All allocations must be a power of two and must be expressed by a
14668
** 32-bit signed integer.  Hence the largest allocation is 0x40000000
14669
** or 1073741824 bytes.
14670
*/
14671
static int memsys5Roundup(int n){
14672
  int iFullSz;
14673
  if( n > 0x40000000 ) return 0;
14674
  for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
14675
  return iFullSz;
14676
}
14677
14678
/*
14679
** Return the ceiling of the logarithm base 2 of iValue.
14680
**
14681
** Examples:   memsys5Log(1) -> 0
14682
**             memsys5Log(2) -> 1
14683
**             memsys5Log(4) -> 2
14684
**             memsys5Log(5) -> 3
14685
**             memsys5Log(8) -> 3
14686
**             memsys5Log(9) -> 4
14687
*/
14688
static int memsys5Log(int iValue){
14689
  int iLog;
14690
  for(iLog=0; (1<<iLog)<iValue; iLog++);
14691
  return iLog;
14692
}
14693
14694
/*
14695
** Initialize the memory allocator.
14696
**
14697
** This routine is not threadsafe.  The caller must be holding a mutex
14698
** to prevent multiple threads from entering at the same time.
14699
*/
14700
static int memsys5Init(void *NotUsed){
14701
  int ii;            /* Loop counter */
14702
  int nByte;         /* Number of bytes of memory available to this allocator */
14703
  u8 *zByte;         /* Memory usable by this allocator */
14704
  int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
14705
  int iOffset;       /* An offset into mem5.aCtrl[] */
14706
14707
  UNUSED_PARAMETER(NotUsed);
14708
14709
  /* For the purposes of this routine, disable the mutex */
14710
  mem5.mutex = 0;
14711
14712
  /* The size of a Mem5Link object must be a power of two.  Verify that
14713
  ** this is case.
14714
  */
14715
  assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
14716
14717
  nByte = sqlite3GlobalConfig.nHeap;
14718
  zByte = (u8*)sqlite3GlobalConfig.pHeap;
14719
  assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
14720
14721
  nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
14722
  mem5.szAtom = (1<<nMinLog);
14723
  while( (int)sizeof(Mem5Link)>mem5.szAtom ){
14724
    mem5.szAtom = mem5.szAtom << 1;
14725
  }
14726
14727
  mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
14728
  mem5.zPool = zByte;
14729
  mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
14730
14731
  for(ii=0; ii<=LOGMAX; ii++){
14732
    mem5.aiFreelist[ii] = -1;
14733
  }
14734
14735
  iOffset = 0;
14736
  for(ii=LOGMAX; ii>=0; ii--){
14737
    int nAlloc = (1<<ii);
14738
    if( (iOffset+nAlloc)<=mem5.nBlock ){
14739
      mem5.aCtrl[iOffset] = ii | CTRL_FREE;
14740
      memsys5Link(iOffset, ii);
14741
      iOffset += nAlloc;
14742
    }
14743
    assert((iOffset+nAlloc)>mem5.nBlock);
14744
  }
14745
14746
  /* If a mutex is required for normal operation, allocate one */
14747
  if( sqlite3GlobalConfig.bMemstat==0 ){
14748
    mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
14749
  }
14750
14751
  return SQLITE_OK;
14752
}
14753
14754
/*
14755
** Deinitialize this module.
14756
*/
14757
static void memsys5Shutdown(void *NotUsed){
14758
  UNUSED_PARAMETER(NotUsed);
14759
  mem5.mutex = 0;
14760
  return;
14761
}
14762
14763
#ifdef SQLITE_TEST
14764
/*
14765
** Open the file indicated and write a log of all unfreed memory 
14766
** allocations into that log.
14767
*/
14768
SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
14769
  FILE *out;
14770
  int i, j, n;
14771
  int nMinLog;
14772
14773
  if( zFilename==0 || zFilename[0]==0 ){
14774
    out = stdout;
14775
  }else{
14776
    out = fopen(zFilename, "w");
14777
    if( out==0 ){
14778
      fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
14779
                      zFilename);
14780
      return;
14781
    }
14782
  }
14783
  memsys5Enter();
14784
  nMinLog = memsys5Log(mem5.szAtom);
14785
  for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
14786
    for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
14787
    fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
14788
  }
14789
  fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
14790
  fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
14791
  fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
14792
  fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
14793
  fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
14794
  fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
14795
  fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
14796
  fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
14797
  memsys5Leave();
14798
  if( out==stdout ){
14799
    fflush(stdout);
14800
  }else{
14801
    fclose(out);
14802
  }
14803
}
14804
#endif
14805
14806
/*
14807
** This routine is the only routine in this file with external 
14808
** linkage. It returns a pointer to a static sqlite3_mem_methods
14809
** struct populated with the memsys5 methods.
14810
*/
14811
SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
14812
  static const sqlite3_mem_methods memsys5Methods = {
14813
     memsys5Malloc,
14814
     memsys5Free,
14815
     memsys5Realloc,
14816
     memsys5Size,
14817
     memsys5Roundup,
14818
     memsys5Init,
14819
     memsys5Shutdown,
14820
     0
14821
  };
14822
  return &memsys5Methods;
14823
}
14824
14825
#endif /* SQLITE_ENABLE_MEMSYS5 */
14826
14827
/************** End of mem5.c ************************************************/
14828
/************** Begin file mutex.c *******************************************/
14829
/*
14830
** 2007 August 14
14831
**
14832
** The author disclaims copyright to this source code.  In place of
14833
** a legal notice, here is a blessing:
14834
**
14835
**    May you do good and not evil.
14836
**    May you find forgiveness for yourself and forgive others.
14837
**    May you share freely, never taking more than you give.
14838
**
14839
*************************************************************************
14840
** This file contains the C functions that implement mutexes.
14841
**
14842
** This file contains code that is common across all mutex implementations.
14843
*/
14844
14845
#if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
14846
/*
14847
** For debugging purposes, record when the mutex subsystem is initialized
14848
** and uninitialized so that we can assert() if there is an attempt to
14849
** allocate a mutex while the system is uninitialized.
14850
*/
14851
static SQLITE_WSD int mutexIsInit = 0;
14852
#endif /* SQLITE_DEBUG */
14853
14854
14855
#ifndef SQLITE_MUTEX_OMIT
14856
/*
14857
** Initialize the mutex system.
14858
*/
14859
SQLITE_PRIVATE int sqlite3MutexInit(void){ 
14860
  int rc = SQLITE_OK;
14861
  if( sqlite3GlobalConfig.bCoreMutex ){
14862
    if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
14863
      /* If the xMutexAlloc method has not been set, then the user did not
14864
      ** install a mutex implementation via sqlite3_config() prior to 
14865
      ** sqlite3_initialize() being called. This block copies pointers to
14866
      ** the default implementation into the sqlite3GlobalConfig structure.
14867
      */
14868
      sqlite3_mutex_methods *pFrom = sqlite3DefaultMutex();
14869
      sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
14870
14871
      memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
14872
      memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
14873
             sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
14874
      pTo->xMutexAlloc = pFrom->xMutexAlloc;
14875
    }
14876
    rc = sqlite3GlobalConfig.mutex.xMutexInit();
14877
  }
14878
14879
#ifdef SQLITE_DEBUG
14880
  GLOBAL(int, mutexIsInit) = 1;
14881
#endif
14882
14883
  return rc;
14884
}
14885
14886
/*
14887
** Shutdown the mutex system. This call frees resources allocated by
14888
** sqlite3MutexInit().
14889
*/
14890
SQLITE_PRIVATE int sqlite3MutexEnd(void){
14891
  int rc = SQLITE_OK;
14892
  if( sqlite3GlobalConfig.mutex.xMutexEnd ){
14893
    rc = sqlite3GlobalConfig.mutex.xMutexEnd();
14894
  }
14895
14896
#ifdef SQLITE_DEBUG
14897
  GLOBAL(int, mutexIsInit) = 0;
14898
#endif
14899
14900
  return rc;
14901
}
14902
14903
/*
14904
** Retrieve a pointer to a static mutex or allocate a new dynamic one.
14905
*/
14906
SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
14907
#ifndef SQLITE_OMIT_AUTOINIT
14908
  if( sqlite3_initialize() ) return 0;
14909
#endif
14910
  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
14911
}
14912
14913
SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
14914
  if( !sqlite3GlobalConfig.bCoreMutex ){
14915
    return 0;
14916
  }
14917
  assert( GLOBAL(int, mutexIsInit) );
14918
  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
14919
}
14920
14921
/*
14922
** Free a dynamic mutex.
14923
*/
14924
SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
14925
  if( p ){
14926
    sqlite3GlobalConfig.mutex.xMutexFree(p);
14927
  }
14928
}
14929
14930
/*
14931
** Obtain the mutex p. If some other thread already has the mutex, block
14932
** until it can be obtained.
14933
*/
14934
SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
14935
  if( p ){
14936
    sqlite3GlobalConfig.mutex.xMutexEnter(p);
14937
  }
14938
}
14939
14940
/*
14941
** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
14942
** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
14943
*/
14944
SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
14945
  int rc = SQLITE_OK;
14946
  if( p ){
14947
    return sqlite3GlobalConfig.mutex.xMutexTry(p);
14948
  }
14949
  return rc;
14950
}
14951
14952
/*
14953
** The sqlite3_mutex_leave() routine exits a mutex that was previously
14954
** entered by the same thread.  The behavior is undefined if the mutex 
14955
** is not currently entered. If a NULL pointer is passed as an argument
14956
** this function is a no-op.
14957
*/
14958
SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
14959
  if( p ){
14960
    sqlite3GlobalConfig.mutex.xMutexLeave(p);
14961
  }
14962
}
14963
14964
#ifndef NDEBUG
14965
/*
14966
** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
14967
** intended for use inside assert() statements.
14968
*/
14969
SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
14970
  return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
14971
}
14972
SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
14973
  return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
14974
}
14975
#endif
14976
14977
#endif /* SQLITE_MUTEX_OMIT */
14978
14979
/************** End of mutex.c ***********************************************/
14980
/************** Begin file mutex_noop.c **************************************/
14981
/*
14982
** 2008 October 07
14983
**
14984
** The author disclaims copyright to this source code.  In place of
14985
** a legal notice, here is a blessing:
14986
**
14987
**    May you do good and not evil.
14988
**    May you find forgiveness for yourself and forgive others.
14989
**    May you share freely, never taking more than you give.
14990
**
14991
*************************************************************************
14992
** This file contains the C functions that implement mutexes.
14993
**
14994
** This implementation in this file does not provide any mutual
14995
** exclusion and is thus suitable for use only in applications
14996
** that use SQLite in a single thread.  The routines defined
14997
** here are place-holders.  Applications can substitute working
14998
** mutex routines at start-time using the
14999
**
15000
**     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
15001
**
15002
** interface.
15003
**
15004
** If compiled with SQLITE_DEBUG, then additional logic is inserted
15005
** that does error checking on mutexes to make sure they are being
15006
** called correctly.
15007
*/
15008
15009
15010
#if defined(SQLITE_MUTEX_NOOP) && !defined(SQLITE_DEBUG)
15011
/*
15012
** Stub routines for all mutex methods.
15013
**
15014
** This routines provide no mutual exclusion or error checking.
15015
*/
15016
static int noopMutexHeld(sqlite3_mutex *p){ return 1; }
15017
static int noopMutexNotheld(sqlite3_mutex *p){ return 1; }
15018
static int noopMutexInit(void){ return SQLITE_OK; }
15019
static int noopMutexEnd(void){ return SQLITE_OK; }
15020
static sqlite3_mutex *noopMutexAlloc(int id){ return (sqlite3_mutex*)8; }
15021
static void noopMutexFree(sqlite3_mutex *p){ return; }
15022
static void noopMutexEnter(sqlite3_mutex *p){ return; }
15023
static int noopMutexTry(sqlite3_mutex *p){ return SQLITE_OK; }
15024
static void noopMutexLeave(sqlite3_mutex *p){ return; }
15025
15026
SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
15027
  static sqlite3_mutex_methods sMutex = {
15028
    noopMutexInit,
15029
    noopMutexEnd,
15030
    noopMutexAlloc,
15031
    noopMutexFree,
15032
    noopMutexEnter,
15033
    noopMutexTry,
15034
    noopMutexLeave,
15035
15036
    noopMutexHeld,
15037
    noopMutexNotheld
15038
  };
15039
15040
  return &sMutex;
15041
}
15042
#endif /* defined(SQLITE_MUTEX_NOOP) && !defined(SQLITE_DEBUG) */
15043
15044
#if defined(SQLITE_MUTEX_NOOP) && defined(SQLITE_DEBUG)
15045
/*
15046
** In this implementation, error checking is provided for testing
15047
** and debugging purposes.  The mutexes still do not provide any
15048
** mutual exclusion.
15049
*/
15050
15051
/*
15052
** The mutex object
15053
*/
15054
struct sqlite3_mutex {
15055
  int id;     /* The mutex type */
15056
  int cnt;    /* Number of entries without a matching leave */
15057
};
15058
15059
/*
15060
** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15061
** intended for use inside assert() statements.
15062
*/
15063
static int debugMutexHeld(sqlite3_mutex *p){
15064
  return p==0 || p->cnt>0;
15065
}
15066
static int debugMutexNotheld(sqlite3_mutex *p){
15067
  return p==0 || p->cnt==0;
15068
}
15069
15070
/*
15071
** Initialize and deinitialize the mutex subsystem.
15072
*/
15073
static int debugMutexInit(void){ return SQLITE_OK; }
15074
static int debugMutexEnd(void){ return SQLITE_OK; }
15075
15076
/*
15077
** The sqlite3_mutex_alloc() routine allocates a new
15078
** mutex and returns a pointer to it.  If it returns NULL
15079
** that means that a mutex could not be allocated. 
15080
*/
15081
static sqlite3_mutex *debugMutexAlloc(int id){
15082
  static sqlite3_mutex aStatic[6];
15083
  sqlite3_mutex *pNew = 0;
15084
  switch( id ){
15085
    case SQLITE_MUTEX_FAST:
15086
    case SQLITE_MUTEX_RECURSIVE: {
15087
      pNew = sqlite3Malloc(sizeof(*pNew));
15088
      if( pNew ){
15089
        pNew->id = id;
15090
        pNew->cnt = 0;
15091
      }
15092
      break;
15093
    }
15094
    default: {
15095
      assert( id-2 >= 0 );
15096
      assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
15097
      pNew = &aStatic[id-2];
15098
      pNew->id = id;
15099
      break;
15100
    }
15101
  }
15102
  return pNew;
15103
}
15104
15105
/*
15106
** This routine deallocates a previously allocated mutex.
15107
*/
15108
static void debugMutexFree(sqlite3_mutex *p){
15109
  assert( p->cnt==0 );
15110
  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
15111
  sqlite3_free(p);
15112
}
15113
15114
/*
15115
** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
15116
** to enter a mutex.  If another thread is already within the mutex,
15117
** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
15118
** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
15119
** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
15120
** be entered multiple times by the same thread.  In such cases the,
15121
** mutex must be exited an equal number of times before another thread
15122
** can enter.  If the same thread tries to enter any other kind of mutex
15123
** more than once, the behavior is undefined.
15124
*/
15125
static void debugMutexEnter(sqlite3_mutex *p){
15126
  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) );
15127
  p->cnt++;
15128
}
15129
static int debugMutexTry(sqlite3_mutex *p){
15130
  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) );
15131
  p->cnt++;
15132
  return SQLITE_OK;
15133
}
15134
15135
/*
15136
** The sqlite3_mutex_leave() routine exits a mutex that was
15137
** previously entered by the same thread.  The behavior
15138
** is undefined if the mutex is not currently entered or
15139
** is not currently allocated.  SQLite will never do either.
15140
*/
15141
static void debugMutexLeave(sqlite3_mutex *p){
15142
  assert( debugMutexHeld(p) );
15143
  p->cnt--;
15144
  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) );
15145
}
15146
15147
SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
15148
  static sqlite3_mutex_methods sMutex = {
15149
    debugMutexInit,
15150
    debugMutexEnd,
15151
    debugMutexAlloc,
15152
    debugMutexFree,
15153
    debugMutexEnter,
15154
    debugMutexTry,
15155
    debugMutexLeave,
15156
15157
    debugMutexHeld,
15158
    debugMutexNotheld
15159
  };
15160
15161
  return &sMutex;
15162
}
15163
#endif /* defined(SQLITE_MUTEX_NOOP) && defined(SQLITE_DEBUG) */
15164
15165
/************** End of mutex_noop.c ******************************************/
15166
/************** Begin file mutex_os2.c ***************************************/
15167
/*
15168
** 2007 August 28
15169
**
15170
** The author disclaims copyright to this source code.  In place of
15171
** a legal notice, here is a blessing:
15172
**
15173
**    May you do good and not evil.
15174
**    May you find forgiveness for yourself and forgive others.
15175
**    May you share freely, never taking more than you give.
15176
**
15177
*************************************************************************
15178
** This file contains the C functions that implement mutexes for OS/2
15179
*/
15180
15181
/*
15182
** The code in this file is only used if SQLITE_MUTEX_OS2 is defined.
15183
** See the mutex.h file for details.
15184
*/
15185
#ifdef SQLITE_MUTEX_OS2
15186
15187
/********************** OS/2 Mutex Implementation **********************
15188
**
15189
** This implementation of mutexes is built using the OS/2 API.
15190
*/
15191
15192
/*
15193
** The mutex object
15194
** Each recursive mutex is an instance of the following structure.
15195
*/
15196
struct sqlite3_mutex {
15197
  HMTX mutex;       /* Mutex controlling the lock */
15198
  int  id;          /* Mutex type */
15199
  int  nRef;        /* Number of references */
15200
  TID  owner;       /* Thread holding this mutex */
15201
};
15202
15203
#define OS2_MUTEX_INITIALIZER   0,0,0,0
15204
15205
/*
15206
** Initialize and deinitialize the mutex subsystem.
15207
*/
15208
static int os2MutexInit(void){ return SQLITE_OK; }
15209
static int os2MutexEnd(void){ return SQLITE_OK; }
15210
15211
/*
15212
** The sqlite3_mutex_alloc() routine allocates a new
15213
** mutex and returns a pointer to it.  If it returns NULL
15214
** that means that a mutex could not be allocated. 
15215
** SQLite will unwind its stack and return an error.  The argument
15216
** to sqlite3_mutex_alloc() is one of these integer constants:
15217
**
15218
** <ul>
15219
** <li>  SQLITE_MUTEX_FAST               0
15220
** <li>  SQLITE_MUTEX_RECURSIVE          1
15221
** <li>  SQLITE_MUTEX_STATIC_MASTER      2
15222
** <li>  SQLITE_MUTEX_STATIC_MEM         3
15223
** <li>  SQLITE_MUTEX_STATIC_PRNG        4
15224
** </ul>
15225
**
15226
** The first two constants cause sqlite3_mutex_alloc() to create
15227
** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
15228
** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
15229
** The mutex implementation does not need to make a distinction
15230
** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
15231
** not want to.  But SQLite will only request a recursive mutex in
15232
** cases where it really needs one.  If a faster non-recursive mutex
15233
** implementation is available on the host platform, the mutex subsystem
15234
** might return such a mutex in response to SQLITE_MUTEX_FAST.
15235
**
15236
** The other allowed parameters to sqlite3_mutex_alloc() each return
15237
** a pointer to a static preexisting mutex.  Three static mutexes are
15238
** used by the current version of SQLite.  Future versions of SQLite
15239
** may add additional static mutexes.  Static mutexes are for internal
15240
** use by SQLite only.  Applications that use SQLite mutexes should
15241
** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
15242
** SQLITE_MUTEX_RECURSIVE.
15243
**
15244
** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
15245
** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
15246
** returns a different mutex on every call.  But for the static
15247
** mutex types, the same mutex is returned on every call that has
15248
** the same type number.
15249
*/
15250
static sqlite3_mutex *os2MutexAlloc(int iType){
15251
  sqlite3_mutex *p = NULL;
15252
  switch( iType ){
15253
    case SQLITE_MUTEX_FAST:
15254
    case SQLITE_MUTEX_RECURSIVE: {
15255
      p = sqlite3MallocZero( sizeof(*p) );
15256
      if( p ){
15257
        p->id = iType;
15258
        if( DosCreateMutexSem( 0, &p->mutex, 0, FALSE ) != NO_ERROR ){
15259
          sqlite3_free( p );
15260
          p = NULL;
15261
        }
15262
      }
15263
      break;
15264
    }
15265
    default: {
15266
      static volatile int isInit = 0;
15267
      static sqlite3_mutex staticMutexes[] = {
15268
        { OS2_MUTEX_INITIALIZER, },
15269
        { OS2_MUTEX_INITIALIZER, },
15270
        { OS2_MUTEX_INITIALIZER, },
15271
        { OS2_MUTEX_INITIALIZER, },
15272
        { OS2_MUTEX_INITIALIZER, },
15273
        { OS2_MUTEX_INITIALIZER, },
15274
      };
15275
      if ( !isInit ){
15276
        APIRET rc;
15277
        PTIB ptib;
15278
        PPIB ppib;
15279
        HMTX mutex;
15280
        char name[32];
15281
        DosGetInfoBlocks( &ptib, &ppib );
15282
        sqlite3_snprintf( sizeof(name), name, "\\SEM32\\SQLITE%04x",
15283
                          ppib->pib_ulpid );
15284
        while( !isInit ){
15285
          mutex = 0;
15286
          rc = DosCreateMutexSem( name, &mutex, 0, FALSE);
15287
          if( rc == NO_ERROR ){
15288
            unsigned int i;
15289
            if( !isInit ){
15290
              for( i = 0; i < sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++ ){
15291
                DosCreateMutexSem( 0, &staticMutexes[i].mutex, 0, FALSE );
15292
              }
15293
              isInit = 1;
15294
            }
15295
            DosCloseMutexSem( mutex );
15296
          }else if( rc == ERROR_DUPLICATE_NAME ){
15297
            DosSleep( 1 );
15298
          }else{
15299
            return p;
15300
          }
15301
        }
15302
      }
15303
      assert( iType-2 >= 0 );
15304
      assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
15305
      p = &staticMutexes[iType-2];
15306
      p->id = iType;
15307
      break;
15308
    }
15309
  }
15310
  return p;
15311
}
15312
15313
15314
/*
15315
** This routine deallocates a previously allocated mutex.
15316
** SQLite is careful to deallocate every mutex that it allocates.
15317
*/
15318
static void os2MutexFree(sqlite3_mutex *p){
15319
  if( p==0 ) return;
15320
  assert( p->nRef==0 );
15321
  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
15322
  DosCloseMutexSem( p->mutex );
15323
  sqlite3_free( p );
15324
}
15325
15326
#ifdef SQLITE_DEBUG
15327
/*
15328
** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15329
** intended for use inside assert() statements.
15330
*/
15331
static int os2MutexHeld(sqlite3_mutex *p){
15332
  TID tid;
15333
  PID pid;
15334
  ULONG ulCount;
15335
  PTIB ptib;
15336
  if( p!=0 ) {
15337
    DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
15338
  } else {
15339
    DosGetInfoBlocks(&ptib, NULL);
15340
    tid = ptib->tib_ptib2->tib2_ultid;
15341
  }
15342
  return p==0 || (p->nRef!=0 && p->owner==tid);
15343
}
15344
static int os2MutexNotheld(sqlite3_mutex *p){
15345
  TID tid;
15346
  PID pid;
15347
  ULONG ulCount;
15348
  PTIB ptib;
15349
  if( p!= 0 ) {
15350
    DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
15351
  } else {
15352
    DosGetInfoBlocks(&ptib, NULL);
15353
    tid = ptib->tib_ptib2->tib2_ultid;
15354
  }
15355
  return p==0 || p->nRef==0 || p->owner!=tid;
15356
}
15357
#endif
15358
15359
/*
15360
** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
15361
** to enter a mutex.  If another thread is already within the mutex,
15362
** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
15363
** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
15364
** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
15365
** be entered multiple times by the same thread.  In such cases the,
15366
** mutex must be exited an equal number of times before another thread
15367
** can enter.  If the same thread tries to enter any other kind of mutex
15368
** more than once, the behavior is undefined.
15369
*/
15370
static void os2MutexEnter(sqlite3_mutex *p){
15371
  TID tid;
15372
  PID holder1;
15373
  ULONG holder2;
15374
  if( p==0 ) return;
15375
  assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
15376
  DosRequestMutexSem(p->mutex, SEM_INDEFINITE_WAIT);
15377
  DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
15378
  p->owner = tid;
15379
  p->nRef++;
15380
}
15381
static int os2MutexTry(sqlite3_mutex *p){
15382
  int rc;
15383
  TID tid;
15384
  PID holder1;
15385
  ULONG holder2;
15386
  if( p==0 ) return SQLITE_OK;
15387
  assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
15388
  if( DosRequestMutexSem(p->mutex, SEM_IMMEDIATE_RETURN) == NO_ERROR) {
15389
    DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
15390
    p->owner = tid;
15391
    p->nRef++;
15392
    rc = SQLITE_OK;
15393
  } else {
15394
    rc = SQLITE_BUSY;
15395
  }
15396
15397
  return rc;
15398
}
15399
15400
/*
15401
** The sqlite3_mutex_leave() routine exits a mutex that was
15402
** previously entered by the same thread.  The behavior
15403
** is undefined if the mutex is not currently entered or
15404
** is not currently allocated.  SQLite will never do either.
15405
*/
15406
static void os2MutexLeave(sqlite3_mutex *p){
15407
  TID tid;
15408
  PID holder1;
15409
  ULONG holder2;
15410
  if( p==0 ) return;
15411
  assert( p->nRef>0 );
15412
  DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
15413
  assert( p->owner==tid );
15414
  p->nRef--;
15415
  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
15416
  DosReleaseMutexSem(p->mutex);
15417
}
15418
15419
SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
15420
  static sqlite3_mutex_methods sMutex = {
15421
    os2MutexInit,
15422
    os2MutexEnd,
15423
    os2MutexAlloc,
15424
    os2MutexFree,
15425
    os2MutexEnter,
15426
    os2MutexTry,
15427
    os2MutexLeave,
15428
#ifdef SQLITE_DEBUG
15429
    os2MutexHeld,
15430
    os2MutexNotheld
15431
#endif
15432
  };
15433
15434
  return &sMutex;
15435
}
15436
#endif /* SQLITE_MUTEX_OS2 */
15437
15438
/************** End of mutex_os2.c *******************************************/
15439
/************** Begin file mutex_unix.c **************************************/
15440
/*
15441
** 2007 August 28
15442
**
15443
** The author disclaims copyright to this source code.  In place of
15444
** a legal notice, here is a blessing:
15445
**
15446
**    May you do good and not evil.
15447
**    May you find forgiveness for yourself and forgive others.
15448
**    May you share freely, never taking more than you give.
15449
**
15450
*************************************************************************
15451
** This file contains the C functions that implement mutexes for pthreads
15452
*/
15453
15454
/*
15455
** The code in this file is only used if we are compiling threadsafe
15456
** under unix with pthreads.
15457
**
15458
** Note that this implementation requires a version of pthreads that
15459
** supports recursive mutexes.
15460
*/
15461
#ifdef SQLITE_MUTEX_PTHREADS
15462
15463
#include <pthread.h>
15464
15465
15466
/*
15467
** Each recursive mutex is an instance of the following structure.
15468
*/
15469
struct sqlite3_mutex {
15470
  pthread_mutex_t mutex;     /* Mutex controlling the lock */
15471
  int id;                    /* Mutex type */
15472
  int nRef;                  /* Number of entrances */
15473
  pthread_t owner;           /* Thread that is within this mutex */
15474
#ifdef SQLITE_DEBUG
15475
  int trace;                 /* True to trace changes */
15476
#endif
15477
};
15478
#ifdef SQLITE_DEBUG
15479
#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
15480
#else
15481
#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0 }
15482
#endif
15483
15484
/*
15485
** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15486
** intended for use only inside assert() statements.  On some platforms,
15487
** there might be race conditions that can cause these routines to
15488
** deliver incorrect results.  In particular, if pthread_equal() is
15489
** not an atomic operation, then these routines might delivery
15490
** incorrect results.  On most platforms, pthread_equal() is a 
15491
** comparison of two integers and is therefore atomic.  But we are
15492
** told that HPUX is not such a platform.  If so, then these routines
15493
** will not always work correctly on HPUX.
15494
**
15495
** On those platforms where pthread_equal() is not atomic, SQLite
15496
** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
15497
** make sure no assert() statements are evaluated and hence these
15498
** routines are never called.
15499
*/
15500
#if !defined(NDEBUG) || defined(SQLITE_DEBUG)
15501
static int pthreadMutexHeld(sqlite3_mutex *p){
15502
  return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
15503
}
15504
static int pthreadMutexNotheld(sqlite3_mutex *p){
15505
  return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
15506
}
15507
#endif
15508
15509
/*
15510
** Initialize and deinitialize the mutex subsystem.
15511
*/
15512
static int pthreadMutexInit(void){ return SQLITE_OK; }
15513
static int pthreadMutexEnd(void){ return SQLITE_OK; }
15514
15515
/*
15516
** The sqlite3_mutex_alloc() routine allocates a new
15517
** mutex and returns a pointer to it.  If it returns NULL
15518
** that means that a mutex could not be allocated.  SQLite
15519
** will unwind its stack and return an error.  The argument
15520
** to sqlite3_mutex_alloc() is one of these integer constants:
15521
**
15522
** <ul>
15523
** <li>  SQLITE_MUTEX_FAST
15524
** <li>  SQLITE_MUTEX_RECURSIVE
15525
** <li>  SQLITE_MUTEX_STATIC_MASTER
15526
** <li>  SQLITE_MUTEX_STATIC_MEM
15527
** <li>  SQLITE_MUTEX_STATIC_MEM2
15528
** <li>  SQLITE_MUTEX_STATIC_PRNG
15529
** <li>  SQLITE_MUTEX_STATIC_LRU
15530
** <li>  SQLITE_MUTEX_STATIC_LRU2
15531
** </ul>
15532
**
15533
** The first two constants cause sqlite3_mutex_alloc() to create
15534
** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
15535
** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
15536
** The mutex implementation does not need to make a distinction
15537
** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
15538
** not want to.  But SQLite will only request a recursive mutex in
15539
** cases where it really needs one.  If a faster non-recursive mutex
15540
** implementation is available on the host platform, the mutex subsystem
15541
** might return such a mutex in response to SQLITE_MUTEX_FAST.
15542
**
15543
** The other allowed parameters to sqlite3_mutex_alloc() each return
15544
** a pointer to a static preexisting mutex.  Six static mutexes are
15545
** used by the current version of SQLite.  Future versions of SQLite
15546
** may add additional static mutexes.  Static mutexes are for internal
15547
** use by SQLite only.  Applications that use SQLite mutexes should
15548
** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
15549
** SQLITE_MUTEX_RECURSIVE.
15550
**
15551
** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
15552
** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
15553
** returns a different mutex on every call.  But for the static 
15554
** mutex types, the same mutex is returned on every call that has
15555
** the same type number.
15556
*/
15557
static sqlite3_mutex *pthreadMutexAlloc(int iType){
15558
  static sqlite3_mutex staticMutexes[] = {
15559
    SQLITE3_MUTEX_INITIALIZER,
15560
    SQLITE3_MUTEX_INITIALIZER,
15561
    SQLITE3_MUTEX_INITIALIZER,
15562
    SQLITE3_MUTEX_INITIALIZER,
15563
    SQLITE3_MUTEX_INITIALIZER,
15564
    SQLITE3_MUTEX_INITIALIZER
15565
  };
15566
  sqlite3_mutex *p;
15567
  switch( iType ){
15568
    case SQLITE_MUTEX_RECURSIVE: {
15569
      p = sqlite3MallocZero( sizeof(*p) );
15570
      if( p ){
15571
#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15572
        /* If recursive mutexes are not available, we will have to
15573
        ** build our own.  See below. */
15574
        pthread_mutex_init(&p->mutex, 0);
15575
#else
15576
        /* Use a recursive mutex if it is available */
15577
        pthread_mutexattr_t recursiveAttr;
15578
        pthread_mutexattr_init(&recursiveAttr);
15579
        pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
15580
        pthread_mutex_init(&p->mutex, &recursiveAttr);
15581
        pthread_mutexattr_destroy(&recursiveAttr);
15582
#endif
15583
        p->id = iType;
15584
      }
15585
      break;
15586
    }
15587
    case SQLITE_MUTEX_FAST: {
15588
      p = sqlite3MallocZero( sizeof(*p) );
15589
      if( p ){
15590
        p->id = iType;
15591
        pthread_mutex_init(&p->mutex, 0);
15592
      }
15593
      break;
15594
    }
15595
    default: {
15596
      assert( iType-2 >= 0 );
15597
      assert( iType-2 < ArraySize(staticMutexes) );
15598
      p = &staticMutexes[iType-2];
15599
      p->id = iType;
15600
      break;
15601
    }
15602
  }
15603
  return p;
15604
}
15605
15606
15607
/*
15608
** This routine deallocates a previously
15609
** allocated mutex.  SQLite is careful to deallocate every
15610
** mutex that it allocates.
15611
*/
15612
static void pthreadMutexFree(sqlite3_mutex *p){
15613
  assert( p->nRef==0 );
15614
  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
15615
  pthread_mutex_destroy(&p->mutex);
15616
  sqlite3_free(p);
15617
}
15618
15619
/*
15620
** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
15621
** to enter a mutex.  If another thread is already within the mutex,
15622
** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
15623
** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
15624
** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
15625
** be entered multiple times by the same thread.  In such cases the,
15626
** mutex must be exited an equal number of times before another thread
15627
** can enter.  If the same thread tries to enter any other kind of mutex
15628
** more than once, the behavior is undefined.
15629
*/
15630
static void pthreadMutexEnter(sqlite3_mutex *p){
15631
  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
15632
15633
#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15634
  /* If recursive mutexes are not available, then we have to grow
15635
  ** our own.  This implementation assumes that pthread_equal()
15636
  ** is atomic - that it cannot be deceived into thinking self
15637
  ** and p->owner are equal if p->owner changes between two values
15638
  ** that are not equal to self while the comparison is taking place.
15639
  ** This implementation also assumes a coherent cache - that 
15640
  ** separate processes cannot read different values from the same
15641
  ** address at the same time.  If either of these two conditions
15642
  ** are not met, then the mutexes will fail and problems will result.
15643
  */
15644
  {
15645
    pthread_t self = pthread_self();
15646
    if( p->nRef>0 && pthread_equal(p->owner, self) ){
15647
      p->nRef++;
15648
    }else{
15649
      pthread_mutex_lock(&p->mutex);
15650
      assert( p->nRef==0 );
15651
      p->owner = self;
15652
      p->nRef = 1;
15653
    }
15654
  }
15655
#else
15656
  /* Use the built-in recursive mutexes if they are available.
15657
  */
15658
  pthread_mutex_lock(&p->mutex);
15659
  p->owner = pthread_self();
15660
  p->nRef++;
15661
#endif
15662
15663
#ifdef SQLITE_DEBUG
15664
  if( p->trace ){
15665
    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
15666
  }
15667
#endif
15668
}
15669
static int pthreadMutexTry(sqlite3_mutex *p){
15670
  int rc;
15671
  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
15672
15673
#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15674
  /* If recursive mutexes are not available, then we have to grow
15675
  ** our own.  This implementation assumes that pthread_equal()
15676
  ** is atomic - that it cannot be deceived into thinking self
15677
  ** and p->owner are equal if p->owner changes between two values
15678
  ** that are not equal to self while the comparison is taking place.
15679
  ** This implementation also assumes a coherent cache - that 
15680
  ** separate processes cannot read different values from the same
15681
  ** address at the same time.  If either of these two conditions
15682
  ** are not met, then the mutexes will fail and problems will result.
15683
  */
15684
  {
15685
    pthread_t self = pthread_self();
15686
    if( p->nRef>0 && pthread_equal(p->owner, self) ){
15687
      p->nRef++;
15688
      rc = SQLITE_OK;
15689
    }else if( pthread_mutex_trylock(&p->mutex)==0 ){
15690
      assert( p->nRef==0 );
15691
      p->owner = self;
15692
      p->nRef = 1;
15693
      rc = SQLITE_OK;
15694
    }else{
15695
      rc = SQLITE_BUSY;
15696
    }
15697
  }
15698
#else
15699
  /* Use the built-in recursive mutexes if they are available.
15700
  */
15701
  if( pthread_mutex_trylock(&p->mutex)==0 ){
15702
    p->owner = pthread_self();
15703
    p->nRef++;
15704
    rc = SQLITE_OK;
15705
  }else{
15706
    rc = SQLITE_BUSY;
15707
  }
15708
#endif
15709
15710
#ifdef SQLITE_DEBUG
15711
  if( rc==SQLITE_OK && p->trace ){
15712
    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
15713
  }
15714
#endif
15715
  return rc;
15716
}
15717
15718
/*
15719
** The sqlite3_mutex_leave() routine exits a mutex that was
15720
** previously entered by the same thread.  The behavior
15721
** is undefined if the mutex is not currently entered or
15722
** is not currently allocated.  SQLite will never do either.
15723
*/
15724
static void pthreadMutexLeave(sqlite3_mutex *p){
15725
  assert( pthreadMutexHeld(p) );
15726
  p->nRef--;
15727
  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
15728
15729
#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15730
  if( p->nRef==0 ){
15731
    pthread_mutex_unlock(&p->mutex);
15732
  }
15733
#else
15734
  pthread_mutex_unlock(&p->mutex);
15735
#endif
15736
15737
#ifdef SQLITE_DEBUG
15738
  if( p->trace ){
15739
    printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
15740
  }
15741
#endif
15742
}
15743
15744
SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
15745
  static sqlite3_mutex_methods sMutex = {
15746
    pthreadMutexInit,
15747
    pthreadMutexEnd,
15748
    pthreadMutexAlloc,
15749
    pthreadMutexFree,
15750
    pthreadMutexEnter,
15751
    pthreadMutexTry,
15752
    pthreadMutexLeave,
15753
#ifdef SQLITE_DEBUG
15754
    pthreadMutexHeld,
15755
    pthreadMutexNotheld
15756
#else
15757
    0,
15758
    0
15759
#endif
15760
  };
15761
15762
  return &sMutex;
15763
}
15764
15765
#endif /* SQLITE_MUTEX_PTHREAD */
15766
15767
/************** End of mutex_unix.c ******************************************/
15768
/************** Begin file mutex_w32.c ***************************************/
15769
/*
15770
** 2007 August 14
15771
**
15772
** The author disclaims copyright to this source code.  In place of
15773
** a legal notice, here is a blessing:
15774
**
15775
**    May you do good and not evil.
15776
**    May you find forgiveness for yourself and forgive others.
15777
**    May you share freely, never taking more than you give.
15778
**
15779
*************************************************************************
15780
** This file contains the C functions that implement mutexes for win32
15781
*/
15782
15783
/*
15784
** The code in this file is only used if we are compiling multithreaded
15785
** on a win32 system.
15786
*/
15787
#ifdef SQLITE_MUTEX_W32
15788
15789
/*
15790
** Each recursive mutex is an instance of the following structure.
15791
*/
15792
struct sqlite3_mutex {
15793
  CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
15794
  int id;                    /* Mutex type */
15795
  int nRef;                  /* Number of enterances */
15796
  DWORD owner;               /* Thread holding this mutex */
15797
#ifdef SQLITE_DEBUG
15798
  int trace;                 /* True to trace changes */
15799
#endif
15800
};
15801
#define SQLITE_W32_MUTEX_INITIALIZER { 0 }
15802
#ifdef SQLITE_DEBUG
15803
#define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }
15804
#else
15805
#define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0 }
15806
#endif
15807
15808
/*
15809
** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
15810
** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
15811
**
15812
** Here is an interesting observation:  Win95, Win98, and WinME lack
15813
** the LockFileEx() API.  But we can still statically link against that
15814
** API as long as we don't call it win running Win95/98/ME.  A call to
15815
** this routine is used to determine if the host is Win95/98/ME or
15816
** WinNT/2K/XP so that we will know whether or not we can safely call
15817
** the LockFileEx() API.
15818
**
15819
** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
15820
** which is only available if your application was compiled with 
15821
** _WIN32_WINNT defined to a value >= 0x0400.  Currently, the only
15822
** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef 
15823
** this out as well.
15824
*/
15825
#if 0
15826
#if SQLITE_OS_WINCE
15827
# define mutexIsNT()  (1)
15828
#else
15829
  static int mutexIsNT(void){
15830
    static int osType = 0;
15831
    if( osType==0 ){
15832
      OSVERSIONINFO sInfo;
15833
      sInfo.dwOSVersionInfoSize = sizeof(sInfo);
15834
      GetVersionEx(&sInfo);
15835
      osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
15836
    }
15837
    return osType==2;
15838
  }
15839
#endif /* SQLITE_OS_WINCE */
15840
#endif
15841
15842
#ifdef SQLITE_DEBUG
15843
/*
15844
** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15845
** intended for use only inside assert() statements.
15846
*/
15847
static int winMutexHeld(sqlite3_mutex *p){
15848
  return p->nRef!=0 && p->owner==GetCurrentThreadId();
15849
}
15850
static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
15851
  return p->nRef==0 || p->owner!=tid;
15852
}
15853
static int winMutexNotheld(sqlite3_mutex *p){
15854
  DWORD tid = GetCurrentThreadId(); 
15855
  return winMutexNotheld2(p, tid);
15856
}
15857
#endif
15858
15859
15860
/*
15861
** Initialize and deinitialize the mutex subsystem.
15862
*/
15863
static sqlite3_mutex winMutex_staticMutexes[6] = {
15864
  SQLITE3_MUTEX_INITIALIZER,
15865
  SQLITE3_MUTEX_INITIALIZER,
15866
  SQLITE3_MUTEX_INITIALIZER,
15867
  SQLITE3_MUTEX_INITIALIZER,
15868
  SQLITE3_MUTEX_INITIALIZER,
15869
  SQLITE3_MUTEX_INITIALIZER
15870
};
15871
static int winMutex_isInit = 0;
15872
/* As winMutexInit() and winMutexEnd() are called as part
15873
** of the sqlite3_initialize and sqlite3_shutdown()
15874
** processing, the "interlocked" magic is probably not
15875
** strictly necessary.
15876
*/
15877
static long winMutex_lock = 0;
15878
15879
static int winMutexInit(void){ 
15880
  /* The first to increment to 1 does actual initialization */
15881
  if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
15882
    int i;
15883
    for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
15884
      InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
15885
    }
15886
    winMutex_isInit = 1;
15887
  }else{
15888
    /* Someone else is in the process of initing the static mutexes */
15889
    while( !winMutex_isInit ){
15890
      Sleep(1);
15891
    }
15892
  }
15893
  return SQLITE_OK; 
15894
}
15895
15896
static int winMutexEnd(void){ 
15897
  /* The first to decrement to 0 does actual shutdown 
15898
  ** (which should be the last to shutdown.) */
15899
  if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
15900
    if( winMutex_isInit==1 ){
15901
      int i;
15902
      for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
15903
        DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
15904
      }
15905
      winMutex_isInit = 0;
15906
    }
15907
  }
15908
  return SQLITE_OK; 
15909
}
15910
15911
/*
15912
** The sqlite3_mutex_alloc() routine allocates a new
15913
** mutex and returns a pointer to it.  If it returns NULL
15914
** that means that a mutex could not be allocated.  SQLite
15915
** will unwind its stack and return an error.  The argument
15916
** to sqlite3_mutex_alloc() is one of these integer constants:
15917
**
15918
** <ul>
15919
** <li>  SQLITE_MUTEX_FAST
15920
** <li>  SQLITE_MUTEX_RECURSIVE
15921
** <li>  SQLITE_MUTEX_STATIC_MASTER
15922
** <li>  SQLITE_MUTEX_STATIC_MEM
15923
** <li>  SQLITE_MUTEX_STATIC_MEM2
15924
** <li>  SQLITE_MUTEX_STATIC_PRNG
15925
** <li>  SQLITE_MUTEX_STATIC_LRU
15926
** <li>  SQLITE_MUTEX_STATIC_LRU2
15927
** </ul>
15928
**
15929
** The first two constants cause sqlite3_mutex_alloc() to create
15930
** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
15931
** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
15932
** The mutex implementation does not need to make a distinction
15933
** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
15934
** not want to.  But SQLite will only request a recursive mutex in
15935
** cases where it really needs one.  If a faster non-recursive mutex
15936
** implementation is available on the host platform, the mutex subsystem
15937
** might return such a mutex in response to SQLITE_MUTEX_FAST.
15938
**
15939
** The other allowed parameters to sqlite3_mutex_alloc() each return
15940
** a pointer to a static preexisting mutex.  Six static mutexes are
15941
** used by the current version of SQLite.  Future versions of SQLite
15942
** may add additional static mutexes.  Static mutexes are for internal
15943
** use by SQLite only.  Applications that use SQLite mutexes should
15944
** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
15945
** SQLITE_MUTEX_RECURSIVE.
15946
**
15947
** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
15948
** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
15949
** returns a different mutex on every call.  But for the static 
15950
** mutex types, the same mutex is returned on every call that has
15951
** the same type number.
15952
*/
15953
static sqlite3_mutex *winMutexAlloc(int iType){
15954
  sqlite3_mutex *p;
15955
15956
  switch( iType ){
15957
    case SQLITE_MUTEX_FAST:
15958
    case SQLITE_MUTEX_RECURSIVE: {
15959
      p = sqlite3MallocZero( sizeof(*p) );
15960
      if( p ){  
15961
        p->id = iType;
15962
        InitializeCriticalSection(&p->mutex);
15963
      }
15964
      break;
15965
    }
15966
    default: {
15967
      assert( winMutex_isInit==1 );
15968
      assert( iType-2 >= 0 );
15969
      assert( iType-2 < ArraySize(winMutex_staticMutexes) );
15970
      p = &winMutex_staticMutexes[iType-2];
15971
      p->id = iType;
15972
      break;
15973
    }
15974
  }
15975
  return p;
15976
}
15977
15978
15979
/*
15980
** This routine deallocates a previously
15981
** allocated mutex.  SQLite is careful to deallocate every
15982
** mutex that it allocates.
15983
*/
15984
static void winMutexFree(sqlite3_mutex *p){
15985
  assert( p );
15986
  assert( p->nRef==0 );
15987
  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
15988
  DeleteCriticalSection(&p->mutex);
15989
  sqlite3_free(p);
15990
}
15991
15992
/*
15993
** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
15994
** to enter a mutex.  If another thread is already within the mutex,
15995
** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
15996
** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
15997
** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
15998
** be entered multiple times by the same thread.  In such cases the,
15999
** mutex must be exited an equal number of times before another thread
16000
** can enter.  If the same thread tries to enter any other kind of mutex
16001
** more than once, the behavior is undefined.
16002
*/
16003
static void winMutexEnter(sqlite3_mutex *p){
16004
  DWORD tid = GetCurrentThreadId(); 
16005
  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
16006
  EnterCriticalSection(&p->mutex);
16007
  p->owner = tid; 
16008
  p->nRef++;
16009
#ifdef SQLITE_DEBUG
16010
  if( p->trace ){
16011
    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
16012
  }
16013
#endif
16014
}
16015
static int winMutexTry(sqlite3_mutex *p){
16016
#ifndef NDEBUG
16017
  DWORD tid = GetCurrentThreadId(); 
16018
#endif
16019
  int rc = SQLITE_BUSY;
16020
  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
16021
  /*
16022
  ** The sqlite3_mutex_try() routine is very rarely used, and when it
16023
  ** is used it is merely an optimization.  So it is OK for it to always
16024
  ** fail.  
16025
  **
16026
  ** The TryEnterCriticalSection() interface is only available on WinNT.
16027
  ** And some windows compilers complain if you try to use it without
16028
  ** first doing some #defines that prevent SQLite from building on Win98.
16029
  ** For that reason, we will omit this optimization for now.  See
16030
  ** ticket #2685.
16031
  */
16032
#if 0
16033
  if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
16034
    p->owner = tid;
16035
    p->nRef++;
16036
    rc = SQLITE_OK;
16037
  }
16038
#else
16039
  UNUSED_PARAMETER(p);
16040
#endif
16041
#ifdef SQLITE_DEBUG
16042
  if( rc==SQLITE_OK && p->trace ){
16043
    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
16044
  }
16045
#endif
16046
  return rc;
16047
}
16048
16049
/*
16050
** The sqlite3_mutex_leave() routine exits a mutex that was
16051
** previously entered by the same thread.  The behavior
16052
** is undefined if the mutex is not currently entered or
16053
** is not currently allocated.  SQLite will never do either.
16054
*/
16055
static void winMutexLeave(sqlite3_mutex *p){
16056
#ifndef NDEBUG
16057
  DWORD tid = GetCurrentThreadId();
16058
#endif
16059
  assert( p->nRef>0 );
16060
  assert( p->owner==tid );
16061
  p->nRef--;
16062
  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
16063
  LeaveCriticalSection(&p->mutex);
16064
#ifdef SQLITE_DEBUG
16065
  if( p->trace ){
16066
    printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
16067
  }
16068
#endif
16069
}
16070
16071
SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
16072
  static sqlite3_mutex_methods sMutex = {
16073
    winMutexInit,
16074
    winMutexEnd,
16075
    winMutexAlloc,
16076
    winMutexFree,
16077
    winMutexEnter,
16078
    winMutexTry,
16079
    winMutexLeave,
16080
#ifdef SQLITE_DEBUG
16081
    winMutexHeld,
16082
    winMutexNotheld
16083
#else
16084
    0,
16085
    0
16086
#endif
16087
  };
16088
16089
  return &sMutex;
16090
}
16091
#endif /* SQLITE_MUTEX_W32 */
16092
16093
/************** End of mutex_w32.c *******************************************/
16094
/************** Begin file malloc.c ******************************************/
16095
/*
16096
** 2001 September 15
16097
**
16098
** The author disclaims copyright to this source code.  In place of
16099
** a legal notice, here is a blessing:
16100
**
16101
**    May you do good and not evil.
16102
**    May you find forgiveness for yourself and forgive others.
16103
**    May you share freely, never taking more than you give.
16104
**
16105
*************************************************************************
16106
**
16107
** Memory allocation functions used throughout sqlite.
16108
*/
16109
16110
/*
16111
** This routine runs when the memory allocator sees that the
16112
** total memory allocation is about to exceed the soft heap
16113
** limit.
16114
*/
16115
static void softHeapLimitEnforcer(
16116
  void *NotUsed, 
16117
  sqlite3_int64 NotUsed2,
16118
  int allocSize
16119
){
16120
  UNUSED_PARAMETER2(NotUsed, NotUsed2);
16121
  sqlite3_release_memory(allocSize);
16122
}
16123
16124
/*
16125
** Set the soft heap-size limit for the library. Passing a zero or 
16126
** negative value indicates no limit.
16127
*/
16128
SQLITE_API void sqlite3_soft_heap_limit(int n){
16129
  sqlite3_uint64 iLimit;
16130
  int overage;
16131
  if( n<0 ){
16132
    iLimit = 0;
16133
  }else{
16134
    iLimit = n;
16135
  }
16136
#ifndef SQLITE_OMIT_AUTOINIT
16137
  sqlite3_initialize();
16138
#endif
16139
  if( iLimit>0 ){
16140
    sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, iLimit);
16141
  }else{
16142
    sqlite3MemoryAlarm(0, 0, 0);
16143
  }
16144
  overage = (int)(sqlite3_memory_used() - (i64)n);
16145
  if( overage>0 ){
16146
    sqlite3_release_memory(overage);
16147
  }
16148
}
16149
16150
/*
16151
** Attempt to release up to n bytes of non-essential memory currently
16152
** held by SQLite. An example of non-essential memory is memory used to
16153
** cache database pages that are not currently in use.
16154
*/
16155
SQLITE_API int sqlite3_release_memory(int n){
16156
#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
16157
  int nRet = 0;
16158
  nRet += sqlite3PcacheReleaseMemory(n-nRet);
16159
  return nRet;
16160
#else
16161
  UNUSED_PARAMETER(n);
16162
  return SQLITE_OK;
16163
#endif
16164
}
16165
16166
/*
16167
** State information local to the memory allocation subsystem.
16168
*/
16169
static SQLITE_WSD struct Mem0Global {
16170
  /* Number of free pages for scratch and page-cache memory */
16171
  u32 nScratchFree;
16172
  u32 nPageFree;
16173
16174
  sqlite3_mutex *mutex;         /* Mutex to serialize access */
16175
16176
  /*
16177
  ** The alarm callback and its arguments.  The mem0.mutex lock will
16178
  ** be held while the callback is running.  Recursive calls into
16179
  ** the memory subsystem are allowed, but no new callbacks will be
16180
  ** issued.
16181
  */
16182
  sqlite3_int64 alarmThreshold;
16183
  void (*alarmCallback)(void*, sqlite3_int64,int);
16184
  void *alarmArg;
16185
16186
  /*
16187
  ** Pointers to the end of sqlite3GlobalConfig.pScratch and
16188
  ** sqlite3GlobalConfig.pPage to a block of memory that records
16189
  ** which pages are available.
16190
  */
16191
  u32 *aScratchFree;
16192
  u32 *aPageFree;
16193
} mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
16194
16195
#define mem0 GLOBAL(struct Mem0Global, mem0)
16196
16197
/*
16198
** Initialize the memory allocation subsystem.
16199
*/
16200
SQLITE_PRIVATE int sqlite3MallocInit(void){
16201
  if( sqlite3GlobalConfig.m.xMalloc==0 ){
16202
    sqlite3MemSetDefault();
16203
  }
16204
  memset(&mem0, 0, sizeof(mem0));
16205
  if( sqlite3GlobalConfig.bCoreMutex ){
16206
    mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
16207
  }
16208
  if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
16209
      && sqlite3GlobalConfig.nScratch>=0 ){
16210
    int i;
16211
    sqlite3GlobalConfig.szScratch = ROUNDDOWN8(sqlite3GlobalConfig.szScratch-4);
16212
    mem0.aScratchFree = (u32*)&((char*)sqlite3GlobalConfig.pScratch)
16213
                  [sqlite3GlobalConfig.szScratch*sqlite3GlobalConfig.nScratch];
16214
    for(i=0; i<sqlite3GlobalConfig.nScratch; i++){ mem0.aScratchFree[i] = i; }
16215
    mem0.nScratchFree = sqlite3GlobalConfig.nScratch;
16216
  }else{
16217
    sqlite3GlobalConfig.pScratch = 0;
16218
    sqlite3GlobalConfig.szScratch = 0;
16219
  }
16220
  if( sqlite3GlobalConfig.pPage && sqlite3GlobalConfig.szPage>=512
16221
      && sqlite3GlobalConfig.nPage>=1 ){
16222
    int i;
16223
    int overhead;
16224
    int sz = ROUNDDOWN8(sqlite3GlobalConfig.szPage);
16225
    int n = sqlite3GlobalConfig.nPage;
16226
    overhead = (4*n + sz - 1)/sz;
16227
    sqlite3GlobalConfig.nPage -= overhead;
16228
    mem0.aPageFree = (u32*)&((char*)sqlite3GlobalConfig.pPage)
16229
                  [sqlite3GlobalConfig.szPage*sqlite3GlobalConfig.nPage];
16230
    for(i=0; i<sqlite3GlobalConfig.nPage; i++){ mem0.aPageFree[i] = i; }
16231
    mem0.nPageFree = sqlite3GlobalConfig.nPage;
16232
  }else{
16233
    sqlite3GlobalConfig.pPage = 0;
16234
    sqlite3GlobalConfig.szPage = 0;
16235
  }
16236
  return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
16237
}
16238
16239
/*
16240
** Deinitialize the memory allocation subsystem.
16241
*/
16242
SQLITE_PRIVATE void sqlite3MallocEnd(void){
16243
  if( sqlite3GlobalConfig.m.xShutdown ){
16244
    sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
16245
  }
16246
  memset(&mem0, 0, sizeof(mem0));
16247
}
16248
16249
/*
16250
** Return the amount of memory currently checked out.
16251
*/
16252
SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
16253
  int n, mx;
16254
  sqlite3_int64 res;
16255
  sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
16256
  res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
16257
  return res;
16258
}
16259
16260
/*
16261
** Return the maximum amount of memory that has ever been
16262
** checked out since either the beginning of this process
16263
** or since the most recent reset.
16264
*/
16265
SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
16266
  int n, mx;
16267
  sqlite3_int64 res;
16268
  sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
16269
  res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
16270
  return res;
16271
}
16272
16273
/*
16274
** Change the alarm callback
16275
*/
16276
SQLITE_PRIVATE int sqlite3MemoryAlarm(
16277
  void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
16278
  void *pArg,
16279
  sqlite3_int64 iThreshold
16280
){
16281
  sqlite3_mutex_enter(mem0.mutex);
16282
  mem0.alarmCallback = xCallback;
16283
  mem0.alarmArg = pArg;
16284
  mem0.alarmThreshold = iThreshold;
16285
  sqlite3_mutex_leave(mem0.mutex);
16286
  return SQLITE_OK;
16287
}
16288
16289
#ifndef SQLITE_OMIT_DEPRECATED
16290
/*
16291
** Deprecated external interface.  Internal/core SQLite code
16292
** should call sqlite3MemoryAlarm.
16293
*/
16294
SQLITE_API int sqlite3_memory_alarm(
16295
  void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
16296
  void *pArg,
16297
  sqlite3_int64 iThreshold
16298
){
16299
  return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
16300
}
16301
#endif
16302
16303
/*
16304
** Trigger the alarm 
16305
*/
16306
static void sqlite3MallocAlarm(int nByte){
16307
  void (*xCallback)(void*,sqlite3_int64,int);
16308
  sqlite3_int64 nowUsed;
16309
  void *pArg;
16310
  if( mem0.alarmCallback==0 ) return;
16311
  xCallback = mem0.alarmCallback;
16312
  nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
16313
  pArg = mem0.alarmArg;
16314
  mem0.alarmCallback = 0;
16315
  sqlite3_mutex_leave(mem0.mutex);
16316
  xCallback(pArg, nowUsed, nByte);
16317
  sqlite3_mutex_enter(mem0.mutex);
16318
  mem0.alarmCallback = xCallback;
16319
  mem0.alarmArg = pArg;
16320
}
16321
16322
/*
16323
** Do a memory allocation with statistics and alarms.  Assume the
16324
** lock is already held.
16325
*/
16326
static int mallocWithAlarm(int n, void **pp){
16327
  int nFull;
16328
  void *p;
16329
  assert( sqlite3_mutex_held(mem0.mutex) );
16330
  nFull = sqlite3GlobalConfig.m.xRoundup(n);
16331
  sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
16332
  if( mem0.alarmCallback!=0 ){
16333
    int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
16334
    if( nUsed+nFull >= mem0.alarmThreshold ){
16335
      sqlite3MallocAlarm(nFull);
16336
    }
16337
  }
16338
  p = sqlite3GlobalConfig.m.xMalloc(nFull);
16339
  if( p==0 && mem0.alarmCallback ){
16340
    sqlite3MallocAlarm(nFull);
16341
    p = sqlite3GlobalConfig.m.xMalloc(nFull);
16342
  }
16343
  if( p ){
16344
    nFull = sqlite3MallocSize(p);
16345
    sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
16346
  }
16347
  *pp = p;
16348
  return nFull;
16349
}
16350
16351
/*
16352
** Allocate memory.  This routine is like sqlite3_malloc() except that it
16353
** assumes the memory subsystem has already been initialized.
16354
*/
16355
SQLITE_PRIVATE void *sqlite3Malloc(int n){
16356
  void *p;
16357
  if( n<=0 || n>=0x7fffff00 ){
16358
    /* A memory allocation of a number of bytes which is near the maximum
16359
    ** signed integer value might cause an integer overflow inside of the
16360
    ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
16361
    ** 255 bytes of overhead.  SQLite itself will never use anything near
16362
    ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
16363
    p = 0;
16364
  }else if( sqlite3GlobalConfig.bMemstat ){
16365
    sqlite3_mutex_enter(mem0.mutex);
16366
    mallocWithAlarm(n, &p);
16367
    sqlite3_mutex_leave(mem0.mutex);
16368
  }else{
16369
    p = sqlite3GlobalConfig.m.xMalloc(n);
16370
  }
16371
  return p;
16372
}
16373
16374
/*
16375
** This version of the memory allocation is for use by the application.
16376
** First make sure the memory subsystem is initialized, then do the
16377
** allocation.
16378
*/
16379
SQLITE_API void *sqlite3_malloc(int n){
16380
#ifndef SQLITE_OMIT_AUTOINIT
16381
  if( sqlite3_initialize() ) return 0;
16382
#endif
16383
  return sqlite3Malloc(n);
16384
}
16385
16386
/*
16387
** Each thread may only have a single outstanding allocation from
16388
** xScratchMalloc().  We verify this constraint in the single-threaded
16389
** case by setting scratchAllocOut to 1 when an allocation
16390
** is outstanding clearing it when the allocation is freed.
16391
*/
16392
#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16393
static int scratchAllocOut = 0;
16394
#endif
16395
16396
16397
/*
16398
** Allocate memory that is to be used and released right away.
16399
** This routine is similar to alloca() in that it is not intended
16400
** for situations where the memory might be held long-term.  This
16401
** routine is intended to get memory to old large transient data
16402
** structures that would not normally fit on the stack of an
16403
** embedded processor.
16404
*/
16405
SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
16406
  void *p;
16407
  assert( n>0 );
16408
16409
#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16410
  /* Verify that no more than one scratch allocation per thread
16411
  ** is outstanding at one time.  (This is only checked in the
16412
  ** single-threaded case since checking in the multi-threaded case
16413
  ** would be much more complicated.) */
16414
  assert( scratchAllocOut==0 );
16415
#endif
16416
16417
  if( sqlite3GlobalConfig.szScratch<n ){
16418
    goto scratch_overflow;
16419
  }else{  
16420
    sqlite3_mutex_enter(mem0.mutex);
16421
    if( mem0.nScratchFree==0 ){
16422
      sqlite3_mutex_leave(mem0.mutex);
16423
      goto scratch_overflow;
16424
    }else{
16425
      int i;
16426
      i = mem0.aScratchFree[--mem0.nScratchFree];
16427
      i *= sqlite3GlobalConfig.szScratch;
16428
      sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
16429
      sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
16430
      sqlite3_mutex_leave(mem0.mutex);
16431
      p = (void*)&((char*)sqlite3GlobalConfig.pScratch)[i];
16432
      assert(  (((u8*)p - (u8*)0) & 7)==0 );
16433
    }
16434
  }
16435
#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16436
  scratchAllocOut = p!=0;
16437
#endif
16438
16439
  return p;
16440
16441
scratch_overflow:
16442
  if( sqlite3GlobalConfig.bMemstat ){
16443
    sqlite3_mutex_enter(mem0.mutex);
16444
    sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
16445
    n = mallocWithAlarm(n, &p);
16446
    if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
16447
    sqlite3_mutex_leave(mem0.mutex);
16448
  }else{
16449
    p = sqlite3GlobalConfig.m.xMalloc(n);
16450
  }
16451
#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16452
  scratchAllocOut = p!=0;
16453
#endif
16454
  return p;    
16455
}
16456
SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
16457
  if( p ){
16458
16459
#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16460
    /* Verify that no more than one scratch allocation per thread
16461
    ** is outstanding at one time.  (This is only checked in the
16462
    ** single-threaded case since checking in the multi-threaded case
16463
    ** would be much more complicated.) */
16464
    assert( scratchAllocOut==1 );
16465
    scratchAllocOut = 0;
16466
#endif
16467
16468
    if( sqlite3GlobalConfig.pScratch==0
16469
           || p<sqlite3GlobalConfig.pScratch
16470
           || p>=(void*)mem0.aScratchFree ){
16471
      if( sqlite3GlobalConfig.bMemstat ){
16472
        int iSize = sqlite3MallocSize(p);
16473
        sqlite3_mutex_enter(mem0.mutex);
16474
        sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
16475
        sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
16476
        sqlite3GlobalConfig.m.xFree(p);
16477
        sqlite3_mutex_leave(mem0.mutex);
16478
      }else{
16479
        sqlite3GlobalConfig.m.xFree(p);
16480
      }
16481
    }else{
16482
      int i;
16483
      i = (int)((u8*)p - (u8*)sqlite3GlobalConfig.pScratch);
16484
      i /= sqlite3GlobalConfig.szScratch;
16485
      assert( i>=0 && i<sqlite3GlobalConfig.nScratch );
16486
      sqlite3_mutex_enter(mem0.mutex);
16487
      assert( mem0.nScratchFree<(u32)sqlite3GlobalConfig.nScratch );
16488
      mem0.aScratchFree[mem0.nScratchFree++] = i;
16489
      sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
16490
      sqlite3_mutex_leave(mem0.mutex);
16491
    }
16492
  }
16493
}
16494
16495
/*
16496
** TRUE if p is a lookaside memory allocation from db
16497
*/
16498
#ifndef SQLITE_OMIT_LOOKASIDE
16499
static int isLookaside(sqlite3 *db, void *p){
16500
  return db && p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
16501
}
16502
#else
16503
#define isLookaside(A,B) 0
16504
#endif
16505
16506
/*
16507
** Return the size of a memory allocation previously obtained from
16508
** sqlite3Malloc() or sqlite3_malloc().
16509
*/
16510
SQLITE_PRIVATE int sqlite3MallocSize(void *p){
16511
  return sqlite3GlobalConfig.m.xSize(p);
16512
}
16513
SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
16514
  assert( db==0 || sqlite3_mutex_held(db->mutex) );
16515
  if( isLookaside(db, p) ){
16516
    return db->lookaside.sz;
16517
  }else{
16518
    return sqlite3GlobalConfig.m.xSize(p);
16519
  }
16520
}
16521
16522
/*
16523
** Free memory previously obtained from sqlite3Malloc().
16524
*/
16525
SQLITE_API void sqlite3_free(void *p){
16526
  if( p==0 ) return;
16527
  if( sqlite3GlobalConfig.bMemstat ){
16528
    sqlite3_mutex_enter(mem0.mutex);
16529
    sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
16530
    sqlite3GlobalConfig.m.xFree(p);
16531
    sqlite3_mutex_leave(mem0.mutex);
16532
  }else{
16533
    sqlite3GlobalConfig.m.xFree(p);
16534
  }
16535
}
16536
16537
/*
16538
** Free memory that might be associated with a particular database
16539
** connection.
16540
*/
16541
SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
16542
  assert( db==0 || sqlite3_mutex_held(db->mutex) );
16543
  if( isLookaside(db, p) ){
16544
    LookasideSlot *pBuf = (LookasideSlot*)p;
16545
    pBuf->pNext = db->lookaside.pFree;
16546
    db->lookaside.pFree = pBuf;
16547
    db->lookaside.nOut--;
16548
  }else{
16549
    sqlite3_free(p);
16550
  }
16551
}
16552
16553
/*
16554
** Change the size of an existing memory allocation
16555
*/
16556
SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
16557
  int nOld, nNew;
16558
  void *pNew;
16559
  if( pOld==0 ){
16560
    return sqlite3Malloc(nBytes);
16561
  }
16562
  if( nBytes<=0 ){
16563
    sqlite3_free(pOld);
16564
    return 0;
16565
  }
16566
  if( nBytes>=0x7fffff00 ){
16567
    /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
16568
    return 0;
16569
  }
16570
  nOld = sqlite3MallocSize(pOld);
16571
  nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
16572
  if( nOld==nNew ){
16573
    pNew = pOld;
16574
  }else if( sqlite3GlobalConfig.bMemstat ){
16575
    sqlite3_mutex_enter(mem0.mutex);
16576
    sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
16577
    if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nNew-nOld >= 
16578
          mem0.alarmThreshold ){
16579
      sqlite3MallocAlarm(nNew-nOld);
16580
    }
16581
    pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
16582
    if( pNew==0 && mem0.alarmCallback ){
16583
      sqlite3MallocAlarm(nBytes);
16584
      pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
16585
    }
16586
    if( pNew ){
16587
      nNew = sqlite3MallocSize(pNew);
16588
      sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
16589
    }
16590
    sqlite3_mutex_leave(mem0.mutex);
16591
  }else{
16592
    pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
16593
  }
16594
  return pNew;
16595
}
16596
16597
/*
16598
** The public interface to sqlite3Realloc.  Make sure that the memory
16599
** subsystem is initialized prior to invoking sqliteRealloc.
16600
*/
16601
SQLITE_API void *sqlite3_realloc(void *pOld, int n){
16602
#ifndef SQLITE_OMIT_AUTOINIT
16603
  if( sqlite3_initialize() ) return 0;
16604
#endif
16605
  return sqlite3Realloc(pOld, n);
16606
}
16607
16608
16609
/*
16610
** Allocate and zero memory.
16611
*/ 
16612
SQLITE_PRIVATE void *sqlite3MallocZero(int n){
16613
  void *p = sqlite3Malloc(n);
16614
  if( p ){
16615
    memset(p, 0, n);
16616
  }
16617
  return p;
16618
}
16619
16620
/*
16621
** Allocate and zero memory.  If the allocation fails, make
16622
** the mallocFailed flag in the connection pointer.
16623
*/
16624
SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
16625
  void *p = sqlite3DbMallocRaw(db, n);
16626
  if( p ){
16627
    memset(p, 0, n);
16628
  }
16629
  return p;
16630
}
16631
16632
/*
16633
** Allocate and zero memory.  If the allocation fails, make
16634
** the mallocFailed flag in the connection pointer.
16635
**
16636
** If db!=0 and db->mallocFailed is true (indicating a prior malloc
16637
** failure on the same database connection) then always return 0.
16638
** Hence for a particular database connection, once malloc starts
16639
** failing, it fails consistently until mallocFailed is reset.
16640
** This is an important assumption.  There are many places in the
16641
** code that do things like this:
16642
**
16643
**         int *a = (int*)sqlite3DbMallocRaw(db, 100);
16644
**         int *b = (int*)sqlite3DbMallocRaw(db, 200);
16645
**         if( b ) a[10] = 9;
16646
**
16647
** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
16648
** that all prior mallocs (ex: "a") worked too.
16649
*/
16650
SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
16651
  void *p;
16652
  assert( db==0 || sqlite3_mutex_held(db->mutex) );
16653
#ifndef SQLITE_OMIT_LOOKASIDE
16654
  if( db ){
16655
    LookasideSlot *pBuf;
16656
    if( db->mallocFailed ){
16657
      return 0;
16658
    }
16659
    if( db->lookaside.bEnabled && n<=db->lookaside.sz
16660
         && (pBuf = db->lookaside.pFree)!=0 ){
16661
      db->lookaside.pFree = pBuf->pNext;
16662
      db->lookaside.nOut++;
16663
      if( db->lookaside.nOut>db->lookaside.mxOut ){
16664
        db->lookaside.mxOut = db->lookaside.nOut;
16665
      }
16666
      return (void*)pBuf;
16667
    }
16668
  }
16669
#else
16670
  if( db && db->mallocFailed ){
16671
    return 0;
16672
  }
16673
#endif
16674
  p = sqlite3Malloc(n);
16675
  if( !p && db ){
16676
    db->mallocFailed = 1;
16677
  }
16678
  return p;
16679
}
16680
16681
/*
16682
** Resize the block of memory pointed to by p to n bytes. If the
16683
** resize fails, set the mallocFailed flag in the connection object.
16684
*/
16685
SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
16686
  void *pNew = 0;
16687
  assert( db!=0 );
16688
  assert( sqlite3_mutex_held(db->mutex) );
16689
  if( db->mallocFailed==0 ){
16690
    if( p==0 ){
16691
      return sqlite3DbMallocRaw(db, n);
16692
    }
16693
    if( isLookaside(db, p) ){
16694
      if( n<=db->lookaside.sz ){
16695
        return p;
16696
      }
16697
      pNew = sqlite3DbMallocRaw(db, n);
16698
      if( pNew ){
16699
        memcpy(pNew, p, db->lookaside.sz);
16700
        sqlite3DbFree(db, p);
16701
      }
16702
    }else{
16703
      pNew = sqlite3_realloc(p, n);
16704
      if( !pNew ){
16705
        db->mallocFailed = 1;
16706
      }
16707
    }
16708
  }
16709
  return pNew;
16710
}
16711
16712
/*
16713
** Attempt to reallocate p.  If the reallocation fails, then free p
16714
** and set the mallocFailed flag in the database connection.
16715
*/
16716
SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
16717
  void *pNew;
16718
  pNew = sqlite3DbRealloc(db, p, n);
16719
  if( !pNew ){
16720
    sqlite3DbFree(db, p);
16721
  }
16722
  return pNew;
16723
}
16724
16725
/*
16726
** Make a copy of a string in memory obtained from sqliteMalloc(). These 
16727
** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
16728
** is because when memory debugging is turned on, these two functions are 
16729
** called via macros that record the current file and line number in the
16730
** ThreadData structure.
16731
*/
16732
SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
16733
  char *zNew;
16734
  size_t n;
16735
  if( z==0 ){
16736
    return 0;
16737
  }
16738
  n = sqlite3Strlen30(z) + 1;
16739
  assert( (n&0x7fffffff)==n );
16740
  zNew = sqlite3DbMallocRaw(db, (int)n);
16741
  if( zNew ){
16742
    memcpy(zNew, z, n);
16743
  }
16744
  return zNew;
16745
}
16746
SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
16747
  char *zNew;
16748
  if( z==0 ){
16749
    return 0;
16750
  }
16751
  assert( (n&0x7fffffff)==n );
16752
  zNew = sqlite3DbMallocRaw(db, n+1);
16753
  if( zNew ){
16754
    memcpy(zNew, z, n);
16755
    zNew[n] = 0;
16756
  }
16757
  return zNew;
16758
}
16759
16760
/*
16761
** Create a string from the zFromat argument and the va_list that follows.
16762
** Store the string in memory obtained from sqliteMalloc() and make *pz
16763
** point to that string.
16764
*/
16765
SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
16766
  va_list ap;
16767
  char *z;
16768
16769
  va_start(ap, zFormat);
16770
  z = sqlite3VMPrintf(db, zFormat, ap);
16771
  va_end(ap);
16772
  sqlite3DbFree(db, *pz);
16773
  *pz = z;
16774
}
16775
16776
16777
/*
16778
** This function must be called before exiting any API function (i.e. 
16779
** returning control to the user) that has called sqlite3_malloc or
16780
** sqlite3_realloc.
16781
**
16782
** The returned value is normally a copy of the second argument to this
16783
** function. However, if a malloc() failure has occurred since the previous
16784
** invocation SQLITE_NOMEM is returned instead. 
16785
**
16786
** If the first argument, db, is not NULL and a malloc() error has occurred,
16787
** then the connection error-code (the value returned by sqlite3_errcode())
16788
** is set to SQLITE_NOMEM.
16789
*/
16790
SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
16791
  /* If the db handle is not NULL, then we must hold the connection handle
16792
  ** mutex here. Otherwise the read (and possible write) of db->mallocFailed 
16793
  ** is unsafe, as is the call to sqlite3Error().
16794
  */
16795
  assert( !db || sqlite3_mutex_held(db->mutex) );
16796
  if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
16797
    sqlite3Error(db, SQLITE_NOMEM, 0);
16798
    db->mallocFailed = 0;
16799
    rc = SQLITE_NOMEM;
16800
  }
16801
  return rc & (db ? db->errMask : 0xff);
16802
}
16803
16804
/************** End of malloc.c **********************************************/
16805
/************** Begin file printf.c ******************************************/
16806
/*
16807
** The "printf" code that follows dates from the 1980's.  It is in
16808
** the public domain.  The original comments are included here for
16809
** completeness.  They are very out-of-date but might be useful as
16810
** an historical reference.  Most of the "enhancements" have been backed
16811
** out so that the functionality is now the same as standard printf().
16812
**
16813
**************************************************************************
16814
**
16815
** The following modules is an enhanced replacement for the "printf" subroutines
16816
** found in the standard C library.  The following enhancements are
16817
** supported:
16818
**
16819
**      +  Additional functions.  The standard set of "printf" functions
16820
**         includes printf, fprintf, sprintf, vprintf, vfprintf, and
16821
**         vsprintf.  This module adds the following:
16822
**
16823
**           *  snprintf -- Works like sprintf, but has an extra argument
16824
**                          which is the size of the buffer written to.
16825
**
16826
**           *  mprintf --  Similar to sprintf.  Writes output to memory
16827
**                          obtained from malloc.
16828
**
16829
**           *  xprintf --  Calls a function to dispose of output.
16830
**
16831
**           *  nprintf --  No output, but returns the number of characters
16832
**                          that would have been output by printf.
16833
**
16834
**           *  A v- version (ex: vsnprintf) of every function is also
16835
**              supplied.
16836
**
16837
**      +  A few extensions to the formatting notation are supported:
16838
**
16839
**           *  The "=" flag (similar to "-") causes the output to be
16840
**              be centered in the appropriately sized field.
16841
**
16842
**           *  The %b field outputs an integer in binary notation.
16843
**
16844
**           *  The %c field now accepts a precision.  The character output
16845
**              is repeated by the number of times the precision specifies.
16846
**
16847
**           *  The %' field works like %c, but takes as its character the
16848
**              next character of the format string, instead of the next
16849
**              argument.  For example,  printf("%.78'-")  prints 78 minus
16850
**              signs, the same as  printf("%.78c",'-').
16851
**
16852
**      +  When compiled using GCC on a SPARC, this version of printf is
16853
**         faster than the library printf for SUN OS 4.1.
16854
**
16855
**      +  All functions are fully reentrant.
16856
**
16857
*/
16858
16859
/*
16860
** Conversion types fall into various categories as defined by the
16861
** following enumeration.
16862
*/
16863
#define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
16864
#define etFLOAT       2 /* Floating point.  %f */
16865
#define etEXP         3 /* Exponentional notation. %e and %E */
16866
#define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
16867
#define etSIZE        5 /* Return number of characters processed so far. %n */
16868
#define etSTRING      6 /* Strings. %s */
16869
#define etDYNSTRING   7 /* Dynamically allocated strings. %z */
16870
#define etPERCENT     8 /* Percent symbol. %% */
16871
#define etCHARX       9 /* Characters. %c */
16872
/* The rest are extensions, not normally found in printf() */
16873
#define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
16874
#define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
16875
                          NULL pointers replaced by SQL NULL.  %Q */
16876
#define etTOKEN      12 /* a pointer to a Token structure */
16877
#define etSRCLIST    13 /* a pointer to a SrcList */
16878
#define etPOINTER    14 /* The %p conversion */
16879
#define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
16880
#define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
16881
16882
#define etINVALID     0 /* Any unrecognized conversion type */
16883
16884
16885
/*
16886
** An "etByte" is an 8-bit unsigned value.
16887
*/
16888
typedef unsigned char etByte;
16889
16890
/*
16891
** Each builtin conversion character (ex: the 'd' in "%d") is described
16892
** by an instance of the following structure
16893
*/
16894
typedef struct et_info {   /* Information about each format field */
16895
  char fmttype;            /* The format field code letter */
16896
  etByte base;             /* The base for radix conversion */
16897
  etByte flags;            /* One or more of FLAG_ constants below */
16898
  etByte type;             /* Conversion paradigm */
16899
  etByte charset;          /* Offset into aDigits[] of the digits string */
16900
  etByte prefix;           /* Offset into aPrefix[] of the prefix string */
16901
} et_info;
16902
16903
/*
16904
** Allowed values for et_info.flags
16905
*/
16906
#define FLAG_SIGNED  1     /* True if the value to convert is signed */
16907
#define FLAG_INTERN  2     /* True if for internal use only */
16908
#define FLAG_STRING  4     /* Allow infinity precision */
16909
16910
16911
/*
16912
** The following table is searched linearly, so it is good to put the
16913
** most frequently used conversion types first.
16914
*/
16915
static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
16916
static const char aPrefix[] = "-x0\000X0";
16917
static const et_info fmtinfo[] = {
16918
  {  'd', 10, 1, etRADIX,      0,  0 },
16919
  {  's',  0, 4, etSTRING,     0,  0 },
16920
  {  'g',  0, 1, etGENERIC,    30, 0 },
16921
  {  'z',  0, 4, etDYNSTRING,  0,  0 },
16922
  {  'q',  0, 4, etSQLESCAPE,  0,  0 },
16923
  {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
16924
  {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
16925
  {  'c',  0, 0, etCHARX,      0,  0 },
16926
  {  'o',  8, 0, etRADIX,      0,  2 },
16927
  {  'u', 10, 0, etRADIX,      0,  0 },
16928
  {  'x', 16, 0, etRADIX,      16, 1 },
16929
  {  'X', 16, 0, etRADIX,      0,  4 },
16930
#ifndef SQLITE_OMIT_FLOATING_POINT
16931
  {  'f',  0, 1, etFLOAT,      0,  0 },
16932
  {  'e',  0, 1, etEXP,        30, 0 },
16933
  {  'E',  0, 1, etEXP,        14, 0 },
16934
  {  'G',  0, 1, etGENERIC,    14, 0 },
16935
#endif
16936
  {  'i', 10, 1, etRADIX,      0,  0 },
16937
  {  'n',  0, 0, etSIZE,       0,  0 },
16938
  {  '%',  0, 0, etPERCENT,    0,  0 },
16939
  {  'p', 16, 0, etPOINTER,    0,  1 },
16940
16941
/* All the rest have the FLAG_INTERN bit set and are thus for internal
16942
** use only */
16943
  {  'T',  0, 2, etTOKEN,      0,  0 },
16944
  {  'S',  0, 2, etSRCLIST,    0,  0 },
16945
  {  'r', 10, 3, etORDINAL,    0,  0 },
16946
};
16947
16948
/*
16949
** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
16950
** conversions will work.
16951
*/
16952
#ifndef SQLITE_OMIT_FLOATING_POINT
16953
/*
16954
** "*val" is a double such that 0.1 <= *val < 10.0
16955
** Return the ascii code for the leading digit of *val, then
16956
** multiply "*val" by 10.0 to renormalize.
16957
**
16958
** Example:
16959
**     input:     *val = 3.14159
16960
**     output:    *val = 1.4159    function return = '3'
16961
**
16962
** The counter *cnt is incremented each time.  After counter exceeds
16963
** 16 (the number of significant digits in a 64-bit float) '0' is
16964
** always returned.
16965
*/
16966
static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
16967
  int digit;
16968
  LONGDOUBLE_TYPE d;
16969
  if( (*cnt)++ >= 16 ) return '0';
16970
  digit = (int)*val;
16971
  d = digit;
16972
  digit += '0';
16973
  *val = (*val - d)*10.0;
16974
  return (char)digit;
16975
}
16976
#endif /* SQLITE_OMIT_FLOATING_POINT */
16977
16978
/*
16979
** Append N space characters to the given string buffer.
16980
*/
16981
static void appendSpace(StrAccum *pAccum, int N){
16982
  static const char zSpaces[] = "                             ";
16983
  while( N>=(int)sizeof(zSpaces)-1 ){
16984
    sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
16985
    N -= sizeof(zSpaces)-1;
16986
  }
16987
  if( N>0 ){
16988
    sqlite3StrAccumAppend(pAccum, zSpaces, N);
16989
  }
16990
}
16991
16992
/*
16993
** On machines with a small stack size, you can redefine the
16994
** SQLITE_PRINT_BUF_SIZE to be less than 350.
16995
*/
16996
#ifndef SQLITE_PRINT_BUF_SIZE
16997
# if defined(SQLITE_SMALL_STACK)
16998
#   define SQLITE_PRINT_BUF_SIZE 50
16999
# else
17000
#   define SQLITE_PRINT_BUF_SIZE 350
17001
# endif
17002
#endif
17003
#define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
17004
17005
/*
17006
** The root program.  All variations call this core.
17007
**
17008
** INPUTS:
17009
**   func   This is a pointer to a function taking three arguments
17010
**            1. A pointer to anything.  Same as the "arg" parameter.
17011
**            2. A pointer to the list of characters to be output
17012
**               (Note, this list is NOT null terminated.)
17013
**            3. An integer number of characters to be output.
17014
**               (Note: This number might be zero.)
17015
**
17016
**   arg    This is the pointer to anything which will be passed as the
17017
**          first argument to "func".  Use it for whatever you like.
17018
**
17019
**   fmt    This is the format string, as in the usual print.
17020
**
17021
**   ap     This is a pointer to a list of arguments.  Same as in
17022
**          vfprint.
17023
**
17024
** OUTPUTS:
17025
**          The return value is the total number of characters sent to
17026
**          the function "func".  Returns -1 on a error.
17027
**
17028
** Note that the order in which automatic variables are declared below
17029
** seems to make a big difference in determining how fast this beast
17030
** will run.
17031
*/
17032
SQLITE_PRIVATE void sqlite3VXPrintf(
17033
  StrAccum *pAccum,                  /* Accumulate results here */
17034
  int useExtended,                   /* Allow extended %-conversions */
17035
  const char *fmt,                   /* Format string */
17036
  va_list ap                         /* arguments */
17037
){
17038
  int c;                     /* Next character in the format string */
17039
  char *bufpt;               /* Pointer to the conversion buffer */
17040
  int precision;             /* Precision of the current field */
17041
  int length;                /* Length of the field */
17042
  int idx;                   /* A general purpose loop counter */
17043
  int width;                 /* Width of the current field */
17044
  etByte flag_leftjustify;   /* True if "-" flag is present */
17045
  etByte flag_plussign;      /* True if "+" flag is present */
17046
  etByte flag_blanksign;     /* True if " " flag is present */
17047
  etByte flag_alternateform; /* True if "#" flag is present */
17048
  etByte flag_altform2;      /* True if "!" flag is present */
17049
  etByte flag_zeropad;       /* True if field width constant starts with zero */
17050
  etByte flag_long;          /* True if "l" flag is present */
17051
  etByte flag_longlong;      /* True if the "ll" flag is present */
17052
  etByte done;               /* Loop termination flag */
17053
  sqlite_uint64 longvalue;   /* Value for integer types */
17054
  LONGDOUBLE_TYPE realvalue; /* Value for real types */
17055
  const et_info *infop;      /* Pointer to the appropriate info structure */
17056
  char buf[etBUFSIZE];       /* Conversion buffer */
17057
  char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
17058
  etByte xtype = 0;          /* Conversion paradigm */
17059
  char *zExtra;              /* Extra memory used for etTCLESCAPE conversions */
17060
#ifndef SQLITE_OMIT_FLOATING_POINT
17061
  int  exp, e2;              /* exponent of real numbers */
17062
  double rounder;            /* Used for rounding floating point values */
17063
  etByte flag_dp;            /* True if decimal point should be shown */
17064
  etByte flag_rtz;           /* True if trailing zeros should be removed */
17065
  etByte flag_exp;           /* True to force display of the exponent */
17066
  int nsd;                   /* Number of significant digits returned */
17067
#endif
17068
17069
  length = 0;
17070
  bufpt = 0;
17071
  for(; (c=(*fmt))!=0; ++fmt){
17072
    if( c!='%' ){
17073
      int amt;
17074
      bufpt = (char *)fmt;
17075
      amt = 1;
17076
      while( (c=(*++fmt))!='%' && c!=0 ) amt++;
17077
      sqlite3StrAccumAppend(pAccum, bufpt, amt);
17078
      if( c==0 ) break;
17079
    }
17080
    if( (c=(*++fmt))==0 ){
17081
      sqlite3StrAccumAppend(pAccum, "%", 1);
17082
      break;
17083
    }
17084
    /* Find out what flags are present */
17085
    flag_leftjustify = flag_plussign = flag_blanksign = 
17086
     flag_alternateform = flag_altform2 = flag_zeropad = 0;
17087
    done = 0;
17088
    do{
17089
      switch( c ){
17090
        case '-':   flag_leftjustify = 1;     break;
17091
        case '+':   flag_plussign = 1;        break;
17092
        case ' ':   flag_blanksign = 1;       break;
17093
        case '#':   flag_alternateform = 1;   break;
17094
        case '!':   flag_altform2 = 1;        break;
17095
        case '0':   flag_zeropad = 1;         break;
17096
        default:    done = 1;                 break;
17097
      }
17098
    }while( !done && (c=(*++fmt))!=0 );
17099
    /* Get the field width */
17100
    width = 0;
17101
    if( c=='*' ){
17102
      width = va_arg(ap,int);
17103
      if( width<0 ){
17104
        flag_leftjustify = 1;
17105
        width = -width;
17106
      }
17107
      c = *++fmt;
17108
    }else{
17109
      while( c>='0' && c<='9' ){
17110
        width = width*10 + c - '0';
17111
        c = *++fmt;
17112
      }
17113
    }
17114
    if( width > etBUFSIZE-10 ){
17115
      width = etBUFSIZE-10;
17116
    }
17117
    /* Get the precision */
17118
    if( c=='.' ){
17119
      precision = 0;
17120
      c = *++fmt;
17121
      if( c=='*' ){
17122
        precision = va_arg(ap,int);
17123
        if( precision<0 ) precision = -precision;
17124
        c = *++fmt;
17125
      }else{
17126
        while( c>='0' && c<='9' ){
17127
          precision = precision*10 + c - '0';
17128
          c = *++fmt;
17129
        }
17130
      }
17131
    }else{
17132
      precision = -1;
17133
    }
17134
    /* Get the conversion type modifier */
17135
    if( c=='l' ){
17136
      flag_long = 1;
17137
      c = *++fmt;
17138
      if( c=='l' ){
17139
        flag_longlong = 1;
17140
        c = *++fmt;
17141
      }else{
17142
        flag_longlong = 0;
17143
      }
17144
    }else{
17145
      flag_long = flag_longlong = 0;
17146
    }
17147
    /* Fetch the info entry for the field */
17148
    infop = &fmtinfo[0];
17149
    xtype = etINVALID;
17150
    for(idx=0; idx<ArraySize(fmtinfo); idx++){
17151
      if( c==fmtinfo[idx].fmttype ){
17152
        infop = &fmtinfo[idx];
17153
        if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
17154
          xtype = infop->type;
17155
        }else{
17156
          return;
17157
        }
17158
        break;
17159
      }
17160
    }
17161
    zExtra = 0;
17162
17163
17164
    /* Limit the precision to prevent overflowing buf[] during conversion */
17165
    if( precision>etBUFSIZE-40 && (infop->flags & FLAG_STRING)==0 ){
17166
      precision = etBUFSIZE-40;
17167
    }
17168
17169
    /*
17170
    ** At this point, variables are initialized as follows:
17171
    **
17172
    **   flag_alternateform          TRUE if a '#' is present.
17173
    **   flag_altform2               TRUE if a '!' is present.
17174
    **   flag_plussign               TRUE if a '+' is present.
17175
    **   flag_leftjustify            TRUE if a '-' is present or if the
17176
    **                               field width was negative.
17177
    **   flag_zeropad                TRUE if the width began with 0.
17178
    **   flag_long                   TRUE if the letter 'l' (ell) prefixed
17179
    **                               the conversion character.
17180
    **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
17181
    **                               the conversion character.
17182
    **   flag_blanksign              TRUE if a ' ' is present.
17183
    **   width                       The specified field width.  This is
17184
    **                               always non-negative.  Zero is the default.
17185
    **   precision                   The specified precision.  The default
17186
    **                               is -1.
17187
    **   xtype                       The class of the conversion.
17188
    **   infop                       Pointer to the appropriate info struct.
17189
    */
17190
    switch( xtype ){
17191
      case etPOINTER:
17192
        flag_longlong = sizeof(char*)==sizeof(i64);
17193
        flag_long = sizeof(char*)==sizeof(long int);
17194
        /* Fall through into the next case */
17195
      case etORDINAL:
17196
      case etRADIX:
17197
        if( infop->flags & FLAG_SIGNED ){
17198
          i64 v;
17199
          if( flag_longlong ){
17200
            v = va_arg(ap,i64);
17201
          }else if( flag_long ){
17202
            v = va_arg(ap,long int);
17203
          }else{
17204
            v = va_arg(ap,int);
17205
          }
17206
          if( v<0 ){
17207
            longvalue = -v;
17208
            prefix = '-';
17209
          }else{
17210
            longvalue = v;
17211
            if( flag_plussign )        prefix = '+';
17212
            else if( flag_blanksign )  prefix = ' ';
17213
            else                       prefix = 0;
17214
          }
17215
        }else{
17216
          if( flag_longlong ){
17217
            longvalue = va_arg(ap,u64);
17218
          }else if( flag_long ){
17219
            longvalue = va_arg(ap,unsigned long int);
17220
          }else{
17221
            longvalue = va_arg(ap,unsigned int);
17222
          }
17223
          prefix = 0;
17224
        }
17225
        if( longvalue==0 ) flag_alternateform = 0;
17226
        if( flag_zeropad && precision<width-(prefix!=0) ){
17227
          precision = width-(prefix!=0);
17228
        }
17229
        bufpt = &buf[etBUFSIZE-1];
17230
        if( xtype==etORDINAL ){
17231
          static const char zOrd[] = "thstndrd";
17232
          int x = (int)(longvalue % 10);
17233
          if( x>=4 || (longvalue/10)%10==1 ){
17234
            x = 0;
17235
          }
17236
          buf[etBUFSIZE-3] = zOrd[x*2];
17237
          buf[etBUFSIZE-2] = zOrd[x*2+1];
17238
          bufpt -= 2;
17239
        }
17240
        {
17241
          register const char *cset;      /* Use registers for speed */
17242
          register int base;
17243
          cset = &aDigits[infop->charset];
17244
          base = infop->base;
17245
          do{                                           /* Convert to ascii */
17246
            *(--bufpt) = cset[longvalue%base];
17247
            longvalue = longvalue/base;
17248
          }while( longvalue>0 );
17249
        }
17250
        length = (int)(&buf[etBUFSIZE-1]-bufpt);
17251
        for(idx=precision-length; idx>0; idx--){
17252
          *(--bufpt) = '0';                             /* Zero pad */
17253
        }
17254
        if( prefix ) *(--bufpt) = prefix;               /* Add sign */
17255
        if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
17256
          const char *pre;
17257
          char x;
17258
          pre = &aPrefix[infop->prefix];
17259
          for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
17260
        }
17261
        length = (int)(&buf[etBUFSIZE-1]-bufpt);
17262
        break;
17263
      case etFLOAT:
17264
      case etEXP:
17265
      case etGENERIC:
17266
        realvalue = va_arg(ap,double);
17267
#ifdef SQLITE_OMIT_FLOATING_POINT
17268
        length = 0;
17269
#else
17270
        if( precision<0 ) precision = 6;         /* Set default precision */
17271
        if( precision>etBUFSIZE/2-10 ) precision = etBUFSIZE/2-10;
17272
        if( realvalue<0.0 ){
17273
          realvalue = -realvalue;
17274
          prefix = '-';
17275
        }else{
17276
          if( flag_plussign )          prefix = '+';
17277
          else if( flag_blanksign )    prefix = ' ';
17278
          else                         prefix = 0;
17279
        }
17280
        if( xtype==etGENERIC && precision>0 ) precision--;
17281
#if 0
17282
        /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
17283
        for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
17284
#else
17285
        /* It makes more sense to use 0.5 */
17286
        for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
17287
#endif
17288
        if( xtype==etFLOAT ) realvalue += rounder;
17289
        /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
17290
        exp = 0;
17291
        if( sqlite3IsNaN((double)realvalue) ){
17292
          bufpt = "NaN";
17293
          length = 3;
17294
          break;
17295
        }
17296
        if( realvalue>0.0 ){
17297
          while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
17298
          while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
17299
          while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
17300
          while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
17301
          while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
17302
          if( exp>350 ){
17303
            if( prefix=='-' ){
17304
              bufpt = "-Inf";
17305
            }else if( prefix=='+' ){
17306
              bufpt = "+Inf";
17307
            }else{
17308
              bufpt = "Inf";
17309
            }
17310
            length = sqlite3Strlen30(bufpt);
17311
            break;
17312
          }
17313
        }
17314
        bufpt = buf;
17315
        /*
17316
        ** If the field type is etGENERIC, then convert to either etEXP
17317
        ** or etFLOAT, as appropriate.
17318
        */
17319
        flag_exp = xtype==etEXP;
17320
        if( xtype!=etFLOAT ){
17321
          realvalue += rounder;
17322
          if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
17323
        }
17324
        if( xtype==etGENERIC ){
17325
          flag_rtz = !flag_alternateform;
17326
          if( exp<-4 || exp>precision ){
17327
            xtype = etEXP;
17328
          }else{
17329
            precision = precision - exp;
17330
            xtype = etFLOAT;
17331
          }
17332
        }else{
17333
          flag_rtz = 0;
17334
        }
17335
        if( xtype==etEXP ){
17336
          e2 = 0;
17337
        }else{
17338
          e2 = exp;
17339
        }
17340
        nsd = 0;
17341
        flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
17342
        /* The sign in front of the number */
17343
        if( prefix ){
17344
          *(bufpt++) = prefix;
17345
        }
17346
        /* Digits prior to the decimal point */
17347
        if( e2<0 ){
17348
          *(bufpt++) = '0';
17349
        }else{
17350
          for(; e2>=0; e2--){
17351
            *(bufpt++) = et_getdigit(&realvalue,&nsd);
17352
          }
17353
        }
17354
        /* The decimal point */
17355
        if( flag_dp ){
17356
          *(bufpt++) = '.';
17357
        }
17358
        /* "0" digits after the decimal point but before the first
17359
        ** significant digit of the number */
17360
        for(e2++; e2<0; precision--, e2++){
17361
          assert( precision>0 );
17362
          *(bufpt++) = '0';
17363
        }
17364
        /* Significant digits after the decimal point */
17365
        while( (precision--)>0 ){
17366
          *(bufpt++) = et_getdigit(&realvalue,&nsd);
17367
        }
17368
        /* Remove trailing zeros and the "." if no digits follow the "." */
17369
        if( flag_rtz && flag_dp ){
17370
          while( bufpt[-1]=='0' ) *(--bufpt) = 0;
17371
          assert( bufpt>buf );
17372
          if( bufpt[-1]=='.' ){
17373
            if( flag_altform2 ){
17374
              *(bufpt++) = '0';
17375
            }else{
17376
              *(--bufpt) = 0;
17377
            }
17378
          }
17379
        }
17380
        /* Add the "eNNN" suffix */
17381
        if( flag_exp || xtype==etEXP ){
17382
          *(bufpt++) = aDigits[infop->charset];
17383
          if( exp<0 ){
17384
            *(bufpt++) = '-'; exp = -exp;
17385
          }else{
17386
            *(bufpt++) = '+';
17387
          }
17388
          if( exp>=100 ){
17389
            *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
17390
            exp %= 100;
17391
          }
17392
          *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
17393
          *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
17394
        }
17395
        *bufpt = 0;
17396
17397
        /* The converted number is in buf[] and zero terminated. Output it.
17398
        ** Note that the number is in the usual order, not reversed as with
17399
        ** integer conversions. */
17400
        length = (int)(bufpt-buf);
17401
        bufpt = buf;
17402
17403
        /* Special case:  Add leading zeros if the flag_zeropad flag is
17404
        ** set and we are not left justified */
17405
        if( flag_zeropad && !flag_leftjustify && length < width){
17406
          int i;
17407
          int nPad = width - length;
17408
          for(i=width; i>=nPad; i--){
17409
            bufpt[i] = bufpt[i-nPad];
17410
          }
17411
          i = prefix!=0;
17412
          while( nPad-- ) bufpt[i++] = '0';
17413
          length = width;
17414
        }
17415
#endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
17416
        break;
17417
      case etSIZE:
17418
        *(va_arg(ap,int*)) = pAccum->nChar;
17419
        length = width = 0;
17420
        break;
17421
      case etPERCENT:
17422
        buf[0] = '%';
17423
        bufpt = buf;
17424
        length = 1;
17425
        break;
17426
      case etCHARX:
17427
        c = va_arg(ap,int);
17428
        buf[0] = (char)c;
17429
        if( precision>=0 ){
17430
          for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
17431
          length = precision;
17432
        }else{
17433
          length =1;
17434
        }
17435
        bufpt = buf;
17436
        break;
17437
      case etSTRING:
17438
      case etDYNSTRING:
17439
        bufpt = va_arg(ap,char*);
17440
        if( bufpt==0 ){
17441
          bufpt = "";
17442
        }else if( xtype==etDYNSTRING ){
17443
          zExtra = bufpt;
17444
        }
17445
        if( precision>=0 ){
17446
          for(length=0; length<precision && bufpt[length]; length++){}
17447
        }else{
17448
          length = sqlite3Strlen30(bufpt);
17449
        }
17450
        break;
17451
      case etSQLESCAPE:
17452
      case etSQLESCAPE2:
17453
      case etSQLESCAPE3: {
17454
        int i, j, k, n, isnull;
17455
        int needQuote;
17456
        char ch;
17457
        char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
17458
        char *escarg = va_arg(ap,char*);
17459
        isnull = escarg==0;
17460
        if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
17461
        k = precision;
17462
        for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
17463
          if( ch==q )  n++;
17464
        }
17465
        needQuote = !isnull && xtype==etSQLESCAPE2;
17466
        n += i + 1 + needQuote*2;
17467
        if( n>etBUFSIZE ){
17468
          bufpt = zExtra = sqlite3Malloc( n );
17469
          if( bufpt==0 ){
17470
            pAccum->mallocFailed = 1;
17471
            return;
17472
          }
17473
        }else{
17474
          bufpt = buf;
17475
        }
17476
        j = 0;
17477
        if( needQuote ) bufpt[j++] = q;
17478
        k = i;
17479
        for(i=0; i<k; i++){
17480
          bufpt[j++] = ch = escarg[i];
17481
          if( ch==q ) bufpt[j++] = ch;
17482
        }
17483
        if( needQuote ) bufpt[j++] = q;
17484
        bufpt[j] = 0;
17485
        length = j;
17486
        /* The precision in %q and %Q means how many input characters to
17487
        ** consume, not the length of the output...
17488
        ** if( precision>=0 && precision<length ) length = precision; */
17489
        break;
17490
      }
17491
      case etTOKEN: {
17492
        Token *pToken = va_arg(ap, Token*);
17493
        if( pToken ){
17494
          sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
17495
        }
17496
        length = width = 0;
17497
        break;
17498
      }
17499
      case etSRCLIST: {
17500
        SrcList *pSrc = va_arg(ap, SrcList*);
17501
        int k = va_arg(ap, int);
17502
        struct SrcList_item *pItem = &pSrc->a[k];
17503
        assert( k>=0 && k<pSrc->nSrc );
17504
        if( pItem->zDatabase ){
17505
          sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
17506
          sqlite3StrAccumAppend(pAccum, ".", 1);
17507
        }
17508
        sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
17509
        length = width = 0;
17510
        break;
17511
      }
17512
      default: {
17513
        assert( xtype==etINVALID );
17514
        return;
17515
      }
17516
    }/* End switch over the format type */
17517
    /*
17518
    ** The text of the conversion is pointed to by "bufpt" and is
17519
    ** "length" characters long.  The field width is "width".  Do
17520
    ** the output.
17521
    */
17522
    if( !flag_leftjustify ){
17523
      register int nspace;
17524
      nspace = width-length;
17525
      if( nspace>0 ){
17526
        appendSpace(pAccum, nspace);
17527
      }
17528
    }
17529
    if( length>0 ){
17530
      sqlite3StrAccumAppend(pAccum, bufpt, length);
17531
    }
17532
    if( flag_leftjustify ){
17533
      register int nspace;
17534
      nspace = width-length;
17535
      if( nspace>0 ){
17536
        appendSpace(pAccum, nspace);
17537
      }
17538
    }
17539
    if( zExtra ){
17540
      sqlite3_free(zExtra);
17541
    }
17542
  }/* End for loop over the format string */
17543
} /* End of function */
17544
17545
/*
17546
** Append N bytes of text from z to the StrAccum object.
17547
*/
17548
SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
17549
  assert( z!=0 || N==0 );
17550
  if( p->tooBig | p->mallocFailed ){
17551
    testcase(p->tooBig);
17552
    testcase(p->mallocFailed);
17553
    return;
17554
  }
17555
  if( N<0 ){
17556
    N = sqlite3Strlen30(z);
17557
  }
17558
  if( N==0 || NEVER(z==0) ){
17559
    return;
17560
  }
17561
  if( p->nChar+N >= p->nAlloc ){
17562
    char *zNew;
17563
    if( !p->useMalloc ){
17564
      p->tooBig = 1;
17565
      N = p->nAlloc - p->nChar - 1;
17566
      if( N<=0 ){
17567
        return;
17568
      }
17569
    }else{
17570
      i64 szNew = p->nChar;
17571
      szNew += N + 1;
17572
      if( szNew > p->mxAlloc ){
17573
        sqlite3StrAccumReset(p);
17574
        p->tooBig = 1;
17575
        return;
17576
      }else{
17577
        p->nAlloc = (int)szNew;
17578
      }
17579
      zNew = sqlite3DbMallocRaw(p->db, p->nAlloc );
17580
      if( zNew ){
17581
        memcpy(zNew, p->zText, p->nChar);
17582
        sqlite3StrAccumReset(p);
17583
        p->zText = zNew;
17584
      }else{
17585
        p->mallocFailed = 1;
17586
        sqlite3StrAccumReset(p);
17587
        return;
17588
      }
17589
    }
17590
  }
17591
  memcpy(&p->zText[p->nChar], z, N);
17592
  p->nChar += N;
17593
}
17594
17595
/*
17596
** Finish off a string by making sure it is zero-terminated.
17597
** Return a pointer to the resulting string.  Return a NULL
17598
** pointer if any kind of error was encountered.
17599
*/
17600
SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
17601
  if( p->zText ){
17602
    p->zText[p->nChar] = 0;
17603
    if( p->useMalloc && p->zText==p->zBase ){
17604
      p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
17605
      if( p->zText ){
17606
        memcpy(p->zText, p->zBase, p->nChar+1);
17607
      }else{
17608
        p->mallocFailed = 1;
17609
      }
17610
    }
17611
  }
17612
  return p->zText;
17613
}
17614
17615
/*
17616
** Reset an StrAccum string.  Reclaim all malloced memory.
17617
*/
17618
SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
17619
  if( p->zText!=p->zBase ){
17620
    sqlite3DbFree(p->db, p->zText);
17621
  }
17622
  p->zText = 0;
17623
}
17624
17625
/*
17626
** Initialize a string accumulator
17627
*/
17628
SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
17629
  p->zText = p->zBase = zBase;
17630
  p->db = 0;
17631
  p->nChar = 0;
17632
  p->nAlloc = n;
17633
  p->mxAlloc = mx;
17634
  p->useMalloc = 1;
17635
  p->tooBig = 0;
17636
  p->mallocFailed = 0;
17637
}
17638
17639
/*
17640
** Print into memory obtained from sqliteMalloc().  Use the internal
17641
** %-conversion extensions.
17642
*/
17643
SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
17644
  char *z;
17645
  char zBase[SQLITE_PRINT_BUF_SIZE];
17646
  StrAccum acc;
17647
  assert( db!=0 );
17648
  sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
17649
                      db->aLimit[SQLITE_LIMIT_LENGTH]);
17650
  acc.db = db;
17651
  sqlite3VXPrintf(&acc, 1, zFormat, ap);
17652
  z = sqlite3StrAccumFinish(&acc);
17653
  if( acc.mallocFailed ){
17654
    db->mallocFailed = 1;
17655
  }
17656
  return z;
17657
}
17658
17659
/*
17660
** Print into memory obtained from sqliteMalloc().  Use the internal
17661
** %-conversion extensions.
17662
*/
17663
SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
17664
  va_list ap;
17665
  char *z;
17666
  va_start(ap, zFormat);
17667
  z = sqlite3VMPrintf(db, zFormat, ap);
17668
  va_end(ap);
17669
  return z;
17670
}
17671
17672
/*
17673
** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
17674
** the string and before returnning.  This routine is intended to be used
17675
** to modify an existing string.  For example:
17676
**
17677
**       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
17678
**
17679
*/
17680
SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
17681
  va_list ap;
17682
  char *z;
17683
  va_start(ap, zFormat);
17684
  z = sqlite3VMPrintf(db, zFormat, ap);
17685
  va_end(ap);
17686
  sqlite3DbFree(db, zStr);
17687
  return z;
17688
}
17689
17690
/*
17691
** Print into memory obtained from sqlite3_malloc().  Omit the internal
17692
** %-conversion extensions.
17693
*/
17694
SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
17695
  char *z;
17696
  char zBase[SQLITE_PRINT_BUF_SIZE];
17697
  StrAccum acc;
17698
#ifndef SQLITE_OMIT_AUTOINIT
17699
  if( sqlite3_initialize() ) return 0;
17700
#endif
17701
  sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
17702
  sqlite3VXPrintf(&acc, 0, zFormat, ap);
17703
  z = sqlite3StrAccumFinish(&acc);
17704
  return z;
17705
}
17706
17707
/*
17708
** Print into memory obtained from sqlite3_malloc()().  Omit the internal
17709
** %-conversion extensions.
17710
*/
17711
SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
17712
  va_list ap;
17713
  char *z;
17714
#ifndef SQLITE_OMIT_AUTOINIT
17715
  if( sqlite3_initialize() ) return 0;
17716
#endif
17717
  va_start(ap, zFormat);
17718
  z = sqlite3_vmprintf(zFormat, ap);
17719
  va_end(ap);
17720
  return z;
17721
}
17722
17723
/*
17724
** sqlite3_snprintf() works like snprintf() except that it ignores the
17725
** current locale settings.  This is important for SQLite because we
17726
** are not able to use a "," as the decimal point in place of "." as
17727
** specified by some locales.
17728
*/
17729
SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
17730
  char *z;
17731
  va_list ap;
17732
  StrAccum acc;
17733
17734
  if( n<=0 ){
17735
    return zBuf;
17736
  }
17737
  sqlite3StrAccumInit(&acc, zBuf, n, 0);
17738
  acc.useMalloc = 0;
17739
  va_start(ap,zFormat);
17740
  sqlite3VXPrintf(&acc, 0, zFormat, ap);
17741
  va_end(ap);
17742
  z = sqlite3StrAccumFinish(&acc);
17743
  return z;
17744
}
17745
17746
/*
17747
** This is the routine that actually formats the sqlite3_log() message.
17748
** We house it in a separate routine from sqlite3_log() to avoid using
17749
** stack space on small-stack systems when logging is disabled.
17750
**
17751
** sqlite3_log() must render into a static buffer.  It cannot dynamically
17752
** allocate memory because it might be called while the memory allocator
17753
** mutex is held.
17754
*/
17755
static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
17756
  StrAccum acc;                          /* String accumulator */
17757
  char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
17758
17759
  sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
17760
  acc.useMalloc = 0;
17761
  sqlite3VXPrintf(&acc, 0, zFormat, ap);
17762
  sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
17763
                           sqlite3StrAccumFinish(&acc));
17764
}
17765
17766
/*
17767
** Format and write a message to the log if logging is enabled.
17768
*/
17769
SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
17770
  va_list ap;                             /* Vararg list */
17771
  if( sqlite3GlobalConfig.xLog ){
17772
    va_start(ap, zFormat);
17773
    renderLogMsg(iErrCode, zFormat, ap);
17774
    va_end(ap);
17775
  }
17776
}
17777
17778
#if defined(SQLITE_DEBUG)
17779
/*
17780
** A version of printf() that understands %lld.  Used for debugging.
17781
** The printf() built into some versions of windows does not understand %lld
17782
** and segfaults if you give it a long long int.
17783
*/
17784
SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
17785
  va_list ap;
17786
  StrAccum acc;
17787
  char zBuf[500];
17788
  sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
17789
  acc.useMalloc = 0;
17790
  va_start(ap,zFormat);
17791
  sqlite3VXPrintf(&acc, 0, zFormat, ap);
17792
  va_end(ap);
17793
  sqlite3StrAccumFinish(&acc);
17794
  fprintf(stdout,"%s", zBuf);
17795
  fflush(stdout);
17796
}
17797
#endif
17798
17799
#ifndef SQLITE_OMIT_TRACE
17800
/*
17801
** variable-argument wrapper around sqlite3VXPrintf().
17802
*/
17803
SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
17804
  va_list ap;
17805
  va_start(ap,zFormat);
17806
  sqlite3VXPrintf(p, 1, zFormat, ap);
17807
  va_end(ap);
17808
}
17809
#endif
17810
17811
/************** End of printf.c **********************************************/
17812
/************** Begin file random.c ******************************************/
17813
/*
17814
** 2001 September 15
17815
**
17816
** The author disclaims copyright to this source code.  In place of
17817
** a legal notice, here is a blessing:
17818
**
17819
**    May you do good and not evil.
17820
**    May you find forgiveness for yourself and forgive others.
17821
**    May you share freely, never taking more than you give.
17822
**
17823
*************************************************************************
17824
** This file contains code to implement a pseudo-random number
17825
** generator (PRNG) for SQLite.
17826
**
17827
** Random numbers are used by some of the database backends in order
17828
** to generate random integer keys for tables or random filenames.
17829
*/
17830
17831
17832
/* All threads share a single random number generator.
17833
** This structure is the current state of the generator.
17834
*/
17835
static SQLITE_WSD struct sqlite3PrngType {
17836
  unsigned char isInit;          /* True if initialized */
17837
  unsigned char i, j;            /* State variables */
17838
  unsigned char s[256];          /* State variables */
17839
} sqlite3Prng;
17840
17841
/*
17842
** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
17843
** must be held while executing this routine.
17844
**
17845
** Why not just use a library random generator like lrand48() for this?
17846
** Because the OP_NewRowid opcode in the VDBE depends on having a very
17847
** good source of random numbers.  The lrand48() library function may
17848
** well be good enough.  But maybe not.  Or maybe lrand48() has some
17849
** subtle problems on some systems that could cause problems.  It is hard
17850
** to know.  To minimize the risk of problems due to bad lrand48()
17851
** implementations, SQLite uses this random number generator based
17852
** on RC4, which we know works very well.
17853
**
17854
** (Later):  Actually, OP_NewRowid does not depend on a good source of
17855
** randomness any more.  But we will leave this code in all the same.
17856
*/
17857
static u8 randomByte(void){
17858
  unsigned char t;
17859
17860
17861
  /* The "wsdPrng" macro will resolve to the pseudo-random number generator
17862
  ** state vector.  If writable static data is unsupported on the target,
17863
  ** we have to locate the state vector at run-time.  In the more common
17864
  ** case where writable static data is supported, wsdPrng can refer directly
17865
  ** to the "sqlite3Prng" state vector declared above.
17866
  */
17867
#ifdef SQLITE_OMIT_WSD
17868
  struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
17869
# define wsdPrng p[0]
17870
#else
17871
# define wsdPrng sqlite3Prng
17872
#endif
17873
17874
17875
  /* Initialize the state of the random number generator once,
17876
  ** the first time this routine is called.  The seed value does
17877
  ** not need to contain a lot of randomness since we are not
17878
  ** trying to do secure encryption or anything like that...
17879
  **
17880
  ** Nothing in this file or anywhere else in SQLite does any kind of
17881
  ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
17882
  ** number generator) not as an encryption device.
17883
  */
17884
  if( !wsdPrng.isInit ){
17885
    int i;
17886
    char k[256];
17887
    wsdPrng.j = 0;
17888
    wsdPrng.i = 0;
17889
    sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
17890
    for(i=0; i<256; i++){
17891
      wsdPrng.s[i] = (u8)i;
17892
    }
17893
    for(i=0; i<256; i++){
17894
      wsdPrng.j += wsdPrng.s[i] + k[i];
17895
      t = wsdPrng.s[wsdPrng.j];
17896
      wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
17897
      wsdPrng.s[i] = t;
17898
    }
17899
    wsdPrng.isInit = 1;
17900
  }
17901
17902
  /* Generate and return single random byte
17903
  */
17904
  wsdPrng.i++;
17905
  t = wsdPrng.s[wsdPrng.i];
17906
  wsdPrng.j += t;
17907
  wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
17908
  wsdPrng.s[wsdPrng.j] = t;
17909
  t += wsdPrng.s[wsdPrng.i];
17910
  return wsdPrng.s[t];
17911
}
17912
17913
/*
17914
** Return N random bytes.
17915
*/
17916
SQLITE_API void sqlite3_randomness(int N, void *pBuf){
17917
  unsigned char *zBuf = pBuf;
17918
#if SQLITE_THREADSAFE
17919
  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
17920
#endif
17921
  sqlite3_mutex_enter(mutex);
17922
  while( N-- ){
17923
    *(zBuf++) = randomByte();
17924
  }
17925
  sqlite3_mutex_leave(mutex);
17926
}
17927
17928
#ifndef SQLITE_OMIT_BUILTIN_TEST
17929
/*
17930
** For testing purposes, we sometimes want to preserve the state of
17931
** PRNG and restore the PRNG to its saved state at a later time, or
17932
** to reset the PRNG to its initial state.  These routines accomplish
17933
** those tasks.
17934
**
17935
** The sqlite3_test_control() interface calls these routines to
17936
** control the PRNG.
17937
*/
17938
static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
17939
SQLITE_PRIVATE void sqlite3PrngSaveState(void){
17940
  memcpy(
17941
    &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
17942
    &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
17943
    sizeof(sqlite3Prng)
17944
  );
17945
}
17946
SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
17947
  memcpy(
17948
    &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
17949
    &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
17950
    sizeof(sqlite3Prng)
17951
  );
17952
}
17953
SQLITE_PRIVATE void sqlite3PrngResetState(void){
17954
  GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
17955
}
17956
#endif /* SQLITE_OMIT_BUILTIN_TEST */
17957
17958
/************** End of random.c **********************************************/
17959
/************** Begin file utf.c *********************************************/
17960
/*
17961
** 2004 April 13
17962
**
17963
** The author disclaims copyright to this source code.  In place of
17964
** a legal notice, here is a blessing:
17965
**
17966
**    May you do good and not evil.
17967
**    May you find forgiveness for yourself and forgive others.
17968
**    May you share freely, never taking more than you give.
17969
**
17970
*************************************************************************
17971
** This file contains routines used to translate between UTF-8, 
17972
** UTF-16, UTF-16BE, and UTF-16LE.
17973
**
17974
** Notes on UTF-8:
17975
**
17976
**   Byte-0    Byte-1    Byte-2    Byte-3    Value
17977
**  0xxxxxxx                                 00000000 00000000 0xxxxxxx
17978
**  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
17979
**  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
17980
**  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
17981
**
17982
**
17983
** Notes on UTF-16:  (with wwww+1==uuuuu)
17984
**
17985
**      Word-0               Word-1          Value
17986
**  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
17987
**  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
17988
**
17989
**
17990
** BOM or Byte Order Mark:
17991
**     0xff 0xfe   little-endian utf-16 follows
17992
**     0xfe 0xff   big-endian utf-16 follows
17993
**
17994
*/
17995
/************** Include vdbeInt.h in the middle of utf.c *********************/
17996
/************** Begin file vdbeInt.h *****************************************/
11624
/************** Begin file vdbeInt.h *****************************************/
17997
/*
11625
/*
17998
** 2003 September 6
11626
** 2003 September 6
 Lines 18307-18313   struct Vdbe { Link Here 
18307
  int btreeMask;          /* Bitmask of db->aDb[] entries referenced */
11935
  int btreeMask;          /* Bitmask of db->aDb[] entries referenced */
18308
  i64 startTime;          /* Time when query started - used for profiling */
11936
  i64 startTime;          /* Time when query started - used for profiling */
18309
  BtreeMutexArray aMutex; /* An array of Btree used here and needing locks */
11937
  BtreeMutexArray aMutex; /* An array of Btree used here and needing locks */
18310
  int aCounter[2];        /* Counters used by sqlite3_stmt_status() */
11938
  int aCounter[3];        /* Counters used by sqlite3_stmt_status() */
18311
  char *zSql;             /* Text of the SQL statement that generated this */
11939
  char *zSql;             /* Text of the SQL statement that generated this */
18312
  void *pFree;            /* Free this when deleting the vdbe */
11940
  void *pFree;            /* Free this when deleting the vdbe */
18313
  i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
11941
  i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
 Lines 18319-18324   struct Vdbe { Link Here 
18319
  VdbeFrame *pFrame;      /* Parent frame */
11947
  VdbeFrame *pFrame;      /* Parent frame */
18320
  int nFrame;             /* Number of frames in pFrame list */
11948
  int nFrame;             /* Number of frames in pFrame list */
18321
  u32 expmask;            /* Binding to these vars invalidates VM */
11949
  u32 expmask;            /* Binding to these vars invalidates VM */
11950
  SubProgram *pProgram;   /* Linked list of all sub-programs used by VM */
18322
};
11951
};
18323
11952
18324
/*
11953
/*
 Lines 18414-18420   SQLITE_PRIVATE int sqlite3VdbeMemExpan Link Here 
18414
#endif /* !defined(_VDBEINT_H_) */
12043
#endif /* !defined(_VDBEINT_H_) */
18415
12044
18416
/************** End of vdbeInt.h *********************************************/
12045
/************** End of vdbeInt.h *********************************************/
18417
/************** Continuing where we left off in utf.c ************************/
12046
/************** Continuing where we left off in status.c *********************/
12047
12048
/*
12049
** Variables in which to record status information.
12050
*/
12051
typedef struct sqlite3StatType sqlite3StatType;
12052
static SQLITE_WSD struct sqlite3StatType {
12053
  int nowValue[10];         /* Current value */
12054
  int mxValue[10];          /* Maximum value */
12055
} sqlite3Stat = { {0,}, {0,} };
12056
12057
12058
/* The "wsdStat" macro will resolve to the status information
12059
** state vector.  If writable static data is unsupported on the target,
12060
** we have to locate the state vector at run-time.  In the more common
12061
** case where writable static data is supported, wsdStat can refer directly
12062
** to the "sqlite3Stat" state vector declared above.
12063
*/
12064
#ifdef SQLITE_OMIT_WSD
12065
# define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
12066
# define wsdStat x[0]
12067
#else
12068
# define wsdStatInit
12069
# define wsdStat sqlite3Stat
12070
#endif
12071
12072
/*
12073
** Return the current value of a status parameter.
12074
*/
12075
SQLITE_PRIVATE int sqlite3StatusValue(int op){
12076
  wsdStatInit;
12077
  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
12078
  return wsdStat.nowValue[op];
12079
}
12080
12081
/*
12082
** Add N to the value of a status record.  It is assumed that the
12083
** caller holds appropriate locks.
12084
*/
12085
SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
12086
  wsdStatInit;
12087
  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
12088
  wsdStat.nowValue[op] += N;
12089
  if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
12090
    wsdStat.mxValue[op] = wsdStat.nowValue[op];
12091
  }
12092
}
12093
12094
/*
12095
** Set the value of a status to X.
12096
*/
12097
SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
12098
  wsdStatInit;
12099
  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
12100
  wsdStat.nowValue[op] = X;
12101
  if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
12102
    wsdStat.mxValue[op] = wsdStat.nowValue[op];
12103
  }
12104
}
12105
12106
/*
12107
** Query status information.
12108
**
12109
** This implementation assumes that reading or writing an aligned
12110
** 32-bit integer is an atomic operation.  If that assumption is not true,
12111
** then this routine is not threadsafe.
12112
*/
12113
SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
12114
  wsdStatInit;
12115
  if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
12116
    return SQLITE_MISUSE_BKPT;
12117
  }
12118
  *pCurrent = wsdStat.nowValue[op];
12119
  *pHighwater = wsdStat.mxValue[op];
12120
  if( resetFlag ){
12121
    wsdStat.mxValue[op] = wsdStat.nowValue[op];
12122
  }
12123
  return SQLITE_OK;
12124
}
12125
12126
/*
12127
** Query status information for a single database connection
12128
*/
12129
SQLITE_API int sqlite3_db_status(
12130
  sqlite3 *db,          /* The database connection whose status is desired */
12131
  int op,               /* Status verb */
12132
  int *pCurrent,        /* Write current value here */
12133
  int *pHighwater,      /* Write high-water mark here */
12134
  int resetFlag         /* Reset high-water mark if true */
12135
){
12136
  int rc = SQLITE_OK;   /* Return code */
12137
  sqlite3_mutex_enter(db->mutex);
12138
  switch( op ){
12139
    case SQLITE_DBSTATUS_LOOKASIDE_USED: {
12140
      *pCurrent = db->lookaside.nOut;
12141
      *pHighwater = db->lookaside.mxOut;
12142
      if( resetFlag ){
12143
        db->lookaside.mxOut = db->lookaside.nOut;
12144
      }
12145
      break;
12146
    }
12147
12148
    /* 
12149
    ** Return an approximation for the amount of memory currently used
12150
    ** by all pagers associated with the given database connection.  The
12151
    ** highwater mark is meaningless and is returned as zero.
12152
    */
12153
    case SQLITE_DBSTATUS_CACHE_USED: {
12154
      int totalUsed = 0;
12155
      int i;
12156
      sqlite3BtreeEnterAll(db);
12157
      for(i=0; i<db->nDb; i++){
12158
        Btree *pBt = db->aDb[i].pBt;
12159
        if( pBt ){
12160
          Pager *pPager = sqlite3BtreePager(pBt);
12161
          totalUsed += sqlite3PagerMemUsed(pPager);
12162
        }
12163
      }
12164
      sqlite3BtreeLeaveAll(db);
12165
      *pCurrent = totalUsed;
12166
      *pHighwater = 0;
12167
      break;
12168
    }
12169
12170
    /*
12171
    ** *pCurrent gets an accurate estimate of the amount of memory used
12172
    ** to store the schema for all databases (main, temp, and any ATTACHed
12173
    ** databases.  *pHighwater is set to zero.
12174
    */
12175
    case SQLITE_DBSTATUS_SCHEMA_USED: {
12176
      int i;                      /* Used to iterate through schemas */
12177
      int nByte = 0;              /* Used to accumulate return value */
12178
12179
      db->pnBytesFreed = &nByte;
12180
      for(i=0; i<db->nDb; i++){
12181
        Schema *pSchema = db->aDb[i].pSchema;
12182
        if( ALWAYS(pSchema!=0) ){
12183
          HashElem *p;
12184
12185
          nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
12186
              pSchema->tblHash.count 
12187
            + pSchema->trigHash.count
12188
            + pSchema->idxHash.count
12189
            + pSchema->fkeyHash.count
12190
          );
12191
          nByte += sqlite3MallocSize(pSchema->tblHash.ht);
12192
          nByte += sqlite3MallocSize(pSchema->trigHash.ht);
12193
          nByte += sqlite3MallocSize(pSchema->idxHash.ht);
12194
          nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
12195
12196
          for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
12197
            sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
12198
          }
12199
          for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
12200
            sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
12201
          }
12202
        }
12203
      }
12204
      db->pnBytesFreed = 0;
12205
12206
      *pHighwater = 0;
12207
      *pCurrent = nByte;
12208
      break;
12209
    }
12210
12211
    /*
12212
    ** *pCurrent gets an accurate estimate of the amount of memory used
12213
    ** to store all prepared statements.
12214
    ** *pHighwater is set to zero.
12215
    */
12216
    case SQLITE_DBSTATUS_STMT_USED: {
12217
      struct Vdbe *pVdbe;         /* Used to iterate through VMs */
12218
      int nByte = 0;              /* Used to accumulate return value */
12219
12220
      db->pnBytesFreed = &nByte;
12221
      for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
12222
        sqlite3VdbeDeleteObject(db, pVdbe);
12223
      }
12224
      db->pnBytesFreed = 0;
12225
12226
      *pHighwater = 0;
12227
      *pCurrent = nByte;
12228
12229
      break;
12230
    }
12231
12232
    default: {
12233
      rc = SQLITE_ERROR;
12234
    }
12235
  }
12236
  sqlite3_mutex_leave(db->mutex);
12237
  return rc;
12238
}
12239
12240
/************** End of status.c **********************************************/
12241
/************** Begin file date.c ********************************************/
12242
/*
12243
** 2003 October 31
12244
**
12245
** The author disclaims copyright to this source code.  In place of
12246
** a legal notice, here is a blessing:
12247
**
12248
**    May you do good and not evil.
12249
**    May you find forgiveness for yourself and forgive others.
12250
**    May you share freely, never taking more than you give.
12251
**
12252
*************************************************************************
12253
** This file contains the C functions that implement date and time
12254
** functions for SQLite.  
12255
**
12256
** There is only one exported symbol in this file - the function
12257
** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
12258
** All other code has file scope.
12259
**
12260
** SQLite processes all times and dates as Julian Day numbers.  The
12261
** dates and times are stored as the number of days since noon
12262
** in Greenwich on November 24, 4714 B.C. according to the Gregorian
12263
** calendar system. 
12264
**
12265
** 1970-01-01 00:00:00 is JD 2440587.5
12266
** 2000-01-01 00:00:00 is JD 2451544.5
12267
**
12268
** This implemention requires years to be expressed as a 4-digit number
12269
** which means that only dates between 0000-01-01 and 9999-12-31 can
12270
** be represented, even though julian day numbers allow a much wider
12271
** range of dates.
12272
**
12273
** The Gregorian calendar system is used for all dates and times,
12274
** even those that predate the Gregorian calendar.  Historians usually
12275
** use the Julian calendar for dates prior to 1582-10-15 and for some
12276
** dates afterwards, depending on locale.  Beware of this difference.
12277
**
12278
** The conversion algorithms are implemented based on descriptions
12279
** in the following text:
12280
**
12281
**      Jean Meeus
12282
**      Astronomical Algorithms, 2nd Edition, 1998
12283
**      ISBM 0-943396-61-1
12284
**      Willmann-Bell, Inc
12285
**      Richmond, Virginia (USA)
12286
*/
12287
#include <time.h>
12288
12289
#ifndef SQLITE_OMIT_DATETIME_FUNCS
12290
12291
/*
12292
** On recent Windows platforms, the localtime_s() function is available
12293
** as part of the "Secure CRT". It is essentially equivalent to 
12294
** localtime_r() available under most POSIX platforms, except that the 
12295
** order of the parameters is reversed.
12296
**
12297
** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
12298
**
12299
** If the user has not indicated to use localtime_r() or localtime_s()
12300
** already, check for an MSVC build environment that provides 
12301
** localtime_s().
12302
*/
12303
#if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
12304
     defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
12305
#define HAVE_LOCALTIME_S 1
12306
#endif
12307
12308
/*
12309
** A structure for holding a single date and time.
12310
*/
12311
typedef struct DateTime DateTime;
12312
struct DateTime {
12313
  sqlite3_int64 iJD; /* The julian day number times 86400000 */
12314
  int Y, M, D;       /* Year, month, and day */
12315
  int h, m;          /* Hour and minutes */
12316
  int tz;            /* Timezone offset in minutes */
12317
  double s;          /* Seconds */
12318
  char validYMD;     /* True (1) if Y,M,D are valid */
12319
  char validHMS;     /* True (1) if h,m,s are valid */
12320
  char validJD;      /* True (1) if iJD is valid */
12321
  char validTZ;      /* True (1) if tz is valid */
12322
};
12323
12324
12325
/*
12326
** Convert zDate into one or more integers.  Additional arguments
12327
** come in groups of 5 as follows:
12328
**
12329
**       N       number of digits in the integer
12330
**       min     minimum allowed value of the integer
12331
**       max     maximum allowed value of the integer
12332
**       nextC   first character after the integer
12333
**       pVal    where to write the integers value.
12334
**
12335
** Conversions continue until one with nextC==0 is encountered.
12336
** The function returns the number of successful conversions.
12337
*/
12338
static int getDigits(const char *zDate, ...){
12339
  va_list ap;
12340
  int val;
12341
  int N;
12342
  int min;
12343
  int max;
12344
  int nextC;
12345
  int *pVal;
12346
  int cnt = 0;
12347
  va_start(ap, zDate);
12348
  do{
12349
    N = va_arg(ap, int);
12350
    min = va_arg(ap, int);
12351
    max = va_arg(ap, int);
12352
    nextC = va_arg(ap, int);
12353
    pVal = va_arg(ap, int*);
12354
    val = 0;
12355
    while( N-- ){
12356
      if( !sqlite3Isdigit(*zDate) ){
12357
        goto end_getDigits;
12358
      }
12359
      val = val*10 + *zDate - '0';
12360
      zDate++;
12361
    }
12362
    if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
12363
      goto end_getDigits;
12364
    }
12365
    *pVal = val;
12366
    zDate++;
12367
    cnt++;
12368
  }while( nextC );
12369
end_getDigits:
12370
  va_end(ap);
12371
  return cnt;
12372
}
12373
12374
/*
12375
** Read text from z[] and convert into a floating point number.  Return
12376
** the number of digits converted.
12377
*/
12378
#define getValue sqlite3AtoF
12379
12380
/*
12381
** Parse a timezone extension on the end of a date-time.
12382
** The extension is of the form:
12383
**
12384
**        (+/-)HH:MM
12385
**
12386
** Or the "zulu" notation:
12387
**
12388
**        Z
12389
**
12390
** If the parse is successful, write the number of minutes
12391
** of change in p->tz and return 0.  If a parser error occurs,
12392
** return non-zero.
12393
**
12394
** A missing specifier is not considered an error.
12395
*/
12396
static int parseTimezone(const char *zDate, DateTime *p){
12397
  int sgn = 0;
12398
  int nHr, nMn;
12399
  int c;
12400
  while( sqlite3Isspace(*zDate) ){ zDate++; }
12401
  p->tz = 0;
12402
  c = *zDate;
12403
  if( c=='-' ){
12404
    sgn = -1;
12405
  }else if( c=='+' ){
12406
    sgn = +1;
12407
  }else if( c=='Z' || c=='z' ){
12408
    zDate++;
12409
    goto zulu_time;
12410
  }else{
12411
    return c!=0;
12412
  }
12413
  zDate++;
12414
  if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
12415
    return 1;
12416
  }
12417
  zDate += 5;
12418
  p->tz = sgn*(nMn + nHr*60);
12419
zulu_time:
12420
  while( sqlite3Isspace(*zDate) ){ zDate++; }
12421
  return *zDate!=0;
12422
}
12423
12424
/*
12425
** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
12426
** The HH, MM, and SS must each be exactly 2 digits.  The
12427
** fractional seconds FFFF can be one or more digits.
12428
**
12429
** Return 1 if there is a parsing error and 0 on success.
12430
*/
12431
static int parseHhMmSs(const char *zDate, DateTime *p){
12432
  int h, m, s;
12433
  double ms = 0.0;
12434
  if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
12435
    return 1;
12436
  }
12437
  zDate += 5;
12438
  if( *zDate==':' ){
12439
    zDate++;
12440
    if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
12441
      return 1;
12442
    }
12443
    zDate += 2;
12444
    if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
12445
      double rScale = 1.0;
12446
      zDate++;
12447
      while( sqlite3Isdigit(*zDate) ){
12448
        ms = ms*10.0 + *zDate - '0';
12449
        rScale *= 10.0;
12450
        zDate++;
12451
      }
12452
      ms /= rScale;
12453
    }
12454
  }else{
12455
    s = 0;
12456
  }
12457
  p->validJD = 0;
12458
  p->validHMS = 1;
12459
  p->h = h;
12460
  p->m = m;
12461
  p->s = s + ms;
12462
  if( parseTimezone(zDate, p) ) return 1;
12463
  p->validTZ = (p->tz!=0)?1:0;
12464
  return 0;
12465
}
12466
12467
/*
12468
** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
12469
** that the YYYY-MM-DD is according to the Gregorian calendar.
12470
**
12471
** Reference:  Meeus page 61
12472
*/
12473
static void computeJD(DateTime *p){
12474
  int Y, M, D, A, B, X1, X2;
12475
12476
  if( p->validJD ) return;
12477
  if( p->validYMD ){
12478
    Y = p->Y;
12479
    M = p->M;
12480
    D = p->D;
12481
  }else{
12482
    Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
12483
    M = 1;
12484
    D = 1;
12485
  }
12486
  if( M<=2 ){
12487
    Y--;
12488
    M += 12;
12489
  }
12490
  A = Y/100;
12491
  B = 2 - A + (A/4);
12492
  X1 = 36525*(Y+4716)/100;
12493
  X2 = 306001*(M+1)/10000;
12494
  p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
12495
  p->validJD = 1;
12496
  if( p->validHMS ){
12497
    p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
12498
    if( p->validTZ ){
12499
      p->iJD -= p->tz*60000;
12500
      p->validYMD = 0;
12501
      p->validHMS = 0;
12502
      p->validTZ = 0;
12503
    }
12504
  }
12505
}
12506
12507
/*
12508
** Parse dates of the form
12509
**
12510
**     YYYY-MM-DD HH:MM:SS.FFF
12511
**     YYYY-MM-DD HH:MM:SS
12512
**     YYYY-MM-DD HH:MM
12513
**     YYYY-MM-DD
12514
**
12515
** Write the result into the DateTime structure and return 0
12516
** on success and 1 if the input string is not a well-formed
12517
** date.
12518
*/
12519
static int parseYyyyMmDd(const char *zDate, DateTime *p){
12520
  int Y, M, D, neg;
12521
12522
  if( zDate[0]=='-' ){
12523
    zDate++;
12524
    neg = 1;
12525
  }else{
12526
    neg = 0;
12527
  }
12528
  if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
12529
    return 1;
12530
  }
12531
  zDate += 10;
12532
  while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
12533
  if( parseHhMmSs(zDate, p)==0 ){
12534
    /* We got the time */
12535
  }else if( *zDate==0 ){
12536
    p->validHMS = 0;
12537
  }else{
12538
    return 1;
12539
  }
12540
  p->validJD = 0;
12541
  p->validYMD = 1;
12542
  p->Y = neg ? -Y : Y;
12543
  p->M = M;
12544
  p->D = D;
12545
  if( p->validTZ ){
12546
    computeJD(p);
12547
  }
12548
  return 0;
12549
}
12550
12551
/*
12552
** Set the time to the current time reported by the VFS
12553
*/
12554
static void setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
12555
  sqlite3 *db = sqlite3_context_db_handle(context);
12556
  sqlite3OsCurrentTimeInt64(db->pVfs, &p->iJD);
12557
  p->validJD = 1;
12558
}
12559
12560
/*
12561
** Attempt to parse the given string into a Julian Day Number.  Return
12562
** the number of errors.
12563
**
12564
** The following are acceptable forms for the input string:
12565
**
12566
**      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
12567
**      DDDD.DD 
12568
**      now
12569
**
12570
** In the first form, the +/-HH:MM is always optional.  The fractional
12571
** seconds extension (the ".FFF") is optional.  The seconds portion
12572
** (":SS.FFF") is option.  The year and date can be omitted as long
12573
** as there is a time string.  The time string can be omitted as long
12574
** as there is a year and date.
12575
*/
12576
static int parseDateOrTime(
12577
  sqlite3_context *context, 
12578
  const char *zDate, 
12579
  DateTime *p
12580
){
12581
  int isRealNum;    /* Return from sqlite3IsNumber().  Not used */
12582
  if( parseYyyyMmDd(zDate,p)==0 ){
12583
    return 0;
12584
  }else if( parseHhMmSs(zDate, p)==0 ){
12585
    return 0;
12586
  }else if( sqlite3StrICmp(zDate,"now")==0){
12587
    setDateTimeToCurrent(context, p);
12588
    return 0;
12589
  }else if( sqlite3IsNumber(zDate, &isRealNum, SQLITE_UTF8) ){
12590
    double r;
12591
    getValue(zDate, &r);
12592
    p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
12593
    p->validJD = 1;
12594
    return 0;
12595
  }
12596
  return 1;
12597
}
12598
12599
/*
12600
** Compute the Year, Month, and Day from the julian day number.
12601
*/
12602
static void computeYMD(DateTime *p){
12603
  int Z, A, B, C, D, E, X1;
12604
  if( p->validYMD ) return;
12605
  if( !p->validJD ){
12606
    p->Y = 2000;
12607
    p->M = 1;
12608
    p->D = 1;
12609
  }else{
12610
    Z = (int)((p->iJD + 43200000)/86400000);
12611
    A = (int)((Z - 1867216.25)/36524.25);
12612
    A = Z + 1 + A - (A/4);
12613
    B = A + 1524;
12614
    C = (int)((B - 122.1)/365.25);
12615
    D = (36525*C)/100;
12616
    E = (int)((B-D)/30.6001);
12617
    X1 = (int)(30.6001*E);
12618
    p->D = B - D - X1;
12619
    p->M = E<14 ? E-1 : E-13;
12620
    p->Y = p->M>2 ? C - 4716 : C - 4715;
12621
  }
12622
  p->validYMD = 1;
12623
}
12624
12625
/*
12626
** Compute the Hour, Minute, and Seconds from the julian day number.
12627
*/
12628
static void computeHMS(DateTime *p){
12629
  int s;
12630
  if( p->validHMS ) return;
12631
  computeJD(p);
12632
  s = (int)((p->iJD + 43200000) % 86400000);
12633
  p->s = s/1000.0;
12634
  s = (int)p->s;
12635
  p->s -= s;
12636
  p->h = s/3600;
12637
  s -= p->h*3600;
12638
  p->m = s/60;
12639
  p->s += s - p->m*60;
12640
  p->validHMS = 1;
12641
}
12642
12643
/*
12644
** Compute both YMD and HMS
12645
*/
12646
static void computeYMD_HMS(DateTime *p){
12647
  computeYMD(p);
12648
  computeHMS(p);
12649
}
12650
12651
/*
12652
** Clear the YMD and HMS and the TZ
12653
*/
12654
static void clearYMD_HMS_TZ(DateTime *p){
12655
  p->validYMD = 0;
12656
  p->validHMS = 0;
12657
  p->validTZ = 0;
12658
}
12659
12660
#ifndef SQLITE_OMIT_LOCALTIME
12661
/*
12662
** Compute the difference (in milliseconds)
12663
** between localtime and UTC (a.k.a. GMT)
12664
** for the time value p where p is in UTC.
12665
*/
12666
static sqlite3_int64 localtimeOffset(DateTime *p){
12667
  DateTime x, y;
12668
  time_t t;
12669
  x = *p;
12670
  computeYMD_HMS(&x);
12671
  if( x.Y<1971 || x.Y>=2038 ){
12672
    x.Y = 2000;
12673
    x.M = 1;
12674
    x.D = 1;
12675
    x.h = 0;
12676
    x.m = 0;
12677
    x.s = 0.0;
12678
  } else {
12679
    int s = (int)(x.s + 0.5);
12680
    x.s = s;
12681
  }
12682
  x.tz = 0;
12683
  x.validJD = 0;
12684
  computeJD(&x);
12685
  t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
12686
#ifdef HAVE_LOCALTIME_R
12687
  {
12688
    struct tm sLocal;
12689
    localtime_r(&t, &sLocal);
12690
    y.Y = sLocal.tm_year + 1900;
12691
    y.M = sLocal.tm_mon + 1;
12692
    y.D = sLocal.tm_mday;
12693
    y.h = sLocal.tm_hour;
12694
    y.m = sLocal.tm_min;
12695
    y.s = sLocal.tm_sec;
12696
  }
12697
#elif defined(HAVE_LOCALTIME_S) && HAVE_LOCALTIME_S
12698
  {
12699
    struct tm sLocal;
12700
    localtime_s(&sLocal, &t);
12701
    y.Y = sLocal.tm_year + 1900;
12702
    y.M = sLocal.tm_mon + 1;
12703
    y.D = sLocal.tm_mday;
12704
    y.h = sLocal.tm_hour;
12705
    y.m = sLocal.tm_min;
12706
    y.s = sLocal.tm_sec;
12707
  }
12708
#else
12709
  {
12710
    struct tm *pTm;
12711
    sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
12712
    pTm = localtime(&t);
12713
    y.Y = pTm->tm_year + 1900;
12714
    y.M = pTm->tm_mon + 1;
12715
    y.D = pTm->tm_mday;
12716
    y.h = pTm->tm_hour;
12717
    y.m = pTm->tm_min;
12718
    y.s = pTm->tm_sec;
12719
    sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
12720
  }
12721
#endif
12722
  y.validYMD = 1;
12723
  y.validHMS = 1;
12724
  y.validJD = 0;
12725
  y.validTZ = 0;
12726
  computeJD(&y);
12727
  return y.iJD - x.iJD;
12728
}
12729
#endif /* SQLITE_OMIT_LOCALTIME */
12730
12731
/*
12732
** Process a modifier to a date-time stamp.  The modifiers are
12733
** as follows:
12734
**
12735
**     NNN days
12736
**     NNN hours
12737
**     NNN minutes
12738
**     NNN.NNNN seconds
12739
**     NNN months
12740
**     NNN years
12741
**     start of month
12742
**     start of year
12743
**     start of week
12744
**     start of day
12745
**     weekday N
12746
**     unixepoch
12747
**     localtime
12748
**     utc
12749
**
12750
** Return 0 on success and 1 if there is any kind of error.
12751
*/
12752
static int parseModifier(const char *zMod, DateTime *p){
12753
  int rc = 1;
12754
  int n;
12755
  double r;
12756
  char *z, zBuf[30];
12757
  z = zBuf;
12758
  for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
12759
    z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
12760
  }
12761
  z[n] = 0;
12762
  switch( z[0] ){
12763
#ifndef SQLITE_OMIT_LOCALTIME
12764
    case 'l': {
12765
      /*    localtime
12766
      **
12767
      ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
12768
      ** show local time.
12769
      */
12770
      if( strcmp(z, "localtime")==0 ){
12771
        computeJD(p);
12772
        p->iJD += localtimeOffset(p);
12773
        clearYMD_HMS_TZ(p);
12774
        rc = 0;
12775
      }
12776
      break;
12777
    }
12778
#endif
12779
    case 'u': {
12780
      /*
12781
      **    unixepoch
12782
      **
12783
      ** Treat the current value of p->iJD as the number of
12784
      ** seconds since 1970.  Convert to a real julian day number.
12785
      */
12786
      if( strcmp(z, "unixepoch")==0 && p->validJD ){
12787
        p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
12788
        clearYMD_HMS_TZ(p);
12789
        rc = 0;
12790
      }
12791
#ifndef SQLITE_OMIT_LOCALTIME
12792
      else if( strcmp(z, "utc")==0 ){
12793
        sqlite3_int64 c1;
12794
        computeJD(p);
12795
        c1 = localtimeOffset(p);
12796
        p->iJD -= c1;
12797
        clearYMD_HMS_TZ(p);
12798
        p->iJD += c1 - localtimeOffset(p);
12799
        rc = 0;
12800
      }
12801
#endif
12802
      break;
12803
    }
12804
    case 'w': {
12805
      /*
12806
      **    weekday N
12807
      **
12808
      ** Move the date to the same time on the next occurrence of
12809
      ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
12810
      ** date is already on the appropriate weekday, this is a no-op.
12811
      */
12812
      if( strncmp(z, "weekday ", 8)==0 && getValue(&z[8],&r)>0
12813
                 && (n=(int)r)==r && n>=0 && r<7 ){
12814
        sqlite3_int64 Z;
12815
        computeYMD_HMS(p);
12816
        p->validTZ = 0;
12817
        p->validJD = 0;
12818
        computeJD(p);
12819
        Z = ((p->iJD + 129600000)/86400000) % 7;
12820
        if( Z>n ) Z -= 7;
12821
        p->iJD += (n - Z)*86400000;
12822
        clearYMD_HMS_TZ(p);
12823
        rc = 0;
12824
      }
12825
      break;
12826
    }
12827
    case 's': {
12828
      /*
12829
      **    start of TTTTT
12830
      **
12831
      ** Move the date backwards to the beginning of the current day,
12832
      ** or month or year.
12833
      */
12834
      if( strncmp(z, "start of ", 9)!=0 ) break;
12835
      z += 9;
12836
      computeYMD(p);
12837
      p->validHMS = 1;
12838
      p->h = p->m = 0;
12839
      p->s = 0.0;
12840
      p->validTZ = 0;
12841
      p->validJD = 0;
12842
      if( strcmp(z,"month")==0 ){
12843
        p->D = 1;
12844
        rc = 0;
12845
      }else if( strcmp(z,"year")==0 ){
12846
        computeYMD(p);
12847
        p->M = 1;
12848
        p->D = 1;
12849
        rc = 0;
12850
      }else if( strcmp(z,"day")==0 ){
12851
        rc = 0;
12852
      }
12853
      break;
12854
    }
12855
    case '+':
12856
    case '-':
12857
    case '0':
12858
    case '1':
12859
    case '2':
12860
    case '3':
12861
    case '4':
12862
    case '5':
12863
    case '6':
12864
    case '7':
12865
    case '8':
12866
    case '9': {
12867
      double rRounder;
12868
      n = getValue(z, &r);
12869
      assert( n>=1 );
12870
      if( z[n]==':' ){
12871
        /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
12872
        ** specified number of hours, minutes, seconds, and fractional seconds
12873
        ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
12874
        ** omitted.
12875
        */
12876
        const char *z2 = z;
12877
        DateTime tx;
12878
        sqlite3_int64 day;
12879
        if( !sqlite3Isdigit(*z2) ) z2++;
12880
        memset(&tx, 0, sizeof(tx));
12881
        if( parseHhMmSs(z2, &tx) ) break;
12882
        computeJD(&tx);
12883
        tx.iJD -= 43200000;
12884
        day = tx.iJD/86400000;
12885
        tx.iJD -= day*86400000;
12886
        if( z[0]=='-' ) tx.iJD = -tx.iJD;
12887
        computeJD(p);
12888
        clearYMD_HMS_TZ(p);
12889
        p->iJD += tx.iJD;
12890
        rc = 0;
12891
        break;
12892
      }
12893
      z += n;
12894
      while( sqlite3Isspace(*z) ) z++;
12895
      n = sqlite3Strlen30(z);
12896
      if( n>10 || n<3 ) break;
12897
      if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
12898
      computeJD(p);
12899
      rc = 0;
12900
      rRounder = r<0 ? -0.5 : +0.5;
12901
      if( n==3 && strcmp(z,"day")==0 ){
12902
        p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
12903
      }else if( n==4 && strcmp(z,"hour")==0 ){
12904
        p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
12905
      }else if( n==6 && strcmp(z,"minute")==0 ){
12906
        p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
12907
      }else if( n==6 && strcmp(z,"second")==0 ){
12908
        p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
12909
      }else if( n==5 && strcmp(z,"month")==0 ){
12910
        int x, y;
12911
        computeYMD_HMS(p);
12912
        p->M += (int)r;
12913
        x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
12914
        p->Y += x;
12915
        p->M -= x*12;
12916
        p->validJD = 0;
12917
        computeJD(p);
12918
        y = (int)r;
12919
        if( y!=r ){
12920
          p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
12921
        }
12922
      }else if( n==4 && strcmp(z,"year")==0 ){
12923
        int y = (int)r;
12924
        computeYMD_HMS(p);
12925
        p->Y += y;
12926
        p->validJD = 0;
12927
        computeJD(p);
12928
        if( y!=r ){
12929
          p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
12930
        }
12931
      }else{
12932
        rc = 1;
12933
      }
12934
      clearYMD_HMS_TZ(p);
12935
      break;
12936
    }
12937
    default: {
12938
      break;
12939
    }
12940
  }
12941
  return rc;
12942
}
12943
12944
/*
12945
** Process time function arguments.  argv[0] is a date-time stamp.
12946
** argv[1] and following are modifiers.  Parse them all and write
12947
** the resulting time into the DateTime structure p.  Return 0
12948
** on success and 1 if there are any errors.
12949
**
12950
** If there are zero parameters (if even argv[0] is undefined)
12951
** then assume a default value of "now" for argv[0].
12952
*/
12953
static int isDate(
12954
  sqlite3_context *context, 
12955
  int argc, 
12956
  sqlite3_value **argv, 
12957
  DateTime *p
12958
){
12959
  int i;
12960
  const unsigned char *z;
12961
  int eType;
12962
  memset(p, 0, sizeof(*p));
12963
  if( argc==0 ){
12964
    setDateTimeToCurrent(context, p);
12965
  }else if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
12966
                   || eType==SQLITE_INTEGER ){
12967
    p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
12968
    p->validJD = 1;
12969
  }else{
12970
    z = sqlite3_value_text(argv[0]);
12971
    if( !z || parseDateOrTime(context, (char*)z, p) ){
12972
      return 1;
12973
    }
12974
  }
12975
  for(i=1; i<argc; i++){
12976
    if( (z = sqlite3_value_text(argv[i]))==0 || parseModifier((char*)z, p) ){
12977
      return 1;
12978
    }
12979
  }
12980
  return 0;
12981
}
12982
12983
12984
/*
12985
** The following routines implement the various date and time functions
12986
** of SQLite.
12987
*/
12988
12989
/*
12990
**    julianday( TIMESTRING, MOD, MOD, ...)
12991
**
12992
** Return the julian day number of the date specified in the arguments
12993
*/
12994
static void juliandayFunc(
12995
  sqlite3_context *context,
12996
  int argc,
12997
  sqlite3_value **argv
12998
){
12999
  DateTime x;
13000
  if( isDate(context, argc, argv, &x)==0 ){
13001
    computeJD(&x);
13002
    sqlite3_result_double(context, x.iJD/86400000.0);
13003
  }
13004
}
13005
13006
/*
13007
**    datetime( TIMESTRING, MOD, MOD, ...)
13008
**
13009
** Return YYYY-MM-DD HH:MM:SS
13010
*/
13011
static void datetimeFunc(
13012
  sqlite3_context *context,
13013
  int argc,
13014
  sqlite3_value **argv
13015
){
13016
  DateTime x;
13017
  if( isDate(context, argc, argv, &x)==0 ){
13018
    char zBuf[100];
13019
    computeYMD_HMS(&x);
13020
    sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
13021
                     x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
13022
    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
13023
  }
13024
}
13025
13026
/*
13027
**    time( TIMESTRING, MOD, MOD, ...)
13028
**
13029
** Return HH:MM:SS
13030
*/
13031
static void timeFunc(
13032
  sqlite3_context *context,
13033
  int argc,
13034
  sqlite3_value **argv
13035
){
13036
  DateTime x;
13037
  if( isDate(context, argc, argv, &x)==0 ){
13038
    char zBuf[100];
13039
    computeHMS(&x);
13040
    sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
13041
    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
13042
  }
13043
}
13044
13045
/*
13046
**    date( TIMESTRING, MOD, MOD, ...)
13047
**
13048
** Return YYYY-MM-DD
13049
*/
13050
static void dateFunc(
13051
  sqlite3_context *context,
13052
  int argc,
13053
  sqlite3_value **argv
13054
){
13055
  DateTime x;
13056
  if( isDate(context, argc, argv, &x)==0 ){
13057
    char zBuf[100];
13058
    computeYMD(&x);
13059
    sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
13060
    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
13061
  }
13062
}
13063
13064
/*
13065
**    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
13066
**
13067
** Return a string described by FORMAT.  Conversions as follows:
13068
**
13069
**   %d  day of month
13070
**   %f  ** fractional seconds  SS.SSS
13071
**   %H  hour 00-24
13072
**   %j  day of year 000-366
13073
**   %J  ** Julian day number
13074
**   %m  month 01-12
13075
**   %M  minute 00-59
13076
**   %s  seconds since 1970-01-01
13077
**   %S  seconds 00-59
13078
**   %w  day of week 0-6  sunday==0
13079
**   %W  week of year 00-53
13080
**   %Y  year 0000-9999
13081
**   %%  %
13082
*/
13083
static void strftimeFunc(
13084
  sqlite3_context *context,
13085
  int argc,
13086
  sqlite3_value **argv
13087
){
13088
  DateTime x;
13089
  u64 n;
13090
  size_t i,j;
13091
  char *z;
13092
  sqlite3 *db;
13093
  const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
13094
  char zBuf[100];
13095
  if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
13096
  db = sqlite3_context_db_handle(context);
13097
  for(i=0, n=1; zFmt[i]; i++, n++){
13098
    if( zFmt[i]=='%' ){
13099
      switch( zFmt[i+1] ){
13100
        case 'd':
13101
        case 'H':
13102
        case 'm':
13103
        case 'M':
13104
        case 'S':
13105
        case 'W':
13106
          n++;
13107
          /* fall thru */
13108
        case 'w':
13109
        case '%':
13110
          break;
13111
        case 'f':
13112
          n += 8;
13113
          break;
13114
        case 'j':
13115
          n += 3;
13116
          break;
13117
        case 'Y':
13118
          n += 8;
13119
          break;
13120
        case 's':
13121
        case 'J':
13122
          n += 50;
13123
          break;
13124
        default:
13125
          return;  /* ERROR.  return a NULL */
13126
      }
13127
      i++;
13128
    }
13129
  }
13130
  testcase( n==sizeof(zBuf)-1 );
13131
  testcase( n==sizeof(zBuf) );
13132
  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
13133
  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
13134
  if( n<sizeof(zBuf) ){
13135
    z = zBuf;
13136
  }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
13137
    sqlite3_result_error_toobig(context);
13138
    return;
13139
  }else{
13140
    z = sqlite3DbMallocRaw(db, (int)n);
13141
    if( z==0 ){
13142
      sqlite3_result_error_nomem(context);
13143
      return;
13144
    }
13145
  }
13146
  computeJD(&x);
13147
  computeYMD_HMS(&x);
13148
  for(i=j=0; zFmt[i]; i++){
13149
    if( zFmt[i]!='%' ){
13150
      z[j++] = zFmt[i];
13151
    }else{
13152
      i++;
13153
      switch( zFmt[i] ){
13154
        case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
13155
        case 'f': {
13156
          double s = x.s;
13157
          if( s>59.999 ) s = 59.999;
13158
          sqlite3_snprintf(7, &z[j],"%06.3f", s);
13159
          j += sqlite3Strlen30(&z[j]);
13160
          break;
13161
        }
13162
        case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
13163
        case 'W': /* Fall thru */
13164
        case 'j': {
13165
          int nDay;             /* Number of days since 1st day of year */
13166
          DateTime y = x;
13167
          y.validJD = 0;
13168
          y.M = 1;
13169
          y.D = 1;
13170
          computeJD(&y);
13171
          nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
13172
          if( zFmt[i]=='W' ){
13173
            int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
13174
            wd = (int)(((x.iJD+43200000)/86400000)%7);
13175
            sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
13176
            j += 2;
13177
          }else{
13178
            sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
13179
            j += 3;
13180
          }
13181
          break;
13182
        }
13183
        case 'J': {
13184
          sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
13185
          j+=sqlite3Strlen30(&z[j]);
13186
          break;
13187
        }
13188
        case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
13189
        case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
13190
        case 's': {
13191
          sqlite3_snprintf(30,&z[j],"%lld",
13192
                           (i64)(x.iJD/1000 - 21086676*(i64)10000));
13193
          j += sqlite3Strlen30(&z[j]);
13194
          break;
13195
        }
13196
        case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
13197
        case 'w': {
13198
          z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
13199
          break;
13200
        }
13201
        case 'Y': {
13202
          sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
13203
          break;
13204
        }
13205
        default:   z[j++] = '%'; break;
13206
      }
13207
    }
13208
  }
13209
  z[j] = 0;
13210
  sqlite3_result_text(context, z, -1,
13211
                      z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
13212
}
13213
13214
/*
13215
** current_time()
13216
**
13217
** This function returns the same value as time('now').
13218
*/
13219
static void ctimeFunc(
13220
  sqlite3_context *context,
13221
  int NotUsed,
13222
  sqlite3_value **NotUsed2
13223
){
13224
  UNUSED_PARAMETER2(NotUsed, NotUsed2);
13225
  timeFunc(context, 0, 0);
13226
}
13227
13228
/*
13229
** current_date()
13230
**
13231
** This function returns the same value as date('now').
13232
*/
13233
static void cdateFunc(
13234
  sqlite3_context *context,
13235
  int NotUsed,
13236
  sqlite3_value **NotUsed2
13237
){
13238
  UNUSED_PARAMETER2(NotUsed, NotUsed2);
13239
  dateFunc(context, 0, 0);
13240
}
13241
13242
/*
13243
** current_timestamp()
13244
**
13245
** This function returns the same value as datetime('now').
13246
*/
13247
static void ctimestampFunc(
13248
  sqlite3_context *context,
13249
  int NotUsed,
13250
  sqlite3_value **NotUsed2
13251
){
13252
  UNUSED_PARAMETER2(NotUsed, NotUsed2);
13253
  datetimeFunc(context, 0, 0);
13254
}
13255
#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
13256
13257
#ifdef SQLITE_OMIT_DATETIME_FUNCS
13258
/*
13259
** If the library is compiled to omit the full-scale date and time
13260
** handling (to get a smaller binary), the following minimal version
13261
** of the functions current_time(), current_date() and current_timestamp()
13262
** are included instead. This is to support column declarations that
13263
** include "DEFAULT CURRENT_TIME" etc.
13264
**
13265
** This function uses the C-library functions time(), gmtime()
13266
** and strftime(). The format string to pass to strftime() is supplied
13267
** as the user-data for the function.
13268
*/
13269
static void currentTimeFunc(
13270
  sqlite3_context *context,
13271
  int argc,
13272
  sqlite3_value **argv
13273
){
13274
  time_t t;
13275
  char *zFormat = (char *)sqlite3_user_data(context);
13276
  sqlite3 *db;
13277
  sqlite3_int64 iT;
13278
  char zBuf[20];
13279
13280
  UNUSED_PARAMETER(argc);
13281
  UNUSED_PARAMETER(argv);
13282
13283
  db = sqlite3_context_db_handle(context);
13284
  sqlite3OsCurrentTimeInt64(db->pVfs, &iT);
13285
  t = iT/1000 - 10000*(sqlite3_int64)21086676;
13286
#ifdef HAVE_GMTIME_R
13287
  {
13288
    struct tm sNow;
13289
    gmtime_r(&t, &sNow);
13290
    strftime(zBuf, 20, zFormat, &sNow);
13291
  }
13292
#else
13293
  {
13294
    struct tm *pTm;
13295
    sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
13296
    pTm = gmtime(&t);
13297
    strftime(zBuf, 20, zFormat, pTm);
13298
    sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
13299
  }
13300
#endif
13301
13302
  sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
13303
}
13304
#endif
13305
13306
/*
13307
** This function registered all of the above C functions as SQL
13308
** functions.  This should be the only routine in this file with
13309
** external linkage.
13310
*/
13311
SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
13312
  static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
13313
#ifndef SQLITE_OMIT_DATETIME_FUNCS
13314
    FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
13315
    FUNCTION(date,             -1, 0, 0, dateFunc      ),
13316
    FUNCTION(time,             -1, 0, 0, timeFunc      ),
13317
    FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
13318
    FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
13319
    FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
13320
    FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
13321
    FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
13322
#else
13323
    STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
13324
    STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
13325
    STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
13326
#endif
13327
  };
13328
  int i;
13329
  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
13330
  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
13331
13332
  for(i=0; i<ArraySize(aDateTimeFuncs); i++){
13333
    sqlite3FuncDefInsert(pHash, &aFunc[i]);
13334
  }
13335
}
13336
13337
/************** End of date.c ************************************************/
13338
/************** Begin file os.c **********************************************/
13339
/*
13340
** 2005 November 29
13341
**
13342
** The author disclaims copyright to this source code.  In place of
13343
** a legal notice, here is a blessing:
13344
**
13345
**    May you do good and not evil.
13346
**    May you find forgiveness for yourself and forgive others.
13347
**    May you share freely, never taking more than you give.
13348
**
13349
******************************************************************************
13350
**
13351
** This file contains OS interface code that is common to all
13352
** architectures.
13353
*/
13354
#define _SQLITE_OS_C_ 1
13355
#undef _SQLITE_OS_C_
13356
13357
/*
13358
** The default SQLite sqlite3_vfs implementations do not allocate
13359
** memory (actually, os_unix.c allocates a small amount of memory
13360
** from within OsOpen()), but some third-party implementations may.
13361
** So we test the effects of a malloc() failing and the sqlite3OsXXX()
13362
** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
13363
**
13364
** The following functions are instrumented for malloc() failure 
13365
** testing:
13366
**
13367
**     sqlite3OsOpen()
13368
**     sqlite3OsRead()
13369
**     sqlite3OsWrite()
13370
**     sqlite3OsSync()
13371
**     sqlite3OsLock()
13372
**
13373
*/
13374
#if defined(SQLITE_TEST)
13375
SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
13376
  #define DO_OS_MALLOC_TEST(x)                                       \
13377
  if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) {  \
13378
    void *pTstAlloc = sqlite3Malloc(10);                             \
13379
    if (!pTstAlloc) return SQLITE_IOERR_NOMEM;                       \
13380
    sqlite3_free(pTstAlloc);                                         \
13381
  }
13382
#else
13383
  #define DO_OS_MALLOC_TEST(x)
13384
#endif
13385
13386
/*
13387
** The following routines are convenience wrappers around methods
13388
** of the sqlite3_file object.  This is mostly just syntactic sugar. All
13389
** of this would be completely automatic if SQLite were coded using
13390
** C++ instead of plain old C.
13391
*/
13392
SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
13393
  int rc = SQLITE_OK;
13394
  if( pId->pMethods ){
13395
    rc = pId->pMethods->xClose(pId);
13396
    pId->pMethods = 0;
13397
  }
13398
  return rc;
13399
}
13400
SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
13401
  DO_OS_MALLOC_TEST(id);
13402
  return id->pMethods->xRead(id, pBuf, amt, offset);
13403
}
13404
SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
13405
  DO_OS_MALLOC_TEST(id);
13406
  return id->pMethods->xWrite(id, pBuf, amt, offset);
13407
}
13408
SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
13409
  return id->pMethods->xTruncate(id, size);
13410
}
13411
SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
13412
  DO_OS_MALLOC_TEST(id);
13413
  return id->pMethods->xSync(id, flags);
13414
}
13415
SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
13416
  DO_OS_MALLOC_TEST(id);
13417
  return id->pMethods->xFileSize(id, pSize);
13418
}
13419
SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
13420
  DO_OS_MALLOC_TEST(id);
13421
  return id->pMethods->xLock(id, lockType);
13422
}
13423
SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
13424
  return id->pMethods->xUnlock(id, lockType);
13425
}
13426
SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
13427
  DO_OS_MALLOC_TEST(id);
13428
  return id->pMethods->xCheckReservedLock(id, pResOut);
13429
}
13430
SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
13431
  return id->pMethods->xFileControl(id, op, pArg);
13432
}
13433
SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
13434
  int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
13435
  return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
13436
}
13437
SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
13438
  return id->pMethods->xDeviceCharacteristics(id);
13439
}
13440
SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
13441
  return id->pMethods->xShmLock(id, offset, n, flags);
13442
}
13443
SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
13444
  id->pMethods->xShmBarrier(id);
13445
}
13446
SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
13447
  return id->pMethods->xShmUnmap(id, deleteFlag);
13448
}
13449
SQLITE_PRIVATE int sqlite3OsShmMap(
13450
  sqlite3_file *id,               /* Database file handle */
13451
  int iPage,
13452
  int pgsz,
13453
  int bExtend,                    /* True to extend file if necessary */
13454
  void volatile **pp              /* OUT: Pointer to mapping */
13455
){
13456
  return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
13457
}
13458
13459
/*
13460
** The next group of routines are convenience wrappers around the
13461
** VFS methods.
13462
*/
13463
SQLITE_PRIVATE int sqlite3OsOpen(
13464
  sqlite3_vfs *pVfs, 
13465
  const char *zPath, 
13466
  sqlite3_file *pFile, 
13467
  int flags, 
13468
  int *pFlagsOut
13469
){
13470
  int rc;
13471
  DO_OS_MALLOC_TEST(0);
13472
  /* 0x87f3f is a mask of SQLITE_OPEN_ flags that are valid to be passed
13473
  ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
13474
  ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
13475
  ** reaching the VFS. */
13476
  rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f3f, pFlagsOut);
13477
  assert( rc==SQLITE_OK || pFile->pMethods==0 );
13478
  return rc;
13479
}
13480
SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
13481
  return pVfs->xDelete(pVfs, zPath, dirSync);
13482
}
13483
SQLITE_PRIVATE int sqlite3OsAccess(
13484
  sqlite3_vfs *pVfs, 
13485
  const char *zPath, 
13486
  int flags, 
13487
  int *pResOut
13488
){
13489
  DO_OS_MALLOC_TEST(0);
13490
  return pVfs->xAccess(pVfs, zPath, flags, pResOut);
13491
}
13492
SQLITE_PRIVATE int sqlite3OsFullPathname(
13493
  sqlite3_vfs *pVfs, 
13494
  const char *zPath, 
13495
  int nPathOut, 
13496
  char *zPathOut
13497
){
13498
  zPathOut[0] = 0;
13499
  return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
13500
}
13501
#ifndef SQLITE_OMIT_LOAD_EXTENSION
13502
SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
13503
  return pVfs->xDlOpen(pVfs, zPath);
13504
}
13505
SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
13506
  pVfs->xDlError(pVfs, nByte, zBufOut);
13507
}
13508
SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
13509
  return pVfs->xDlSym(pVfs, pHdle, zSym);
13510
}
13511
SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
13512
  pVfs->xDlClose(pVfs, pHandle);
13513
}
13514
#endif /* SQLITE_OMIT_LOAD_EXTENSION */
13515
SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
13516
  return pVfs->xRandomness(pVfs, nByte, zBufOut);
13517
}
13518
SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
13519
  return pVfs->xSleep(pVfs, nMicro);
13520
}
13521
SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
13522
  int rc;
13523
  if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
13524
    rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
13525
  }else{
13526
    double r;
13527
    rc = pVfs->xCurrentTime(pVfs, &r);
13528
    *pTimeOut = (sqlite3_int64)(r*86400000.0);
13529
  }
13530
  return rc;
13531
}
13532
13533
SQLITE_PRIVATE int sqlite3OsOpenMalloc(
13534
  sqlite3_vfs *pVfs, 
13535
  const char *zFile, 
13536
  sqlite3_file **ppFile, 
13537
  int flags,
13538
  int *pOutFlags
13539
){
13540
  int rc = SQLITE_NOMEM;
13541
  sqlite3_file *pFile;
13542
  pFile = (sqlite3_file *)sqlite3Malloc(pVfs->szOsFile);
13543
  if( pFile ){
13544
    rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
13545
    if( rc!=SQLITE_OK ){
13546
      sqlite3_free(pFile);
13547
    }else{
13548
      *ppFile = pFile;
13549
    }
13550
  }
13551
  return rc;
13552
}
13553
SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
13554
  int rc = SQLITE_OK;
13555
  assert( pFile );
13556
  rc = sqlite3OsClose(pFile);
13557
  sqlite3_free(pFile);
13558
  return rc;
13559
}
13560
13561
/*
13562
** This function is a wrapper around the OS specific implementation of
13563
** sqlite3_os_init(). The purpose of the wrapper is to provide the
13564
** ability to simulate a malloc failure, so that the handling of an
13565
** error in sqlite3_os_init() by the upper layers can be tested.
13566
*/
13567
SQLITE_PRIVATE int sqlite3OsInit(void){
13568
  void *p = sqlite3_malloc(10);
13569
  if( p==0 ) return SQLITE_NOMEM;
13570
  sqlite3_free(p);
13571
  return sqlite3_os_init();
13572
}
13573
13574
/*
13575
** The list of all registered VFS implementations.
13576
*/
13577
static sqlite3_vfs * SQLITE_WSD vfsList = 0;
13578
#define vfsList GLOBAL(sqlite3_vfs *, vfsList)
13579
13580
/*
13581
** Locate a VFS by name.  If no name is given, simply return the
13582
** first VFS on the list.
13583
*/
13584
SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
13585
  sqlite3_vfs *pVfs = 0;
13586
#if SQLITE_THREADSAFE
13587
  sqlite3_mutex *mutex;
13588
#endif
13589
#ifndef SQLITE_OMIT_AUTOINIT
13590
  int rc = sqlite3_initialize();
13591
  if( rc ) return 0;
13592
#endif
13593
#if SQLITE_THREADSAFE
13594
  mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
13595
#endif
13596
  sqlite3_mutex_enter(mutex);
13597
  for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
13598
    if( zVfs==0 ) break;
13599
    if( strcmp(zVfs, pVfs->zName)==0 ) break;
13600
  }
13601
  sqlite3_mutex_leave(mutex);
13602
  return pVfs;
13603
}
13604
13605
/*
13606
** Unlink a VFS from the linked list
13607
*/
13608
static void vfsUnlink(sqlite3_vfs *pVfs){
13609
  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
13610
  if( pVfs==0 ){
13611
    /* No-op */
13612
  }else if( vfsList==pVfs ){
13613
    vfsList = pVfs->pNext;
13614
  }else if( vfsList ){
13615
    sqlite3_vfs *p = vfsList;
13616
    while( p->pNext && p->pNext!=pVfs ){
13617
      p = p->pNext;
13618
    }
13619
    if( p->pNext==pVfs ){
13620
      p->pNext = pVfs->pNext;
13621
    }
13622
  }
13623
}
13624
13625
/*
13626
** Register a VFS with the system.  It is harmless to register the same
13627
** VFS multiple times.  The new VFS becomes the default if makeDflt is
13628
** true.
13629
*/
13630
SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
13631
  sqlite3_mutex *mutex = 0;
13632
#ifndef SQLITE_OMIT_AUTOINIT
13633
  int rc = sqlite3_initialize();
13634
  if( rc ) return rc;
13635
#endif
13636
  mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
13637
  sqlite3_mutex_enter(mutex);
13638
  vfsUnlink(pVfs);
13639
  if( makeDflt || vfsList==0 ){
13640
    pVfs->pNext = vfsList;
13641
    vfsList = pVfs;
13642
  }else{
13643
    pVfs->pNext = vfsList->pNext;
13644
    vfsList->pNext = pVfs;
13645
  }
13646
  assert(vfsList);
13647
  sqlite3_mutex_leave(mutex);
13648
  return SQLITE_OK;
13649
}
13650
13651
/*
13652
** Unregister a VFS so that it is no longer accessible.
13653
*/
13654
SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
13655
#if SQLITE_THREADSAFE
13656
  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
13657
#endif
13658
  sqlite3_mutex_enter(mutex);
13659
  vfsUnlink(pVfs);
13660
  sqlite3_mutex_leave(mutex);
13661
  return SQLITE_OK;
13662
}
13663
13664
/************** End of os.c **************************************************/
13665
/************** Begin file fault.c *******************************************/
13666
/*
13667
** 2008 Jan 22
13668
**
13669
** The author disclaims copyright to this source code.  In place of
13670
** a legal notice, here is a blessing:
13671
**
13672
**    May you do good and not evil.
13673
**    May you find forgiveness for yourself and forgive others.
13674
**    May you share freely, never taking more than you give.
13675
**
13676
*************************************************************************
13677
**
13678
** This file contains code to support the concept of "benign" 
13679
** malloc failures (when the xMalloc() or xRealloc() method of the
13680
** sqlite3_mem_methods structure fails to allocate a block of memory
13681
** and returns 0). 
13682
**
13683
** Most malloc failures are non-benign. After they occur, SQLite
13684
** abandons the current operation and returns an error code (usually
13685
** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
13686
** fatal. For example, if a malloc fails while resizing a hash table, this 
13687
** is completely recoverable simply by not carrying out the resize. The 
13688
** hash table will continue to function normally.  So a malloc failure 
13689
** during a hash table resize is a benign fault.
13690
*/
13691
13692
13693
#ifndef SQLITE_OMIT_BUILTIN_TEST
13694
13695
/*
13696
** Global variables.
13697
*/
13698
typedef struct BenignMallocHooks BenignMallocHooks;
13699
static SQLITE_WSD struct BenignMallocHooks {
13700
  void (*xBenignBegin)(void);
13701
  void (*xBenignEnd)(void);
13702
} sqlite3Hooks = { 0, 0 };
13703
13704
/* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
13705
** structure.  If writable static data is unsupported on the target,
13706
** we have to locate the state vector at run-time.  In the more common
13707
** case where writable static data is supported, wsdHooks can refer directly
13708
** to the "sqlite3Hooks" state vector declared above.
13709
*/
13710
#ifdef SQLITE_OMIT_WSD
13711
# define wsdHooksInit \
13712
  BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
13713
# define wsdHooks x[0]
13714
#else
13715
# define wsdHooksInit
13716
# define wsdHooks sqlite3Hooks
13717
#endif
13718
13719
13720
/*
13721
** Register hooks to call when sqlite3BeginBenignMalloc() and
13722
** sqlite3EndBenignMalloc() are called, respectively.
13723
*/
13724
SQLITE_PRIVATE void sqlite3BenignMallocHooks(
13725
  void (*xBenignBegin)(void),
13726
  void (*xBenignEnd)(void)
13727
){
13728
  wsdHooksInit;
13729
  wsdHooks.xBenignBegin = xBenignBegin;
13730
  wsdHooks.xBenignEnd = xBenignEnd;
13731
}
13732
13733
/*
13734
** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
13735
** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
13736
** indicates that subsequent malloc failures are non-benign.
13737
*/
13738
SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
13739
  wsdHooksInit;
13740
  if( wsdHooks.xBenignBegin ){
13741
    wsdHooks.xBenignBegin();
13742
  }
13743
}
13744
SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
13745
  wsdHooksInit;
13746
  if( wsdHooks.xBenignEnd ){
13747
    wsdHooks.xBenignEnd();
13748
  }
13749
}
13750
13751
#endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
13752
13753
/************** End of fault.c ***********************************************/
13754
/************** Begin file mem0.c ********************************************/
13755
/*
13756
** 2008 October 28
13757
**
13758
** The author disclaims copyright to this source code.  In place of
13759
** a legal notice, here is a blessing:
13760
**
13761
**    May you do good and not evil.
13762
**    May you find forgiveness for yourself and forgive others.
13763
**    May you share freely, never taking more than you give.
13764
**
13765
*************************************************************************
13766
**
13767
** This file contains a no-op memory allocation drivers for use when
13768
** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
13769
** here always fail.  SQLite will not operate with these drivers.  These
13770
** are merely placeholders.  Real drivers must be substituted using
13771
** sqlite3_config() before SQLite will operate.
13772
*/
13773
13774
/*
13775
** This version of the memory allocator is the default.  It is
13776
** used when no other memory allocator is specified using compile-time
13777
** macros.
13778
*/
13779
#ifdef SQLITE_ZERO_MALLOC
13780
13781
/*
13782
** No-op versions of all memory allocation routines
13783
*/
13784
static void *sqlite3MemMalloc(int nByte){ return 0; }
13785
static void sqlite3MemFree(void *pPrior){ return; }
13786
static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
13787
static int sqlite3MemSize(void *pPrior){ return 0; }
13788
static int sqlite3MemRoundup(int n){ return n; }
13789
static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
13790
static void sqlite3MemShutdown(void *NotUsed){ return; }
13791
13792
/*
13793
** This routine is the only routine in this file with external linkage.
13794
**
13795
** Populate the low-level memory allocation function pointers in
13796
** sqlite3GlobalConfig.m with pointers to the routines in this file.
13797
*/
13798
SQLITE_PRIVATE void sqlite3MemSetDefault(void){
13799
  static const sqlite3_mem_methods defaultMethods = {
13800
     sqlite3MemMalloc,
13801
     sqlite3MemFree,
13802
     sqlite3MemRealloc,
13803
     sqlite3MemSize,
13804
     sqlite3MemRoundup,
13805
     sqlite3MemInit,
13806
     sqlite3MemShutdown,
13807
     0
13808
  };
13809
  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
13810
}
13811
13812
#endif /* SQLITE_ZERO_MALLOC */
13813
13814
/************** End of mem0.c ************************************************/
13815
/************** Begin file mem1.c ********************************************/
13816
/*
13817
** 2007 August 14
13818
**
13819
** The author disclaims copyright to this source code.  In place of
13820
** a legal notice, here is a blessing:
13821
**
13822
**    May you do good and not evil.
13823
**    May you find forgiveness for yourself and forgive others.
13824
**    May you share freely, never taking more than you give.
13825
**
13826
*************************************************************************
13827
**
13828
** This file contains low-level memory allocation drivers for when
13829
** SQLite will use the standard C-library malloc/realloc/free interface
13830
** to obtain the memory it needs.
13831
**
13832
** This file contains implementations of the low-level memory allocation
13833
** routines specified in the sqlite3_mem_methods object.
13834
*/
13835
13836
/*
13837
** This version of the memory allocator is the default.  It is
13838
** used when no other memory allocator is specified using compile-time
13839
** macros.
13840
*/
13841
#ifdef SQLITE_SYSTEM_MALLOC
13842
13843
/*
13844
** Like malloc(), but remember the size of the allocation
13845
** so that we can find it later using sqlite3MemSize().
13846
**
13847
** For this low-level routine, we are guaranteed that nByte>0 because
13848
** cases of nByte<=0 will be intercepted and dealt with by higher level
13849
** routines.
13850
*/
13851
static void *sqlite3MemMalloc(int nByte){
13852
  sqlite3_int64 *p;
13853
  assert( nByte>0 );
13854
  nByte = ROUND8(nByte);
13855
  p = malloc( nByte+8 );
13856
  if( p ){
13857
    p[0] = nByte;
13858
    p++;
13859
  }else{
13860
    testcase( sqlite3GlobalConfig.xLog!=0 );
13861
    sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
13862
  }
13863
  return (void *)p;
13864
}
13865
13866
/*
13867
** Like free() but works for allocations obtained from sqlite3MemMalloc()
13868
** or sqlite3MemRealloc().
13869
**
13870
** For this low-level routine, we already know that pPrior!=0 since
13871
** cases where pPrior==0 will have been intecepted and dealt with
13872
** by higher-level routines.
13873
*/
13874
static void sqlite3MemFree(void *pPrior){
13875
  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
13876
  assert( pPrior!=0 );
13877
  p--;
13878
  free(p);
13879
}
13880
13881
/*
13882
** Report the allocated size of a prior return from xMalloc()
13883
** or xRealloc().
13884
*/
13885
static int sqlite3MemSize(void *pPrior){
13886
  sqlite3_int64 *p;
13887
  if( pPrior==0 ) return 0;
13888
  p = (sqlite3_int64*)pPrior;
13889
  p--;
13890
  return (int)p[0];
13891
}
13892
13893
/*
13894
** Like realloc().  Resize an allocation previously obtained from
13895
** sqlite3MemMalloc().
13896
**
13897
** For this low-level interface, we know that pPrior!=0.  Cases where
13898
** pPrior==0 while have been intercepted by higher-level routine and
13899
** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
13900
** cases where nByte<=0 will have been intercepted by higher-level
13901
** routines and redirected to xFree.
13902
*/
13903
static void *sqlite3MemRealloc(void *pPrior, int nByte){
13904
  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
13905
  assert( pPrior!=0 && nByte>0 );
13906
  nByte = ROUND8(nByte);
13907
  p--;
13908
  p = realloc(p, nByte+8 );
13909
  if( p ){
13910
    p[0] = nByte;
13911
    p++;
13912
  }else{
13913
    testcase( sqlite3GlobalConfig.xLog!=0 );
13914
    sqlite3_log(SQLITE_NOMEM,
13915
      "failed memory resize %u to %u bytes",
13916
      sqlite3MemSize(pPrior), nByte);
13917
  }
13918
  return (void*)p;
13919
}
13920
13921
/*
13922
** Round up a request size to the next valid allocation size.
13923
*/
13924
static int sqlite3MemRoundup(int n){
13925
  return ROUND8(n);
13926
}
13927
13928
/*
13929
** Initialize this module.
13930
*/
13931
static int sqlite3MemInit(void *NotUsed){
13932
  UNUSED_PARAMETER(NotUsed);
13933
  return SQLITE_OK;
13934
}
13935
13936
/*
13937
** Deinitialize this module.
13938
*/
13939
static void sqlite3MemShutdown(void *NotUsed){
13940
  UNUSED_PARAMETER(NotUsed);
13941
  return;
13942
}
13943
13944
/*
13945
** This routine is the only routine in this file with external linkage.
13946
**
13947
** Populate the low-level memory allocation function pointers in
13948
** sqlite3GlobalConfig.m with pointers to the routines in this file.
13949
*/
13950
SQLITE_PRIVATE void sqlite3MemSetDefault(void){
13951
  static const sqlite3_mem_methods defaultMethods = {
13952
     sqlite3MemMalloc,
13953
     sqlite3MemFree,
13954
     sqlite3MemRealloc,
13955
     sqlite3MemSize,
13956
     sqlite3MemRoundup,
13957
     sqlite3MemInit,
13958
     sqlite3MemShutdown,
13959
     0
13960
  };
13961
  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
13962
}
13963
13964
#endif /* SQLITE_SYSTEM_MALLOC */
13965
13966
/************** End of mem1.c ************************************************/
13967
/************** Begin file mem2.c ********************************************/
13968
/*
13969
** 2007 August 15
13970
**
13971
** The author disclaims copyright to this source code.  In place of
13972
** a legal notice, here is a blessing:
13973
**
13974
**    May you do good and not evil.
13975
**    May you find forgiveness for yourself and forgive others.
13976
**    May you share freely, never taking more than you give.
13977
**
13978
*************************************************************************
13979
**
13980
** This file contains low-level memory allocation drivers for when
13981
** SQLite will use the standard C-library malloc/realloc/free interface
13982
** to obtain the memory it needs while adding lots of additional debugging
13983
** information to each allocation in order to help detect and fix memory
13984
** leaks and memory usage errors.
13985
**
13986
** This file contains implementations of the low-level memory allocation
13987
** routines specified in the sqlite3_mem_methods object.
13988
*/
13989
13990
/*
13991
** This version of the memory allocator is used only if the
13992
** SQLITE_MEMDEBUG macro is defined
13993
*/
13994
#ifdef SQLITE_MEMDEBUG
13995
13996
/*
13997
** The backtrace functionality is only available with GLIBC
13998
*/
13999
#ifdef __GLIBC__
14000
  extern int backtrace(void**,int);
14001
  extern void backtrace_symbols_fd(void*const*,int,int);
14002
#else
14003
# define backtrace(A,B) 1
14004
# define backtrace_symbols_fd(A,B,C)
14005
#endif
14006
14007
/*
14008
** Each memory allocation looks like this:
14009
**
14010
**  ------------------------------------------------------------------------
14011
**  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
14012
**  ------------------------------------------------------------------------
14013
**
14014
** The application code sees only a pointer to the allocation.  We have
14015
** to back up from the allocation pointer to find the MemBlockHdr.  The
14016
** MemBlockHdr tells us the size of the allocation and the number of
14017
** backtrace pointers.  There is also a guard word at the end of the
14018
** MemBlockHdr.
14019
*/
14020
struct MemBlockHdr {
14021
  i64 iSize;                          /* Size of this allocation */
14022
  struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
14023
  char nBacktrace;                    /* Number of backtraces on this alloc */
14024
  char nBacktraceSlots;               /* Available backtrace slots */
14025
  u8 nTitle;                          /* Bytes of title; includes '\0' */
14026
  u8 eType;                           /* Allocation type code */
14027
  int iForeGuard;                     /* Guard word for sanity */
14028
};
14029
14030
/*
14031
** Guard words
14032
*/
14033
#define FOREGUARD 0x80F5E153
14034
#define REARGUARD 0xE4676B53
14035
14036
/*
14037
** Number of malloc size increments to track.
14038
*/
14039
#define NCSIZE  1000
14040
14041
/*
14042
** All of the static variables used by this module are collected
14043
** into a single structure named "mem".  This is to keep the
14044
** static variables organized and to reduce namespace pollution
14045
** when this module is combined with other in the amalgamation.
14046
*/
14047
static struct {
14048
  
14049
  /*
14050
  ** Mutex to control access to the memory allocation subsystem.
14051
  */
14052
  sqlite3_mutex *mutex;
14053
14054
  /*
14055
  ** Head and tail of a linked list of all outstanding allocations
14056
  */
14057
  struct MemBlockHdr *pFirst;
14058
  struct MemBlockHdr *pLast;
14059
  
14060
  /*
14061
  ** The number of levels of backtrace to save in new allocations.
14062
  */
14063
  int nBacktrace;
14064
  void (*xBacktrace)(int, int, void **);
14065
14066
  /*
14067
  ** Title text to insert in front of each block
14068
  */
14069
  int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
14070
  char zTitle[100];  /* The title text */
14071
14072
  /* 
14073
  ** sqlite3MallocDisallow() increments the following counter.
14074
  ** sqlite3MallocAllow() decrements it.
14075
  */
14076
  int disallow; /* Do not allow memory allocation */
14077
14078
  /*
14079
  ** Gather statistics on the sizes of memory allocations.
14080
  ** nAlloc[i] is the number of allocation attempts of i*8
14081
  ** bytes.  i==NCSIZE is the number of allocation attempts for
14082
  ** sizes more than NCSIZE*8 bytes.
14083
  */
14084
  int nAlloc[NCSIZE];      /* Total number of allocations */
14085
  int nCurrent[NCSIZE];    /* Current number of allocations */
14086
  int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
14087
14088
} mem;
14089
14090
14091
/*
14092
** Adjust memory usage statistics
14093
*/
14094
static void adjustStats(int iSize, int increment){
14095
  int i = ROUND8(iSize)/8;
14096
  if( i>NCSIZE-1 ){
14097
    i = NCSIZE - 1;
14098
  }
14099
  if( increment>0 ){
14100
    mem.nAlloc[i]++;
14101
    mem.nCurrent[i]++;
14102
    if( mem.nCurrent[i]>mem.mxCurrent[i] ){
14103
      mem.mxCurrent[i] = mem.nCurrent[i];
14104
    }
14105
  }else{
14106
    mem.nCurrent[i]--;
14107
    assert( mem.nCurrent[i]>=0 );
14108
  }
14109
}
14110
14111
/*
14112
** Given an allocation, find the MemBlockHdr for that allocation.
14113
**
14114
** This routine checks the guards at either end of the allocation and
14115
** if they are incorrect it asserts.
14116
*/
14117
static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
14118
  struct MemBlockHdr *p;
14119
  int *pInt;
14120
  u8 *pU8;
14121
  int nReserve;
14122
14123
  p = (struct MemBlockHdr*)pAllocation;
14124
  p--;
14125
  assert( p->iForeGuard==(int)FOREGUARD );
14126
  nReserve = ROUND8(p->iSize);
14127
  pInt = (int*)pAllocation;
14128
  pU8 = (u8*)pAllocation;
14129
  assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
14130
  /* This checks any of the "extra" bytes allocated due
14131
  ** to rounding up to an 8 byte boundary to ensure 
14132
  ** they haven't been overwritten.
14133
  */
14134
  while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
14135
  return p;
14136
}
14137
14138
/*
14139
** Return the number of bytes currently allocated at address p.
14140
*/
14141
static int sqlite3MemSize(void *p){
14142
  struct MemBlockHdr *pHdr;
14143
  if( !p ){
14144
    return 0;
14145
  }
14146
  pHdr = sqlite3MemsysGetHeader(p);
14147
  return pHdr->iSize;
14148
}
14149
14150
/*
14151
** Initialize the memory allocation subsystem.
14152
*/
14153
static int sqlite3MemInit(void *NotUsed){
14154
  UNUSED_PARAMETER(NotUsed);
14155
  assert( (sizeof(struct MemBlockHdr)&7) == 0 );
14156
  if( !sqlite3GlobalConfig.bMemstat ){
14157
    /* If memory status is enabled, then the malloc.c wrapper will already
14158
    ** hold the STATIC_MEM mutex when the routines here are invoked. */
14159
    mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
14160
  }
14161
  return SQLITE_OK;
14162
}
14163
14164
/*
14165
** Deinitialize the memory allocation subsystem.
14166
*/
14167
static void sqlite3MemShutdown(void *NotUsed){
14168
  UNUSED_PARAMETER(NotUsed);
14169
  mem.mutex = 0;
14170
}
14171
14172
/*
14173
** Round up a request size to the next valid allocation size.
14174
*/
14175
static int sqlite3MemRoundup(int n){
14176
  return ROUND8(n);
14177
}
14178
14179
/*
14180
** Fill a buffer with pseudo-random bytes.  This is used to preset
14181
** the content of a new memory allocation to unpredictable values and
14182
** to clear the content of a freed allocation to unpredictable values.
14183
*/
14184
static void randomFill(char *pBuf, int nByte){
14185
  unsigned int x, y, r;
14186
  x = SQLITE_PTR_TO_INT(pBuf);
14187
  y = nByte | 1;
14188
  while( nByte >= 4 ){
14189
    x = (x>>1) ^ (-(x&1) & 0xd0000001);
14190
    y = y*1103515245 + 12345;
14191
    r = x ^ y;
14192
    *(int*)pBuf = r;
14193
    pBuf += 4;
14194
    nByte -= 4;
14195
  }
14196
  while( nByte-- > 0 ){
14197
    x = (x>>1) ^ (-(x&1) & 0xd0000001);
14198
    y = y*1103515245 + 12345;
14199
    r = x ^ y;
14200
    *(pBuf++) = r & 0xff;
14201
  }
14202
}
14203
14204
/*
14205
** Allocate nByte bytes of memory.
14206
*/
14207
static void *sqlite3MemMalloc(int nByte){
14208
  struct MemBlockHdr *pHdr;
14209
  void **pBt;
14210
  char *z;
14211
  int *pInt;
14212
  void *p = 0;
14213
  int totalSize;
14214
  int nReserve;
14215
  sqlite3_mutex_enter(mem.mutex);
14216
  assert( mem.disallow==0 );
14217
  nReserve = ROUND8(nByte);
14218
  totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
14219
               mem.nBacktrace*sizeof(void*) + mem.nTitle;
14220
  p = malloc(totalSize);
14221
  if( p ){
14222
    z = p;
14223
    pBt = (void**)&z[mem.nTitle];
14224
    pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
14225
    pHdr->pNext = 0;
14226
    pHdr->pPrev = mem.pLast;
14227
    if( mem.pLast ){
14228
      mem.pLast->pNext = pHdr;
14229
    }else{
14230
      mem.pFirst = pHdr;
14231
    }
14232
    mem.pLast = pHdr;
14233
    pHdr->iForeGuard = FOREGUARD;
14234
    pHdr->eType = MEMTYPE_HEAP;
14235
    pHdr->nBacktraceSlots = mem.nBacktrace;
14236
    pHdr->nTitle = mem.nTitle;
14237
    if( mem.nBacktrace ){
14238
      void *aAddr[40];
14239
      pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
14240
      memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
14241
      assert(pBt[0]);
14242
      if( mem.xBacktrace ){
14243
        mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
14244
      }
14245
    }else{
14246
      pHdr->nBacktrace = 0;
14247
    }
14248
    if( mem.nTitle ){
14249
      memcpy(z, mem.zTitle, mem.nTitle);
14250
    }
14251
    pHdr->iSize = nByte;
14252
    adjustStats(nByte, +1);
14253
    pInt = (int*)&pHdr[1];
14254
    pInt[nReserve/sizeof(int)] = REARGUARD;
14255
    randomFill((char*)pInt, nByte);
14256
    memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
14257
    p = (void*)pInt;
14258
  }
14259
  sqlite3_mutex_leave(mem.mutex);
14260
  return p; 
14261
}
14262
14263
/*
14264
** Free memory.
14265
*/
14266
static void sqlite3MemFree(void *pPrior){
14267
  struct MemBlockHdr *pHdr;
14268
  void **pBt;
14269
  char *z;
14270
  assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0 
14271
       || mem.mutex!=0 );
14272
  pHdr = sqlite3MemsysGetHeader(pPrior);
14273
  pBt = (void**)pHdr;
14274
  pBt -= pHdr->nBacktraceSlots;
14275
  sqlite3_mutex_enter(mem.mutex);
14276
  if( pHdr->pPrev ){
14277
    assert( pHdr->pPrev->pNext==pHdr );
14278
    pHdr->pPrev->pNext = pHdr->pNext;
14279
  }else{
14280
    assert( mem.pFirst==pHdr );
14281
    mem.pFirst = pHdr->pNext;
14282
  }
14283
  if( pHdr->pNext ){
14284
    assert( pHdr->pNext->pPrev==pHdr );
14285
    pHdr->pNext->pPrev = pHdr->pPrev;
14286
  }else{
14287
    assert( mem.pLast==pHdr );
14288
    mem.pLast = pHdr->pPrev;
14289
  }
14290
  z = (char*)pBt;
14291
  z -= pHdr->nTitle;
14292
  adjustStats(pHdr->iSize, -1);
14293
  randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
14294
                pHdr->iSize + sizeof(int) + pHdr->nTitle);
14295
  free(z);
14296
  sqlite3_mutex_leave(mem.mutex);  
14297
}
14298
14299
/*
14300
** Change the size of an existing memory allocation.
14301
**
14302
** For this debugging implementation, we *always* make a copy of the
14303
** allocation into a new place in memory.  In this way, if the 
14304
** higher level code is using pointer to the old allocation, it is 
14305
** much more likely to break and we are much more liking to find
14306
** the error.
14307
*/
14308
static void *sqlite3MemRealloc(void *pPrior, int nByte){
14309
  struct MemBlockHdr *pOldHdr;
14310
  void *pNew;
14311
  assert( mem.disallow==0 );
14312
  pOldHdr = sqlite3MemsysGetHeader(pPrior);
14313
  pNew = sqlite3MemMalloc(nByte);
14314
  if( pNew ){
14315
    memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
14316
    if( nByte>pOldHdr->iSize ){
14317
      randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
14318
    }
14319
    sqlite3MemFree(pPrior);
14320
  }
14321
  return pNew;
14322
}
14323
14324
/*
14325
** Populate the low-level memory allocation function pointers in
14326
** sqlite3GlobalConfig.m with pointers to the routines in this file.
14327
*/
14328
SQLITE_PRIVATE void sqlite3MemSetDefault(void){
14329
  static const sqlite3_mem_methods defaultMethods = {
14330
     sqlite3MemMalloc,
14331
     sqlite3MemFree,
14332
     sqlite3MemRealloc,
14333
     sqlite3MemSize,
14334
     sqlite3MemRoundup,
14335
     sqlite3MemInit,
14336
     sqlite3MemShutdown,
14337
     0
14338
  };
14339
  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
14340
}
14341
14342
/*
14343
** Set the "type" of an allocation.
14344
*/
14345
SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
14346
  if( p ){
14347
    struct MemBlockHdr *pHdr;
14348
    pHdr = sqlite3MemsysGetHeader(p);
14349
    assert( pHdr->iForeGuard==FOREGUARD );
14350
    pHdr->eType = eType;
14351
  }
14352
}
14353
14354
/*
14355
** Return TRUE if the mask of type in eType matches the type of the
14356
** allocation p.  Also return true if p==NULL.
14357
**
14358
** This routine is designed for use within an assert() statement, to
14359
** verify the type of an allocation.  For example:
14360
**
14361
**     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
14362
*/
14363
SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
14364
  int rc = 1;
14365
  if( p ){
14366
    struct MemBlockHdr *pHdr;
14367
    pHdr = sqlite3MemsysGetHeader(p);
14368
    assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
14369
    if( (pHdr->eType&eType)==0 ){
14370
      rc = 0;
14371
    }
14372
  }
14373
  return rc;
14374
}
14375
14376
/*
14377
** Return TRUE if the mask of type in eType matches no bits of the type of the
14378
** allocation p.  Also return true if p==NULL.
14379
**
14380
** This routine is designed for use within an assert() statement, to
14381
** verify the type of an allocation.  For example:
14382
**
14383
**     assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
14384
*/
14385
SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
14386
  int rc = 1;
14387
  if( p ){
14388
    struct MemBlockHdr *pHdr;
14389
    pHdr = sqlite3MemsysGetHeader(p);
14390
    assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
14391
    if( (pHdr->eType&eType)!=0 ){
14392
      rc = 0;
14393
    }
14394
  }
14395
  return rc;
14396
}
14397
14398
/*
14399
** Set the number of backtrace levels kept for each allocation.
14400
** A value of zero turns off backtracing.  The number is always rounded
14401
** up to a multiple of 2.
14402
*/
14403
SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
14404
  if( depth<0 ){ depth = 0; }
14405
  if( depth>20 ){ depth = 20; }
14406
  depth = (depth+1)&0xfe;
14407
  mem.nBacktrace = depth;
14408
}
14409
14410
SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
14411
  mem.xBacktrace = xBacktrace;
14412
}
14413
14414
/*
14415
** Set the title string for subsequent allocations.
14416
*/
14417
SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
14418
  unsigned int n = sqlite3Strlen30(zTitle) + 1;
14419
  sqlite3_mutex_enter(mem.mutex);
14420
  if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
14421
  memcpy(mem.zTitle, zTitle, n);
14422
  mem.zTitle[n] = 0;
14423
  mem.nTitle = ROUND8(n);
14424
  sqlite3_mutex_leave(mem.mutex);
14425
}
14426
14427
SQLITE_PRIVATE void sqlite3MemdebugSync(){
14428
  struct MemBlockHdr *pHdr;
14429
  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
14430
    void **pBt = (void**)pHdr;
14431
    pBt -= pHdr->nBacktraceSlots;
14432
    mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
14433
  }
14434
}
14435
14436
/*
14437
** Open the file indicated and write a log of all unfreed memory 
14438
** allocations into that log.
14439
*/
14440
SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
14441
  FILE *out;
14442
  struct MemBlockHdr *pHdr;
14443
  void **pBt;
14444
  int i;
14445
  out = fopen(zFilename, "w");
14446
  if( out==0 ){
14447
    fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
14448
                    zFilename);
14449
    return;
14450
  }
14451
  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
14452
    char *z = (char*)pHdr;
14453
    z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
14454
    fprintf(out, "**** %lld bytes at %p from %s ****\n", 
14455
            pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
14456
    if( pHdr->nBacktrace ){
14457
      fflush(out);
14458
      pBt = (void**)pHdr;
14459
      pBt -= pHdr->nBacktraceSlots;
14460
      backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
14461
      fprintf(out, "\n");
14462
    }
14463
  }
14464
  fprintf(out, "COUNTS:\n");
14465
  for(i=0; i<NCSIZE-1; i++){
14466
    if( mem.nAlloc[i] ){
14467
      fprintf(out, "   %5d: %10d %10d %10d\n", 
14468
            i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
14469
    }
14470
  }
14471
  if( mem.nAlloc[NCSIZE-1] ){
14472
    fprintf(out, "   %5d: %10d %10d %10d\n",
14473
             NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
14474
             mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
14475
  }
14476
  fclose(out);
14477
}
14478
14479
/*
14480
** Return the number of times sqlite3MemMalloc() has been called.
14481
*/
14482
SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
14483
  int i;
14484
  int nTotal = 0;
14485
  for(i=0; i<NCSIZE; i++){
14486
    nTotal += mem.nAlloc[i];
14487
  }
14488
  return nTotal;
14489
}
14490
14491
14492
#endif /* SQLITE_MEMDEBUG */
14493
14494
/************** End of mem2.c ************************************************/
14495
/************** Begin file mem3.c ********************************************/
14496
/*
14497
** 2007 October 14
14498
**
14499
** The author disclaims copyright to this source code.  In place of
14500
** a legal notice, here is a blessing:
14501
**
14502
**    May you do good and not evil.
14503
**    May you find forgiveness for yourself and forgive others.
14504
**    May you share freely, never taking more than you give.
14505
**
14506
*************************************************************************
14507
** This file contains the C functions that implement a memory
14508
** allocation subsystem for use by SQLite. 
14509
**
14510
** This version of the memory allocation subsystem omits all
14511
** use of malloc(). The SQLite user supplies a block of memory
14512
** before calling sqlite3_initialize() from which allocations
14513
** are made and returned by the xMalloc() and xRealloc() 
14514
** implementations. Once sqlite3_initialize() has been called,
14515
** the amount of memory available to SQLite is fixed and cannot
14516
** be changed.
14517
**
14518
** This version of the memory allocation subsystem is included
14519
** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
14520
*/
14521
14522
/*
14523
** This version of the memory allocator is only built into the library
14524
** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
14525
** mean that the library will use a memory-pool by default, just that
14526
** it is available. The mempool allocator is activated by calling
14527
** sqlite3_config().
14528
*/
14529
#ifdef SQLITE_ENABLE_MEMSYS3
14530
14531
/*
14532
** Maximum size (in Mem3Blocks) of a "small" chunk.
14533
*/
14534
#define MX_SMALL 10
14535
14536
14537
/*
14538
** Number of freelist hash slots
14539
*/
14540
#define N_HASH  61
14541
14542
/*
14543
** A memory allocation (also called a "chunk") consists of two or 
14544
** more blocks where each block is 8 bytes.  The first 8 bytes are 
14545
** a header that is not returned to the user.
14546
**
14547
** A chunk is two or more blocks that is either checked out or
14548
** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
14549
** size of the allocation in blocks if the allocation is free.
14550
** The u.hdr.size4x&1 bit is true if the chunk is checked out and
14551
** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
14552
** is true if the previous chunk is checked out and false if the
14553
** previous chunk is free.  The u.hdr.prevSize field is the size of
14554
** the previous chunk in blocks if the previous chunk is on the
14555
** freelist. If the previous chunk is checked out, then
14556
** u.hdr.prevSize can be part of the data for that chunk and should
14557
** not be read or written.
14558
**
14559
** We often identify a chunk by its index in mem3.aPool[].  When
14560
** this is done, the chunk index refers to the second block of
14561
** the chunk.  In this way, the first chunk has an index of 1.
14562
** A chunk index of 0 means "no such chunk" and is the equivalent
14563
** of a NULL pointer.
14564
**
14565
** The second block of free chunks is of the form u.list.  The
14566
** two fields form a double-linked list of chunks of related sizes.
14567
** Pointers to the head of the list are stored in mem3.aiSmall[] 
14568
** for smaller chunks and mem3.aiHash[] for larger chunks.
14569
**
14570
** The second block of a chunk is user data if the chunk is checked 
14571
** out.  If a chunk is checked out, the user data may extend into
14572
** the u.hdr.prevSize value of the following chunk.
14573
*/
14574
typedef struct Mem3Block Mem3Block;
14575
struct Mem3Block {
14576
  union {
14577
    struct {
14578
      u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
14579
      u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
14580
    } hdr;
14581
    struct {
14582
      u32 next;       /* Index in mem3.aPool[] of next free chunk */
14583
      u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
14584
    } list;
14585
  } u;
14586
};
14587
14588
/*
14589
** All of the static variables used by this module are collected
14590
** into a single structure named "mem3".  This is to keep the
14591
** static variables organized and to reduce namespace pollution
14592
** when this module is combined with other in the amalgamation.
14593
*/
14594
static SQLITE_WSD struct Mem3Global {
14595
  /*
14596
  ** Memory available for allocation. nPool is the size of the array
14597
  ** (in Mem3Blocks) pointed to by aPool less 2.
14598
  */
14599
  u32 nPool;
14600
  Mem3Block *aPool;
14601
14602
  /*
14603
  ** True if we are evaluating an out-of-memory callback.
14604
  */
14605
  int alarmBusy;
14606
  
14607
  /*
14608
  ** Mutex to control access to the memory allocation subsystem.
14609
  */
14610
  sqlite3_mutex *mutex;
14611
  
14612
  /*
14613
  ** The minimum amount of free space that we have seen.
14614
  */
14615
  u32 mnMaster;
14616
14617
  /*
14618
  ** iMaster is the index of the master chunk.  Most new allocations
14619
  ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
14620
  ** of the current master.  iMaster is 0 if there is not master chunk.
14621
  ** The master chunk is not in either the aiHash[] or aiSmall[].
14622
  */
14623
  u32 iMaster;
14624
  u32 szMaster;
14625
14626
  /*
14627
  ** Array of lists of free blocks according to the block size 
14628
  ** for smaller chunks, or a hash on the block size for larger
14629
  ** chunks.
14630
  */
14631
  u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
14632
  u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
14633
} mem3 = { 97535575 };
14634
14635
#define mem3 GLOBAL(struct Mem3Global, mem3)
14636
14637
/*
14638
** Unlink the chunk at mem3.aPool[i] from list it is currently
14639
** on.  *pRoot is the list that i is a member of.
14640
*/
14641
static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
14642
  u32 next = mem3.aPool[i].u.list.next;
14643
  u32 prev = mem3.aPool[i].u.list.prev;
14644
  assert( sqlite3_mutex_held(mem3.mutex) );
14645
  if( prev==0 ){
14646
    *pRoot = next;
14647
  }else{
14648
    mem3.aPool[prev].u.list.next = next;
14649
  }
14650
  if( next ){
14651
    mem3.aPool[next].u.list.prev = prev;
14652
  }
14653
  mem3.aPool[i].u.list.next = 0;
14654
  mem3.aPool[i].u.list.prev = 0;
14655
}
14656
14657
/*
14658
** Unlink the chunk at index i from 
14659
** whatever list is currently a member of.
14660
*/
14661
static void memsys3Unlink(u32 i){
14662
  u32 size, hash;
14663
  assert( sqlite3_mutex_held(mem3.mutex) );
14664
  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
14665
  assert( i>=1 );
14666
  size = mem3.aPool[i-1].u.hdr.size4x/4;
14667
  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
14668
  assert( size>=2 );
14669
  if( size <= MX_SMALL ){
14670
    memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
14671
  }else{
14672
    hash = size % N_HASH;
14673
    memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
14674
  }
14675
}
14676
14677
/*
14678
** Link the chunk at mem3.aPool[i] so that is on the list rooted
14679
** at *pRoot.
14680
*/
14681
static void memsys3LinkIntoList(u32 i, u32 *pRoot){
14682
  assert( sqlite3_mutex_held(mem3.mutex) );
14683
  mem3.aPool[i].u.list.next = *pRoot;
14684
  mem3.aPool[i].u.list.prev = 0;
14685
  if( *pRoot ){
14686
    mem3.aPool[*pRoot].u.list.prev = i;
14687
  }
14688
  *pRoot = i;
14689
}
14690
14691
/*
14692
** Link the chunk at index i into either the appropriate
14693
** small chunk list, or into the large chunk hash table.
14694
*/
14695
static void memsys3Link(u32 i){
14696
  u32 size, hash;
14697
  assert( sqlite3_mutex_held(mem3.mutex) );
14698
  assert( i>=1 );
14699
  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
14700
  size = mem3.aPool[i-1].u.hdr.size4x/4;
14701
  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
14702
  assert( size>=2 );
14703
  if( size <= MX_SMALL ){
14704
    memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
14705
  }else{
14706
    hash = size % N_HASH;
14707
    memsys3LinkIntoList(i, &mem3.aiHash[hash]);
14708
  }
14709
}
14710
14711
/*
14712
** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
14713
** will already be held (obtained by code in malloc.c) if
14714
** sqlite3GlobalConfig.bMemStat is true.
14715
*/
14716
static void memsys3Enter(void){
14717
  if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
14718
    mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
14719
  }
14720
  sqlite3_mutex_enter(mem3.mutex);
14721
}
14722
static void memsys3Leave(void){
14723
  sqlite3_mutex_leave(mem3.mutex);
14724
}
14725
14726
/*
14727
** Called when we are unable to satisfy an allocation of nBytes.
14728
*/
14729
static void memsys3OutOfMemory(int nByte){
14730
  if( !mem3.alarmBusy ){
14731
    mem3.alarmBusy = 1;
14732
    assert( sqlite3_mutex_held(mem3.mutex) );
14733
    sqlite3_mutex_leave(mem3.mutex);
14734
    sqlite3_release_memory(nByte);
14735
    sqlite3_mutex_enter(mem3.mutex);
14736
    mem3.alarmBusy = 0;
14737
  }
14738
}
14739
14740
14741
/*
14742
** Chunk i is a free chunk that has been unlinked.  Adjust its 
14743
** size parameters for check-out and return a pointer to the 
14744
** user portion of the chunk.
14745
*/
14746
static void *memsys3Checkout(u32 i, u32 nBlock){
14747
  u32 x;
14748
  assert( sqlite3_mutex_held(mem3.mutex) );
14749
  assert( i>=1 );
14750
  assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
14751
  assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
14752
  x = mem3.aPool[i-1].u.hdr.size4x;
14753
  mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
14754
  mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
14755
  mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
14756
  return &mem3.aPool[i];
14757
}
14758
14759
/*
14760
** Carve a piece off of the end of the mem3.iMaster free chunk.
14761
** Return a pointer to the new allocation.  Or, if the master chunk
14762
** is not large enough, return 0.
14763
*/
14764
static void *memsys3FromMaster(u32 nBlock){
14765
  assert( sqlite3_mutex_held(mem3.mutex) );
14766
  assert( mem3.szMaster>=nBlock );
14767
  if( nBlock>=mem3.szMaster-1 ){
14768
    /* Use the entire master */
14769
    void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
14770
    mem3.iMaster = 0;
14771
    mem3.szMaster = 0;
14772
    mem3.mnMaster = 0;
14773
    return p;
14774
  }else{
14775
    /* Split the master block.  Return the tail. */
14776
    u32 newi, x;
14777
    newi = mem3.iMaster + mem3.szMaster - nBlock;
14778
    assert( newi > mem3.iMaster+1 );
14779
    mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
14780
    mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
14781
    mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
14782
    mem3.szMaster -= nBlock;
14783
    mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
14784
    x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
14785
    mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
14786
    if( mem3.szMaster < mem3.mnMaster ){
14787
      mem3.mnMaster = mem3.szMaster;
14788
    }
14789
    return (void*)&mem3.aPool[newi];
14790
  }
14791
}
14792
14793
/*
14794
** *pRoot is the head of a list of free chunks of the same size
14795
** or same size hash.  In other words, *pRoot is an entry in either
14796
** mem3.aiSmall[] or mem3.aiHash[].  
14797
**
14798
** This routine examines all entries on the given list and tries
14799
** to coalesce each entries with adjacent free chunks.  
14800
**
14801
** If it sees a chunk that is larger than mem3.iMaster, it replaces 
14802
** the current mem3.iMaster with the new larger chunk.  In order for
14803
** this mem3.iMaster replacement to work, the master chunk must be
14804
** linked into the hash tables.  That is not the normal state of
14805
** affairs, of course.  The calling routine must link the master
14806
** chunk before invoking this routine, then must unlink the (possibly
14807
** changed) master chunk once this routine has finished.
14808
*/
14809
static void memsys3Merge(u32 *pRoot){
14810
  u32 iNext, prev, size, i, x;
14811
14812
  assert( sqlite3_mutex_held(mem3.mutex) );
14813
  for(i=*pRoot; i>0; i=iNext){
14814
    iNext = mem3.aPool[i].u.list.next;
14815
    size = mem3.aPool[i-1].u.hdr.size4x;
14816
    assert( (size&1)==0 );
14817
    if( (size&2)==0 ){
14818
      memsys3UnlinkFromList(i, pRoot);
14819
      assert( i > mem3.aPool[i-1].u.hdr.prevSize );
14820
      prev = i - mem3.aPool[i-1].u.hdr.prevSize;
14821
      if( prev==iNext ){
14822
        iNext = mem3.aPool[prev].u.list.next;
14823
      }
14824
      memsys3Unlink(prev);
14825
      size = i + size/4 - prev;
14826
      x = mem3.aPool[prev-1].u.hdr.size4x & 2;
14827
      mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
14828
      mem3.aPool[prev+size-1].u.hdr.prevSize = size;
14829
      memsys3Link(prev);
14830
      i = prev;
14831
    }else{
14832
      size /= 4;
14833
    }
14834
    if( size>mem3.szMaster ){
14835
      mem3.iMaster = i;
14836
      mem3.szMaster = size;
14837
    }
14838
  }
14839
}
14840
14841
/*
14842
** Return a block of memory of at least nBytes in size.
14843
** Return NULL if unable.
14844
**
14845
** This function assumes that the necessary mutexes, if any, are
14846
** already held by the caller. Hence "Unsafe".
14847
*/
14848
static void *memsys3MallocUnsafe(int nByte){
14849
  u32 i;
14850
  u32 nBlock;
14851
  u32 toFree;
14852
14853
  assert( sqlite3_mutex_held(mem3.mutex) );
14854
  assert( sizeof(Mem3Block)==8 );
14855
  if( nByte<=12 ){
14856
    nBlock = 2;
14857
  }else{
14858
    nBlock = (nByte + 11)/8;
14859
  }
14860
  assert( nBlock>=2 );
14861
14862
  /* STEP 1:
14863
  ** Look for an entry of the correct size in either the small
14864
  ** chunk table or in the large chunk hash table.  This is
14865
  ** successful most of the time (about 9 times out of 10).
14866
  */
14867
  if( nBlock <= MX_SMALL ){
14868
    i = mem3.aiSmall[nBlock-2];
14869
    if( i>0 ){
14870
      memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
14871
      return memsys3Checkout(i, nBlock);
14872
    }
14873
  }else{
14874
    int hash = nBlock % N_HASH;
14875
    for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
14876
      if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
14877
        memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
14878
        return memsys3Checkout(i, nBlock);
14879
      }
14880
    }
14881
  }
14882
14883
  /* STEP 2:
14884
  ** Try to satisfy the allocation by carving a piece off of the end
14885
  ** of the master chunk.  This step usually works if step 1 fails.
14886
  */
14887
  if( mem3.szMaster>=nBlock ){
14888
    return memsys3FromMaster(nBlock);
14889
  }
14890
14891
14892
  /* STEP 3:  
14893
  ** Loop through the entire memory pool.  Coalesce adjacent free
14894
  ** chunks.  Recompute the master chunk as the largest free chunk.
14895
  ** Then try again to satisfy the allocation by carving a piece off
14896
  ** of the end of the master chunk.  This step happens very
14897
  ** rarely (we hope!)
14898
  */
14899
  for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
14900
    memsys3OutOfMemory(toFree);
14901
    if( mem3.iMaster ){
14902
      memsys3Link(mem3.iMaster);
14903
      mem3.iMaster = 0;
14904
      mem3.szMaster = 0;
14905
    }
14906
    for(i=0; i<N_HASH; i++){
14907
      memsys3Merge(&mem3.aiHash[i]);
14908
    }
14909
    for(i=0; i<MX_SMALL-1; i++){
14910
      memsys3Merge(&mem3.aiSmall[i]);
14911
    }
14912
    if( mem3.szMaster ){
14913
      memsys3Unlink(mem3.iMaster);
14914
      if( mem3.szMaster>=nBlock ){
14915
        return memsys3FromMaster(nBlock);
14916
      }
14917
    }
14918
  }
14919
14920
  /* If none of the above worked, then we fail. */
14921
  return 0;
14922
}
14923
14924
/*
14925
** Free an outstanding memory allocation.
14926
**
14927
** This function assumes that the necessary mutexes, if any, are
14928
** already held by the caller. Hence "Unsafe".
14929
*/
14930
void memsys3FreeUnsafe(void *pOld){
14931
  Mem3Block *p = (Mem3Block*)pOld;
14932
  int i;
14933
  u32 size, x;
14934
  assert( sqlite3_mutex_held(mem3.mutex) );
14935
  assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
14936
  i = p - mem3.aPool;
14937
  assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
14938
  size = mem3.aPool[i-1].u.hdr.size4x/4;
14939
  assert( i+size<=mem3.nPool+1 );
14940
  mem3.aPool[i-1].u.hdr.size4x &= ~1;
14941
  mem3.aPool[i+size-1].u.hdr.prevSize = size;
14942
  mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
14943
  memsys3Link(i);
14944
14945
  /* Try to expand the master using the newly freed chunk */
14946
  if( mem3.iMaster ){
14947
    while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
14948
      size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
14949
      mem3.iMaster -= size;
14950
      mem3.szMaster += size;
14951
      memsys3Unlink(mem3.iMaster);
14952
      x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
14953
      mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
14954
      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
14955
    }
14956
    x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
14957
    while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
14958
      memsys3Unlink(mem3.iMaster+mem3.szMaster);
14959
      mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
14960
      mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
14961
      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
14962
    }
14963
  }
14964
}
14965
14966
/*
14967
** Return the size of an outstanding allocation, in bytes.  The
14968
** size returned omits the 8-byte header overhead.  This only
14969
** works for chunks that are currently checked out.
14970
*/
14971
static int memsys3Size(void *p){
14972
  Mem3Block *pBlock;
14973
  if( p==0 ) return 0;
14974
  pBlock = (Mem3Block*)p;
14975
  assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
14976
  return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
14977
}
14978
14979
/*
14980
** Round up a request size to the next valid allocation size.
14981
*/
14982
static int memsys3Roundup(int n){
14983
  if( n<=12 ){
14984
    return 12;
14985
  }else{
14986
    return ((n+11)&~7) - 4;
14987
  }
14988
}
14989
14990
/*
14991
** Allocate nBytes of memory.
14992
*/
14993
static void *memsys3Malloc(int nBytes){
14994
  sqlite3_int64 *p;
14995
  assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
14996
  memsys3Enter();
14997
  p = memsys3MallocUnsafe(nBytes);
14998
  memsys3Leave();
14999
  return (void*)p; 
15000
}
15001
15002
/*
15003
** Free memory.
15004
*/
15005
void memsys3Free(void *pPrior){
15006
  assert( pPrior );
15007
  memsys3Enter();
15008
  memsys3FreeUnsafe(pPrior);
15009
  memsys3Leave();
15010
}
15011
15012
/*
15013
** Change the size of an existing memory allocation
15014
*/
15015
void *memsys3Realloc(void *pPrior, int nBytes){
15016
  int nOld;
15017
  void *p;
15018
  if( pPrior==0 ){
15019
    return sqlite3_malloc(nBytes);
15020
  }
15021
  if( nBytes<=0 ){
15022
    sqlite3_free(pPrior);
15023
    return 0;
15024
  }
15025
  nOld = memsys3Size(pPrior);
15026
  if( nBytes<=nOld && nBytes>=nOld-128 ){
15027
    return pPrior;
15028
  }
15029
  memsys3Enter();
15030
  p = memsys3MallocUnsafe(nBytes);
15031
  if( p ){
15032
    if( nOld<nBytes ){
15033
      memcpy(p, pPrior, nOld);
15034
    }else{
15035
      memcpy(p, pPrior, nBytes);
15036
    }
15037
    memsys3FreeUnsafe(pPrior);
15038
  }
15039
  memsys3Leave();
15040
  return p;
15041
}
15042
15043
/*
15044
** Initialize this module.
15045
*/
15046
static int memsys3Init(void *NotUsed){
15047
  UNUSED_PARAMETER(NotUsed);
15048
  if( !sqlite3GlobalConfig.pHeap ){
15049
    return SQLITE_ERROR;
15050
  }
15051
15052
  /* Store a pointer to the memory block in global structure mem3. */
15053
  assert( sizeof(Mem3Block)==8 );
15054
  mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
15055
  mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
15056
15057
  /* Initialize the master block. */
15058
  mem3.szMaster = mem3.nPool;
15059
  mem3.mnMaster = mem3.szMaster;
15060
  mem3.iMaster = 1;
15061
  mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
15062
  mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
15063
  mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
15064
15065
  return SQLITE_OK;
15066
}
15067
15068
/*
15069
** Deinitialize this module.
15070
*/
15071
static void memsys3Shutdown(void *NotUsed){
15072
  UNUSED_PARAMETER(NotUsed);
15073
  mem3.mutex = 0;
15074
  return;
15075
}
15076
15077
15078
15079
/*
15080
** Open the file indicated and write a log of all unfreed memory 
15081
** allocations into that log.
15082
*/
15083
SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
15084
#ifdef SQLITE_DEBUG
15085
  FILE *out;
15086
  u32 i, j;
15087
  u32 size;
15088
  if( zFilename==0 || zFilename[0]==0 ){
15089
    out = stdout;
15090
  }else{
15091
    out = fopen(zFilename, "w");
15092
    if( out==0 ){
15093
      fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
15094
                      zFilename);
15095
      return;
15096
    }
15097
  }
15098
  memsys3Enter();
15099
  fprintf(out, "CHUNKS:\n");
15100
  for(i=1; i<=mem3.nPool; i+=size/4){
15101
    size = mem3.aPool[i-1].u.hdr.size4x;
15102
    if( size/4<=1 ){
15103
      fprintf(out, "%p size error\n", &mem3.aPool[i]);
15104
      assert( 0 );
15105
      break;
15106
    }
15107
    if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
15108
      fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
15109
      assert( 0 );
15110
      break;
15111
    }
15112
    if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
15113
      fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
15114
      assert( 0 );
15115
      break;
15116
    }
15117
    if( size&1 ){
15118
      fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
15119
    }else{
15120
      fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
15121
                  i==mem3.iMaster ? " **master**" : "");
15122
    }
15123
  }
15124
  for(i=0; i<MX_SMALL-1; i++){
15125
    if( mem3.aiSmall[i]==0 ) continue;
15126
    fprintf(out, "small(%2d):", i);
15127
    for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
15128
      fprintf(out, " %p(%d)", &mem3.aPool[j],
15129
              (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
15130
    }
15131
    fprintf(out, "\n"); 
15132
  }
15133
  for(i=0; i<N_HASH; i++){
15134
    if( mem3.aiHash[i]==0 ) continue;
15135
    fprintf(out, "hash(%2d):", i);
15136
    for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
15137
      fprintf(out, " %p(%d)", &mem3.aPool[j],
15138
              (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
15139
    }
15140
    fprintf(out, "\n"); 
15141
  }
15142
  fprintf(out, "master=%d\n", mem3.iMaster);
15143
  fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
15144
  fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
15145
  sqlite3_mutex_leave(mem3.mutex);
15146
  if( out==stdout ){
15147
    fflush(stdout);
15148
  }else{
15149
    fclose(out);
15150
  }
15151
#else
15152
  UNUSED_PARAMETER(zFilename);
15153
#endif
15154
}
15155
15156
/*
15157
** This routine is the only routine in this file with external 
15158
** linkage.
15159
**
15160
** Populate the low-level memory allocation function pointers in
15161
** sqlite3GlobalConfig.m with pointers to the routines in this file. The
15162
** arguments specify the block of memory to manage.
15163
**
15164
** This routine is only called by sqlite3_config(), and therefore
15165
** is not required to be threadsafe (it is not).
15166
*/
15167
SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
15168
  static const sqlite3_mem_methods mempoolMethods = {
15169
     memsys3Malloc,
15170
     memsys3Free,
15171
     memsys3Realloc,
15172
     memsys3Size,
15173
     memsys3Roundup,
15174
     memsys3Init,
15175
     memsys3Shutdown,
15176
     0
15177
  };
15178
  return &mempoolMethods;
15179
}
15180
15181
#endif /* SQLITE_ENABLE_MEMSYS3 */
15182
15183
/************** End of mem3.c ************************************************/
15184
/************** Begin file mem5.c ********************************************/
15185
/*
15186
** 2007 October 14
15187
**
15188
** The author disclaims copyright to this source code.  In place of
15189
** a legal notice, here is a blessing:
15190
**
15191
**    May you do good and not evil.
15192
**    May you find forgiveness for yourself and forgive others.
15193
**    May you share freely, never taking more than you give.
15194
**
15195
*************************************************************************
15196
** This file contains the C functions that implement a memory
15197
** allocation subsystem for use by SQLite. 
15198
**
15199
** This version of the memory allocation subsystem omits all
15200
** use of malloc(). The application gives SQLite a block of memory
15201
** before calling sqlite3_initialize() from which allocations
15202
** are made and returned by the xMalloc() and xRealloc() 
15203
** implementations. Once sqlite3_initialize() has been called,
15204
** the amount of memory available to SQLite is fixed and cannot
15205
** be changed.
15206
**
15207
** This version of the memory allocation subsystem is included
15208
** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
15209
**
15210
** This memory allocator uses the following algorithm:
15211
**
15212
**   1.  All memory allocations sizes are rounded up to a power of 2.
15213
**
15214
**   2.  If two adjacent free blocks are the halves of a larger block,
15215
**       then the two blocks are coalesed into the single larger block.
15216
**
15217
**   3.  New memory is allocated from the first available free block.
15218
**
15219
** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
15220
** Concerning Dynamic Storage Allocation". Journal of the Association for
15221
** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
15222
** 
15223
** Let n be the size of the largest allocation divided by the minimum
15224
** allocation size (after rounding all sizes up to a power of 2.)  Let M
15225
** be the maximum amount of memory ever outstanding at one time.  Let
15226
** N be the total amount of memory available for allocation.  Robson
15227
** proved that this memory allocator will never breakdown due to 
15228
** fragmentation as long as the following constraint holds:
15229
**
15230
**      N >=  M*(1 + log2(n)/2) - n + 1
15231
**
15232
** The sqlite3_status() logic tracks the maximum values of n and M so
15233
** that an application can, at any time, verify this constraint.
15234
*/
15235
15236
/*
15237
** This version of the memory allocator is used only when 
15238
** SQLITE_ENABLE_MEMSYS5 is defined.
15239
*/
15240
#ifdef SQLITE_ENABLE_MEMSYS5
15241
15242
/*
15243
** A minimum allocation is an instance of the following structure.
15244
** Larger allocations are an array of these structures where the
15245
** size of the array is a power of 2.
15246
**
15247
** The size of this object must be a power of two.  That fact is
15248
** verified in memsys5Init().
15249
*/
15250
typedef struct Mem5Link Mem5Link;
15251
struct Mem5Link {
15252
  int next;       /* Index of next free chunk */
15253
  int prev;       /* Index of previous free chunk */
15254
};
15255
15256
/*
15257
** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
15258
** mem5.szAtom is always at least 8 and 32-bit integers are used,
15259
** it is not actually possible to reach this limit.
15260
*/
15261
#define LOGMAX 30
15262
15263
/*
15264
** Masks used for mem5.aCtrl[] elements.
15265
*/
15266
#define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
15267
#define CTRL_FREE     0x20    /* True if not checked out */
15268
15269
/*
15270
** All of the static variables used by this module are collected
15271
** into a single structure named "mem5".  This is to keep the
15272
** static variables organized and to reduce namespace pollution
15273
** when this module is combined with other in the amalgamation.
15274
*/
15275
static SQLITE_WSD struct Mem5Global {
15276
  /*
15277
  ** Memory available for allocation
15278
  */
15279
  int szAtom;      /* Smallest possible allocation in bytes */
15280
  int nBlock;      /* Number of szAtom sized blocks in zPool */
15281
  u8 *zPool;       /* Memory available to be allocated */
15282
  
15283
  /*
15284
  ** Mutex to control access to the memory allocation subsystem.
15285
  */
15286
  sqlite3_mutex *mutex;
15287
15288
  /*
15289
  ** Performance statistics
15290
  */
15291
  u64 nAlloc;         /* Total number of calls to malloc */
15292
  u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
15293
  u64 totalExcess;    /* Total internal fragmentation */
15294
  u32 currentOut;     /* Current checkout, including internal fragmentation */
15295
  u32 currentCount;   /* Current number of distinct checkouts */
15296
  u32 maxOut;         /* Maximum instantaneous currentOut */
15297
  u32 maxCount;       /* Maximum instantaneous currentCount */
15298
  u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
15299
  
15300
  /*
15301
  ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
15302
  ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
15303
  ** and so forth.
15304
  */
15305
  int aiFreelist[LOGMAX+1];
15306
15307
  /*
15308
  ** Space for tracking which blocks are checked out and the size
15309
  ** of each block.  One byte per block.
15310
  */
15311
  u8 *aCtrl;
15312
15313
} mem5 = { 0 };
15314
15315
/*
15316
** Access the static variable through a macro for SQLITE_OMIT_WSD
15317
*/
15318
#define mem5 GLOBAL(struct Mem5Global, mem5)
15319
15320
/*
15321
** Assuming mem5.zPool is divided up into an array of Mem5Link
15322
** structures, return a pointer to the idx-th such lik.
15323
*/
15324
#define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
15325
15326
/*
15327
** Unlink the chunk at mem5.aPool[i] from list it is currently
15328
** on.  It should be found on mem5.aiFreelist[iLogsize].
15329
*/
15330
static void memsys5Unlink(int i, int iLogsize){
15331
  int next, prev;
15332
  assert( i>=0 && i<mem5.nBlock );
15333
  assert( iLogsize>=0 && iLogsize<=LOGMAX );
15334
  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
15335
15336
  next = MEM5LINK(i)->next;
15337
  prev = MEM5LINK(i)->prev;
15338
  if( prev<0 ){
15339
    mem5.aiFreelist[iLogsize] = next;
15340
  }else{
15341
    MEM5LINK(prev)->next = next;
15342
  }
15343
  if( next>=0 ){
15344
    MEM5LINK(next)->prev = prev;
15345
  }
15346
}
15347
15348
/*
15349
** Link the chunk at mem5.aPool[i] so that is on the iLogsize
15350
** free list.
15351
*/
15352
static void memsys5Link(int i, int iLogsize){
15353
  int x;
15354
  assert( sqlite3_mutex_held(mem5.mutex) );
15355
  assert( i>=0 && i<mem5.nBlock );
15356
  assert( iLogsize>=0 && iLogsize<=LOGMAX );
15357
  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
15358
15359
  x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
15360
  MEM5LINK(i)->prev = -1;
15361
  if( x>=0 ){
15362
    assert( x<mem5.nBlock );
15363
    MEM5LINK(x)->prev = i;
15364
  }
15365
  mem5.aiFreelist[iLogsize] = i;
15366
}
15367
15368
/*
15369
** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
15370
** will already be held (obtained by code in malloc.c) if
15371
** sqlite3GlobalConfig.bMemStat is true.
15372
*/
15373
static void memsys5Enter(void){
15374
  sqlite3_mutex_enter(mem5.mutex);
15375
}
15376
static void memsys5Leave(void){
15377
  sqlite3_mutex_leave(mem5.mutex);
15378
}
15379
15380
/*
15381
** Return the size of an outstanding allocation, in bytes.  The
15382
** size returned omits the 8-byte header overhead.  This only
15383
** works for chunks that are currently checked out.
15384
*/
15385
static int memsys5Size(void *p){
15386
  int iSize = 0;
15387
  if( p ){
15388
    int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
15389
    assert( i>=0 && i<mem5.nBlock );
15390
    iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
15391
  }
15392
  return iSize;
15393
}
15394
15395
/*
15396
** Find the first entry on the freelist iLogsize.  Unlink that
15397
** entry and return its index. 
15398
*/
15399
static int memsys5UnlinkFirst(int iLogsize){
15400
  int i;
15401
  int iFirst;
15402
15403
  assert( iLogsize>=0 && iLogsize<=LOGMAX );
15404
  i = iFirst = mem5.aiFreelist[iLogsize];
15405
  assert( iFirst>=0 );
15406
  while( i>0 ){
15407
    if( i<iFirst ) iFirst = i;
15408
    i = MEM5LINK(i)->next;
15409
  }
15410
  memsys5Unlink(iFirst, iLogsize);
15411
  return iFirst;
15412
}
15413
15414
/*
15415
** Return a block of memory of at least nBytes in size.
15416
** Return NULL if unable.  Return NULL if nBytes==0.
15417
**
15418
** The caller guarantees that nByte positive.
15419
**
15420
** The caller has obtained a mutex prior to invoking this
15421
** routine so there is never any chance that two or more
15422
** threads can be in this routine at the same time.
15423
*/
15424
static void *memsys5MallocUnsafe(int nByte){
15425
  int i;           /* Index of a mem5.aPool[] slot */
15426
  int iBin;        /* Index into mem5.aiFreelist[] */
15427
  int iFullSz;     /* Size of allocation rounded up to power of 2 */
15428
  int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
15429
15430
  /* nByte must be a positive */
15431
  assert( nByte>0 );
15432
15433
  /* Keep track of the maximum allocation request.  Even unfulfilled
15434
  ** requests are counted */
15435
  if( (u32)nByte>mem5.maxRequest ){
15436
    mem5.maxRequest = nByte;
15437
  }
15438
15439
  /* Abort if the requested allocation size is larger than the largest
15440
  ** power of two that we can represent using 32-bit signed integers.
15441
  */
15442
  if( nByte > 0x40000000 ){
15443
    return 0;
15444
  }
15445
15446
  /* Round nByte up to the next valid power of two */
15447
  for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
15448
15449
  /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
15450
  ** block.  If not, then split a block of the next larger power of
15451
  ** two in order to create a new free block of size iLogsize.
15452
  */
15453
  for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
15454
  if( iBin>LOGMAX ){
15455
    testcase( sqlite3GlobalConfig.xLog!=0 );
15456
    sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
15457
    return 0;
15458
  }
15459
  i = memsys5UnlinkFirst(iBin);
15460
  while( iBin>iLogsize ){
15461
    int newSize;
15462
15463
    iBin--;
15464
    newSize = 1 << iBin;
15465
    mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
15466
    memsys5Link(i+newSize, iBin);
15467
  }
15468
  mem5.aCtrl[i] = iLogsize;
15469
15470
  /* Update allocator performance statistics. */
15471
  mem5.nAlloc++;
15472
  mem5.totalAlloc += iFullSz;
15473
  mem5.totalExcess += iFullSz - nByte;
15474
  mem5.currentCount++;
15475
  mem5.currentOut += iFullSz;
15476
  if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
15477
  if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
15478
15479
  /* Return a pointer to the allocated memory. */
15480
  return (void*)&mem5.zPool[i*mem5.szAtom];
15481
}
15482
15483
/*
15484
** Free an outstanding memory allocation.
15485
*/
15486
static void memsys5FreeUnsafe(void *pOld){
15487
  u32 size, iLogsize;
15488
  int iBlock;
15489
15490
  /* Set iBlock to the index of the block pointed to by pOld in 
15491
  ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
15492
  */
15493
  iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
15494
15495
  /* Check that the pointer pOld points to a valid, non-free block. */
15496
  assert( iBlock>=0 && iBlock<mem5.nBlock );
15497
  assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
15498
  assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
15499
15500
  iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
15501
  size = 1<<iLogsize;
15502
  assert( iBlock+size-1<(u32)mem5.nBlock );
15503
15504
  mem5.aCtrl[iBlock] |= CTRL_FREE;
15505
  mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
15506
  assert( mem5.currentCount>0 );
15507
  assert( mem5.currentOut>=(size*mem5.szAtom) );
15508
  mem5.currentCount--;
15509
  mem5.currentOut -= size*mem5.szAtom;
15510
  assert( mem5.currentOut>0 || mem5.currentCount==0 );
15511
  assert( mem5.currentCount>0 || mem5.currentOut==0 );
15512
15513
  mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
15514
  while( ALWAYS(iLogsize<LOGMAX) ){
15515
    int iBuddy;
15516
    if( (iBlock>>iLogsize) & 1 ){
15517
      iBuddy = iBlock - size;
15518
    }else{
15519
      iBuddy = iBlock + size;
15520
    }
15521
    assert( iBuddy>=0 );
15522
    if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
15523
    if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
15524
    memsys5Unlink(iBuddy, iLogsize);
15525
    iLogsize++;
15526
    if( iBuddy<iBlock ){
15527
      mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
15528
      mem5.aCtrl[iBlock] = 0;
15529
      iBlock = iBuddy;
15530
    }else{
15531
      mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
15532
      mem5.aCtrl[iBuddy] = 0;
15533
    }
15534
    size *= 2;
15535
  }
15536
  memsys5Link(iBlock, iLogsize);
15537
}
15538
15539
/*
15540
** Allocate nBytes of memory
15541
*/
15542
static void *memsys5Malloc(int nBytes){
15543
  sqlite3_int64 *p = 0;
15544
  if( nBytes>0 ){
15545
    memsys5Enter();
15546
    p = memsys5MallocUnsafe(nBytes);
15547
    memsys5Leave();
15548
  }
15549
  return (void*)p; 
15550
}
15551
15552
/*
15553
** Free memory.
15554
**
15555
** The outer layer memory allocator prevents this routine from
15556
** being called with pPrior==0.
15557
*/
15558
static void memsys5Free(void *pPrior){
15559
  assert( pPrior!=0 );
15560
  memsys5Enter();
15561
  memsys5FreeUnsafe(pPrior);
15562
  memsys5Leave();  
15563
}
15564
15565
/*
15566
** Change the size of an existing memory allocation.
15567
**
15568
** The outer layer memory allocator prevents this routine from
15569
** being called with pPrior==0.  
15570
**
15571
** nBytes is always a value obtained from a prior call to
15572
** memsys5Round().  Hence nBytes is always a non-negative power
15573
** of two.  If nBytes==0 that means that an oversize allocation
15574
** (an allocation larger than 0x40000000) was requested and this
15575
** routine should return 0 without freeing pPrior.
15576
*/
15577
static void *memsys5Realloc(void *pPrior, int nBytes){
15578
  int nOld;
15579
  void *p;
15580
  assert( pPrior!=0 );
15581
  assert( (nBytes&(nBytes-1))==0 );
15582
  assert( nBytes>=0 );
15583
  if( nBytes==0 ){
15584
    return 0;
15585
  }
15586
  nOld = memsys5Size(pPrior);
15587
  if( nBytes<=nOld ){
15588
    return pPrior;
15589
  }
15590
  memsys5Enter();
15591
  p = memsys5MallocUnsafe(nBytes);
15592
  if( p ){
15593
    memcpy(p, pPrior, nOld);
15594
    memsys5FreeUnsafe(pPrior);
15595
  }
15596
  memsys5Leave();
15597
  return p;
15598
}
15599
15600
/*
15601
** Round up a request size to the next valid allocation size.  If
15602
** the allocation is too large to be handled by this allocation system,
15603
** return 0.
15604
**
15605
** All allocations must be a power of two and must be expressed by a
15606
** 32-bit signed integer.  Hence the largest allocation is 0x40000000
15607
** or 1073741824 bytes.
15608
*/
15609
static int memsys5Roundup(int n){
15610
  int iFullSz;
15611
  if( n > 0x40000000 ) return 0;
15612
  for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
15613
  return iFullSz;
15614
}
15615
15616
/*
15617
** Return the ceiling of the logarithm base 2 of iValue.
15618
**
15619
** Examples:   memsys5Log(1) -> 0
15620
**             memsys5Log(2) -> 1
15621
**             memsys5Log(4) -> 2
15622
**             memsys5Log(5) -> 3
15623
**             memsys5Log(8) -> 3
15624
**             memsys5Log(9) -> 4
15625
*/
15626
static int memsys5Log(int iValue){
15627
  int iLog;
15628
  for(iLog=0; (1<<iLog)<iValue; iLog++);
15629
  return iLog;
15630
}
15631
15632
/*
15633
** Initialize the memory allocator.
15634
**
15635
** This routine is not threadsafe.  The caller must be holding a mutex
15636
** to prevent multiple threads from entering at the same time.
15637
*/
15638
static int memsys5Init(void *NotUsed){
15639
  int ii;            /* Loop counter */
15640
  int nByte;         /* Number of bytes of memory available to this allocator */
15641
  u8 *zByte;         /* Memory usable by this allocator */
15642
  int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
15643
  int iOffset;       /* An offset into mem5.aCtrl[] */
15644
15645
  UNUSED_PARAMETER(NotUsed);
15646
15647
  /* For the purposes of this routine, disable the mutex */
15648
  mem5.mutex = 0;
15649
15650
  /* The size of a Mem5Link object must be a power of two.  Verify that
15651
  ** this is case.
15652
  */
15653
  assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
15654
15655
  nByte = sqlite3GlobalConfig.nHeap;
15656
  zByte = (u8*)sqlite3GlobalConfig.pHeap;
15657
  assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
15658
15659
  nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
15660
  mem5.szAtom = (1<<nMinLog);
15661
  while( (int)sizeof(Mem5Link)>mem5.szAtom ){
15662
    mem5.szAtom = mem5.szAtom << 1;
15663
  }
15664
15665
  mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
15666
  mem5.zPool = zByte;
15667
  mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
15668
15669
  for(ii=0; ii<=LOGMAX; ii++){
15670
    mem5.aiFreelist[ii] = -1;
15671
  }
15672
15673
  iOffset = 0;
15674
  for(ii=LOGMAX; ii>=0; ii--){
15675
    int nAlloc = (1<<ii);
15676
    if( (iOffset+nAlloc)<=mem5.nBlock ){
15677
      mem5.aCtrl[iOffset] = ii | CTRL_FREE;
15678
      memsys5Link(iOffset, ii);
15679
      iOffset += nAlloc;
15680
    }
15681
    assert((iOffset+nAlloc)>mem5.nBlock);
15682
  }
15683
15684
  /* If a mutex is required for normal operation, allocate one */
15685
  if( sqlite3GlobalConfig.bMemstat==0 ){
15686
    mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
15687
  }
15688
15689
  return SQLITE_OK;
15690
}
15691
15692
/*
15693
** Deinitialize this module.
15694
*/
15695
static void memsys5Shutdown(void *NotUsed){
15696
  UNUSED_PARAMETER(NotUsed);
15697
  mem5.mutex = 0;
15698
  return;
15699
}
15700
15701
#ifdef SQLITE_TEST
15702
/*
15703
** Open the file indicated and write a log of all unfreed memory 
15704
** allocations into that log.
15705
*/
15706
SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
15707
  FILE *out;
15708
  int i, j, n;
15709
  int nMinLog;
15710
15711
  if( zFilename==0 || zFilename[0]==0 ){
15712
    out = stdout;
15713
  }else{
15714
    out = fopen(zFilename, "w");
15715
    if( out==0 ){
15716
      fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
15717
                      zFilename);
15718
      return;
15719
    }
15720
  }
15721
  memsys5Enter();
15722
  nMinLog = memsys5Log(mem5.szAtom);
15723
  for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
15724
    for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
15725
    fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
15726
  }
15727
  fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
15728
  fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
15729
  fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
15730
  fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
15731
  fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
15732
  fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
15733
  fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
15734
  fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
15735
  memsys5Leave();
15736
  if( out==stdout ){
15737
    fflush(stdout);
15738
  }else{
15739
    fclose(out);
15740
  }
15741
}
15742
#endif
15743
15744
/*
15745
** This routine is the only routine in this file with external 
15746
** linkage. It returns a pointer to a static sqlite3_mem_methods
15747
** struct populated with the memsys5 methods.
15748
*/
15749
SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
15750
  static const sqlite3_mem_methods memsys5Methods = {
15751
     memsys5Malloc,
15752
     memsys5Free,
15753
     memsys5Realloc,
15754
     memsys5Size,
15755
     memsys5Roundup,
15756
     memsys5Init,
15757
     memsys5Shutdown,
15758
     0
15759
  };
15760
  return &memsys5Methods;
15761
}
15762
15763
#endif /* SQLITE_ENABLE_MEMSYS5 */
15764
15765
/************** End of mem5.c ************************************************/
15766
/************** Begin file mutex.c *******************************************/
15767
/*
15768
** 2007 August 14
15769
**
15770
** The author disclaims copyright to this source code.  In place of
15771
** a legal notice, here is a blessing:
15772
**
15773
**    May you do good and not evil.
15774
**    May you find forgiveness for yourself and forgive others.
15775
**    May you share freely, never taking more than you give.
15776
**
15777
*************************************************************************
15778
** This file contains the C functions that implement mutexes.
15779
**
15780
** This file contains code that is common across all mutex implementations.
15781
*/
15782
15783
#if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
15784
/*
15785
** For debugging purposes, record when the mutex subsystem is initialized
15786
** and uninitialized so that we can assert() if there is an attempt to
15787
** allocate a mutex while the system is uninitialized.
15788
*/
15789
static SQLITE_WSD int mutexIsInit = 0;
15790
#endif /* SQLITE_DEBUG */
15791
15792
15793
#ifndef SQLITE_MUTEX_OMIT
15794
/*
15795
** Initialize the mutex system.
15796
*/
15797
SQLITE_PRIVATE int sqlite3MutexInit(void){ 
15798
  int rc = SQLITE_OK;
15799
  if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
15800
    /* If the xMutexAlloc method has not been set, then the user did not
15801
    ** install a mutex implementation via sqlite3_config() prior to 
15802
    ** sqlite3_initialize() being called. This block copies pointers to
15803
    ** the default implementation into the sqlite3GlobalConfig structure.
15804
    */
15805
    sqlite3_mutex_methods const *pFrom;
15806
    sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
15807
15808
    if( sqlite3GlobalConfig.bCoreMutex ){
15809
      pFrom = sqlite3DefaultMutex();
15810
    }else{
15811
      pFrom = sqlite3NoopMutex();
15812
    }
15813
    memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
15814
    memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
15815
           sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
15816
    pTo->xMutexAlloc = pFrom->xMutexAlloc;
15817
  }
15818
  rc = sqlite3GlobalConfig.mutex.xMutexInit();
15819
15820
#ifdef SQLITE_DEBUG
15821
  GLOBAL(int, mutexIsInit) = 1;
15822
#endif
15823
15824
  return rc;
15825
}
15826
15827
/*
15828
** Shutdown the mutex system. This call frees resources allocated by
15829
** sqlite3MutexInit().
15830
*/
15831
SQLITE_PRIVATE int sqlite3MutexEnd(void){
15832
  int rc = SQLITE_OK;
15833
  if( sqlite3GlobalConfig.mutex.xMutexEnd ){
15834
    rc = sqlite3GlobalConfig.mutex.xMutexEnd();
15835
  }
15836
15837
#ifdef SQLITE_DEBUG
15838
  GLOBAL(int, mutexIsInit) = 0;
15839
#endif
15840
15841
  return rc;
15842
}
15843
15844
/*
15845
** Retrieve a pointer to a static mutex or allocate a new dynamic one.
15846
*/
15847
SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
15848
#ifndef SQLITE_OMIT_AUTOINIT
15849
  if( sqlite3_initialize() ) return 0;
15850
#endif
15851
  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
15852
}
15853
15854
SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
15855
  if( !sqlite3GlobalConfig.bCoreMutex ){
15856
    return 0;
15857
  }
15858
  assert( GLOBAL(int, mutexIsInit) );
15859
  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
15860
}
15861
15862
/*
15863
** Free a dynamic mutex.
15864
*/
15865
SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
15866
  if( p ){
15867
    sqlite3GlobalConfig.mutex.xMutexFree(p);
15868
  }
15869
}
15870
15871
/*
15872
** Obtain the mutex p. If some other thread already has the mutex, block
15873
** until it can be obtained.
15874
*/
15875
SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
15876
  if( p ){
15877
    sqlite3GlobalConfig.mutex.xMutexEnter(p);
15878
  }
15879
}
15880
15881
/*
15882
** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
15883
** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
15884
*/
15885
SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
15886
  int rc = SQLITE_OK;
15887
  if( p ){
15888
    return sqlite3GlobalConfig.mutex.xMutexTry(p);
15889
  }
15890
  return rc;
15891
}
15892
15893
/*
15894
** The sqlite3_mutex_leave() routine exits a mutex that was previously
15895
** entered by the same thread.  The behavior is undefined if the mutex 
15896
** is not currently entered. If a NULL pointer is passed as an argument
15897
** this function is a no-op.
15898
*/
15899
SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
15900
  if( p ){
15901
    sqlite3GlobalConfig.mutex.xMutexLeave(p);
15902
  }
15903
}
15904
15905
#ifndef NDEBUG
15906
/*
15907
** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15908
** intended for use inside assert() statements.
15909
*/
15910
SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
15911
  return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
15912
}
15913
SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
15914
  return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
15915
}
15916
#endif
15917
15918
#endif /* SQLITE_MUTEX_OMIT */
15919
15920
/************** End of mutex.c ***********************************************/
15921
/************** Begin file mutex_noop.c **************************************/
15922
/*
15923
** 2008 October 07
15924
**
15925
** The author disclaims copyright to this source code.  In place of
15926
** a legal notice, here is a blessing:
15927
**
15928
**    May you do good and not evil.
15929
**    May you find forgiveness for yourself and forgive others.
15930
**    May you share freely, never taking more than you give.
15931
**
15932
*************************************************************************
15933
** This file contains the C functions that implement mutexes.
15934
**
15935
** This implementation in this file does not provide any mutual
15936
** exclusion and is thus suitable for use only in applications
15937
** that use SQLite in a single thread.  The routines defined
15938
** here are place-holders.  Applications can substitute working
15939
** mutex routines at start-time using the
15940
**
15941
**     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
15942
**
15943
** interface.
15944
**
15945
** If compiled with SQLITE_DEBUG, then additional logic is inserted
15946
** that does error checking on mutexes to make sure they are being
15947
** called correctly.
15948
*/
15949
15950
#ifndef SQLITE_MUTEX_OMIT
15951
15952
#ifndef SQLITE_DEBUG
15953
/*
15954
** Stub routines for all mutex methods.
15955
**
15956
** This routines provide no mutual exclusion or error checking.
15957
*/
15958
static int noopMutexInit(void){ return SQLITE_OK; }
15959
static int noopMutexEnd(void){ return SQLITE_OK; }
15960
static sqlite3_mutex *noopMutexAlloc(int id){ 
15961
  UNUSED_PARAMETER(id);
15962
  return (sqlite3_mutex*)8; 
15963
}
15964
static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
15965
static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
15966
static int noopMutexTry(sqlite3_mutex *p){
15967
  UNUSED_PARAMETER(p);
15968
  return SQLITE_OK;
15969
}
15970
static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
15971
15972
SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
15973
  static const sqlite3_mutex_methods sMutex = {
15974
    noopMutexInit,
15975
    noopMutexEnd,
15976
    noopMutexAlloc,
15977
    noopMutexFree,
15978
    noopMutexEnter,
15979
    noopMutexTry,
15980
    noopMutexLeave,
15981
15982
    0,
15983
    0,
15984
  };
15985
15986
  return &sMutex;
15987
}
15988
#endif /* !SQLITE_DEBUG */
15989
15990
#ifdef SQLITE_DEBUG
15991
/*
15992
** In this implementation, error checking is provided for testing
15993
** and debugging purposes.  The mutexes still do not provide any
15994
** mutual exclusion.
15995
*/
15996
15997
/*
15998
** The mutex object
15999
*/
16000
typedef struct sqlite3_debug_mutex {
16001
  int id;     /* The mutex type */
16002
  int cnt;    /* Number of entries without a matching leave */
16003
} sqlite3_debug_mutex;
16004
16005
/*
16006
** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
16007
** intended for use inside assert() statements.
16008
*/
16009
static int debugMutexHeld(sqlite3_mutex *pX){
16010
  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16011
  return p==0 || p->cnt>0;
16012
}
16013
static int debugMutexNotheld(sqlite3_mutex *pX){
16014
  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16015
  return p==0 || p->cnt==0;
16016
}
16017
16018
/*
16019
** Initialize and deinitialize the mutex subsystem.
16020
*/
16021
static int debugMutexInit(void){ return SQLITE_OK; }
16022
static int debugMutexEnd(void){ return SQLITE_OK; }
16023
16024
/*
16025
** The sqlite3_mutex_alloc() routine allocates a new
16026
** mutex and returns a pointer to it.  If it returns NULL
16027
** that means that a mutex could not be allocated. 
16028
*/
16029
static sqlite3_mutex *debugMutexAlloc(int id){
16030
  static sqlite3_debug_mutex aStatic[6];
16031
  sqlite3_debug_mutex *pNew = 0;
16032
  switch( id ){
16033
    case SQLITE_MUTEX_FAST:
16034
    case SQLITE_MUTEX_RECURSIVE: {
16035
      pNew = sqlite3Malloc(sizeof(*pNew));
16036
      if( pNew ){
16037
        pNew->id = id;
16038
        pNew->cnt = 0;
16039
      }
16040
      break;
16041
    }
16042
    default: {
16043
      assert( id-2 >= 0 );
16044
      assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
16045
      pNew = &aStatic[id-2];
16046
      pNew->id = id;
16047
      break;
16048
    }
16049
  }
16050
  return (sqlite3_mutex*)pNew;
16051
}
16052
16053
/*
16054
** This routine deallocates a previously allocated mutex.
16055
*/
16056
static void debugMutexFree(sqlite3_mutex *pX){
16057
  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16058
  assert( p->cnt==0 );
16059
  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
16060
  sqlite3_free(p);
16061
}
16062
16063
/*
16064
** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
16065
** to enter a mutex.  If another thread is already within the mutex,
16066
** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
16067
** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
16068
** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
16069
** be entered multiple times by the same thread.  In such cases the,
16070
** mutex must be exited an equal number of times before another thread
16071
** can enter.  If the same thread tries to enter any other kind of mutex
16072
** more than once, the behavior is undefined.
16073
*/
16074
static void debugMutexEnter(sqlite3_mutex *pX){
16075
  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16076
  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
16077
  p->cnt++;
16078
}
16079
static int debugMutexTry(sqlite3_mutex *pX){
16080
  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16081
  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
16082
  p->cnt++;
16083
  return SQLITE_OK;
16084
}
16085
16086
/*
16087
** The sqlite3_mutex_leave() routine exits a mutex that was
16088
** previously entered by the same thread.  The behavior
16089
** is undefined if the mutex is not currently entered or
16090
** is not currently allocated.  SQLite will never do either.
16091
*/
16092
static void debugMutexLeave(sqlite3_mutex *pX){
16093
  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16094
  assert( debugMutexHeld(pX) );
16095
  p->cnt--;
16096
  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
16097
}
16098
16099
SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
16100
  static const sqlite3_mutex_methods sMutex = {
16101
    debugMutexInit,
16102
    debugMutexEnd,
16103
    debugMutexAlloc,
16104
    debugMutexFree,
16105
    debugMutexEnter,
16106
    debugMutexTry,
16107
    debugMutexLeave,
16108
16109
    debugMutexHeld,
16110
    debugMutexNotheld
16111
  };
16112
16113
  return &sMutex;
16114
}
16115
#endif /* SQLITE_DEBUG */
16116
16117
/*
16118
** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
16119
** is used regardless of the run-time threadsafety setting.
16120
*/
16121
#ifdef SQLITE_MUTEX_NOOP
16122
SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
16123
  return sqlite3NoopMutex();
16124
}
16125
#endif /* SQLITE_MUTEX_NOOP */
16126
#endif /* SQLITE_MUTEX_OMIT */
16127
16128
/************** End of mutex_noop.c ******************************************/
16129
/************** Begin file mutex_os2.c ***************************************/
16130
/*
16131
** 2007 August 28
16132
**
16133
** The author disclaims copyright to this source code.  In place of
16134
** a legal notice, here is a blessing:
16135
**
16136
**    May you do good and not evil.
16137
**    May you find forgiveness for yourself and forgive others.
16138
**    May you share freely, never taking more than you give.
16139
**
16140
*************************************************************************
16141
** This file contains the C functions that implement mutexes for OS/2
16142
*/
16143
16144
/*
16145
** The code in this file is only used if SQLITE_MUTEX_OS2 is defined.
16146
** See the mutex.h file for details.
16147
*/
16148
#ifdef SQLITE_MUTEX_OS2
16149
16150
/********************** OS/2 Mutex Implementation **********************
16151
**
16152
** This implementation of mutexes is built using the OS/2 API.
16153
*/
16154
16155
/*
16156
** The mutex object
16157
** Each recursive mutex is an instance of the following structure.
16158
*/
16159
struct sqlite3_mutex {
16160
  HMTX mutex;       /* Mutex controlling the lock */
16161
  int  id;          /* Mutex type */
16162
  int  nRef;        /* Number of references */
16163
  TID  owner;       /* Thread holding this mutex */
16164
};
16165
16166
#define OS2_MUTEX_INITIALIZER   0,0,0,0
16167
16168
/*
16169
** Initialize and deinitialize the mutex subsystem.
16170
*/
16171
static int os2MutexInit(void){ return SQLITE_OK; }
16172
static int os2MutexEnd(void){ return SQLITE_OK; }
16173
16174
/*
16175
** The sqlite3_mutex_alloc() routine allocates a new
16176
** mutex and returns a pointer to it.  If it returns NULL
16177
** that means that a mutex could not be allocated. 
16178
** SQLite will unwind its stack and return an error.  The argument
16179
** to sqlite3_mutex_alloc() is one of these integer constants:
16180
**
16181
** <ul>
16182
** <li>  SQLITE_MUTEX_FAST               0
16183
** <li>  SQLITE_MUTEX_RECURSIVE          1
16184
** <li>  SQLITE_MUTEX_STATIC_MASTER      2
16185
** <li>  SQLITE_MUTEX_STATIC_MEM         3
16186
** <li>  SQLITE_MUTEX_STATIC_PRNG        4
16187
** </ul>
16188
**
16189
** The first two constants cause sqlite3_mutex_alloc() to create
16190
** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
16191
** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
16192
** The mutex implementation does not need to make a distinction
16193
** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
16194
** not want to.  But SQLite will only request a recursive mutex in
16195
** cases where it really needs one.  If a faster non-recursive mutex
16196
** implementation is available on the host platform, the mutex subsystem
16197
** might return such a mutex in response to SQLITE_MUTEX_FAST.
16198
**
16199
** The other allowed parameters to sqlite3_mutex_alloc() each return
16200
** a pointer to a static preexisting mutex.  Three static mutexes are
16201
** used by the current version of SQLite.  Future versions of SQLite
16202
** may add additional static mutexes.  Static mutexes are for internal
16203
** use by SQLite only.  Applications that use SQLite mutexes should
16204
** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
16205
** SQLITE_MUTEX_RECURSIVE.
16206
**
16207
** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
16208
** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
16209
** returns a different mutex on every call.  But for the static
16210
** mutex types, the same mutex is returned on every call that has
16211
** the same type number.
16212
*/
16213
static sqlite3_mutex *os2MutexAlloc(int iType){
16214
  sqlite3_mutex *p = NULL;
16215
  switch( iType ){
16216
    case SQLITE_MUTEX_FAST:
16217
    case SQLITE_MUTEX_RECURSIVE: {
16218
      p = sqlite3MallocZero( sizeof(*p) );
16219
      if( p ){
16220
        p->id = iType;
16221
        if( DosCreateMutexSem( 0, &p->mutex, 0, FALSE ) != NO_ERROR ){
16222
          sqlite3_free( p );
16223
          p = NULL;
16224
        }
16225
      }
16226
      break;
16227
    }
16228
    default: {
16229
      static volatile int isInit = 0;
16230
      static sqlite3_mutex staticMutexes[] = {
16231
        { OS2_MUTEX_INITIALIZER, },
16232
        { OS2_MUTEX_INITIALIZER, },
16233
        { OS2_MUTEX_INITIALIZER, },
16234
        { OS2_MUTEX_INITIALIZER, },
16235
        { OS2_MUTEX_INITIALIZER, },
16236
        { OS2_MUTEX_INITIALIZER, },
16237
      };
16238
      if ( !isInit ){
16239
        APIRET rc;
16240
        PTIB ptib;
16241
        PPIB ppib;
16242
        HMTX mutex;
16243
        char name[32];
16244
        DosGetInfoBlocks( &ptib, &ppib );
16245
        sqlite3_snprintf( sizeof(name), name, "\\SEM32\\SQLITE%04x",
16246
                          ppib->pib_ulpid );
16247
        while( !isInit ){
16248
          mutex = 0;
16249
          rc = DosCreateMutexSem( name, &mutex, 0, FALSE);
16250
          if( rc == NO_ERROR ){
16251
            unsigned int i;
16252
            if( !isInit ){
16253
              for( i = 0; i < sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++ ){
16254
                DosCreateMutexSem( 0, &staticMutexes[i].mutex, 0, FALSE );
16255
              }
16256
              isInit = 1;
16257
            }
16258
            DosCloseMutexSem( mutex );
16259
          }else if( rc == ERROR_DUPLICATE_NAME ){
16260
            DosSleep( 1 );
16261
          }else{
16262
            return p;
16263
          }
16264
        }
16265
      }
16266
      assert( iType-2 >= 0 );
16267
      assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
16268
      p = &staticMutexes[iType-2];
16269
      p->id = iType;
16270
      break;
16271
    }
16272
  }
16273
  return p;
16274
}
16275
16276
16277
/*
16278
** This routine deallocates a previously allocated mutex.
16279
** SQLite is careful to deallocate every mutex that it allocates.
16280
*/
16281
static void os2MutexFree(sqlite3_mutex *p){
16282
  if( p==0 ) return;
16283
  assert( p->nRef==0 );
16284
  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
16285
  DosCloseMutexSem( p->mutex );
16286
  sqlite3_free( p );
16287
}
16288
16289
#ifdef SQLITE_DEBUG
16290
/*
16291
** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
16292
** intended for use inside assert() statements.
16293
*/
16294
static int os2MutexHeld(sqlite3_mutex *p){
16295
  TID tid;
16296
  PID pid;
16297
  ULONG ulCount;
16298
  PTIB ptib;
16299
  if( p!=0 ) {
16300
    DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
16301
  } else {
16302
    DosGetInfoBlocks(&ptib, NULL);
16303
    tid = ptib->tib_ptib2->tib2_ultid;
16304
  }
16305
  return p==0 || (p->nRef!=0 && p->owner==tid);
16306
}
16307
static int os2MutexNotheld(sqlite3_mutex *p){
16308
  TID tid;
16309
  PID pid;
16310
  ULONG ulCount;
16311
  PTIB ptib;
16312
  if( p!= 0 ) {
16313
    DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
16314
  } else {
16315
    DosGetInfoBlocks(&ptib, NULL);
16316
    tid = ptib->tib_ptib2->tib2_ultid;
16317
  }
16318
  return p==0 || p->nRef==0 || p->owner!=tid;
16319
}
16320
#endif
16321
16322
/*
16323
** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
16324
** to enter a mutex.  If another thread is already within the mutex,
16325
** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
16326
** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
16327
** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
16328
** be entered multiple times by the same thread.  In such cases the,
16329
** mutex must be exited an equal number of times before another thread
16330
** can enter.  If the same thread tries to enter any other kind of mutex
16331
** more than once, the behavior is undefined.
16332
*/
16333
static void os2MutexEnter(sqlite3_mutex *p){
16334
  TID tid;
16335
  PID holder1;
16336
  ULONG holder2;
16337
  if( p==0 ) return;
16338
  assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
16339
  DosRequestMutexSem(p->mutex, SEM_INDEFINITE_WAIT);
16340
  DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
16341
  p->owner = tid;
16342
  p->nRef++;
16343
}
16344
static int os2MutexTry(sqlite3_mutex *p){
16345
  int rc;
16346
  TID tid;
16347
  PID holder1;
16348
  ULONG holder2;
16349
  if( p==0 ) return SQLITE_OK;
16350
  assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
16351
  if( DosRequestMutexSem(p->mutex, SEM_IMMEDIATE_RETURN) == NO_ERROR) {
16352
    DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
16353
    p->owner = tid;
16354
    p->nRef++;
16355
    rc = SQLITE_OK;
16356
  } else {
16357
    rc = SQLITE_BUSY;
16358
  }
16359
16360
  return rc;
16361
}
16362
16363
/*
16364
** The sqlite3_mutex_leave() routine exits a mutex that was
16365
** previously entered by the same thread.  The behavior
16366
** is undefined if the mutex is not currently entered or
16367
** is not currently allocated.  SQLite will never do either.
16368
*/
16369
static void os2MutexLeave(sqlite3_mutex *p){
16370
  TID tid;
16371
  PID holder1;
16372
  ULONG holder2;
16373
  if( p==0 ) return;
16374
  assert( p->nRef>0 );
16375
  DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
16376
  assert( p->owner==tid );
16377
  p->nRef--;
16378
  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
16379
  DosReleaseMutexSem(p->mutex);
16380
}
16381
16382
SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
16383
  static const sqlite3_mutex_methods sMutex = {
16384
    os2MutexInit,
16385
    os2MutexEnd,
16386
    os2MutexAlloc,
16387
    os2MutexFree,
16388
    os2MutexEnter,
16389
    os2MutexTry,
16390
    os2MutexLeave,
16391
#ifdef SQLITE_DEBUG
16392
    os2MutexHeld,
16393
    os2MutexNotheld
16394
#endif
16395
  };
16396
16397
  return &sMutex;
16398
}
16399
#endif /* SQLITE_MUTEX_OS2 */
16400
16401
/************** End of mutex_os2.c *******************************************/
16402
/************** Begin file mutex_unix.c **************************************/
16403
/*
16404
** 2007 August 28
16405
**
16406
** The author disclaims copyright to this source code.  In place of
16407
** a legal notice, here is a blessing:
16408
**
16409
**    May you do good and not evil.
16410
**    May you find forgiveness for yourself and forgive others.
16411
**    May you share freely, never taking more than you give.
16412
**
16413
*************************************************************************
16414
** This file contains the C functions that implement mutexes for pthreads
16415
*/
16416
16417
/*
16418
** The code in this file is only used if we are compiling threadsafe
16419
** under unix with pthreads.
16420
**
16421
** Note that this implementation requires a version of pthreads that
16422
** supports recursive mutexes.
16423
*/
16424
#ifdef SQLITE_MUTEX_PTHREADS
16425
16426
#include <pthread.h>
16427
16428
/*
16429
** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
16430
** are necessary under two condidtions:  (1) Debug builds and (2) using
16431
** home-grown mutexes.  Encapsulate these conditions into a single #define.
16432
*/
16433
#if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
16434
# define SQLITE_MUTEX_NREF 1
16435
#else
16436
# define SQLITE_MUTEX_NREF 0
16437
#endif
16438
16439
/*
16440
** Each recursive mutex is an instance of the following structure.
16441
*/
16442
struct sqlite3_mutex {
16443
  pthread_mutex_t mutex;     /* Mutex controlling the lock */
16444
#if SQLITE_MUTEX_NREF
16445
  int id;                    /* Mutex type */
16446
  volatile int nRef;         /* Number of entrances */
16447
  volatile pthread_t owner;  /* Thread that is within this mutex */
16448
  int trace;                 /* True to trace changes */
16449
#endif
16450
};
16451
#if SQLITE_MUTEX_NREF
16452
#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
16453
#else
16454
#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
16455
#endif
16456
16457
/*
16458
** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
16459
** intended for use only inside assert() statements.  On some platforms,
16460
** there might be race conditions that can cause these routines to
16461
** deliver incorrect results.  In particular, if pthread_equal() is
16462
** not an atomic operation, then these routines might delivery
16463
** incorrect results.  On most platforms, pthread_equal() is a 
16464
** comparison of two integers and is therefore atomic.  But we are
16465
** told that HPUX is not such a platform.  If so, then these routines
16466
** will not always work correctly on HPUX.
16467
**
16468
** On those platforms where pthread_equal() is not atomic, SQLite
16469
** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
16470
** make sure no assert() statements are evaluated and hence these
16471
** routines are never called.
16472
*/
16473
#if !defined(NDEBUG) || defined(SQLITE_DEBUG)
16474
static int pthreadMutexHeld(sqlite3_mutex *p){
16475
  return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
16476
}
16477
static int pthreadMutexNotheld(sqlite3_mutex *p){
16478
  return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
16479
}
16480
#endif
16481
16482
/*
16483
** Initialize and deinitialize the mutex subsystem.
16484
*/
16485
static int pthreadMutexInit(void){ return SQLITE_OK; }
16486
static int pthreadMutexEnd(void){ return SQLITE_OK; }
16487
16488
/*
16489
** The sqlite3_mutex_alloc() routine allocates a new
16490
** mutex and returns a pointer to it.  If it returns NULL
16491
** that means that a mutex could not be allocated.  SQLite
16492
** will unwind its stack and return an error.  The argument
16493
** to sqlite3_mutex_alloc() is one of these integer constants:
16494
**
16495
** <ul>
16496
** <li>  SQLITE_MUTEX_FAST
16497
** <li>  SQLITE_MUTEX_RECURSIVE
16498
** <li>  SQLITE_MUTEX_STATIC_MASTER
16499
** <li>  SQLITE_MUTEX_STATIC_MEM
16500
** <li>  SQLITE_MUTEX_STATIC_MEM2
16501
** <li>  SQLITE_MUTEX_STATIC_PRNG
16502
** <li>  SQLITE_MUTEX_STATIC_LRU
16503
** <li>  SQLITE_MUTEX_STATIC_LRU2
16504
** </ul>
16505
**
16506
** The first two constants cause sqlite3_mutex_alloc() to create
16507
** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
16508
** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
16509
** The mutex implementation does not need to make a distinction
16510
** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
16511
** not want to.  But SQLite will only request a recursive mutex in
16512
** cases where it really needs one.  If a faster non-recursive mutex
16513
** implementation is available on the host platform, the mutex subsystem
16514
** might return such a mutex in response to SQLITE_MUTEX_FAST.
16515
**
16516
** The other allowed parameters to sqlite3_mutex_alloc() each return
16517
** a pointer to a static preexisting mutex.  Six static mutexes are
16518
** used by the current version of SQLite.  Future versions of SQLite
16519
** may add additional static mutexes.  Static mutexes are for internal
16520
** use by SQLite only.  Applications that use SQLite mutexes should
16521
** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
16522
** SQLITE_MUTEX_RECURSIVE.
16523
**
16524
** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
16525
** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
16526
** returns a different mutex on every call.  But for the static 
16527
** mutex types, the same mutex is returned on every call that has
16528
** the same type number.
16529
*/
16530
static sqlite3_mutex *pthreadMutexAlloc(int iType){
16531
  static sqlite3_mutex staticMutexes[] = {
16532
    SQLITE3_MUTEX_INITIALIZER,
16533
    SQLITE3_MUTEX_INITIALIZER,
16534
    SQLITE3_MUTEX_INITIALIZER,
16535
    SQLITE3_MUTEX_INITIALIZER,
16536
    SQLITE3_MUTEX_INITIALIZER,
16537
    SQLITE3_MUTEX_INITIALIZER
16538
  };
16539
  sqlite3_mutex *p;
16540
  switch( iType ){
16541
    case SQLITE_MUTEX_RECURSIVE: {
16542
      p = sqlite3MallocZero( sizeof(*p) );
16543
      if( p ){
16544
#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
16545
        /* If recursive mutexes are not available, we will have to
16546
        ** build our own.  See below. */
16547
        pthread_mutex_init(&p->mutex, 0);
16548
#else
16549
        /* Use a recursive mutex if it is available */
16550
        pthread_mutexattr_t recursiveAttr;
16551
        pthread_mutexattr_init(&recursiveAttr);
16552
        pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
16553
        pthread_mutex_init(&p->mutex, &recursiveAttr);
16554
        pthread_mutexattr_destroy(&recursiveAttr);
16555
#endif
16556
#if SQLITE_MUTEX_NREF
16557
        p->id = iType;
16558
#endif
16559
      }
16560
      break;
16561
    }
16562
    case SQLITE_MUTEX_FAST: {
16563
      p = sqlite3MallocZero( sizeof(*p) );
16564
      if( p ){
16565
#if SQLITE_MUTEX_NREF
16566
        p->id = iType;
16567
#endif
16568
        pthread_mutex_init(&p->mutex, 0);
16569
      }
16570
      break;
16571
    }
16572
    default: {
16573
      assert( iType-2 >= 0 );
16574
      assert( iType-2 < ArraySize(staticMutexes) );
16575
      p = &staticMutexes[iType-2];
16576
#if SQLITE_MUTEX_NREF
16577
      p->id = iType;
16578
#endif
16579
      break;
16580
    }
16581
  }
16582
  return p;
16583
}
16584
16585
16586
/*
16587
** This routine deallocates a previously
16588
** allocated mutex.  SQLite is careful to deallocate every
16589
** mutex that it allocates.
16590
*/
16591
static void pthreadMutexFree(sqlite3_mutex *p){
16592
  assert( p->nRef==0 );
16593
  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
16594
  pthread_mutex_destroy(&p->mutex);
16595
  sqlite3_free(p);
16596
}
16597
16598
/*
16599
** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
16600
** to enter a mutex.  If another thread is already within the mutex,
16601
** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
16602
** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
16603
** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
16604
** be entered multiple times by the same thread.  In such cases the,
16605
** mutex must be exited an equal number of times before another thread
16606
** can enter.  If the same thread tries to enter any other kind of mutex
16607
** more than once, the behavior is undefined.
16608
*/
16609
static void pthreadMutexEnter(sqlite3_mutex *p){
16610
  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
16611
16612
#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
16613
  /* If recursive mutexes are not available, then we have to grow
16614
  ** our own.  This implementation assumes that pthread_equal()
16615
  ** is atomic - that it cannot be deceived into thinking self
16616
  ** and p->owner are equal if p->owner changes between two values
16617
  ** that are not equal to self while the comparison is taking place.
16618
  ** This implementation also assumes a coherent cache - that 
16619
  ** separate processes cannot read different values from the same
16620
  ** address at the same time.  If either of these two conditions
16621
  ** are not met, then the mutexes will fail and problems will result.
16622
  */
16623
  {
16624
    pthread_t self = pthread_self();
16625
    if( p->nRef>0 && pthread_equal(p->owner, self) ){
16626
      p->nRef++;
16627
    }else{
16628
      pthread_mutex_lock(&p->mutex);
16629
      assert( p->nRef==0 );
16630
      p->owner = self;
16631
      p->nRef = 1;
16632
    }
16633
  }
16634
#else
16635
  /* Use the built-in recursive mutexes if they are available.
16636
  */
16637
  pthread_mutex_lock(&p->mutex);
16638
#if SQLITE_MUTEX_NREF
16639
  assert( p->nRef>0 || p->owner==0 );
16640
  p->owner = pthread_self();
16641
  p->nRef++;
16642
#endif
16643
#endif
16644
16645
#ifdef SQLITE_DEBUG
16646
  if( p->trace ){
16647
    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
16648
  }
16649
#endif
16650
}
16651
static int pthreadMutexTry(sqlite3_mutex *p){
16652
  int rc;
16653
  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
16654
16655
#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
16656
  /* If recursive mutexes are not available, then we have to grow
16657
  ** our own.  This implementation assumes that pthread_equal()
16658
  ** is atomic - that it cannot be deceived into thinking self
16659
  ** and p->owner are equal if p->owner changes between two values
16660
  ** that are not equal to self while the comparison is taking place.
16661
  ** This implementation also assumes a coherent cache - that 
16662
  ** separate processes cannot read different values from the same
16663
  ** address at the same time.  If either of these two conditions
16664
  ** are not met, then the mutexes will fail and problems will result.
16665
  */
16666
  {
16667
    pthread_t self = pthread_self();
16668
    if( p->nRef>0 && pthread_equal(p->owner, self) ){
16669
      p->nRef++;
16670
      rc = SQLITE_OK;
16671
    }else if( pthread_mutex_trylock(&p->mutex)==0 ){
16672
      assert( p->nRef==0 );
16673
      p->owner = self;
16674
      p->nRef = 1;
16675
      rc = SQLITE_OK;
16676
    }else{
16677
      rc = SQLITE_BUSY;
16678
    }
16679
  }
16680
#else
16681
  /* Use the built-in recursive mutexes if they are available.
16682
  */
16683
  if( pthread_mutex_trylock(&p->mutex)==0 ){
16684
#if SQLITE_MUTEX_NREF
16685
    p->owner = pthread_self();
16686
    p->nRef++;
16687
#endif
16688
    rc = SQLITE_OK;
16689
  }else{
16690
    rc = SQLITE_BUSY;
16691
  }
16692
#endif
16693
16694
#ifdef SQLITE_DEBUG
16695
  if( rc==SQLITE_OK && p->trace ){
16696
    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
16697
  }
16698
#endif
16699
  return rc;
16700
}
16701
16702
/*
16703
** The sqlite3_mutex_leave() routine exits a mutex that was
16704
** previously entered by the same thread.  The behavior
16705
** is undefined if the mutex is not currently entered or
16706
** is not currently allocated.  SQLite will never do either.
16707
*/
16708
static void pthreadMutexLeave(sqlite3_mutex *p){
16709
  assert( pthreadMutexHeld(p) );
16710
#if SQLITE_MUTEX_NREF
16711
  p->nRef--;
16712
  if( p->nRef==0 ) p->owner = 0;
16713
#endif
16714
  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
16715
16716
#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
16717
  if( p->nRef==0 ){
16718
    pthread_mutex_unlock(&p->mutex);
16719
  }
16720
#else
16721
  pthread_mutex_unlock(&p->mutex);
16722
#endif
16723
16724
#ifdef SQLITE_DEBUG
16725
  if( p->trace ){
16726
    printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
16727
  }
16728
#endif
16729
}
16730
16731
SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
16732
  static const sqlite3_mutex_methods sMutex = {
16733
    pthreadMutexInit,
16734
    pthreadMutexEnd,
16735
    pthreadMutexAlloc,
16736
    pthreadMutexFree,
16737
    pthreadMutexEnter,
16738
    pthreadMutexTry,
16739
    pthreadMutexLeave,
16740
#ifdef SQLITE_DEBUG
16741
    pthreadMutexHeld,
16742
    pthreadMutexNotheld
16743
#else
16744
    0,
16745
    0
16746
#endif
16747
  };
16748
16749
  return &sMutex;
16750
}
16751
16752
#endif /* SQLITE_MUTEX_PTHREAD */
16753
16754
/************** End of mutex_unix.c ******************************************/
16755
/************** Begin file mutex_w32.c ***************************************/
16756
/*
16757
** 2007 August 14
16758
**
16759
** The author disclaims copyright to this source code.  In place of
16760
** a legal notice, here is a blessing:
16761
**
16762
**    May you do good and not evil.
16763
**    May you find forgiveness for yourself and forgive others.
16764
**    May you share freely, never taking more than you give.
16765
**
16766
*************************************************************************
16767
** This file contains the C functions that implement mutexes for win32
16768
*/
16769
16770
/*
16771
** The code in this file is only used if we are compiling multithreaded
16772
** on a win32 system.
16773
*/
16774
#ifdef SQLITE_MUTEX_W32
16775
16776
/*
16777
** Each recursive mutex is an instance of the following structure.
16778
*/
16779
struct sqlite3_mutex {
16780
  CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
16781
  int id;                    /* Mutex type */
16782
#ifdef SQLITE_DEBUG
16783
  volatile int nRef;         /* Number of enterances */
16784
  volatile DWORD owner;      /* Thread holding this mutex */
16785
  int trace;                 /* True to trace changes */
16786
#endif
16787
};
16788
#define SQLITE_W32_MUTEX_INITIALIZER { 0 }
16789
#ifdef SQLITE_DEBUG
16790
#define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }
16791
#else
16792
#define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
16793
#endif
16794
16795
/*
16796
** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
16797
** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
16798
**
16799
** Here is an interesting observation:  Win95, Win98, and WinME lack
16800
** the LockFileEx() API.  But we can still statically link against that
16801
** API as long as we don't call it win running Win95/98/ME.  A call to
16802
** this routine is used to determine if the host is Win95/98/ME or
16803
** WinNT/2K/XP so that we will know whether or not we can safely call
16804
** the LockFileEx() API.
16805
**
16806
** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
16807
** which is only available if your application was compiled with 
16808
** _WIN32_WINNT defined to a value >= 0x0400.  Currently, the only
16809
** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef 
16810
** this out as well.
16811
*/
16812
#if 0
16813
#if SQLITE_OS_WINCE
16814
# define mutexIsNT()  (1)
16815
#else
16816
  static int mutexIsNT(void){
16817
    static int osType = 0;
16818
    if( osType==0 ){
16819
      OSVERSIONINFO sInfo;
16820
      sInfo.dwOSVersionInfoSize = sizeof(sInfo);
16821
      GetVersionEx(&sInfo);
16822
      osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
16823
    }
16824
    return osType==2;
16825
  }
16826
#endif /* SQLITE_OS_WINCE */
16827
#endif
16828
16829
#ifdef SQLITE_DEBUG
16830
/*
16831
** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
16832
** intended for use only inside assert() statements.
16833
*/
16834
static int winMutexHeld(sqlite3_mutex *p){
16835
  return p->nRef!=0 && p->owner==GetCurrentThreadId();
16836
}
16837
static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
16838
  return p->nRef==0 || p->owner!=tid;
16839
}
16840
static int winMutexNotheld(sqlite3_mutex *p){
16841
  DWORD tid = GetCurrentThreadId(); 
16842
  return winMutexNotheld2(p, tid);
16843
}
16844
#endif
16845
16846
16847
/*
16848
** Initialize and deinitialize the mutex subsystem.
16849
*/
16850
static sqlite3_mutex winMutex_staticMutexes[6] = {
16851
  SQLITE3_MUTEX_INITIALIZER,
16852
  SQLITE3_MUTEX_INITIALIZER,
16853
  SQLITE3_MUTEX_INITIALIZER,
16854
  SQLITE3_MUTEX_INITIALIZER,
16855
  SQLITE3_MUTEX_INITIALIZER,
16856
  SQLITE3_MUTEX_INITIALIZER
16857
};
16858
static int winMutex_isInit = 0;
16859
/* As winMutexInit() and winMutexEnd() are called as part
16860
** of the sqlite3_initialize and sqlite3_shutdown()
16861
** processing, the "interlocked" magic is probably not
16862
** strictly necessary.
16863
*/
16864
static long winMutex_lock = 0;
16865
16866
static int winMutexInit(void){ 
16867
  /* The first to increment to 1 does actual initialization */
16868
  if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
16869
    int i;
16870
    for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
16871
      InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
16872
    }
16873
    winMutex_isInit = 1;
16874
  }else{
16875
    /* Someone else is in the process of initing the static mutexes */
16876
    while( !winMutex_isInit ){
16877
      Sleep(1);
16878
    }
16879
  }
16880
  return SQLITE_OK; 
16881
}
16882
16883
static int winMutexEnd(void){ 
16884
  /* The first to decrement to 0 does actual shutdown 
16885
  ** (which should be the last to shutdown.) */
16886
  if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
16887
    if( winMutex_isInit==1 ){
16888
      int i;
16889
      for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
16890
        DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
16891
      }
16892
      winMutex_isInit = 0;
16893
    }
16894
  }
16895
  return SQLITE_OK; 
16896
}
16897
16898
/*
16899
** The sqlite3_mutex_alloc() routine allocates a new
16900
** mutex and returns a pointer to it.  If it returns NULL
16901
** that means that a mutex could not be allocated.  SQLite
16902
** will unwind its stack and return an error.  The argument
16903
** to sqlite3_mutex_alloc() is one of these integer constants:
16904
**
16905
** <ul>
16906
** <li>  SQLITE_MUTEX_FAST
16907
** <li>  SQLITE_MUTEX_RECURSIVE
16908
** <li>  SQLITE_MUTEX_STATIC_MASTER
16909
** <li>  SQLITE_MUTEX_STATIC_MEM
16910
** <li>  SQLITE_MUTEX_STATIC_MEM2
16911
** <li>  SQLITE_MUTEX_STATIC_PRNG
16912
** <li>  SQLITE_MUTEX_STATIC_LRU
16913
** <li>  SQLITE_MUTEX_STATIC_LRU2
16914
** </ul>
16915
**
16916
** The first two constants cause sqlite3_mutex_alloc() to create
16917
** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
16918
** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
16919
** The mutex implementation does not need to make a distinction
16920
** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
16921
** not want to.  But SQLite will only request a recursive mutex in
16922
** cases where it really needs one.  If a faster non-recursive mutex
16923
** implementation is available on the host platform, the mutex subsystem
16924
** might return such a mutex in response to SQLITE_MUTEX_FAST.
16925
**
16926
** The other allowed parameters to sqlite3_mutex_alloc() each return
16927
** a pointer to a static preexisting mutex.  Six static mutexes are
16928
** used by the current version of SQLite.  Future versions of SQLite
16929
** may add additional static mutexes.  Static mutexes are for internal
16930
** use by SQLite only.  Applications that use SQLite mutexes should
16931
** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
16932
** SQLITE_MUTEX_RECURSIVE.
16933
**
16934
** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
16935
** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
16936
** returns a different mutex on every call.  But for the static 
16937
** mutex types, the same mutex is returned on every call that has
16938
** the same type number.
16939
*/
16940
static sqlite3_mutex *winMutexAlloc(int iType){
16941
  sqlite3_mutex *p;
16942
16943
  switch( iType ){
16944
    case SQLITE_MUTEX_FAST:
16945
    case SQLITE_MUTEX_RECURSIVE: {
16946
      p = sqlite3MallocZero( sizeof(*p) );
16947
      if( p ){  
16948
#ifdef SQLITE_DEBUG
16949
        p->id = iType;
16950
#endif
16951
        InitializeCriticalSection(&p->mutex);
16952
      }
16953
      break;
16954
    }
16955
    default: {
16956
      assert( winMutex_isInit==1 );
16957
      assert( iType-2 >= 0 );
16958
      assert( iType-2 < ArraySize(winMutex_staticMutexes) );
16959
      p = &winMutex_staticMutexes[iType-2];
16960
#ifdef SQLITE_DEBUG
16961
      p->id = iType;
16962
#endif
16963
      break;
16964
    }
16965
  }
16966
  return p;
16967
}
16968
16969
16970
/*
16971
** This routine deallocates a previously
16972
** allocated mutex.  SQLite is careful to deallocate every
16973
** mutex that it allocates.
16974
*/
16975
static void winMutexFree(sqlite3_mutex *p){
16976
  assert( p );
16977
  assert( p->nRef==0 && p->owner==0 );
16978
  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
16979
  DeleteCriticalSection(&p->mutex);
16980
  sqlite3_free(p);
16981
}
16982
16983
/*
16984
** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
16985
** to enter a mutex.  If another thread is already within the mutex,
16986
** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
16987
** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
16988
** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
16989
** be entered multiple times by the same thread.  In such cases the,
16990
** mutex must be exited an equal number of times before another thread
16991
** can enter.  If the same thread tries to enter any other kind of mutex
16992
** more than once, the behavior is undefined.
16993
*/
16994
static void winMutexEnter(sqlite3_mutex *p){
16995
#ifdef SQLITE_DEBUG
16996
  DWORD tid = GetCurrentThreadId(); 
16997
  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
16998
#endif
16999
  EnterCriticalSection(&p->mutex);
17000
#ifdef SQLITE_DEBUG
17001
  assert( p->nRef>0 || p->owner==0 );
17002
  p->owner = tid; 
17003
  p->nRef++;
17004
  if( p->trace ){
17005
    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17006
  }
17007
#endif
17008
}
17009
static int winMutexTry(sqlite3_mutex *p){
17010
#ifndef NDEBUG
17011
  DWORD tid = GetCurrentThreadId(); 
17012
#endif
17013
  int rc = SQLITE_BUSY;
17014
  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
17015
  /*
17016
  ** The sqlite3_mutex_try() routine is very rarely used, and when it
17017
  ** is used it is merely an optimization.  So it is OK for it to always
17018
  ** fail.  
17019
  **
17020
  ** The TryEnterCriticalSection() interface is only available on WinNT.
17021
  ** And some windows compilers complain if you try to use it without
17022
  ** first doing some #defines that prevent SQLite from building on Win98.
17023
  ** For that reason, we will omit this optimization for now.  See
17024
  ** ticket #2685.
17025
  */
17026
#if 0
17027
  if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
17028
    p->owner = tid;
17029
    p->nRef++;
17030
    rc = SQLITE_OK;
17031
  }
17032
#else
17033
  UNUSED_PARAMETER(p);
17034
#endif
17035
#ifdef SQLITE_DEBUG
17036
  if( rc==SQLITE_OK && p->trace ){
17037
    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17038
  }
17039
#endif
17040
  return rc;
17041
}
17042
17043
/*
17044
** The sqlite3_mutex_leave() routine exits a mutex that was
17045
** previously entered by the same thread.  The behavior
17046
** is undefined if the mutex is not currently entered or
17047
** is not currently allocated.  SQLite will never do either.
17048
*/
17049
static void winMutexLeave(sqlite3_mutex *p){
17050
#ifndef NDEBUG
17051
  DWORD tid = GetCurrentThreadId();
17052
  assert( p->nRef>0 );
17053
  assert( p->owner==tid );
17054
  p->nRef--;
17055
  if( p->nRef==0 ) p->owner = 0;
17056
  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
17057
#endif
17058
  LeaveCriticalSection(&p->mutex);
17059
#ifdef SQLITE_DEBUG
17060
  if( p->trace ){
17061
    printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17062
  }
17063
#endif
17064
}
17065
17066
SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
17067
  static const sqlite3_mutex_methods sMutex = {
17068
    winMutexInit,
17069
    winMutexEnd,
17070
    winMutexAlloc,
17071
    winMutexFree,
17072
    winMutexEnter,
17073
    winMutexTry,
17074
    winMutexLeave,
17075
#ifdef SQLITE_DEBUG
17076
    winMutexHeld,
17077
    winMutexNotheld
17078
#else
17079
    0,
17080
    0
17081
#endif
17082
  };
17083
17084
  return &sMutex;
17085
}
17086
#endif /* SQLITE_MUTEX_W32 */
17087
17088
/************** End of mutex_w32.c *******************************************/
17089
/************** Begin file malloc.c ******************************************/
17090
/*
17091
** 2001 September 15
17092
**
17093
** The author disclaims copyright to this source code.  In place of
17094
** a legal notice, here is a blessing:
17095
**
17096
**    May you do good and not evil.
17097
**    May you find forgiveness for yourself and forgive others.
17098
**    May you share freely, never taking more than you give.
17099
**
17100
*************************************************************************
17101
**
17102
** Memory allocation functions used throughout sqlite.
17103
*/
17104
17105
/*
17106
** This routine runs when the memory allocator sees that the
17107
** total memory allocation is about to exceed the soft heap
17108
** limit.
17109
*/
17110
static void softHeapLimitEnforcer(
17111
  void *NotUsed, 
17112
  sqlite3_int64 NotUsed2,
17113
  int allocSize
17114
){
17115
  UNUSED_PARAMETER2(NotUsed, NotUsed2);
17116
  sqlite3_release_memory(allocSize);
17117
}
17118
17119
/*
17120
** Set the soft heap-size limit for the library. Passing a zero or 
17121
** negative value indicates no limit.
17122
*/
17123
SQLITE_API void sqlite3_soft_heap_limit(int n){
17124
  sqlite3_uint64 iLimit;
17125
  int overage;
17126
  if( n<0 ){
17127
    iLimit = 0;
17128
  }else{
17129
    iLimit = n;
17130
  }
17131
#ifndef SQLITE_OMIT_AUTOINIT
17132
  sqlite3_initialize();
17133
#endif
17134
  if( iLimit>0 ){
17135
    sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, iLimit);
17136
  }else{
17137
    sqlite3MemoryAlarm(0, 0, 0);
17138
  }
17139
  overage = (int)(sqlite3_memory_used() - (i64)n);
17140
  if( overage>0 ){
17141
    sqlite3_release_memory(overage);
17142
  }
17143
}
17144
17145
/*
17146
** Attempt to release up to n bytes of non-essential memory currently
17147
** held by SQLite. An example of non-essential memory is memory used to
17148
** cache database pages that are not currently in use.
17149
*/
17150
SQLITE_API int sqlite3_release_memory(int n){
17151
#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
17152
  int nRet = 0;
17153
  nRet += sqlite3PcacheReleaseMemory(n-nRet);
17154
  return nRet;
17155
#else
17156
  UNUSED_PARAMETER(n);
17157
  return SQLITE_OK;
17158
#endif
17159
}
17160
17161
/*
17162
** State information local to the memory allocation subsystem.
17163
*/
17164
static SQLITE_WSD struct Mem0Global {
17165
  /* Number of free pages for scratch and page-cache memory */
17166
  u32 nScratchFree;
17167
  u32 nPageFree;
17168
17169
  sqlite3_mutex *mutex;         /* Mutex to serialize access */
17170
17171
  /*
17172
  ** The alarm callback and its arguments.  The mem0.mutex lock will
17173
  ** be held while the callback is running.  Recursive calls into
17174
  ** the memory subsystem are allowed, but no new callbacks will be
17175
  ** issued.
17176
  */
17177
  sqlite3_int64 alarmThreshold;
17178
  void (*alarmCallback)(void*, sqlite3_int64,int);
17179
  void *alarmArg;
17180
17181
  /*
17182
  ** Pointers to the end of sqlite3GlobalConfig.pScratch and
17183
  ** sqlite3GlobalConfig.pPage to a block of memory that records
17184
  ** which pages are available.
17185
  */
17186
  u32 *aScratchFree;
17187
  u32 *aPageFree;
17188
} mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
17189
17190
#define mem0 GLOBAL(struct Mem0Global, mem0)
17191
17192
/*
17193
** Initialize the memory allocation subsystem.
17194
*/
17195
SQLITE_PRIVATE int sqlite3MallocInit(void){
17196
  if( sqlite3GlobalConfig.m.xMalloc==0 ){
17197
    sqlite3MemSetDefault();
17198
  }
17199
  memset(&mem0, 0, sizeof(mem0));
17200
  if( sqlite3GlobalConfig.bCoreMutex ){
17201
    mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
17202
  }
17203
  if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
17204
      && sqlite3GlobalConfig.nScratch>=0 ){
17205
    int i;
17206
    sqlite3GlobalConfig.szScratch = ROUNDDOWN8(sqlite3GlobalConfig.szScratch-4);
17207
    mem0.aScratchFree = (u32*)&((char*)sqlite3GlobalConfig.pScratch)
17208
                  [sqlite3GlobalConfig.szScratch*sqlite3GlobalConfig.nScratch];
17209
    for(i=0; i<sqlite3GlobalConfig.nScratch; i++){ mem0.aScratchFree[i] = i; }
17210
    mem0.nScratchFree = sqlite3GlobalConfig.nScratch;
17211
  }else{
17212
    sqlite3GlobalConfig.pScratch = 0;
17213
    sqlite3GlobalConfig.szScratch = 0;
17214
  }
17215
  if( sqlite3GlobalConfig.pPage && sqlite3GlobalConfig.szPage>=512
17216
      && sqlite3GlobalConfig.nPage>=1 ){
17217
    int i;
17218
    int overhead;
17219
    int sz = ROUNDDOWN8(sqlite3GlobalConfig.szPage);
17220
    int n = sqlite3GlobalConfig.nPage;
17221
    overhead = (4*n + sz - 1)/sz;
17222
    sqlite3GlobalConfig.nPage -= overhead;
17223
    mem0.aPageFree = (u32*)&((char*)sqlite3GlobalConfig.pPage)
17224
                  [sqlite3GlobalConfig.szPage*sqlite3GlobalConfig.nPage];
17225
    for(i=0; i<sqlite3GlobalConfig.nPage; i++){ mem0.aPageFree[i] = i; }
17226
    mem0.nPageFree = sqlite3GlobalConfig.nPage;
17227
  }else{
17228
    sqlite3GlobalConfig.pPage = 0;
17229
    sqlite3GlobalConfig.szPage = 0;
17230
  }
17231
  return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
17232
}
17233
17234
/*
17235
** Deinitialize the memory allocation subsystem.
17236
*/
17237
SQLITE_PRIVATE void sqlite3MallocEnd(void){
17238
  if( sqlite3GlobalConfig.m.xShutdown ){
17239
    sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
17240
  }
17241
  memset(&mem0, 0, sizeof(mem0));
17242
}
17243
17244
/*
17245
** Return the amount of memory currently checked out.
17246
*/
17247
SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
17248
  int n, mx;
17249
  sqlite3_int64 res;
17250
  sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
17251
  res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
17252
  return res;
17253
}
17254
17255
/*
17256
** Return the maximum amount of memory that has ever been
17257
** checked out since either the beginning of this process
17258
** or since the most recent reset.
17259
*/
17260
SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
17261
  int n, mx;
17262
  sqlite3_int64 res;
17263
  sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
17264
  res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
17265
  return res;
17266
}
17267
17268
/*
17269
** Change the alarm callback
17270
*/
17271
SQLITE_PRIVATE int sqlite3MemoryAlarm(
17272
  void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
17273
  void *pArg,
17274
  sqlite3_int64 iThreshold
17275
){
17276
  sqlite3_mutex_enter(mem0.mutex);
17277
  mem0.alarmCallback = xCallback;
17278
  mem0.alarmArg = pArg;
17279
  mem0.alarmThreshold = iThreshold;
17280
  sqlite3_mutex_leave(mem0.mutex);
17281
  return SQLITE_OK;
17282
}
17283
17284
#ifndef SQLITE_OMIT_DEPRECATED
17285
/*
17286
** Deprecated external interface.  Internal/core SQLite code
17287
** should call sqlite3MemoryAlarm.
17288
*/
17289
SQLITE_API int sqlite3_memory_alarm(
17290
  void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
17291
  void *pArg,
17292
  sqlite3_int64 iThreshold
17293
){
17294
  return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
17295
}
17296
#endif
17297
17298
/*
17299
** Trigger the alarm 
17300
*/
17301
static void sqlite3MallocAlarm(int nByte){
17302
  void (*xCallback)(void*,sqlite3_int64,int);
17303
  sqlite3_int64 nowUsed;
17304
  void *pArg;
17305
  if( mem0.alarmCallback==0 ) return;
17306
  xCallback = mem0.alarmCallback;
17307
  nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
17308
  pArg = mem0.alarmArg;
17309
  mem0.alarmCallback = 0;
17310
  sqlite3_mutex_leave(mem0.mutex);
17311
  xCallback(pArg, nowUsed, nByte);
17312
  sqlite3_mutex_enter(mem0.mutex);
17313
  mem0.alarmCallback = xCallback;
17314
  mem0.alarmArg = pArg;
17315
}
17316
17317
/*
17318
** Do a memory allocation with statistics and alarms.  Assume the
17319
** lock is already held.
17320
*/
17321
static int mallocWithAlarm(int n, void **pp){
17322
  int nFull;
17323
  void *p;
17324
  assert( sqlite3_mutex_held(mem0.mutex) );
17325
  nFull = sqlite3GlobalConfig.m.xRoundup(n);
17326
  sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
17327
  if( mem0.alarmCallback!=0 ){
17328
    int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
17329
    if( nUsed+nFull >= mem0.alarmThreshold ){
17330
      sqlite3MallocAlarm(nFull);
17331
    }
17332
  }
17333
  p = sqlite3GlobalConfig.m.xMalloc(nFull);
17334
  if( p==0 && mem0.alarmCallback ){
17335
    sqlite3MallocAlarm(nFull);
17336
    p = sqlite3GlobalConfig.m.xMalloc(nFull);
17337
  }
17338
  if( p ){
17339
    nFull = sqlite3MallocSize(p);
17340
    sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
17341
    sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
17342
  }
17343
  *pp = p;
17344
  return nFull;
17345
}
17346
17347
/*
17348
** Allocate memory.  This routine is like sqlite3_malloc() except that it
17349
** assumes the memory subsystem has already been initialized.
17350
*/
17351
SQLITE_PRIVATE void *sqlite3Malloc(int n){
17352
  void *p;
17353
  if( n<=0 || n>=0x7fffff00 ){
17354
    /* A memory allocation of a number of bytes which is near the maximum
17355
    ** signed integer value might cause an integer overflow inside of the
17356
    ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
17357
    ** 255 bytes of overhead.  SQLite itself will never use anything near
17358
    ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
17359
    p = 0;
17360
  }else if( sqlite3GlobalConfig.bMemstat ){
17361
    sqlite3_mutex_enter(mem0.mutex);
17362
    mallocWithAlarm(n, &p);
17363
    sqlite3_mutex_leave(mem0.mutex);
17364
  }else{
17365
    p = sqlite3GlobalConfig.m.xMalloc(n);
17366
  }
17367
  return p;
17368
}
17369
17370
/*
17371
** This version of the memory allocation is for use by the application.
17372
** First make sure the memory subsystem is initialized, then do the
17373
** allocation.
17374
*/
17375
SQLITE_API void *sqlite3_malloc(int n){
17376
#ifndef SQLITE_OMIT_AUTOINIT
17377
  if( sqlite3_initialize() ) return 0;
17378
#endif
17379
  return sqlite3Malloc(n);
17380
}
17381
17382
/*
17383
** Each thread may only have a single outstanding allocation from
17384
** xScratchMalloc().  We verify this constraint in the single-threaded
17385
** case by setting scratchAllocOut to 1 when an allocation
17386
** is outstanding clearing it when the allocation is freed.
17387
*/
17388
#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
17389
static int scratchAllocOut = 0;
17390
#endif
17391
17392
17393
/*
17394
** Allocate memory that is to be used and released right away.
17395
** This routine is similar to alloca() in that it is not intended
17396
** for situations where the memory might be held long-term.  This
17397
** routine is intended to get memory to old large transient data
17398
** structures that would not normally fit on the stack of an
17399
** embedded processor.
17400
*/
17401
SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
17402
  void *p;
17403
  assert( n>0 );
17404
17405
#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
17406
  /* Verify that no more than two scratch allocation per thread
17407
  ** is outstanding at one time.  (This is only checked in the
17408
  ** single-threaded case since checking in the multi-threaded case
17409
  ** would be much more complicated.) */
17410
  assert( scratchAllocOut<=1 );
17411
#endif
17412
17413
  if( sqlite3GlobalConfig.szScratch<n ){
17414
    goto scratch_overflow;
17415
  }else{  
17416
    sqlite3_mutex_enter(mem0.mutex);
17417
    if( mem0.nScratchFree==0 ){
17418
      sqlite3_mutex_leave(mem0.mutex);
17419
      goto scratch_overflow;
17420
    }else{
17421
      int i;
17422
      i = mem0.aScratchFree[--mem0.nScratchFree];
17423
      i *= sqlite3GlobalConfig.szScratch;
17424
      sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
17425
      sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
17426
      sqlite3_mutex_leave(mem0.mutex);
17427
      p = (void*)&((char*)sqlite3GlobalConfig.pScratch)[i];
17428
      assert(  (((u8*)p - (u8*)0) & 7)==0 );
17429
    }
17430
  }
17431
#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
17432
  scratchAllocOut = p!=0;
17433
#endif
17434
17435
  return p;
17436
17437
scratch_overflow:
17438
  if( sqlite3GlobalConfig.bMemstat ){
17439
    sqlite3_mutex_enter(mem0.mutex);
17440
    sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
17441
    n = mallocWithAlarm(n, &p);
17442
    if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
17443
    sqlite3_mutex_leave(mem0.mutex);
17444
  }else{
17445
    p = sqlite3GlobalConfig.m.xMalloc(n);
17446
  }
17447
  sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
17448
#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
17449
  scratchAllocOut = p!=0;
17450
#endif
17451
  return p;    
17452
}
17453
SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
17454
  if( p ){
17455
    if( sqlite3GlobalConfig.pScratch==0
17456
           || p<sqlite3GlobalConfig.pScratch
17457
           || p>=(void*)mem0.aScratchFree ){
17458
      assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
17459
      assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
17460
      sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
17461
      if( sqlite3GlobalConfig.bMemstat ){
17462
        int iSize = sqlite3MallocSize(p);
17463
        sqlite3_mutex_enter(mem0.mutex);
17464
        sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
17465
        sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
17466
        sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
17467
        sqlite3GlobalConfig.m.xFree(p);
17468
        sqlite3_mutex_leave(mem0.mutex);
17469
      }else{
17470
        sqlite3GlobalConfig.m.xFree(p);
17471
      }
17472
    }else{
17473
      int i;
17474
      i = (int)((u8*)p - (u8*)sqlite3GlobalConfig.pScratch);
17475
      i /= sqlite3GlobalConfig.szScratch;
17476
      assert( i>=0 && i<sqlite3GlobalConfig.nScratch );
17477
      sqlite3_mutex_enter(mem0.mutex);
17478
      assert( mem0.nScratchFree<(u32)sqlite3GlobalConfig.nScratch );
17479
      mem0.aScratchFree[mem0.nScratchFree++] = i;
17480
      sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
17481
      sqlite3_mutex_leave(mem0.mutex);
17482
17483
#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
17484
    /* Verify that no more than two scratch allocation per thread
17485
    ** is outstanding at one time.  (This is only checked in the
17486
    ** single-threaded case since checking in the multi-threaded case
17487
    ** would be much more complicated.) */
17488
    assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
17489
    scratchAllocOut = 0;
17490
#endif
17491
17492
    }
17493
  }
17494
}
17495
17496
/*
17497
** TRUE if p is a lookaside memory allocation from db
17498
*/
17499
#ifndef SQLITE_OMIT_LOOKASIDE
17500
static int isLookaside(sqlite3 *db, void *p){
17501
  return p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
17502
}
17503
#else
17504
#define isLookaside(A,B) 0
17505
#endif
17506
17507
/*
17508
** Return the size of a memory allocation previously obtained from
17509
** sqlite3Malloc() or sqlite3_malloc().
17510
*/
17511
SQLITE_PRIVATE int sqlite3MallocSize(void *p){
17512
  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
17513
  assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
17514
  return sqlite3GlobalConfig.m.xSize(p);
17515
}
17516
SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
17517
  assert( db==0 || sqlite3_mutex_held(db->mutex) );
17518
  if( db && isLookaside(db, p) ){
17519
    return db->lookaside.sz;
17520
  }else{
17521
    assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
17522
    assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
17523
    assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
17524
    return sqlite3GlobalConfig.m.xSize(p);
17525
  }
17526
}
17527
17528
/*
17529
** Free memory previously obtained from sqlite3Malloc().
17530
*/
17531
SQLITE_API void sqlite3_free(void *p){
17532
  if( p==0 ) return;
17533
  assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
17534
  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
17535
  if( sqlite3GlobalConfig.bMemstat ){
17536
    sqlite3_mutex_enter(mem0.mutex);
17537
    sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
17538
    sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
17539
    sqlite3GlobalConfig.m.xFree(p);
17540
    sqlite3_mutex_leave(mem0.mutex);
17541
  }else{
17542
    sqlite3GlobalConfig.m.xFree(p);
17543
  }
17544
}
17545
17546
/*
17547
** Free memory that might be associated with a particular database
17548
** connection.
17549
*/
17550
SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
17551
  assert( db==0 || sqlite3_mutex_held(db->mutex) );
17552
  if( db ){
17553
    if( db->pnBytesFreed ){
17554
      *db->pnBytesFreed += sqlite3DbMallocSize(db, p);
17555
      return;
17556
    }
17557
    if( isLookaside(db, p) ){
17558
      LookasideSlot *pBuf = (LookasideSlot*)p;
17559
      pBuf->pNext = db->lookaside.pFree;
17560
      db->lookaside.pFree = pBuf;
17561
      db->lookaside.nOut--;
17562
      return;
17563
    }
17564
  }
17565
  assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
17566
  assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
17567
  assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
17568
  sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
17569
  sqlite3_free(p);
17570
}
17571
17572
/*
17573
** Change the size of an existing memory allocation
17574
*/
17575
SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
17576
  int nOld, nNew;
17577
  void *pNew;
17578
  if( pOld==0 ){
17579
    return sqlite3Malloc(nBytes);
17580
  }
17581
  if( nBytes<=0 ){
17582
    sqlite3_free(pOld);
17583
    return 0;
17584
  }
17585
  if( nBytes>=0x7fffff00 ){
17586
    /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
17587
    return 0;
17588
  }
17589
  nOld = sqlite3MallocSize(pOld);
17590
  nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
17591
  if( nOld==nNew ){
17592
    pNew = pOld;
17593
  }else if( sqlite3GlobalConfig.bMemstat ){
17594
    sqlite3_mutex_enter(mem0.mutex);
17595
    sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
17596
    if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nNew-nOld >= 
17597
          mem0.alarmThreshold ){
17598
      sqlite3MallocAlarm(nNew-nOld);
17599
    }
17600
    assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
17601
    assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
17602
    pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
17603
    if( pNew==0 && mem0.alarmCallback ){
17604
      sqlite3MallocAlarm(nBytes);
17605
      pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
17606
    }
17607
    if( pNew ){
17608
      nNew = sqlite3MallocSize(pNew);
17609
      sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
17610
    }
17611
    sqlite3_mutex_leave(mem0.mutex);
17612
  }else{
17613
    pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
17614
  }
17615
  return pNew;
17616
}
17617
17618
/*
17619
** The public interface to sqlite3Realloc.  Make sure that the memory
17620
** subsystem is initialized prior to invoking sqliteRealloc.
17621
*/
17622
SQLITE_API void *sqlite3_realloc(void *pOld, int n){
17623
#ifndef SQLITE_OMIT_AUTOINIT
17624
  if( sqlite3_initialize() ) return 0;
17625
#endif
17626
  return sqlite3Realloc(pOld, n);
17627
}
17628
17629
17630
/*
17631
** Allocate and zero memory.
17632
*/ 
17633
SQLITE_PRIVATE void *sqlite3MallocZero(int n){
17634
  void *p = sqlite3Malloc(n);
17635
  if( p ){
17636
    memset(p, 0, n);
17637
  }
17638
  return p;
17639
}
17640
17641
/*
17642
** Allocate and zero memory.  If the allocation fails, make
17643
** the mallocFailed flag in the connection pointer.
17644
*/
17645
SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
17646
  void *p = sqlite3DbMallocRaw(db, n);
17647
  if( p ){
17648
    memset(p, 0, n);
17649
  }
17650
  return p;
17651
}
17652
17653
/*
17654
** Allocate and zero memory.  If the allocation fails, make
17655
** the mallocFailed flag in the connection pointer.
17656
**
17657
** If db!=0 and db->mallocFailed is true (indicating a prior malloc
17658
** failure on the same database connection) then always return 0.
17659
** Hence for a particular database connection, once malloc starts
17660
** failing, it fails consistently until mallocFailed is reset.
17661
** This is an important assumption.  There are many places in the
17662
** code that do things like this:
17663
**
17664
**         int *a = (int*)sqlite3DbMallocRaw(db, 100);
17665
**         int *b = (int*)sqlite3DbMallocRaw(db, 200);
17666
**         if( b ) a[10] = 9;
17667
**
17668
** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
17669
** that all prior mallocs (ex: "a") worked too.
17670
*/
17671
SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
17672
  void *p;
17673
  assert( db==0 || sqlite3_mutex_held(db->mutex) );
17674
  assert( db==0 || db->pnBytesFreed==0 );
17675
#ifndef SQLITE_OMIT_LOOKASIDE
17676
  if( db ){
17677
    LookasideSlot *pBuf;
17678
    if( db->mallocFailed ){
17679
      return 0;
17680
    }
17681
    if( db->lookaside.bEnabled && n<=db->lookaside.sz
17682
         && (pBuf = db->lookaside.pFree)!=0 ){
17683
      db->lookaside.pFree = pBuf->pNext;
17684
      db->lookaside.nOut++;
17685
      if( db->lookaside.nOut>db->lookaside.mxOut ){
17686
        db->lookaside.mxOut = db->lookaside.nOut;
17687
      }
17688
      return (void*)pBuf;
17689
    }
17690
  }
17691
#else
17692
  if( db && db->mallocFailed ){
17693
    return 0;
17694
  }
17695
#endif
17696
  p = sqlite3Malloc(n);
17697
  if( !p && db ){
17698
    db->mallocFailed = 1;
17699
  }
17700
  sqlite3MemdebugSetType(p, MEMTYPE_DB |
17701
         ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
17702
  return p;
17703
}
17704
17705
/*
17706
** Resize the block of memory pointed to by p to n bytes. If the
17707
** resize fails, set the mallocFailed flag in the connection object.
17708
*/
17709
SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
17710
  void *pNew = 0;
17711
  assert( db!=0 );
17712
  assert( sqlite3_mutex_held(db->mutex) );
17713
  if( db->mallocFailed==0 ){
17714
    if( p==0 ){
17715
      return sqlite3DbMallocRaw(db, n);
17716
    }
17717
    if( isLookaside(db, p) ){
17718
      if( n<=db->lookaside.sz ){
17719
        return p;
17720
      }
17721
      pNew = sqlite3DbMallocRaw(db, n);
17722
      if( pNew ){
17723
        memcpy(pNew, p, db->lookaside.sz);
17724
        sqlite3DbFree(db, p);
17725
      }
17726
    }else{
17727
      assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
17728
      assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
17729
      sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
17730
      pNew = sqlite3_realloc(p, n);
17731
      if( !pNew ){
17732
        sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
17733
        db->mallocFailed = 1;
17734
      }
17735
      sqlite3MemdebugSetType(pNew, MEMTYPE_DB | 
17736
            (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
17737
    }
17738
  }
17739
  return pNew;
17740
}
17741
17742
/*
17743
** Attempt to reallocate p.  If the reallocation fails, then free p
17744
** and set the mallocFailed flag in the database connection.
17745
*/
17746
SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
17747
  void *pNew;
17748
  pNew = sqlite3DbRealloc(db, p, n);
17749
  if( !pNew ){
17750
    sqlite3DbFree(db, p);
17751
  }
17752
  return pNew;
17753
}
17754
17755
/*
17756
** Make a copy of a string in memory obtained from sqliteMalloc(). These 
17757
** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
17758
** is because when memory debugging is turned on, these two functions are 
17759
** called via macros that record the current file and line number in the
17760
** ThreadData structure.
17761
*/
17762
SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
17763
  char *zNew;
17764
  size_t n;
17765
  if( z==0 ){
17766
    return 0;
17767
  }
17768
  n = sqlite3Strlen30(z) + 1;
17769
  assert( (n&0x7fffffff)==n );
17770
  zNew = sqlite3DbMallocRaw(db, (int)n);
17771
  if( zNew ){
17772
    memcpy(zNew, z, n);
17773
  }
17774
  return zNew;
17775
}
17776
SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
17777
  char *zNew;
17778
  if( z==0 ){
17779
    return 0;
17780
  }
17781
  assert( (n&0x7fffffff)==n );
17782
  zNew = sqlite3DbMallocRaw(db, n+1);
17783
  if( zNew ){
17784
    memcpy(zNew, z, n);
17785
    zNew[n] = 0;
17786
  }
17787
  return zNew;
17788
}
17789
17790
/*
17791
** Create a string from the zFromat argument and the va_list that follows.
17792
** Store the string in memory obtained from sqliteMalloc() and make *pz
17793
** point to that string.
17794
*/
17795
SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
17796
  va_list ap;
17797
  char *z;
17798
17799
  va_start(ap, zFormat);
17800
  z = sqlite3VMPrintf(db, zFormat, ap);
17801
  va_end(ap);
17802
  sqlite3DbFree(db, *pz);
17803
  *pz = z;
17804
}
17805
17806
17807
/*
17808
** This function must be called before exiting any API function (i.e. 
17809
** returning control to the user) that has called sqlite3_malloc or
17810
** sqlite3_realloc.
17811
**
17812
** The returned value is normally a copy of the second argument to this
17813
** function. However, if a malloc() failure has occurred since the previous
17814
** invocation SQLITE_NOMEM is returned instead. 
17815
**
17816
** If the first argument, db, is not NULL and a malloc() error has occurred,
17817
** then the connection error-code (the value returned by sqlite3_errcode())
17818
** is set to SQLITE_NOMEM.
17819
*/
17820
SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
17821
  /* If the db handle is not NULL, then we must hold the connection handle
17822
  ** mutex here. Otherwise the read (and possible write) of db->mallocFailed 
17823
  ** is unsafe, as is the call to sqlite3Error().
17824
  */
17825
  assert( !db || sqlite3_mutex_held(db->mutex) );
17826
  if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
17827
    sqlite3Error(db, SQLITE_NOMEM, 0);
17828
    db->mallocFailed = 0;
17829
    rc = SQLITE_NOMEM;
17830
  }
17831
  return rc & (db ? db->errMask : 0xff);
17832
}
17833
17834
/************** End of malloc.c **********************************************/
17835
/************** Begin file printf.c ******************************************/
17836
/*
17837
** The "printf" code that follows dates from the 1980's.  It is in
17838
** the public domain.  The original comments are included here for
17839
** completeness.  They are very out-of-date but might be useful as
17840
** an historical reference.  Most of the "enhancements" have been backed
17841
** out so that the functionality is now the same as standard printf().
17842
**
17843
**************************************************************************
17844
**
17845
** The following modules is an enhanced replacement for the "printf" subroutines
17846
** found in the standard C library.  The following enhancements are
17847
** supported:
17848
**
17849
**      +  Additional functions.  The standard set of "printf" functions
17850
**         includes printf, fprintf, sprintf, vprintf, vfprintf, and
17851
**         vsprintf.  This module adds the following:
17852
**
17853
**           *  snprintf -- Works like sprintf, but has an extra argument
17854
**                          which is the size of the buffer written to.
17855
**
17856
**           *  mprintf --  Similar to sprintf.  Writes output to memory
17857
**                          obtained from malloc.
17858
**
17859
**           *  xprintf --  Calls a function to dispose of output.
17860
**
17861
**           *  nprintf --  No output, but returns the number of characters
17862
**                          that would have been output by printf.
17863
**
17864
**           *  A v- version (ex: vsnprintf) of every function is also
17865
**              supplied.
17866
**
17867
**      +  A few extensions to the formatting notation are supported:
17868
**
17869
**           *  The "=" flag (similar to "-") causes the output to be
17870
**              be centered in the appropriately sized field.
17871
**
17872
**           *  The %b field outputs an integer in binary notation.
17873
**
17874
**           *  The %c field now accepts a precision.  The character output
17875
**              is repeated by the number of times the precision specifies.
17876
**
17877
**           *  The %' field works like %c, but takes as its character the
17878
**              next character of the format string, instead of the next
17879
**              argument.  For example,  printf("%.78'-")  prints 78 minus
17880
**              signs, the same as  printf("%.78c",'-').
17881
**
17882
**      +  When compiled using GCC on a SPARC, this version of printf is
17883
**         faster than the library printf for SUN OS 4.1.
17884
**
17885
**      +  All functions are fully reentrant.
17886
**
17887
*/
17888
17889
/*
17890
** Conversion types fall into various categories as defined by the
17891
** following enumeration.
17892
*/
17893
#define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
17894
#define etFLOAT       2 /* Floating point.  %f */
17895
#define etEXP         3 /* Exponentional notation. %e and %E */
17896
#define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
17897
#define etSIZE        5 /* Return number of characters processed so far. %n */
17898
#define etSTRING      6 /* Strings. %s */
17899
#define etDYNSTRING   7 /* Dynamically allocated strings. %z */
17900
#define etPERCENT     8 /* Percent symbol. %% */
17901
#define etCHARX       9 /* Characters. %c */
17902
/* The rest are extensions, not normally found in printf() */
17903
#define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
17904
#define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
17905
                          NULL pointers replaced by SQL NULL.  %Q */
17906
#define etTOKEN      12 /* a pointer to a Token structure */
17907
#define etSRCLIST    13 /* a pointer to a SrcList */
17908
#define etPOINTER    14 /* The %p conversion */
17909
#define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
17910
#define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
17911
17912
#define etINVALID     0 /* Any unrecognized conversion type */
17913
17914
17915
/*
17916
** An "etByte" is an 8-bit unsigned value.
17917
*/
17918
typedef unsigned char etByte;
17919
17920
/*
17921
** Each builtin conversion character (ex: the 'd' in "%d") is described
17922
** by an instance of the following structure
17923
*/
17924
typedef struct et_info {   /* Information about each format field */
17925
  char fmttype;            /* The format field code letter */
17926
  etByte base;             /* The base for radix conversion */
17927
  etByte flags;            /* One or more of FLAG_ constants below */
17928
  etByte type;             /* Conversion paradigm */
17929
  etByte charset;          /* Offset into aDigits[] of the digits string */
17930
  etByte prefix;           /* Offset into aPrefix[] of the prefix string */
17931
} et_info;
17932
17933
/*
17934
** Allowed values for et_info.flags
17935
*/
17936
#define FLAG_SIGNED  1     /* True if the value to convert is signed */
17937
#define FLAG_INTERN  2     /* True if for internal use only */
17938
#define FLAG_STRING  4     /* Allow infinity precision */
17939
17940
17941
/*
17942
** The following table is searched linearly, so it is good to put the
17943
** most frequently used conversion types first.
17944
*/
17945
static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
17946
static const char aPrefix[] = "-x0\000X0";
17947
static const et_info fmtinfo[] = {
17948
  {  'd', 10, 1, etRADIX,      0,  0 },
17949
  {  's',  0, 4, etSTRING,     0,  0 },
17950
  {  'g',  0, 1, etGENERIC,    30, 0 },
17951
  {  'z',  0, 4, etDYNSTRING,  0,  0 },
17952
  {  'q',  0, 4, etSQLESCAPE,  0,  0 },
17953
  {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
17954
  {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
17955
  {  'c',  0, 0, etCHARX,      0,  0 },
17956
  {  'o',  8, 0, etRADIX,      0,  2 },
17957
  {  'u', 10, 0, etRADIX,      0,  0 },
17958
  {  'x', 16, 0, etRADIX,      16, 1 },
17959
  {  'X', 16, 0, etRADIX,      0,  4 },
17960
#ifndef SQLITE_OMIT_FLOATING_POINT
17961
  {  'f',  0, 1, etFLOAT,      0,  0 },
17962
  {  'e',  0, 1, etEXP,        30, 0 },
17963
  {  'E',  0, 1, etEXP,        14, 0 },
17964
  {  'G',  0, 1, etGENERIC,    14, 0 },
17965
#endif
17966
  {  'i', 10, 1, etRADIX,      0,  0 },
17967
  {  'n',  0, 0, etSIZE,       0,  0 },
17968
  {  '%',  0, 0, etPERCENT,    0,  0 },
17969
  {  'p', 16, 0, etPOINTER,    0,  1 },
17970
17971
/* All the rest have the FLAG_INTERN bit set and are thus for internal
17972
** use only */
17973
  {  'T',  0, 2, etTOKEN,      0,  0 },
17974
  {  'S',  0, 2, etSRCLIST,    0,  0 },
17975
  {  'r', 10, 3, etORDINAL,    0,  0 },
17976
};
17977
17978
/*
17979
** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
17980
** conversions will work.
17981
*/
17982
#ifndef SQLITE_OMIT_FLOATING_POINT
17983
/*
17984
** "*val" is a double such that 0.1 <= *val < 10.0
17985
** Return the ascii code for the leading digit of *val, then
17986
** multiply "*val" by 10.0 to renormalize.
17987
**
17988
** Example:
17989
**     input:     *val = 3.14159
17990
**     output:    *val = 1.4159    function return = '3'
17991
**
17992
** The counter *cnt is incremented each time.  After counter exceeds
17993
** 16 (the number of significant digits in a 64-bit float) '0' is
17994
** always returned.
17995
*/
17996
static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
17997
  int digit;
17998
  LONGDOUBLE_TYPE d;
17999
  if( (*cnt)++ >= 16 ) return '0';
18000
  digit = (int)*val;
18001
  d = digit;
18002
  digit += '0';
18003
  *val = (*val - d)*10.0;
18004
  return (char)digit;
18005
}
18006
#endif /* SQLITE_OMIT_FLOATING_POINT */
18007
18008
/*
18009
** Append N space characters to the given string buffer.
18010
*/
18011
static void appendSpace(StrAccum *pAccum, int N){
18012
  static const char zSpaces[] = "                             ";
18013
  while( N>=(int)sizeof(zSpaces)-1 ){
18014
    sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
18015
    N -= sizeof(zSpaces)-1;
18016
  }
18017
  if( N>0 ){
18018
    sqlite3StrAccumAppend(pAccum, zSpaces, N);
18019
  }
18020
}
18021
18022
/*
18023
** On machines with a small stack size, you can redefine the
18024
** SQLITE_PRINT_BUF_SIZE to be less than 350.
18025
*/
18026
#ifndef SQLITE_PRINT_BUF_SIZE
18027
# if defined(SQLITE_SMALL_STACK)
18028
#   define SQLITE_PRINT_BUF_SIZE 50
18029
# else
18030
#   define SQLITE_PRINT_BUF_SIZE 350
18031
# endif
18032
#endif
18033
#define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
18034
18035
/*
18036
** The root program.  All variations call this core.
18037
**
18038
** INPUTS:
18039
**   func   This is a pointer to a function taking three arguments
18040
**            1. A pointer to anything.  Same as the "arg" parameter.
18041
**            2. A pointer to the list of characters to be output
18042
**               (Note, this list is NOT null terminated.)
18043
**            3. An integer number of characters to be output.
18044
**               (Note: This number might be zero.)
18045
**
18046
**   arg    This is the pointer to anything which will be passed as the
18047
**          first argument to "func".  Use it for whatever you like.
18048
**
18049
**   fmt    This is the format string, as in the usual print.
18050
**
18051
**   ap     This is a pointer to a list of arguments.  Same as in
18052
**          vfprint.
18053
**
18054
** OUTPUTS:
18055
**          The return value is the total number of characters sent to
18056
**          the function "func".  Returns -1 on a error.
18057
**
18058
** Note that the order in which automatic variables are declared below
18059
** seems to make a big difference in determining how fast this beast
18060
** will run.
18061
*/
18062
SQLITE_PRIVATE void sqlite3VXPrintf(
18063
  StrAccum *pAccum,                  /* Accumulate results here */
18064
  int useExtended,                   /* Allow extended %-conversions */
18065
  const char *fmt,                   /* Format string */
18066
  va_list ap                         /* arguments */
18067
){
18068
  int c;                     /* Next character in the format string */
18069
  char *bufpt;               /* Pointer to the conversion buffer */
18070
  int precision;             /* Precision of the current field */
18071
  int length;                /* Length of the field */
18072
  int idx;                   /* A general purpose loop counter */
18073
  int width;                 /* Width of the current field */
18074
  etByte flag_leftjustify;   /* True if "-" flag is present */
18075
  etByte flag_plussign;      /* True if "+" flag is present */
18076
  etByte flag_blanksign;     /* True if " " flag is present */
18077
  etByte flag_alternateform; /* True if "#" flag is present */
18078
  etByte flag_altform2;      /* True if "!" flag is present */
18079
  etByte flag_zeropad;       /* True if field width constant starts with zero */
18080
  etByte flag_long;          /* True if "l" flag is present */
18081
  etByte flag_longlong;      /* True if the "ll" flag is present */
18082
  etByte done;               /* Loop termination flag */
18083
  sqlite_uint64 longvalue;   /* Value for integer types */
18084
  LONGDOUBLE_TYPE realvalue; /* Value for real types */
18085
  const et_info *infop;      /* Pointer to the appropriate info structure */
18086
  char buf[etBUFSIZE];       /* Conversion buffer */
18087
  char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
18088
  etByte xtype = 0;          /* Conversion paradigm */
18089
  char *zExtra;              /* Extra memory used for etTCLESCAPE conversions */
18090
#ifndef SQLITE_OMIT_FLOATING_POINT
18091
  int  exp, e2;              /* exponent of real numbers */
18092
  double rounder;            /* Used for rounding floating point values */
18093
  etByte flag_dp;            /* True if decimal point should be shown */
18094
  etByte flag_rtz;           /* True if trailing zeros should be removed */
18095
  etByte flag_exp;           /* True to force display of the exponent */
18096
  int nsd;                   /* Number of significant digits returned */
18097
#endif
18098
18099
  length = 0;
18100
  bufpt = 0;
18101
  for(; (c=(*fmt))!=0; ++fmt){
18102
    if( c!='%' ){
18103
      int amt;
18104
      bufpt = (char *)fmt;
18105
      amt = 1;
18106
      while( (c=(*++fmt))!='%' && c!=0 ) amt++;
18107
      sqlite3StrAccumAppend(pAccum, bufpt, amt);
18108
      if( c==0 ) break;
18109
    }
18110
    if( (c=(*++fmt))==0 ){
18111
      sqlite3StrAccumAppend(pAccum, "%", 1);
18112
      break;
18113
    }
18114
    /* Find out what flags are present */
18115
    flag_leftjustify = flag_plussign = flag_blanksign = 
18116
     flag_alternateform = flag_altform2 = flag_zeropad = 0;
18117
    done = 0;
18118
    do{
18119
      switch( c ){
18120
        case '-':   flag_leftjustify = 1;     break;
18121
        case '+':   flag_plussign = 1;        break;
18122
        case ' ':   flag_blanksign = 1;       break;
18123
        case '#':   flag_alternateform = 1;   break;
18124
        case '!':   flag_altform2 = 1;        break;
18125
        case '0':   flag_zeropad = 1;         break;
18126
        default:    done = 1;                 break;
18127
      }
18128
    }while( !done && (c=(*++fmt))!=0 );
18129
    /* Get the field width */
18130
    width = 0;
18131
    if( c=='*' ){
18132
      width = va_arg(ap,int);
18133
      if( width<0 ){
18134
        flag_leftjustify = 1;
18135
        width = -width;
18136
      }
18137
      c = *++fmt;
18138
    }else{
18139
      while( c>='0' && c<='9' ){
18140
        width = width*10 + c - '0';
18141
        c = *++fmt;
18142
      }
18143
    }
18144
    if( width > etBUFSIZE-10 ){
18145
      width = etBUFSIZE-10;
18146
    }
18147
    /* Get the precision */
18148
    if( c=='.' ){
18149
      precision = 0;
18150
      c = *++fmt;
18151
      if( c=='*' ){
18152
        precision = va_arg(ap,int);
18153
        if( precision<0 ) precision = -precision;
18154
        c = *++fmt;
18155
      }else{
18156
        while( c>='0' && c<='9' ){
18157
          precision = precision*10 + c - '0';
18158
          c = *++fmt;
18159
        }
18160
      }
18161
    }else{
18162
      precision = -1;
18163
    }
18164
    /* Get the conversion type modifier */
18165
    if( c=='l' ){
18166
      flag_long = 1;
18167
      c = *++fmt;
18168
      if( c=='l' ){
18169
        flag_longlong = 1;
18170
        c = *++fmt;
18171
      }else{
18172
        flag_longlong = 0;
18173
      }
18174
    }else{
18175
      flag_long = flag_longlong = 0;
18176
    }
18177
    /* Fetch the info entry for the field */
18178
    infop = &fmtinfo[0];
18179
    xtype = etINVALID;
18180
    for(idx=0; idx<ArraySize(fmtinfo); idx++){
18181
      if( c==fmtinfo[idx].fmttype ){
18182
        infop = &fmtinfo[idx];
18183
        if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
18184
          xtype = infop->type;
18185
        }else{
18186
          return;
18187
        }
18188
        break;
18189
      }
18190
    }
18191
    zExtra = 0;
18192
18193
18194
    /* Limit the precision to prevent overflowing buf[] during conversion */
18195
    if( precision>etBUFSIZE-40 && (infop->flags & FLAG_STRING)==0 ){
18196
      precision = etBUFSIZE-40;
18197
    }
18198
18199
    /*
18200
    ** At this point, variables are initialized as follows:
18201
    **
18202
    **   flag_alternateform          TRUE if a '#' is present.
18203
    **   flag_altform2               TRUE if a '!' is present.
18204
    **   flag_plussign               TRUE if a '+' is present.
18205
    **   flag_leftjustify            TRUE if a '-' is present or if the
18206
    **                               field width was negative.
18207
    **   flag_zeropad                TRUE if the width began with 0.
18208
    **   flag_long                   TRUE if the letter 'l' (ell) prefixed
18209
    **                               the conversion character.
18210
    **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
18211
    **                               the conversion character.
18212
    **   flag_blanksign              TRUE if a ' ' is present.
18213
    **   width                       The specified field width.  This is
18214
    **                               always non-negative.  Zero is the default.
18215
    **   precision                   The specified precision.  The default
18216
    **                               is -1.
18217
    **   xtype                       The class of the conversion.
18218
    **   infop                       Pointer to the appropriate info struct.
18219
    */
18220
    switch( xtype ){
18221
      case etPOINTER:
18222
        flag_longlong = sizeof(char*)==sizeof(i64);
18223
        flag_long = sizeof(char*)==sizeof(long int);
18224
        /* Fall through into the next case */
18225
      case etORDINAL:
18226
      case etRADIX:
18227
        if( infop->flags & FLAG_SIGNED ){
18228
          i64 v;
18229
          if( flag_longlong ){
18230
            v = va_arg(ap,i64);
18231
          }else if( flag_long ){
18232
            v = va_arg(ap,long int);
18233
          }else{
18234
            v = va_arg(ap,int);
18235
          }
18236
          if( v<0 ){
18237
            longvalue = -v;
18238
            prefix = '-';
18239
          }else{
18240
            longvalue = v;
18241
            if( flag_plussign )        prefix = '+';
18242
            else if( flag_blanksign )  prefix = ' ';
18243
            else                       prefix = 0;
18244
          }
18245
        }else{
18246
          if( flag_longlong ){
18247
            longvalue = va_arg(ap,u64);
18248
          }else if( flag_long ){
18249
            longvalue = va_arg(ap,unsigned long int);
18250
          }else{
18251
            longvalue = va_arg(ap,unsigned int);
18252
          }
18253
          prefix = 0;
18254
        }
18255
        if( longvalue==0 ) flag_alternateform = 0;
18256
        if( flag_zeropad && precision<width-(prefix!=0) ){
18257
          precision = width-(prefix!=0);
18258
        }
18259
        bufpt = &buf[etBUFSIZE-1];
18260
        if( xtype==etORDINAL ){
18261
          static const char zOrd[] = "thstndrd";
18262
          int x = (int)(longvalue % 10);
18263
          if( x>=4 || (longvalue/10)%10==1 ){
18264
            x = 0;
18265
          }
18266
          buf[etBUFSIZE-3] = zOrd[x*2];
18267
          buf[etBUFSIZE-2] = zOrd[x*2+1];
18268
          bufpt -= 2;
18269
        }
18270
        {
18271
          register const char *cset;      /* Use registers for speed */
18272
          register int base;
18273
          cset = &aDigits[infop->charset];
18274
          base = infop->base;
18275
          do{                                           /* Convert to ascii */
18276
            *(--bufpt) = cset[longvalue%base];
18277
            longvalue = longvalue/base;
18278
          }while( longvalue>0 );
18279
        }
18280
        length = (int)(&buf[etBUFSIZE-1]-bufpt);
18281
        for(idx=precision-length; idx>0; idx--){
18282
          *(--bufpt) = '0';                             /* Zero pad */
18283
        }
18284
        if( prefix ) *(--bufpt) = prefix;               /* Add sign */
18285
        if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
18286
          const char *pre;
18287
          char x;
18288
          pre = &aPrefix[infop->prefix];
18289
          for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
18290
        }
18291
        length = (int)(&buf[etBUFSIZE-1]-bufpt);
18292
        break;
18293
      case etFLOAT:
18294
      case etEXP:
18295
      case etGENERIC:
18296
        realvalue = va_arg(ap,double);
18297
#ifdef SQLITE_OMIT_FLOATING_POINT
18298
        length = 0;
18299
#else
18300
        if( precision<0 ) precision = 6;         /* Set default precision */
18301
        if( precision>etBUFSIZE/2-10 ) precision = etBUFSIZE/2-10;
18302
        if( realvalue<0.0 ){
18303
          realvalue = -realvalue;
18304
          prefix = '-';
18305
        }else{
18306
          if( flag_plussign )          prefix = '+';
18307
          else if( flag_blanksign )    prefix = ' ';
18308
          else                         prefix = 0;
18309
        }
18310
        if( xtype==etGENERIC && precision>0 ) precision--;
18311
#if 0
18312
        /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
18313
        for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
18314
#else
18315
        /* It makes more sense to use 0.5 */
18316
        for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
18317
#endif
18318
        if( xtype==etFLOAT ) realvalue += rounder;
18319
        /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
18320
        exp = 0;
18321
        if( sqlite3IsNaN((double)realvalue) ){
18322
          bufpt = "NaN";
18323
          length = 3;
18324
          break;
18325
        }
18326
        if( realvalue>0.0 ){
18327
          while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
18328
          while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
18329
          while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
18330
          while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
18331
          while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
18332
          if( exp>350 ){
18333
            if( prefix=='-' ){
18334
              bufpt = "-Inf";
18335
            }else if( prefix=='+' ){
18336
              bufpt = "+Inf";
18337
            }else{
18338
              bufpt = "Inf";
18339
            }
18340
            length = sqlite3Strlen30(bufpt);
18341
            break;
18342
          }
18343
        }
18344
        bufpt = buf;
18345
        /*
18346
        ** If the field type is etGENERIC, then convert to either etEXP
18347
        ** or etFLOAT, as appropriate.
18348
        */
18349
        flag_exp = xtype==etEXP;
18350
        if( xtype!=etFLOAT ){
18351
          realvalue += rounder;
18352
          if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
18353
        }
18354
        if( xtype==etGENERIC ){
18355
          flag_rtz = !flag_alternateform;
18356
          if( exp<-4 || exp>precision ){
18357
            xtype = etEXP;
18358
          }else{
18359
            precision = precision - exp;
18360
            xtype = etFLOAT;
18361
          }
18362
        }else{
18363
          flag_rtz = 0;
18364
        }
18365
        if( xtype==etEXP ){
18366
          e2 = 0;
18367
        }else{
18368
          e2 = exp;
18369
        }
18370
        nsd = 0;
18371
        flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
18372
        /* The sign in front of the number */
18373
        if( prefix ){
18374
          *(bufpt++) = prefix;
18375
        }
18376
        /* Digits prior to the decimal point */
18377
        if( e2<0 ){
18378
          *(bufpt++) = '0';
18379
        }else{
18380
          for(; e2>=0; e2--){
18381
            *(bufpt++) = et_getdigit(&realvalue,&nsd);
18382
          }
18383
        }
18384
        /* The decimal point */
18385
        if( flag_dp ){
18386
          *(bufpt++) = '.';
18387
        }
18388
        /* "0" digits after the decimal point but before the first
18389
        ** significant digit of the number */
18390
        for(e2++; e2<0; precision--, e2++){
18391
          assert( precision>0 );
18392
          *(bufpt++) = '0';
18393
        }
18394
        /* Significant digits after the decimal point */
18395
        while( (precision--)>0 ){
18396
          *(bufpt++) = et_getdigit(&realvalue,&nsd);
18397
        }
18398
        /* Remove trailing zeros and the "." if no digits follow the "." */
18399
        if( flag_rtz && flag_dp ){
18400
          while( bufpt[-1]=='0' ) *(--bufpt) = 0;
18401
          assert( bufpt>buf );
18402
          if( bufpt[-1]=='.' ){
18403
            if( flag_altform2 ){
18404
              *(bufpt++) = '0';
18405
            }else{
18406
              *(--bufpt) = 0;
18407
            }
18408
          }
18409
        }
18410
        /* Add the "eNNN" suffix */
18411
        if( flag_exp || xtype==etEXP ){
18412
          *(bufpt++) = aDigits[infop->charset];
18413
          if( exp<0 ){
18414
            *(bufpt++) = '-'; exp = -exp;
18415
          }else{
18416
            *(bufpt++) = '+';
18417
          }
18418
          if( exp>=100 ){
18419
            *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
18420
            exp %= 100;
18421
          }
18422
          *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
18423
          *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
18424
        }
18425
        *bufpt = 0;
18426
18427
        /* The converted number is in buf[] and zero terminated. Output it.
18428
        ** Note that the number is in the usual order, not reversed as with
18429
        ** integer conversions. */
18430
        length = (int)(bufpt-buf);
18431
        bufpt = buf;
18432
18433
        /* Special case:  Add leading zeros if the flag_zeropad flag is
18434
        ** set and we are not left justified */
18435
        if( flag_zeropad && !flag_leftjustify && length < width){
18436
          int i;
18437
          int nPad = width - length;
18438
          for(i=width; i>=nPad; i--){
18439
            bufpt[i] = bufpt[i-nPad];
18440
          }
18441
          i = prefix!=0;
18442
          while( nPad-- ) bufpt[i++] = '0';
18443
          length = width;
18444
        }
18445
#endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
18446
        break;
18447
      case etSIZE:
18448
        *(va_arg(ap,int*)) = pAccum->nChar;
18449
        length = width = 0;
18450
        break;
18451
      case etPERCENT:
18452
        buf[0] = '%';
18453
        bufpt = buf;
18454
        length = 1;
18455
        break;
18456
      case etCHARX:
18457
        c = va_arg(ap,int);
18458
        buf[0] = (char)c;
18459
        if( precision>=0 ){
18460
          for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
18461
          length = precision;
18462
        }else{
18463
          length =1;
18464
        }
18465
        bufpt = buf;
18466
        break;
18467
      case etSTRING:
18468
      case etDYNSTRING:
18469
        bufpt = va_arg(ap,char*);
18470
        if( bufpt==0 ){
18471
          bufpt = "";
18472
        }else if( xtype==etDYNSTRING ){
18473
          zExtra = bufpt;
18474
        }
18475
        if( precision>=0 ){
18476
          for(length=0; length<precision && bufpt[length]; length++){}
18477
        }else{
18478
          length = sqlite3Strlen30(bufpt);
18479
        }
18480
        break;
18481
      case etSQLESCAPE:
18482
      case etSQLESCAPE2:
18483
      case etSQLESCAPE3: {
18484
        int i, j, k, n, isnull;
18485
        int needQuote;
18486
        char ch;
18487
        char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
18488
        char *escarg = va_arg(ap,char*);
18489
        isnull = escarg==0;
18490
        if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
18491
        k = precision;
18492
        for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
18493
          if( ch==q )  n++;
18494
        }
18495
        needQuote = !isnull && xtype==etSQLESCAPE2;
18496
        n += i + 1 + needQuote*2;
18497
        if( n>etBUFSIZE ){
18498
          bufpt = zExtra = sqlite3Malloc( n );
18499
          if( bufpt==0 ){
18500
            pAccum->mallocFailed = 1;
18501
            return;
18502
          }
18503
        }else{
18504
          bufpt = buf;
18505
        }
18506
        j = 0;
18507
        if( needQuote ) bufpt[j++] = q;
18508
        k = i;
18509
        for(i=0; i<k; i++){
18510
          bufpt[j++] = ch = escarg[i];
18511
          if( ch==q ) bufpt[j++] = ch;
18512
        }
18513
        if( needQuote ) bufpt[j++] = q;
18514
        bufpt[j] = 0;
18515
        length = j;
18516
        /* The precision in %q and %Q means how many input characters to
18517
        ** consume, not the length of the output...
18518
        ** if( precision>=0 && precision<length ) length = precision; */
18519
        break;
18520
      }
18521
      case etTOKEN: {
18522
        Token *pToken = va_arg(ap, Token*);
18523
        if( pToken ){
18524
          sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
18525
        }
18526
        length = width = 0;
18527
        break;
18528
      }
18529
      case etSRCLIST: {
18530
        SrcList *pSrc = va_arg(ap, SrcList*);
18531
        int k = va_arg(ap, int);
18532
        struct SrcList_item *pItem = &pSrc->a[k];
18533
        assert( k>=0 && k<pSrc->nSrc );
18534
        if( pItem->zDatabase ){
18535
          sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
18536
          sqlite3StrAccumAppend(pAccum, ".", 1);
18537
        }
18538
        sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
18539
        length = width = 0;
18540
        break;
18541
      }
18542
      default: {
18543
        assert( xtype==etINVALID );
18544
        return;
18545
      }
18546
    }/* End switch over the format type */
18547
    /*
18548
    ** The text of the conversion is pointed to by "bufpt" and is
18549
    ** "length" characters long.  The field width is "width".  Do
18550
    ** the output.
18551
    */
18552
    if( !flag_leftjustify ){
18553
      register int nspace;
18554
      nspace = width-length;
18555
      if( nspace>0 ){
18556
        appendSpace(pAccum, nspace);
18557
      }
18558
    }
18559
    if( length>0 ){
18560
      sqlite3StrAccumAppend(pAccum, bufpt, length);
18561
    }
18562
    if( flag_leftjustify ){
18563
      register int nspace;
18564
      nspace = width-length;
18565
      if( nspace>0 ){
18566
        appendSpace(pAccum, nspace);
18567
      }
18568
    }
18569
    if( zExtra ){
18570
      sqlite3_free(zExtra);
18571
    }
18572
  }/* End for loop over the format string */
18573
} /* End of function */
18574
18575
/*
18576
** Append N bytes of text from z to the StrAccum object.
18577
*/
18578
SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
18579
  assert( z!=0 || N==0 );
18580
  if( p->tooBig | p->mallocFailed ){
18581
    testcase(p->tooBig);
18582
    testcase(p->mallocFailed);
18583
    return;
18584
  }
18585
  if( N<0 ){
18586
    N = sqlite3Strlen30(z);
18587
  }
18588
  if( N==0 || NEVER(z==0) ){
18589
    return;
18590
  }
18591
  if( p->nChar+N >= p->nAlloc ){
18592
    char *zNew;
18593
    if( !p->useMalloc ){
18594
      p->tooBig = 1;
18595
      N = p->nAlloc - p->nChar - 1;
18596
      if( N<=0 ){
18597
        return;
18598
      }
18599
    }else{
18600
      i64 szNew = p->nChar;
18601
      szNew += N + 1;
18602
      if( szNew > p->mxAlloc ){
18603
        sqlite3StrAccumReset(p);
18604
        p->tooBig = 1;
18605
        return;
18606
      }else{
18607
        p->nAlloc = (int)szNew;
18608
      }
18609
      if( p->useMalloc==1 ){
18610
        zNew = sqlite3DbMallocRaw(p->db, p->nAlloc );
18611
      }else{
18612
        zNew = sqlite3_malloc(p->nAlloc);
18613
      }
18614
      if( zNew ){
18615
        memcpy(zNew, p->zText, p->nChar);
18616
        sqlite3StrAccumReset(p);
18617
        p->zText = zNew;
18618
      }else{
18619
        p->mallocFailed = 1;
18620
        sqlite3StrAccumReset(p);
18621
        return;
18622
      }
18623
    }
18624
  }
18625
  memcpy(&p->zText[p->nChar], z, N);
18626
  p->nChar += N;
18627
}
18628
18629
/*
18630
** Finish off a string by making sure it is zero-terminated.
18631
** Return a pointer to the resulting string.  Return a NULL
18632
** pointer if any kind of error was encountered.
18633
*/
18634
SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
18635
  if( p->zText ){
18636
    p->zText[p->nChar] = 0;
18637
    if( p->useMalloc && p->zText==p->zBase ){
18638
      if( p->useMalloc==1 ){
18639
        p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
18640
      }else{
18641
        p->zText = sqlite3_malloc(p->nChar+1);
18642
      }
18643
      if( p->zText ){
18644
        memcpy(p->zText, p->zBase, p->nChar+1);
18645
      }else{
18646
        p->mallocFailed = 1;
18647
      }
18648
    }
18649
  }
18650
  return p->zText;
18651
}
18652
18653
/*
18654
** Reset an StrAccum string.  Reclaim all malloced memory.
18655
*/
18656
SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
18657
  if( p->zText!=p->zBase ){
18658
    if( p->useMalloc==1 ){
18659
      sqlite3DbFree(p->db, p->zText);
18660
    }else{
18661
      sqlite3_free(p->zText);
18662
    }
18663
  }
18664
  p->zText = 0;
18665
}
18666
18667
/*
18668
** Initialize a string accumulator
18669
*/
18670
SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
18671
  p->zText = p->zBase = zBase;
18672
  p->db = 0;
18673
  p->nChar = 0;
18674
  p->nAlloc = n;
18675
  p->mxAlloc = mx;
18676
  p->useMalloc = 1;
18677
  p->tooBig = 0;
18678
  p->mallocFailed = 0;
18679
}
18680
18681
/*
18682
** Print into memory obtained from sqliteMalloc().  Use the internal
18683
** %-conversion extensions.
18684
*/
18685
SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
18686
  char *z;
18687
  char zBase[SQLITE_PRINT_BUF_SIZE];
18688
  StrAccum acc;
18689
  assert( db!=0 );
18690
  sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
18691
                      db->aLimit[SQLITE_LIMIT_LENGTH]);
18692
  acc.db = db;
18693
  sqlite3VXPrintf(&acc, 1, zFormat, ap);
18694
  z = sqlite3StrAccumFinish(&acc);
18695
  if( acc.mallocFailed ){
18696
    db->mallocFailed = 1;
18697
  }
18698
  return z;
18699
}
18700
18701
/*
18702
** Print into memory obtained from sqliteMalloc().  Use the internal
18703
** %-conversion extensions.
18704
*/
18705
SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
18706
  va_list ap;
18707
  char *z;
18708
  va_start(ap, zFormat);
18709
  z = sqlite3VMPrintf(db, zFormat, ap);
18710
  va_end(ap);
18711
  return z;
18712
}
18713
18714
/*
18715
** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
18716
** the string and before returnning.  This routine is intended to be used
18717
** to modify an existing string.  For example:
18718
**
18719
**       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
18720
**
18721
*/
18722
SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
18723
  va_list ap;
18724
  char *z;
18725
  va_start(ap, zFormat);
18726
  z = sqlite3VMPrintf(db, zFormat, ap);
18727
  va_end(ap);
18728
  sqlite3DbFree(db, zStr);
18729
  return z;
18730
}
18731
18732
/*
18733
** Print into memory obtained from sqlite3_malloc().  Omit the internal
18734
** %-conversion extensions.
18735
*/
18736
SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
18737
  char *z;
18738
  char zBase[SQLITE_PRINT_BUF_SIZE];
18739
  StrAccum acc;
18740
#ifndef SQLITE_OMIT_AUTOINIT
18741
  if( sqlite3_initialize() ) return 0;
18742
#endif
18743
  sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
18744
  acc.useMalloc = 2;
18745
  sqlite3VXPrintf(&acc, 0, zFormat, ap);
18746
  z = sqlite3StrAccumFinish(&acc);
18747
  return z;
18748
}
18749
18750
/*
18751
** Print into memory obtained from sqlite3_malloc()().  Omit the internal
18752
** %-conversion extensions.
18753
*/
18754
SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
18755
  va_list ap;
18756
  char *z;
18757
#ifndef SQLITE_OMIT_AUTOINIT
18758
  if( sqlite3_initialize() ) return 0;
18759
#endif
18760
  va_start(ap, zFormat);
18761
  z = sqlite3_vmprintf(zFormat, ap);
18762
  va_end(ap);
18763
  return z;
18764
}
18765
18766
/*
18767
** sqlite3_snprintf() works like snprintf() except that it ignores the
18768
** current locale settings.  This is important for SQLite because we
18769
** are not able to use a "," as the decimal point in place of "." as
18770
** specified by some locales.
18771
*/
18772
SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
18773
  char *z;
18774
  va_list ap;
18775
  StrAccum acc;
18776
18777
  if( n<=0 ){
18778
    return zBuf;
18779
  }
18780
  sqlite3StrAccumInit(&acc, zBuf, n, 0);
18781
  acc.useMalloc = 0;
18782
  va_start(ap,zFormat);
18783
  sqlite3VXPrintf(&acc, 0, zFormat, ap);
18784
  va_end(ap);
18785
  z = sqlite3StrAccumFinish(&acc);
18786
  return z;
18787
}
18788
18789
/*
18790
** This is the routine that actually formats the sqlite3_log() message.
18791
** We house it in a separate routine from sqlite3_log() to avoid using
18792
** stack space on small-stack systems when logging is disabled.
18793
**
18794
** sqlite3_log() must render into a static buffer.  It cannot dynamically
18795
** allocate memory because it might be called while the memory allocator
18796
** mutex is held.
18797
*/
18798
static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
18799
  StrAccum acc;                          /* String accumulator */
18800
  char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
18801
18802
  sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
18803
  acc.useMalloc = 0;
18804
  sqlite3VXPrintf(&acc, 0, zFormat, ap);
18805
  sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
18806
                           sqlite3StrAccumFinish(&acc));
18807
}
18808
18809
/*
18810
** Format and write a message to the log if logging is enabled.
18811
*/
18812
SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
18813
  va_list ap;                             /* Vararg list */
18814
  if( sqlite3GlobalConfig.xLog ){
18815
    va_start(ap, zFormat);
18816
    renderLogMsg(iErrCode, zFormat, ap);
18817
    va_end(ap);
18818
  }
18819
}
18820
18821
#if defined(SQLITE_DEBUG)
18822
/*
18823
** A version of printf() that understands %lld.  Used for debugging.
18824
** The printf() built into some versions of windows does not understand %lld
18825
** and segfaults if you give it a long long int.
18826
*/
18827
SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
18828
  va_list ap;
18829
  StrAccum acc;
18830
  char zBuf[500];
18831
  sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
18832
  acc.useMalloc = 0;
18833
  va_start(ap,zFormat);
18834
  sqlite3VXPrintf(&acc, 0, zFormat, ap);
18835
  va_end(ap);
18836
  sqlite3StrAccumFinish(&acc);
18837
  fprintf(stdout,"%s", zBuf);
18838
  fflush(stdout);
18839
}
18840
#endif
18841
18842
#ifndef SQLITE_OMIT_TRACE
18843
/*
18844
** variable-argument wrapper around sqlite3VXPrintf().
18845
*/
18846
SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
18847
  va_list ap;
18848
  va_start(ap,zFormat);
18849
  sqlite3VXPrintf(p, 1, zFormat, ap);
18850
  va_end(ap);
18851
}
18852
#endif
18853
18854
/************** End of printf.c **********************************************/
18855
/************** Begin file random.c ******************************************/
18856
/*
18857
** 2001 September 15
18858
**
18859
** The author disclaims copyright to this source code.  In place of
18860
** a legal notice, here is a blessing:
18861
**
18862
**    May you do good and not evil.
18863
**    May you find forgiveness for yourself and forgive others.
18864
**    May you share freely, never taking more than you give.
18865
**
18866
*************************************************************************
18867
** This file contains code to implement a pseudo-random number
18868
** generator (PRNG) for SQLite.
18869
**
18870
** Random numbers are used by some of the database backends in order
18871
** to generate random integer keys for tables or random filenames.
18872
*/
18873
18874
18875
/* All threads share a single random number generator.
18876
** This structure is the current state of the generator.
18877
*/
18878
static SQLITE_WSD struct sqlite3PrngType {
18879
  unsigned char isInit;          /* True if initialized */
18880
  unsigned char i, j;            /* State variables */
18881
  unsigned char s[256];          /* State variables */
18882
} sqlite3Prng;
18883
18884
/*
18885
** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
18886
** must be held while executing this routine.
18887
**
18888
** Why not just use a library random generator like lrand48() for this?
18889
** Because the OP_NewRowid opcode in the VDBE depends on having a very
18890
** good source of random numbers.  The lrand48() library function may
18891
** well be good enough.  But maybe not.  Or maybe lrand48() has some
18892
** subtle problems on some systems that could cause problems.  It is hard
18893
** to know.  To minimize the risk of problems due to bad lrand48()
18894
** implementations, SQLite uses this random number generator based
18895
** on RC4, which we know works very well.
18896
**
18897
** (Later):  Actually, OP_NewRowid does not depend on a good source of
18898
** randomness any more.  But we will leave this code in all the same.
18899
*/
18900
static u8 randomByte(void){
18901
  unsigned char t;
18902
18903
18904
  /* The "wsdPrng" macro will resolve to the pseudo-random number generator
18905
  ** state vector.  If writable static data is unsupported on the target,
18906
  ** we have to locate the state vector at run-time.  In the more common
18907
  ** case where writable static data is supported, wsdPrng can refer directly
18908
  ** to the "sqlite3Prng" state vector declared above.
18909
  */
18910
#ifdef SQLITE_OMIT_WSD
18911
  struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
18912
# define wsdPrng p[0]
18913
#else
18914
# define wsdPrng sqlite3Prng
18915
#endif
18916
18917
18918
  /* Initialize the state of the random number generator once,
18919
  ** the first time this routine is called.  The seed value does
18920
  ** not need to contain a lot of randomness since we are not
18921
  ** trying to do secure encryption or anything like that...
18922
  **
18923
  ** Nothing in this file or anywhere else in SQLite does any kind of
18924
  ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
18925
  ** number generator) not as an encryption device.
18926
  */
18927
  if( !wsdPrng.isInit ){
18928
    int i;
18929
    char k[256];
18930
    wsdPrng.j = 0;
18931
    wsdPrng.i = 0;
18932
    sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
18933
    for(i=0; i<256; i++){
18934
      wsdPrng.s[i] = (u8)i;
18935
    }
18936
    for(i=0; i<256; i++){
18937
      wsdPrng.j += wsdPrng.s[i] + k[i];
18938
      t = wsdPrng.s[wsdPrng.j];
18939
      wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
18940
      wsdPrng.s[i] = t;
18941
    }
18942
    wsdPrng.isInit = 1;
18943
  }
18944
18945
  /* Generate and return single random byte
18946
  */
18947
  wsdPrng.i++;
18948
  t = wsdPrng.s[wsdPrng.i];
18949
  wsdPrng.j += t;
18950
  wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
18951
  wsdPrng.s[wsdPrng.j] = t;
18952
  t += wsdPrng.s[wsdPrng.i];
18953
  return wsdPrng.s[t];
18954
}
18955
18956
/*
18957
** Return N random bytes.
18958
*/
18959
SQLITE_API void sqlite3_randomness(int N, void *pBuf){
18960
  unsigned char *zBuf = pBuf;
18961
#if SQLITE_THREADSAFE
18962
  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
18963
#endif
18964
  sqlite3_mutex_enter(mutex);
18965
  while( N-- ){
18966
    *(zBuf++) = randomByte();
18967
  }
18968
  sqlite3_mutex_leave(mutex);
18969
}
18970
18971
#ifndef SQLITE_OMIT_BUILTIN_TEST
18972
/*
18973
** For testing purposes, we sometimes want to preserve the state of
18974
** PRNG and restore the PRNG to its saved state at a later time, or
18975
** to reset the PRNG to its initial state.  These routines accomplish
18976
** those tasks.
18977
**
18978
** The sqlite3_test_control() interface calls these routines to
18979
** control the PRNG.
18980
*/
18981
static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
18982
SQLITE_PRIVATE void sqlite3PrngSaveState(void){
18983
  memcpy(
18984
    &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
18985
    &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
18986
    sizeof(sqlite3Prng)
18987
  );
18988
}
18989
SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
18990
  memcpy(
18991
    &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
18992
    &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
18993
    sizeof(sqlite3Prng)
18994
  );
18995
}
18996
SQLITE_PRIVATE void sqlite3PrngResetState(void){
18997
  GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
18998
}
18999
#endif /* SQLITE_OMIT_BUILTIN_TEST */
19000
19001
/************** End of random.c **********************************************/
19002
/************** Begin file utf.c *********************************************/
19003
/*
19004
** 2004 April 13
19005
**
19006
** The author disclaims copyright to this source code.  In place of
19007
** a legal notice, here is a blessing:
19008
**
19009
**    May you do good and not evil.
19010
**    May you find forgiveness for yourself and forgive others.
19011
**    May you share freely, never taking more than you give.
19012
**
19013
*************************************************************************
19014
** This file contains routines used to translate between UTF-8, 
19015
** UTF-16, UTF-16BE, and UTF-16LE.
19016
**
19017
** Notes on UTF-8:
19018
**
19019
**   Byte-0    Byte-1    Byte-2    Byte-3    Value
19020
**  0xxxxxxx                                 00000000 00000000 0xxxxxxx
19021
**  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
19022
**  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
19023
**  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
19024
**
19025
**
19026
** Notes on UTF-16:  (with wwww+1==uuuuu)
19027
**
19028
**      Word-0               Word-1          Value
19029
**  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
19030
**  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
19031
**
19032
**
19033
** BOM or Byte Order Mark:
19034
**     0xff 0xfe   little-endian utf-16 follows
19035
**     0xfe 0xff   big-endian utf-16 follows
19036
**
19037
*/
18418
19038
18419
#ifndef SQLITE_AMALGAMATION
19039
#ifndef SQLITE_AMALGAMATION
18420
/*
19040
/*
 Lines 20347-20385   SQLITE_PRIVATE const char *sqlite3Opcode Link Here 
20347
     /*  37 */ "VerifyCookie",
20967
     /*  37 */ "VerifyCookie",
20348
     /*  38 */ "OpenRead",
20968
     /*  38 */ "OpenRead",
20349
     /*  39 */ "OpenWrite",
20969
     /*  39 */ "OpenWrite",
20350
     /*  40 */ "OpenEphemeral",
20970
     /*  40 */ "OpenAutoindex",
20351
     /*  41 */ "OpenPseudo",
20971
     /*  41 */ "OpenEphemeral",
20352
     /*  42 */ "Close",
20972
     /*  42 */ "OpenPseudo",
20353
     /*  43 */ "SeekLt",
20973
     /*  43 */ "Close",
20354
     /*  44 */ "SeekLe",
20974
     /*  44 */ "SeekLt",
20355
     /*  45 */ "SeekGe",
20975
     /*  45 */ "SeekLe",
20356
     /*  46 */ "SeekGt",
20976
     /*  46 */ "SeekGe",
20357
     /*  47 */ "Seek",
20977
     /*  47 */ "SeekGt",
20358
     /*  48 */ "NotFound",
20978
     /*  48 */ "Seek",
20359
     /*  49 */ "Found",
20979
     /*  49 */ "NotFound",
20360
     /*  50 */ "IsUnique",
20980
     /*  50 */ "Found",
20361
     /*  51 */ "NotExists",
20981
     /*  51 */ "IsUnique",
20362
     /*  52 */ "Sequence",
20982
     /*  52 */ "NotExists",
20363
     /*  53 */ "NewRowid",
20983
     /*  53 */ "Sequence",
20364
     /*  54 */ "Insert",
20984
     /*  54 */ "NewRowid",
20365
     /*  55 */ "InsertInt",
20985
     /*  55 */ "Insert",
20366
     /*  56 */ "Delete",
20986
     /*  56 */ "InsertInt",
20367
     /*  57 */ "ResetCount",
20987
     /*  57 */ "Delete",
20368
     /*  58 */ "RowKey",
20988
     /*  58 */ "ResetCount",
20369
     /*  59 */ "RowData",
20989
     /*  59 */ "RowKey",
20370
     /*  60 */ "Rowid",
20990
     /*  60 */ "RowData",
20371
     /*  61 */ "NullRow",
20991
     /*  61 */ "Rowid",
20372
     /*  62 */ "Last",
20992
     /*  62 */ "NullRow",
20373
     /*  63 */ "Sort",
20993
     /*  63 */ "Last",
20374
     /*  64 */ "Rewind",
20994
     /*  64 */ "Sort",
20375
     /*  65 */ "Prev",
20995
     /*  65 */ "Rewind",
20376
     /*  66 */ "Next",
20996
     /*  66 */ "Prev",
20377
     /*  67 */ "IdxInsert",
20997
     /*  67 */ "Next",
20378
     /*  68 */ "Or",
20998
     /*  68 */ "Or",
20379
     /*  69 */ "And",
20999
     /*  69 */ "And",
20380
     /*  70 */ "IdxDelete",
21000
     /*  70 */ "IdxInsert",
20381
     /*  71 */ "IdxRowid",
21001
     /*  71 */ "IdxDelete",
20382
     /*  72 */ "IdxLT",
21002
     /*  72 */ "IdxRowid",
20383
     /*  73 */ "IsNull",
21003
     /*  73 */ "IsNull",
20384
     /*  74 */ "NotNull",
21004
     /*  74 */ "NotNull",
20385
     /*  75 */ "Ne",
21005
     /*  75 */ "Ne",
 Lines 20388-20394   SQLITE_PRIVATE const char *sqlite3Opcode Link Here 
20388
     /*  78 */ "Le",
21008
     /*  78 */ "Le",
20389
     /*  79 */ "Lt",
21009
     /*  79 */ "Lt",
20390
     /*  80 */ "Ge",
21010
     /*  80 */ "Ge",
20391
     /*  81 */ "IdxGE",
21011
     /*  81 */ "IdxLT",
20392
     /*  82 */ "BitAnd",
21012
     /*  82 */ "BitAnd",
20393
     /*  83 */ "BitOr",
21013
     /*  83 */ "BitOr",
20394
     /*  84 */ "ShiftLeft",
21014
     /*  84 */ "ShiftLeft",
 Lines 20399-20450   SQLITE_PRIVATE const char *sqlite3Opcode Link Here 
20399
     /*  89 */ "Divide",
21019
     /*  89 */ "Divide",
20400
     /*  90 */ "Remainder",
21020
     /*  90 */ "Remainder",
20401
     /*  91 */ "Concat",
21021
     /*  91 */ "Concat",
20402
     /*  92 */ "Destroy",
21022
     /*  92 */ "IdxGE",
20403
     /*  93 */ "BitNot",
21023
     /*  93 */ "BitNot",
20404
     /*  94 */ "String8",
21024
     /*  94 */ "String8",
20405
     /*  95 */ "Clear",
21025
     /*  95 */ "Destroy",
20406
     /*  96 */ "CreateIndex",
21026
     /*  96 */ "Clear",
20407
     /*  97 */ "CreateTable",
21027
     /*  97 */ "CreateIndex",
20408
     /*  98 */ "ParseSchema",
21028
     /*  98 */ "CreateTable",
20409
     /*  99 */ "LoadAnalysis",
21029
     /*  99 */ "ParseSchema",
20410
     /* 100 */ "DropTable",
21030
     /* 100 */ "LoadAnalysis",
20411
     /* 101 */ "DropIndex",
21031
     /* 101 */ "DropTable",
20412
     /* 102 */ "DropTrigger",
21032
     /* 102 */ "DropIndex",
20413
     /* 103 */ "IntegrityCk",
21033
     /* 103 */ "DropTrigger",
20414
     /* 104 */ "RowSetAdd",
21034
     /* 104 */ "IntegrityCk",
20415
     /* 105 */ "RowSetRead",
21035
     /* 105 */ "RowSetAdd",
20416
     /* 106 */ "RowSetTest",
21036
     /* 106 */ "RowSetRead",
20417
     /* 107 */ "Program",
21037
     /* 107 */ "RowSetTest",
20418
     /* 108 */ "Param",
21038
     /* 108 */ "Program",
20419
     /* 109 */ "FkCounter",
21039
     /* 109 */ "Param",
20420
     /* 110 */ "FkIfZero",
21040
     /* 110 */ "FkCounter",
20421
     /* 111 */ "MemMax",
21041
     /* 111 */ "FkIfZero",
20422
     /* 112 */ "IfPos",
21042
     /* 112 */ "MemMax",
20423
     /* 113 */ "IfNeg",
21043
     /* 113 */ "IfPos",
20424
     /* 114 */ "IfZero",
21044
     /* 114 */ "IfNeg",
20425
     /* 115 */ "AggStep",
21045
     /* 115 */ "IfZero",
20426
     /* 116 */ "AggFinal",
21046
     /* 116 */ "AggStep",
20427
     /* 117 */ "Vacuum",
21047
     /* 117 */ "AggFinal",
20428
     /* 118 */ "IncrVacuum",
21048
     /* 118 */ "Checkpoint",
20429
     /* 119 */ "Expire",
21049
     /* 119 */ "JournalMode",
20430
     /* 120 */ "TableLock",
21050
     /* 120 */ "Vacuum",
20431
     /* 121 */ "VBegin",
21051
     /* 121 */ "IncrVacuum",
20432
     /* 122 */ "VCreate",
21052
     /* 122 */ "Expire",
20433
     /* 123 */ "VDestroy",
21053
     /* 123 */ "TableLock",
20434
     /* 124 */ "VOpen",
21054
     /* 124 */ "VBegin",
20435
     /* 125 */ "VFilter",
21055
     /* 125 */ "VCreate",
20436
     /* 126 */ "VColumn",
21056
     /* 126 */ "VDestroy",
20437
     /* 127 */ "VNext",
21057
     /* 127 */ "VOpen",
20438
     /* 128 */ "VRename",
21058
     /* 128 */ "VFilter",
20439
     /* 129 */ "VUpdate",
21059
     /* 129 */ "VColumn",
20440
     /* 130 */ "Real",
21060
     /* 130 */ "Real",
20441
     /* 131 */ "Pagecount",
21061
     /* 131 */ "VNext",
20442
     /* 132 */ "Trace",
21062
     /* 132 */ "VRename",
20443
     /* 133 */ "Noop",
21063
     /* 133 */ "VUpdate",
20444
     /* 134 */ "Explain",
21064
     /* 134 */ "Pagecount",
20445
     /* 135 */ "NotUsed_135",
21065
     /* 135 */ "Trace",
20446
     /* 136 */ "NotUsed_136",
21066
     /* 136 */ "Noop",
20447
     /* 137 */ "NotUsed_137",
21067
     /* 137 */ "Explain",
20448
     /* 138 */ "NotUsed_138",
21068
     /* 138 */ "NotUsed_138",
20449
     /* 139 */ "NotUsed_139",
21069
     /* 139 */ "NotUsed_139",
20450
     /* 140 */ "NotUsed_140",
21070
     /* 140 */ "NotUsed_140",
 Lines 20549-20571   SQLITE_PRIVATE const char *sqlite3Opcode Link Here 
20549
21169
20550
#ifdef SQLITE_DEBUG
21170
#ifdef SQLITE_DEBUG
20551
SQLITE_PRIVATE int sqlite3OSTrace = 0;
21171
SQLITE_PRIVATE int sqlite3OSTrace = 0;
20552
#define OSTRACE1(X)         if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
21172
#define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
20553
#define OSTRACE2(X,Y)       if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
21173
#else
20554
#define OSTRACE3(X,Y,Z)     if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
21174
#define OSTRACE(X)
20555
#define OSTRACE4(X,Y,Z,A)   if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
20556
#define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
20557
#define OSTRACE6(X,Y,Z,A,B,C) \
20558
    if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
20559
#define OSTRACE7(X,Y,Z,A,B,C,D) \
20560
    if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
20561
#else
20562
#define OSTRACE1(X)
20563
#define OSTRACE2(X,Y)
20564
#define OSTRACE3(X,Y,Z)
20565
#define OSTRACE4(X,Y,Z,A)
20566
#define OSTRACE5(X,Y,Z,A,B)
20567
#define OSTRACE6(X,Y,Z,A,B,C)
20568
#define OSTRACE7(X,Y,Z,A,B,C,D)
20569
#endif
21175
#endif
20570
21176
20571
/*
21177
/*
 Lines 20761-20767   static int os2Close( sqlite3_file *id ){ Link Here 
20761
  APIRET rc = NO_ERROR;
21367
  APIRET rc = NO_ERROR;
20762
  os2File *pFile;
21368
  os2File *pFile;
20763
  if( id && (pFile = (os2File*)id) != 0 ){
21369
  if( id && (pFile = (os2File*)id) != 0 ){
20764
    OSTRACE2( "CLOSE %d\n", pFile->h );
21370
    OSTRACE(( "CLOSE %d\n", pFile->h ));
20765
    rc = DosClose( pFile->h );
21371
    rc = DosClose( pFile->h );
20766
    pFile->locktype = NO_LOCK;
21372
    pFile->locktype = NO_LOCK;
20767
    if( pFile->pathToDel != NULL ){
21373
    if( pFile->pathToDel != NULL ){
 Lines 20792-20798   static int os2Read( Link Here 
20792
  os2File *pFile = (os2File*)id;
21398
  os2File *pFile = (os2File*)id;
20793
  assert( id!=0 );
21399
  assert( id!=0 );
20794
  SimulateIOError( return SQLITE_IOERR_READ );
21400
  SimulateIOError( return SQLITE_IOERR_READ );
20795
  OSTRACE3( "READ %d lock=%d\n", pFile->h, pFile->locktype );
21401
  OSTRACE(( "READ %d lock=%d\n", pFile->h, pFile->locktype ));
20796
  if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
21402
  if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
20797
    return SQLITE_IOERR;
21403
    return SQLITE_IOERR;
20798
  }
21404
  }
 Lines 20825-20831   static int os2Write( Link Here 
20825
  assert( id!=0 );
21431
  assert( id!=0 );
20826
  SimulateIOError( return SQLITE_IOERR_WRITE );
21432
  SimulateIOError( return SQLITE_IOERR_WRITE );
20827
  SimulateDiskfullError( return SQLITE_FULL );
21433
  SimulateDiskfullError( return SQLITE_FULL );
20828
  OSTRACE3( "WRITE %d lock=%d\n", pFile->h, pFile->locktype );
21434
  OSTRACE(( "WRITE %d lock=%d\n", pFile->h, pFile->locktype ));
20829
  if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
21435
  if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
20830
    return SQLITE_IOERR;
21436
    return SQLITE_IOERR;
20831
  }
21437
  }
 Lines 20847-20853   static int os2Write( Link Here 
20847
static int os2Truncate( sqlite3_file *id, i64 nByte ){
21453
static int os2Truncate( sqlite3_file *id, i64 nByte ){
20848
  APIRET rc = NO_ERROR;
21454
  APIRET rc = NO_ERROR;
20849
  os2File *pFile = (os2File*)id;
21455
  os2File *pFile = (os2File*)id;
20850
  OSTRACE3( "TRUNCATE %d %lld\n", pFile->h, nByte );
21456
  OSTRACE(( "TRUNCATE %d %lld\n", pFile->h, nByte ));
20851
  SimulateIOError( return SQLITE_IOERR_TRUNCATE );
21457
  SimulateIOError( return SQLITE_IOERR_TRUNCATE );
20852
  rc = DosSetFileSize( pFile->h, nByte );
21458
  rc = DosSetFileSize( pFile->h, nByte );
20853
  return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_TRUNCATE;
21459
  return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_TRUNCATE;
 Lines 20867-20873   SQLITE_API int sqlite3_fullsync_count = Link Here 
20867
*/
21473
*/
20868
static int os2Sync( sqlite3_file *id, int flags ){
21474
static int os2Sync( sqlite3_file *id, int flags ){
20869
  os2File *pFile = (os2File*)id;
21475
  os2File *pFile = (os2File*)id;
20870
  OSTRACE3( "SYNC %d lock=%d\n", pFile->h, pFile->locktype );
21476
  OSTRACE(( "SYNC %d lock=%d\n", pFile->h, pFile->locktype ));
20871
#ifdef SQLITE_TEST
21477
#ifdef SQLITE_TEST
20872
  if( flags & SQLITE_SYNC_FULL){
21478
  if( flags & SQLITE_SYNC_FULL){
20873
    sqlite3_fullsync_count++;
21479
    sqlite3_fullsync_count++;
 Lines 20917-20923   static int getReadLock( os2File *pFile ) Link Here 
20917
  UnlockArea.lOffset = 0L;
21523
  UnlockArea.lOffset = 0L;
20918
  UnlockArea.lRange = 0L;
21524
  UnlockArea.lRange = 0L;
20919
  res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
21525
  res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
20920
  OSTRACE3( "GETREADLOCK %d res=%d\n", pFile->h, res );
21526
  OSTRACE(( "GETREADLOCK %d res=%d\n", pFile->h, res ));
20921
  return res;
21527
  return res;
20922
}
21528
}
20923
21529
 Lines 20935-20941   static int unlockReadLock( os2File *id ) Link Here 
20935
  UnlockArea.lOffset = SHARED_FIRST;
21541
  UnlockArea.lOffset = SHARED_FIRST;
20936
  UnlockArea.lRange = SHARED_SIZE;
21542
  UnlockArea.lRange = SHARED_SIZE;
20937
  res = DosSetFileLocks( id->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
21543
  res = DosSetFileLocks( id->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
20938
  OSTRACE3( "UNLOCK-READLOCK file handle=%d res=%d?\n", id->h, res );
21544
  OSTRACE(( "UNLOCK-READLOCK file handle=%d res=%d?\n", id->h, res ));
20939
  return res;
21545
  return res;
20940
}
21546
}
20941
21547
 Lines 20976-20989   static int os2Lock( sqlite3_file *id, in Link Here 
20976
  memset(&LockArea, 0, sizeof(LockArea));
21582
  memset(&LockArea, 0, sizeof(LockArea));
20977
  memset(&UnlockArea, 0, sizeof(UnlockArea));
21583
  memset(&UnlockArea, 0, sizeof(UnlockArea));
20978
  assert( pFile!=0 );
21584
  assert( pFile!=0 );
20979
  OSTRACE4( "LOCK %d %d was %d\n", pFile->h, locktype, pFile->locktype );
21585
  OSTRACE(( "LOCK %d %d was %d\n", pFile->h, locktype, pFile->locktype ));
20980
21586
20981
  /* If there is already a lock of this type or more restrictive on the
21587
  /* If there is already a lock of this type or more restrictive on the
20982
  ** os2File, do nothing. Don't use the end_lock: exit path, as
21588
  ** os2File, do nothing. Don't use the end_lock: exit path, as
20983
  ** sqlite3_mutex_enter() hasn't been called yet.
21589
  ** sqlite3_mutex_enter() hasn't been called yet.
20984
  */
21590
  */
20985
  if( pFile->locktype>=locktype ){
21591
  if( pFile->locktype>=locktype ){
20986
    OSTRACE3( "LOCK %d %d ok (already held)\n", pFile->h, locktype );
21592
    OSTRACE(( "LOCK %d %d ok (already held)\n", pFile->h, locktype ));
20987
    return SQLITE_OK;
21593
    return SQLITE_OK;
20988
  }
21594
  }
20989
21595
 Lines 21010-21016   static int os2Lock( sqlite3_file *id, in Link Here 
21010
    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 100L, 0L );
21616
    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 100L, 0L );
21011
    if( res == NO_ERROR ){
21617
    if( res == NO_ERROR ){
21012
      gotPendingLock = 1;
21618
      gotPendingLock = 1;
21013
      OSTRACE3( "LOCK %d pending lock boolean set.  res=%d\n", pFile->h, res );
21619
      OSTRACE(( "LOCK %d pending lock boolean set.  res=%d\n", pFile->h, res ));
21014
    }
21620
    }
21015
  }
21621
  }
21016
21622
 Lines 21022-21028   static int os2Lock( sqlite3_file *id, in Link Here 
21022
    if( res == NO_ERROR ){
21628
    if( res == NO_ERROR ){
21023
      newLocktype = SHARED_LOCK;
21629
      newLocktype = SHARED_LOCK;
21024
    }
21630
    }
21025
    OSTRACE3( "LOCK %d acquire shared lock. res=%d\n", pFile->h, res );
21631
    OSTRACE(( "LOCK %d acquire shared lock. res=%d\n", pFile->h, res ));
21026
  }
21632
  }
21027
21633
21028
  /* Acquire a RESERVED lock
21634
  /* Acquire a RESERVED lock
 Lines 21037-21043   static int os2Lock( sqlite3_file *id, in Link Here 
21037
    if( res == NO_ERROR ){
21643
    if( res == NO_ERROR ){
21038
      newLocktype = RESERVED_LOCK;
21644
      newLocktype = RESERVED_LOCK;
21039
    }
21645
    }
21040
    OSTRACE3( "LOCK %d acquire reserved lock. res=%d\n", pFile->h, res );
21646
    OSTRACE(( "LOCK %d acquire reserved lock. res=%d\n", pFile->h, res ));
21041
  }
21647
  }
21042
21648
21043
  /* Acquire a PENDING lock
21649
  /* Acquire a PENDING lock
 Lines 21045-21051   static int os2Lock( sqlite3_file *id, in Link Here 
21045
  if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
21651
  if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
21046
    newLocktype = PENDING_LOCK;
21652
    newLocktype = PENDING_LOCK;
21047
    gotPendingLock = 0;
21653
    gotPendingLock = 0;
21048
    OSTRACE2( "LOCK %d acquire pending lock. pending lock boolean unset.\n", pFile->h );
21654
    OSTRACE(( "LOCK %d acquire pending lock. pending lock boolean unset.\n",
21655
               pFile->h ));
21049
  }
21656
  }
21050
21657
21051
  /* Acquire an EXCLUSIVE lock
21658
  /* Acquire an EXCLUSIVE lock
 Lines 21053-21059   static int os2Lock( sqlite3_file *id, in Link Here 
21053
  if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
21660
  if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
21054
    assert( pFile->locktype>=SHARED_LOCK );
21661
    assert( pFile->locktype>=SHARED_LOCK );
21055
    res = unlockReadLock(pFile);
21662
    res = unlockReadLock(pFile);
21056
    OSTRACE2( "unreadlock = %d\n", res );
21663
    OSTRACE(( "unreadlock = %d\n", res ));
21057
    LockArea.lOffset = SHARED_FIRST;
21664
    LockArea.lOffset = SHARED_FIRST;
21058
    LockArea.lRange = SHARED_SIZE;
21665
    LockArea.lRange = SHARED_SIZE;
21059
    UnlockArea.lOffset = 0L;
21666
    UnlockArea.lOffset = 0L;
 Lines 21062-21071   static int os2Lock( sqlite3_file *id, in Link Here 
21062
    if( res == NO_ERROR ){
21669
    if( res == NO_ERROR ){
21063
      newLocktype = EXCLUSIVE_LOCK;
21670
      newLocktype = EXCLUSIVE_LOCK;
21064
    }else{
21671
    }else{
21065
      OSTRACE2( "OS/2 error-code = %d\n", res );
21672
      OSTRACE(( "OS/2 error-code = %d\n", res ));
21066
      getReadLock(pFile);
21673
      getReadLock(pFile);
21067
    }
21674
    }
21068
    OSTRACE3( "LOCK %d acquire exclusive lock.  res=%d\n", pFile->h, res );
21675
    OSTRACE(( "LOCK %d acquire exclusive lock.  res=%d\n", pFile->h, res ));
21069
  }
21676
  }
21070
21677
21071
  /* If we are holding a PENDING lock that ought to be released, then
21678
  /* If we are holding a PENDING lock that ought to be released, then
 Lines 21078-21084   static int os2Lock( sqlite3_file *id, in Link Here 
21078
    UnlockArea.lOffset = PENDING_BYTE;
21685
    UnlockArea.lOffset = PENDING_BYTE;
21079
    UnlockArea.lRange = 1L;
21686
    UnlockArea.lRange = 1L;
21080
    r = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21687
    r = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21081
    OSTRACE3( "LOCK %d unlocking pending/is shared. r=%d\n", pFile->h, r );
21688
    OSTRACE(( "LOCK %d unlocking pending/is shared. r=%d\n", pFile->h, r ));
21082
  }
21689
  }
21083
21690
21084
  /* Update the state of the lock has held in the file descriptor then
21691
  /* Update the state of the lock has held in the file descriptor then
 Lines 21087-21098   static int os2Lock( sqlite3_file *id, in Link Here 
21087
  if( res == NO_ERROR ){
21694
  if( res == NO_ERROR ){
21088
    rc = SQLITE_OK;
21695
    rc = SQLITE_OK;
21089
  }else{
21696
  }else{
21090
    OSTRACE4( "LOCK FAILED %d trying for %d but got %d\n", pFile->h,
21697
    OSTRACE(( "LOCK FAILED %d trying for %d but got %d\n", pFile->h,
21091
              locktype, newLocktype );
21698
              locktype, newLocktype ));
21092
    rc = SQLITE_BUSY;
21699
    rc = SQLITE_BUSY;
21093
  }
21700
  }
21094
  pFile->locktype = newLocktype;
21701
  pFile->locktype = newLocktype;
21095
  OSTRACE3( "LOCK %d now %d\n", pFile->h, pFile->locktype );
21702
  OSTRACE(( "LOCK %d now %d\n", pFile->h, pFile->locktype ));
21096
  return rc;
21703
  return rc;
21097
}
21704
}
21098
21705
 Lines 21107-21113   static int os2CheckReservedLock( sqlite3 Link Here 
21107
  assert( pFile!=0 );
21714
  assert( pFile!=0 );
21108
  if( pFile->locktype>=RESERVED_LOCK ){
21715
  if( pFile->locktype>=RESERVED_LOCK ){
21109
    r = 1;
21716
    r = 1;
21110
    OSTRACE3( "TEST WR-LOCK %d %d (local)\n", pFile->h, r );
21717
    OSTRACE(( "TEST WR-LOCK %d %d (local)\n", pFile->h, r ));
21111
  }else{
21718
  }else{
21112
    FILELOCK  LockArea,
21719
    FILELOCK  LockArea,
21113
              UnlockArea;
21720
              UnlockArea;
 Lines 21119-21125   static int os2CheckReservedLock( sqlite3 Link Here 
21119
    UnlockArea.lOffset = 0L;
21726
    UnlockArea.lOffset = 0L;
21120
    UnlockArea.lRange = 0L;
21727
    UnlockArea.lRange = 0L;
21121
    rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21728
    rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21122
    OSTRACE3( "TEST WR-LOCK %d lock reserved byte rc=%d\n", pFile->h, rc );
21729
    OSTRACE(( "TEST WR-LOCK %d lock reserved byte rc=%d\n", pFile->h, rc ));
21123
    if( rc == NO_ERROR ){
21730
    if( rc == NO_ERROR ){
21124
      APIRET rcu = NO_ERROR; /* return code for unlocking */
21731
      APIRET rcu = NO_ERROR; /* return code for unlocking */
21125
      LockArea.lOffset = 0L;
21732
      LockArea.lOffset = 0L;
 Lines 21127-21136   static int os2CheckReservedLock( sqlite3 Link Here 
21127
      UnlockArea.lOffset = RESERVED_BYTE;
21734
      UnlockArea.lOffset = RESERVED_BYTE;
21128
      UnlockArea.lRange = 1L;
21735
      UnlockArea.lRange = 1L;
21129
      rcu = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21736
      rcu = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21130
      OSTRACE3( "TEST WR-LOCK %d unlock reserved byte r=%d\n", pFile->h, rcu );
21737
      OSTRACE(( "TEST WR-LOCK %d unlock reserved byte r=%d\n", pFile->h, rcu ));
21131
    }
21738
    }
21132
    r = !(rc == NO_ERROR);
21739
    r = !(rc == NO_ERROR);
21133
    OSTRACE3( "TEST WR-LOCK %d %d (remote)\n", pFile->h, r );
21740
    OSTRACE(( "TEST WR-LOCK %d %d (remote)\n", pFile->h, r ));
21134
  }
21741
  }
21135
  *pOut = r;
21742
  *pOut = r;
21136
  return SQLITE_OK;
21743
  return SQLITE_OK;
 Lines 21158-21164   static int os2Unlock( sqlite3_file *id, Link Here 
21158
  memset(&UnlockArea, 0, sizeof(UnlockArea));
21765
  memset(&UnlockArea, 0, sizeof(UnlockArea));
21159
  assert( pFile!=0 );
21766
  assert( pFile!=0 );
21160
  assert( locktype<=SHARED_LOCK );
21767
  assert( locktype<=SHARED_LOCK );
21161
  OSTRACE4( "UNLOCK %d to %d was %d\n", pFile->h, locktype, pFile->locktype );
21768
  OSTRACE(( "UNLOCK %d to %d was %d\n", pFile->h, locktype, pFile->locktype ));
21162
  type = pFile->locktype;
21769
  type = pFile->locktype;
21163
  if( type>=EXCLUSIVE_LOCK ){
21770
  if( type>=EXCLUSIVE_LOCK ){
21164
    LockArea.lOffset = 0L;
21771
    LockArea.lOffset = 0L;
 Lines 21166-21176   static int os2Unlock( sqlite3_file *id, Link Here 
21166
    UnlockArea.lOffset = SHARED_FIRST;
21773
    UnlockArea.lOffset = SHARED_FIRST;
21167
    UnlockArea.lRange = SHARED_SIZE;
21774
    UnlockArea.lRange = SHARED_SIZE;
21168
    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21775
    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21169
    OSTRACE3( "UNLOCK %d exclusive lock res=%d\n", pFile->h, res );
21776
    OSTRACE(( "UNLOCK %d exclusive lock res=%d\n", pFile->h, res ));
21170
    if( locktype==SHARED_LOCK && getReadLock(pFile) != NO_ERROR ){
21777
    if( locktype==SHARED_LOCK && getReadLock(pFile) != NO_ERROR ){
21171
      /* This should never happen.  We should always be able to
21778
      /* This should never happen.  We should always be able to
21172
      ** reacquire the read lock */
21779
      ** reacquire the read lock */
21173
      OSTRACE3( "UNLOCK %d to %d getReadLock() failed\n", pFile->h, locktype );
21780
      OSTRACE(( "UNLOCK %d to %d getReadLock() failed\n", pFile->h, locktype ));
21174
      rc = SQLITE_IOERR_UNLOCK;
21781
      rc = SQLITE_IOERR_UNLOCK;
21175
    }
21782
    }
21176
  }
21783
  }
 Lines 21180-21190   static int os2Unlock( sqlite3_file *id, Link Here 
21180
    UnlockArea.lOffset = RESERVED_BYTE;
21787
    UnlockArea.lOffset = RESERVED_BYTE;
21181
    UnlockArea.lRange = 1L;
21788
    UnlockArea.lRange = 1L;
21182
    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21789
    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21183
    OSTRACE3( "UNLOCK %d reserved res=%d\n", pFile->h, res );
21790
    OSTRACE(( "UNLOCK %d reserved res=%d\n", pFile->h, res ));
21184
  }
21791
  }
21185
  if( locktype==NO_LOCK && type>=SHARED_LOCK ){
21792
  if( locktype==NO_LOCK && type>=SHARED_LOCK ){
21186
    res = unlockReadLock(pFile);
21793
    res = unlockReadLock(pFile);
21187
    OSTRACE5( "UNLOCK %d is %d want %d res=%d\n", pFile->h, type, locktype, res );
21794
    OSTRACE(( "UNLOCK %d is %d want %d res=%d\n",
21795
              pFile->h, type, locktype, res ));
21188
  }
21796
  }
21189
  if( type>=PENDING_LOCK ){
21797
  if( type>=PENDING_LOCK ){
21190
    LockArea.lOffset = 0L;
21798
    LockArea.lOffset = 0L;
 Lines 21192-21201   static int os2Unlock( sqlite3_file *id, Link Here 
21192
    UnlockArea.lOffset = PENDING_BYTE;
21800
    UnlockArea.lOffset = PENDING_BYTE;
21193
    UnlockArea.lRange = 1L;
21801
    UnlockArea.lRange = 1L;
21194
    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21802
    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21195
    OSTRACE3( "UNLOCK %d pending res=%d\n", pFile->h, res );
21803
    OSTRACE(( "UNLOCK %d pending res=%d\n", pFile->h, res ));
21196
  }
21804
  }
21197
  pFile->locktype = locktype;
21805
  pFile->locktype = locktype;
21198
  OSTRACE3( "UNLOCK %d now %d\n", pFile->h, pFile->locktype );
21806
  OSTRACE(( "UNLOCK %d now %d\n", pFile->h, pFile->locktype ));
21199
  return rc;
21807
  return rc;
21200
}
21808
}
21201
21809
 Lines 21206-21212   static int os2FileControl(sqlite3_file * Link Here 
21206
  switch( op ){
21814
  switch( op ){
21207
    case SQLITE_FCNTL_LOCKSTATE: {
21815
    case SQLITE_FCNTL_LOCKSTATE: {
21208
      *(int*)pArg = ((os2File*)id)->locktype;
21816
      *(int*)pArg = ((os2File*)id)->locktype;
21209
      OSTRACE3( "FCNTL_LOCKSTATE %d lock=%d\n", ((os2File*)id)->h, ((os2File*)id)->locktype );
21817
      OSTRACE(( "FCNTL_LOCKSTATE %d lock=%d\n",
21818
                ((os2File*)id)->h, ((os2File*)id)->locktype ));
21210
      return SQLITE_OK;
21819
      return SQLITE_OK;
21211
    }
21820
    }
21212
  }
21821
  }
 Lines 21393-21399   static int getTempname(int nBuf, char *z Link Here 
21393
    zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
22002
    zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
21394
  }
22003
  }
21395
  zBuf[j] = 0;
22004
  zBuf[j] = 0;
21396
  OSTRACE2( "TEMP FILENAME: %s\n", zBuf );
22005
  OSTRACE(( "TEMP FILENAME: %s\n", zBuf ));
21397
  return SQLITE_OK;
22006
  return SQLITE_OK;
21398
}
22007
}
21399
22008
 Lines 21456-21485   static int os2Open( Link Here 
21456
22065
21457
  memset( pFile, 0, sizeof(*pFile) );
22066
  memset( pFile, 0, sizeof(*pFile) );
21458
22067
21459
  OSTRACE2( "OPEN want %d\n", flags );
22068
  OSTRACE(( "OPEN want %d\n", flags ));
21460
22069
21461
  if( flags & SQLITE_OPEN_READWRITE ){
22070
  if( flags & SQLITE_OPEN_READWRITE ){
21462
    ulOpenMode |= OPEN_ACCESS_READWRITE;
22071
    ulOpenMode |= OPEN_ACCESS_READWRITE;
21463
    OSTRACE1( "OPEN read/write\n" );
22072
    OSTRACE(( "OPEN read/write\n" ));
21464
  }else{
22073
  }else{
21465
    ulOpenMode |= OPEN_ACCESS_READONLY;
22074
    ulOpenMode |= OPEN_ACCESS_READONLY;
21466
    OSTRACE1( "OPEN read only\n" );
22075
    OSTRACE(( "OPEN read only\n" ));
21467
  }
22076
  }
21468
22077
21469
  if( flags & SQLITE_OPEN_CREATE ){
22078
  if( flags & SQLITE_OPEN_CREATE ){
21470
    ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW;
22079
    ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW;
21471
    OSTRACE1( "OPEN open new/create\n" );
22080
    OSTRACE(( "OPEN open new/create\n" ));
21472
  }else{
22081
  }else{
21473
    ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_FAIL_IF_NEW;
22082
    ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_FAIL_IF_NEW;
21474
    OSTRACE1( "OPEN open existing\n" );
22083
    OSTRACE(( "OPEN open existing\n" ));
21475
  }
22084
  }
21476
22085
21477
  if( flags & SQLITE_OPEN_MAIN_DB ){
22086
  if( flags & SQLITE_OPEN_MAIN_DB ){
21478
    ulOpenMode |= OPEN_SHARE_DENYNONE;
22087
    ulOpenMode |= OPEN_SHARE_DENYNONE;
21479
    OSTRACE1( "OPEN share read/write\n" );
22088
    OSTRACE(( "OPEN share read/write\n" ));
21480
  }else{
22089
  }else{
21481
    ulOpenMode |= OPEN_SHARE_DENYWRITE;
22090
    ulOpenMode |= OPEN_SHARE_DENYWRITE;
21482
    OSTRACE1( "OPEN share read only\n" );
22091
    OSTRACE(( "OPEN share read only\n" ));
21483
  }
22092
  }
21484
22093
21485
  if( flags & SQLITE_OPEN_DELETEONCLOSE ){
22094
  if( flags & SQLITE_OPEN_DELETEONCLOSE ){
 Lines 21489-21498   static int os2Open( Link Here 
21489
#endif
22098
#endif
21490
    os2FullPathname( pVfs, zName, CCHMAXPATH, pathUtf8 );
22099
    os2FullPathname( pVfs, zName, CCHMAXPATH, pathUtf8 );
21491
    pFile->pathToDel = convertUtf8PathToCp( pathUtf8 );
22100
    pFile->pathToDel = convertUtf8PathToCp( pathUtf8 );
21492
    OSTRACE1( "OPEN hidden/delete on close file attributes\n" );
22101
    OSTRACE(( "OPEN hidden/delete on close file attributes\n" ));
21493
  }else{
22102
  }else{
21494
    pFile->pathToDel = NULL;
22103
    pFile->pathToDel = NULL;
21495
    OSTRACE1( "OPEN normal file attribute\n" );
22104
    OSTRACE(( "OPEN normal file attribute\n" ));
21496
  }
22105
  }
21497
22106
21498
  /* always open in random access mode for possibly better speed */
22107
  /* always open in random access mode for possibly better speed */
 Lines 21511-21523   static int os2Open( Link Here 
21511
                (PEAOP2)NULL );
22120
                (PEAOP2)NULL );
21512
  free( zNameCp );
22121
  free( zNameCp );
21513
  if( rc != NO_ERROR ){
22122
  if( rc != NO_ERROR ){
21514
    OSTRACE7( "OPEN Invalid handle rc=%d: zName=%s, ulAction=%#lx, ulAttr=%#lx, ulFlags=%#lx, ulMode=%#lx\n",
22123
    OSTRACE(( "OPEN Invalid handle rc=%d: zName=%s, ulAction=%#lx, ulAttr=%#lx, ulFlags=%#lx, ulMode=%#lx\n",
21515
              rc, zName, ulAction, ulFileAttribute, ulOpenFlags, ulOpenMode );
22124
              rc, zName, ulAction, ulFileAttribute, ulOpenFlags, ulOpenMode ));
21516
    if( pFile->pathToDel )
22125
    if( pFile->pathToDel )
21517
      free( pFile->pathToDel );
22126
      free( pFile->pathToDel );
21518
    pFile->pathToDel = NULL;
22127
    pFile->pathToDel = NULL;
21519
    if( flags & SQLITE_OPEN_READWRITE ){
22128
    if( flags & SQLITE_OPEN_READWRITE ){
21520
      OSTRACE2( "OPEN %d Invalid handle\n", ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE) );
22129
      OSTRACE(( "OPEN %d Invalid handle\n",
22130
                ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE) ));
21521
      return os2Open( pVfs, zName, id,
22131
      return os2Open( pVfs, zName, id,
21522
                      ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE),
22132
                      ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE),
21523
                      pOutFlags );
22133
                      pOutFlags );
 Lines 21533-21539   static int os2Open( Link Here 
21533
  pFile->pMethod = &os2IoMethod;
22143
  pFile->pMethod = &os2IoMethod;
21534
  pFile->h = h;
22144
  pFile->h = h;
21535
  OpenCounter(+1);
22145
  OpenCounter(+1);
21536
  OSTRACE3( "OPEN %d pOutFlags=%d\n", pFile->h, pOutFlags );
22146
  OSTRACE(( "OPEN %d pOutFlags=%d\n", pFile->h, pOutFlags ));
21537
  return SQLITE_OK;
22147
  return SQLITE_OK;
21538
}
22148
}
21539
22149
 Lines 21550-21556   static int os2Delete( Link Here 
21550
  SimulateIOError( return SQLITE_IOERR_DELETE );
22160
  SimulateIOError( return SQLITE_IOERR_DELETE );
21551
  rc = DosDelete( (PSZ)zFilenameCp );
22161
  rc = DosDelete( (PSZ)zFilenameCp );
21552
  free( zFilenameCp );
22162
  free( zFilenameCp );
21553
  OSTRACE2( "DELETE \"%s\"\n", zFilename );
22163
  OSTRACE(( "DELETE \"%s\"\n", zFilename ));
21554
  return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_DELETE;
22164
  return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_DELETE;
21555
}
22165
}
21556
22166
 Lines 21571-21587   static int os2Access( Link Here 
21571
  rc = DosQueryPathInfo( (PSZ)zFilenameCp, FIL_STANDARD,
22181
  rc = DosQueryPathInfo( (PSZ)zFilenameCp, FIL_STANDARD,
21572
                         &fsts3ConfigInfo, sizeof(FILESTATUS3) );
22182
                         &fsts3ConfigInfo, sizeof(FILESTATUS3) );
21573
  free( zFilenameCp );
22183
  free( zFilenameCp );
21574
  OSTRACE4( "ACCESS fsts3ConfigInfo.attrFile=%d flags=%d rc=%d\n",
22184
  OSTRACE(( "ACCESS fsts3ConfigInfo.attrFile=%d flags=%d rc=%d\n",
21575
            fsts3ConfigInfo.attrFile, flags, rc );
22185
            fsts3ConfigInfo.attrFile, flags, rc ));
21576
  switch( flags ){
22186
  switch( flags ){
21577
    case SQLITE_ACCESS_READ:
22187
    case SQLITE_ACCESS_READ:
21578
    case SQLITE_ACCESS_EXISTS:
22188
    case SQLITE_ACCESS_EXISTS:
21579
      rc = (rc == NO_ERROR);
22189
      rc = (rc == NO_ERROR);
21580
      OSTRACE3( "ACCESS %s access of read and exists  rc=%d\n", zFilename, rc );
22190
      OSTRACE(( "ACCESS %s access of read and exists  rc=%d\n", zFilename, rc));
21581
      break;
22191
      break;
21582
    case SQLITE_ACCESS_READWRITE:
22192
    case SQLITE_ACCESS_READWRITE:
21583
      rc = (rc == NO_ERROR) && ( (fsts3ConfigInfo.attrFile & FILE_READONLY) == 0 );
22193
      rc = (rc == NO_ERROR) && ( (fsts3ConfigInfo.attrFile & FILE_READONLY) == 0 );
21584
      OSTRACE3( "ACCESS %s access of read/write  rc=%d\n", zFilename, rc );
22194
      OSTRACE(( "ACCESS %s access of read/write  rc=%d\n", zFilename, rc ));
21585
      break;
22195
      break;
21586
    default:
22196
    default:
21587
      assert( !"Invalid flags argument" );
22197
      assert( !"Invalid flags argument" );
 Lines 21791-21797   SQLITE_API int sqlite3_os_init(void){ Link Here 
21791
    os2Randomness,     /* xRandomness */
22401
    os2Randomness,     /* xRandomness */
21792
    os2Sleep,          /* xSleep */
22402
    os2Sleep,          /* xSleep */
21793
    os2CurrentTime,    /* xCurrentTime */
22403
    os2CurrentTime,    /* xCurrentTime */
21794
    os2GetLastError    /* xGetLastError */
22404
    os2GetLastError,   /* xGetLastError */
21795
  };
22405
  };
21796
  sqlite3_vfs_register(&os2Vfs, 1);
22406
  sqlite3_vfs_register(&os2Vfs, 1);
21797
  initUconvObjects();
22407
  initUconvObjects();
 Lines 21925-21930   SQLITE_API int sqlite3_os_end(void){ Link Here 
21925
#include <unistd.h>
22535
#include <unistd.h>
21926
#include <sys/time.h>
22536
#include <sys/time.h>
21927
#include <errno.h>
22537
#include <errno.h>
22538
#include <sys/mman.h>
21928
22539
21929
#if SQLITE_ENABLE_LOCKING_STYLE
22540
#if SQLITE_ENABLE_LOCKING_STYLE
21930
# include <sys/ioctl.h>
22541
# include <sys/ioctl.h>
 Lines 21979-21984   SQLITE_API int sqlite3_os_end(void){ Link Here 
21979
*/
22590
*/
21980
#define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
22591
#define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
21981
22592
22593
/* Forward references */
22594
typedef struct unixShm unixShm;               /* Connection shared memory */
22595
typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
22596
typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
22597
typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
21982
22598
21983
/*
22599
/*
21984
** Sometimes, after a file handle is closed by SQLite, the file descriptor
22600
** Sometimes, after a file handle is closed by SQLite, the file descriptor
 Lines 21986-21992   SQLITE_API int sqlite3_os_end(void){ Link Here 
21986
** structure are used to store the file descriptor while waiting for an
22602
** structure are used to store the file descriptor while waiting for an
21987
** opportunity to either close or reuse it.
22603
** opportunity to either close or reuse it.
21988
*/
22604
*/
21989
typedef struct UnixUnusedFd UnixUnusedFd;
21990
struct UnixUnusedFd {
22605
struct UnixUnusedFd {
21991
  int fd;                   /* File descriptor to close */
22606
  int fd;                   /* File descriptor to close */
21992
  int flags;                /* Flags this file descriptor was opened with */
22607
  int flags;                /* Flags this file descriptor was opened with */
 Lines 22000-22026   struct UnixUnusedFd { Link Here 
22000
typedef struct unixFile unixFile;
22615
typedef struct unixFile unixFile;
22001
struct unixFile {
22616
struct unixFile {
22002
  sqlite3_io_methods const *pMethod;  /* Always the first entry */
22617
  sqlite3_io_methods const *pMethod;  /* Always the first entry */
22003
  struct unixOpenCnt *pOpen;       /* Info about all open fd's on this inode */
22618
  unixInodeInfo *pInode;              /* Info about locks on this inode */
22004
  struct unixLockInfo *pLock;      /* Info about locks on this inode */
22619
  int h;                              /* The file descriptor */
22005
  int h;                           /* The file descriptor */
22620
  int dirfd;                          /* File descriptor for the directory */
22006
  int dirfd;                       /* File descriptor for the directory */
22621
  unsigned char eFileLock;            /* The type of lock held on this fd */
22007
  unsigned char locktype;          /* The type of lock held on this fd */
22622
  int lastErrno;                      /* The unix errno from last I/O error */
22008
  int lastErrno;                   /* The unix errno from the last I/O error */
22623
  void *lockingContext;               /* Locking style specific state */
22009
  void *lockingContext;            /* Locking style specific state */
22624
  UnixUnusedFd *pUnused;              /* Pre-allocated UnixUnusedFd */
22010
  UnixUnusedFd *pUnused;           /* Pre-allocated UnixUnusedFd */
22625
  int fileFlags;                      /* Miscellanous flags */
22011
  int fileFlags;                   /* Miscellanous flags */
22626
  const char *zPath;                  /* Name of the file */
22627
  unixShm *pShm;                      /* Shared memory segment information */
22628
  int szChunk;                        /* Configured by FCNTL_CHUNK_SIZE */
22012
#if SQLITE_ENABLE_LOCKING_STYLE
22629
#if SQLITE_ENABLE_LOCKING_STYLE
22013
  int openFlags;                   /* The flags specified at open() */
22630
  int openFlags;                      /* The flags specified at open() */
22014
#endif
22631
#endif
22015
#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
22632
#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
22016
  unsigned fsFlags;                 /* cached details from statfs() */
22633
  unsigned fsFlags;                   /* cached details from statfs() */
22017
#endif
22018
#if SQLITE_THREADSAFE && defined(__linux__)
22019
  pthread_t tid;                   /* The thread that "owns" this unixFile */
22020
#endif
22634
#endif
22021
#if OS_VXWORKS
22635
#if OS_VXWORKS
22022
  int isDelete;                    /* Delete on close if true */
22636
  int isDelete;                       /* Delete on close if true */
22023
  struct vxworksFileId *pId;       /* Unique file ID */
22637
  struct vxworksFileId *pId;          /* Unique file ID */
22024
#endif
22638
#endif
22025
#ifndef NDEBUG
22639
#ifndef NDEBUG
22026
  /* The next group of variables are used to track whether or not the
22640
  /* The next group of variables are used to track whether or not the
 Lines 22085-22107   struct unixFile { Link Here 
22085
22699
22086
#ifdef SQLITE_DEBUG
22700
#ifdef SQLITE_DEBUG
22087
SQLITE_PRIVATE int sqlite3OSTrace = 0;
22701
SQLITE_PRIVATE int sqlite3OSTrace = 0;
22088
#define OSTRACE1(X)         if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
22702
#define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
22089
#define OSTRACE2(X,Y)       if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
22703
#else
22090
#define OSTRACE3(X,Y,Z)     if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
22704
#define OSTRACE(X)
22091
#define OSTRACE4(X,Y,Z,A)   if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
22092
#define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
22093
#define OSTRACE6(X,Y,Z,A,B,C) \
22094
    if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
22095
#define OSTRACE7(X,Y,Z,A,B,C,D) \
22096
    if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
22097
#else
22098
#define OSTRACE1(X)
22099
#define OSTRACE2(X,Y)
22100
#define OSTRACE3(X,Y,Z)
22101
#define OSTRACE4(X,Y,Z,A)
22102
#define OSTRACE5(X,Y,Z,A,B)
22103
#define OSTRACE6(X,Y,Z,A,B,C)
22104
#define OSTRACE7(X,Y,Z,A,B,C,D)
22105
#endif
22705
#endif
22106
22706
22107
/*
22707
/*
 Lines 22311-22317   SQLITE_API int sqlite3_open_file_count = Link Here 
22311
22911
22312
/*
22912
/*
22313
** Helper functions to obtain and relinquish the global mutex. The
22913
** Helper functions to obtain and relinquish the global mutex. The
22314
** global mutex is used to protect the unixOpenCnt, unixLockInfo and
22914
** global mutex is used to protect the unixInodeInfo and
22315
** vxworksFileId objects used by this file, all of which may be 
22915
** vxworksFileId objects used by this file, all of which may be 
22316
** shared by multiple threads.
22916
** shared by multiple threads.
22317
**
22917
**
 Lines 22342-22349   static int unixMutexHeld(void) { Link Here 
22342
** binaries. This returns the string represetation of the supplied
22942
** binaries. This returns the string represetation of the supplied
22343
** integer lock-type.
22943
** integer lock-type.
22344
*/
22944
*/
22345
static const char *locktypeName(int locktype){
22945
static const char *azFileLock(int eFileLock){
22346
  switch( locktype ){
22946
  switch( eFileLock ){
22347
    case NO_LOCK: return "NONE";
22947
    case NO_LOCK: return "NONE";
22348
    case SHARED_LOCK: return "SHARED";
22948
    case SHARED_LOCK: return "SHARED";
22349
    case RESERVED_LOCK: return "RESERVED";
22949
    case RESERVED_LOCK: return "RESERVED";
 Lines 22680-22692   static void vxworksReleaseFileId(struct Link Here 
22680
**
23280
**
22681
** If you close a file descriptor that points to a file that has locks,
23281
** If you close a file descriptor that points to a file that has locks,
22682
** all locks on that file that are owned by the current process are
23282
** all locks on that file that are owned by the current process are
22683
** released.  To work around this problem, each unixFile structure contains
23283
** released.  To work around this problem, each unixInodeInfo object
22684
** a pointer to an unixOpenCnt structure.  There is one unixOpenCnt structure
23284
** maintains a count of the number of pending locks on tha inode.
22685
** per open inode, which means that multiple unixFile can point to a single
23285
** When an attempt is made to close an unixFile, if there are
22686
** unixOpenCnt.  When an attempt is made to close an unixFile, if there are
22687
** other unixFile open on the same inode that are holding locks, the call
23286
** other unixFile open on the same inode that are holding locks, the call
22688
** to close() the file descriptor is deferred until all of the locks clear.
23287
** to close() the file descriptor is deferred until all of the locks clear.
22689
** The unixOpenCnt structure keeps a list of file descriptors that need to
23288
** The unixInodeInfo structure keeps a list of file descriptors that need to
22690
** be closed and that list is walked (and cleared) when the last lock
23289
** be closed and that list is walked (and cleared) when the last lock
22691
** clears.
23290
** clears.
22692
**
23291
**
 Lines 22701-22746   static void vxworksReleaseFileId(struct Link Here 
22701
** in thread B.  But there is no way to know at compile-time which
23300
** in thread B.  But there is no way to know at compile-time which
22702
** threading library is being used.  So there is no way to know at
23301
** threading library is being used.  So there is no way to know at
22703
** compile-time whether or not thread A can override locks on thread B.
23302
** compile-time whether or not thread A can override locks on thread B.
22704
** We have to do a run-time check to discover the behavior of the
23303
** One has to do a run-time check to discover the behavior of the
22705
** current process.
23304
** current process.
22706
**
23305
**
22707
** On systems where thread A is unable to modify locks created by
23306
** SQLite used to support LinuxThreads.  But support for LinuxThreads
22708
** thread B, we have to keep track of which thread created each
23307
** was dropped beginning with version 3.7.0.  SQLite will still work with
22709
** lock.  Hence there is an extra field in the key to the unixLockInfo
23308
** LinuxThreads provided that (1) there is no more than one connection 
22710
** structure to record this information.  And on those systems it
23309
** per database file in the same process and (2) database connections
22711
** is illegal to begin a transaction in one thread and finish it
23310
** do not move across threads.
22712
** in another.  For this latter restriction, there is no work-around.
23311
*/
22713
** It is a limitation of LinuxThreads.
22714
*/
22715
22716
/*
22717
** Set or check the unixFile.tid field.  This field is set when an unixFile
22718
** is first opened.  All subsequent uses of the unixFile verify that the
22719
** same thread is operating on the unixFile.  Some operating systems do
22720
** not allow locks to be overridden by other threads and that restriction
22721
** means that sqlite3* database handles cannot be moved from one thread
22722
** to another while locks are held.
22723
**
22724
** Version 3.3.1 (2006-01-15):  unixFile can be moved from one thread to
22725
** another as long as we are running on a system that supports threads
22726
** overriding each others locks (which is now the most common behavior)
22727
** or if no locks are held.  But the unixFile.pLock field needs to be
22728
** recomputed because its key includes the thread-id.  See the 
22729
** transferOwnership() function below for additional information
22730
*/
22731
#if SQLITE_THREADSAFE && defined(__linux__)
22732
# define SET_THREADID(X)   (X)->tid = pthread_self()
22733
# define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
22734
                            !pthread_equal((X)->tid, pthread_self()))
22735
#else
22736
# define SET_THREADID(X)
22737
# define CHECK_THREADID(X) 0
22738
#endif
22739
23312
22740
/*
23313
/*
22741
** An instance of the following structure serves as the key used
23314
** An instance of the following structure serves as the key used
22742
** to locate a particular unixOpenCnt structure given its inode.  This
23315
** to locate a particular unixInodeInfo object.
22743
** is the same as the unixLockKey except that the thread ID is omitted.
22744
*/
23316
*/
22745
struct unixFileId {
23317
struct unixFileId {
22746
  dev_t dev;                  /* Device number */
23318
  dev_t dev;                  /* Device number */
 Lines 22752-22774   struct unixFileId { Link Here 
22752
};
23324
};
22753
23325
22754
/*
23326
/*
22755
** An instance of the following structure serves as the key used
22756
** to locate a particular unixLockInfo structure given its inode.
22757
**
22758
** If threads cannot override each others locks (LinuxThreads), then we
22759
** set the unixLockKey.tid field to the thread ID.  If threads can override
22760
** each others locks (Posix and NPTL) then tid is always set to zero.
22761
** tid is omitted if we compile without threading support or on an OS
22762
** other than linux.
22763
*/
22764
struct unixLockKey {
22765
  struct unixFileId fid;  /* Unique identifier for the file */
22766
#if SQLITE_THREADSAFE && defined(__linux__)
22767
  pthread_t tid;  /* Thread ID of lock owner. Zero if not using LinuxThreads */
22768
#endif
22769
};
22770
22771
/*
22772
** An instance of the following structure is allocated for each open
23327
** An instance of the following structure is allocated for each open
22773
** inode.  Or, on LinuxThreads, there is one of these structures for
23328
** inode.  Or, on LinuxThreads, there is one of these structures for
22774
** each inode opened by each thread.
23329
** each inode opened by each thread.
 Lines 22777-23006   struct unixLockKey { Link Here 
22777
** structure contains a pointer to an instance of this object and this
23332
** structure contains a pointer to an instance of this object and this
22778
** object keeps a count of the number of unixFile pointing to it.
23333
** object keeps a count of the number of unixFile pointing to it.
22779
*/
23334
*/
22780
struct unixLockInfo {
23335
struct unixInodeInfo {
22781
  struct unixLockKey lockKey;     /* The lookup key */
23336
  struct unixFileId fileId;       /* The lookup key */
22782
  int cnt;                        /* Number of SHARED locks held */
23337
  int nShared;                    /* Number of SHARED locks held */
22783
  int locktype;                   /* One of SHARED_LOCK, RESERVED_LOCK etc. */
23338
  int eFileLock;                  /* One of SHARED_LOCK, RESERVED_LOCK etc. */
22784
  int nRef;                       /* Number of pointers to this structure */
23339
  int nRef;                       /* Number of pointers to this structure */
23340
  unixShmNode *pShmNode;          /* Shared memory associated with this inode */
23341
  int nLock;                      /* Number of outstanding file locks */
23342
  UnixUnusedFd *pUnused;          /* Unused file descriptors to close */
23343
  unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
23344
  unixInodeInfo *pPrev;           /*    .... doubly linked */
22785
#if defined(SQLITE_ENABLE_LOCKING_STYLE)
23345
#if defined(SQLITE_ENABLE_LOCKING_STYLE)
22786
  unsigned long long sharedByte;  /* for AFP simulated shared lock */
23346
  unsigned long long sharedByte;  /* for AFP simulated shared lock */
22787
#endif
23347
#endif
22788
  struct unixLockInfo *pNext;     /* List of all unixLockInfo objects */
22789
  struct unixLockInfo *pPrev;     /*    .... doubly linked */
22790
};
22791
22792
/*
22793
** An instance of the following structure is allocated for each open
22794
** inode.  This structure keeps track of the number of locks on that
22795
** inode.  If a close is attempted against an inode that is holding
22796
** locks, the close is deferred until all locks clear by adding the
22797
** file descriptor to be closed to the pending list.
22798
**
22799
** TODO:  Consider changing this so that there is only a single file
22800
** descriptor for each open file, even when it is opened multiple times.
22801
** The close() system call would only occur when the last database
22802
** using the file closes.
22803
*/
22804
struct unixOpenCnt {
22805
  struct unixFileId fileId;   /* The lookup key */
22806
  int nRef;                   /* Number of pointers to this structure */
22807
  int nLock;                  /* Number of outstanding locks */
22808
  UnixUnusedFd *pUnused;      /* Unused file descriptors to close */
22809
#if OS_VXWORKS
23348
#if OS_VXWORKS
22810
  sem_t *pSem;                     /* Named POSIX semaphore */
23349
  sem_t *pSem;                    /* Named POSIX semaphore */
22811
  char aSemName[MAX_PATHNAME+2];   /* Name of that semaphore */
23350
  char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
22812
#endif
23351
#endif
22813
  struct unixOpenCnt *pNext, *pPrev;   /* List of all unixOpenCnt objects */
23352
};
22814
};
23353
22815
23354
/*
22816
/*
23355
** A lists of all unixInodeInfo objects.
22817
** Lists of all unixLockInfo and unixOpenCnt objects.  These used to be hash
23356
*/
22818
** tables.  But the number of objects is rarely more than a dozen and
23357
static unixInodeInfo *inodeList = 0;
22819
** never exceeds a few thousand.  And lookup is not on a critical
23358
22820
** path so a simple linked list will suffice.
23359
/*
22821
*/
23360
** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
22822
static struct unixLockInfo *lockList = 0;
23361
** If all such file descriptors are closed without error, the list is
22823
static struct unixOpenCnt *openList = 0;
23362
** cleared and SQLITE_OK returned.
22824
23363
**
22825
/*
23364
** Otherwise, if an error occurs, then successfully closed file descriptor
22826
** This variable remembers whether or not threads can override each others
23365
** entries are removed from the list, and SQLITE_IOERR_CLOSE returned. 
22827
** locks.
23366
** not deleted and SQLITE_IOERR_CLOSE returned.
22828
**
22829
**    0:  No.  Threads cannot override each others locks.  (LinuxThreads)
22830
**    1:  Yes.  Threads can override each others locks.  (Posix & NLPT)
22831
**   -1:  We don't know yet.
22832
**
22833
** On some systems, we know at compile-time if threads can override each
22834
** others locks.  On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
22835
** will be set appropriately.  On other systems, we have to check at
22836
** runtime.  On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
22837
** undefined.
22838
**
22839
** This variable normally has file scope only.  But during testing, we make
22840
** it a global so that the test code can change its value in order to verify
22841
** that the right stuff happens in either case.
22842
*/
22843
#if SQLITE_THREADSAFE && defined(__linux__)
22844
#  ifndef SQLITE_THREAD_OVERRIDE_LOCK
22845
#    define SQLITE_THREAD_OVERRIDE_LOCK -1
22846
#  endif
22847
#  ifdef SQLITE_TEST
22848
int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
22849
#  else
22850
static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
22851
#  endif
22852
#endif
22853
22854
/*
22855
** This structure holds information passed into individual test
22856
** threads by the testThreadLockingBehavior() routine.
22857
*/
22858
struct threadTestData {
22859
  int fd;                /* File to be locked */
22860
  struct flock lock;     /* The locking operation */
22861
  int result;            /* Result of the locking operation */
22862
};
22863
22864
#if SQLITE_THREADSAFE && defined(__linux__)
22865
/*
22866
** This function is used as the main routine for a thread launched by
22867
** testThreadLockingBehavior(). It tests whether the shared-lock obtained
22868
** by the main thread in testThreadLockingBehavior() conflicts with a
22869
** hypothetical write-lock obtained by this thread on the same file.
22870
**
22871
** The write-lock is not actually acquired, as this is not possible if 
22872
** the file is open in read-only mode (see ticket #3472).
22873
*/ 
23367
*/ 
22874
static void *threadLockingTest(void *pArg){
23368
static int closePendingFds(unixFile *pFile){
22875
  struct threadTestData *pData = (struct threadTestData*)pArg;
23369
  int rc = SQLITE_OK;
22876
  pData->result = fcntl(pData->fd, F_GETLK, &pData->lock);
23370
  unixInodeInfo *pInode = pFile->pInode;
22877
  return pArg;
23371
  UnixUnusedFd *pError = 0;
22878
}
23372
  UnixUnusedFd *p;
22879
#endif /* SQLITE_THREADSAFE && defined(__linux__) */
23373
  UnixUnusedFd *pNext;
22880
23374
  for(p=pInode->pUnused; p; p=pNext){
22881
23375
    pNext = p->pNext;
22882
#if SQLITE_THREADSAFE && defined(__linux__)
23376
    if( close(p->fd) ){
22883
/*
23377
      pFile->lastErrno = errno;
22884
** This procedure attempts to determine whether or not threads
23378
      rc = SQLITE_IOERR_CLOSE;
22885
** can override each others locks then sets the 
23379
      p->pNext = pError;
22886
** threadsOverrideEachOthersLocks variable appropriately.
23380
      pError = p;
22887
*/
23381
    }else{
22888
static void testThreadLockingBehavior(int fd_orig){
23382
      sqlite3_free(p);
22889
  int fd;
23383
    }
22890
  int rc;
23384
  }
22891
  struct threadTestData d;
23385
  pInode->pUnused = pError;
22892
  struct flock l;
23386
  return rc;
22893
  pthread_t t;
23387
}
22894
23388
22895
  fd = dup(fd_orig);
23389
/*
22896
  if( fd<0 ) return;
23390
** Release a unixInodeInfo structure previously allocated by findInodeInfo().
22897
  memset(&l, 0, sizeof(l));
22898
  l.l_type = F_RDLCK;
22899
  l.l_len = 1;
22900
  l.l_start = 0;
22901
  l.l_whence = SEEK_SET;
22902
  rc = fcntl(fd_orig, F_SETLK, &l);
22903
  if( rc!=0 ) return;
22904
  memset(&d, 0, sizeof(d));
22905
  d.fd = fd;
22906
  d.lock = l;
22907
  d.lock.l_type = F_WRLCK;
22908
  if( pthread_create(&t, 0, threadLockingTest, &d)==0 ){
22909
    pthread_join(t, 0);
22910
  }
22911
  close(fd);
22912
  if( d.result!=0 ) return;
22913
  threadsOverrideEachOthersLocks = (d.lock.l_type==F_UNLCK);
22914
}
22915
#endif /* SQLITE_THREADSAFE && defined(__linux__) */
22916
22917
/*
22918
** Release a unixLockInfo structure previously allocated by findLockInfo().
22919
**
23391
**
22920
** The mutex entered using the unixEnterMutex() function must be held
23392
** The mutex entered using the unixEnterMutex() function must be held
22921
** when this function is called.
23393
** when this function is called.
22922
*/
23394
*/
22923
static void releaseLockInfo(struct unixLockInfo *pLock){
23395
static void releaseInodeInfo(unixFile *pFile){
23396
  unixInodeInfo *pInode = pFile->pInode;
22924
  assert( unixMutexHeld() );
23397
  assert( unixMutexHeld() );
22925
  if( pLock ){
23398
  if( pInode ){
22926
    pLock->nRef--;
23399
    pInode->nRef--;
22927
    if( pLock->nRef==0 ){
23400
    if( pInode->nRef==0 ){
22928
      if( pLock->pPrev ){
23401
      assert( pInode->pShmNode==0 );
22929
        assert( pLock->pPrev->pNext==pLock );
23402
      closePendingFds(pFile);
22930
        pLock->pPrev->pNext = pLock->pNext;
23403
      if( pInode->pPrev ){
22931
      }else{
23404
        assert( pInode->pPrev->pNext==pInode );
22932
        assert( lockList==pLock );
23405
        pInode->pPrev->pNext = pInode->pNext;
22933
        lockList = pLock->pNext;
23406
      }else{
22934
      }
23407
        assert( inodeList==pInode );
22935
      if( pLock->pNext ){
23408
        inodeList = pInode->pNext;
22936
        assert( pLock->pNext->pPrev==pLock );
23409
      }
22937
        pLock->pNext->pPrev = pLock->pPrev;
23410
      if( pInode->pNext ){
22938
      }
23411
        assert( pInode->pNext->pPrev==pInode );
22939
      sqlite3_free(pLock);
23412
        pInode->pNext->pPrev = pInode->pPrev;
22940
    }
23413
      }
22941
  }
23414
      sqlite3_free(pInode);
22942
}
23415
    }
22943
23416
  }
22944
/*
23417
}
22945
** Release a unixOpenCnt structure previously allocated by findLockInfo().
23418
23419
/*
23420
** Given a file descriptor, locate the unixInodeInfo object that
23421
** describes that file descriptor.  Create a new one if necessary.  The
23422
** return value might be uninitialized if an error occurs.
22946
**
23423
**
22947
** The mutex entered using the unixEnterMutex() function must be held
23424
** The mutex entered using the unixEnterMutex() function must be held
22948
** when this function is called.
23425
** when this function is called.
22949
*/
22950
static void releaseOpenCnt(struct unixOpenCnt *pOpen){
22951
  assert( unixMutexHeld() );
22952
  if( pOpen ){
22953
    pOpen->nRef--;
22954
    if( pOpen->nRef==0 ){
22955
      if( pOpen->pPrev ){
22956
        assert( pOpen->pPrev->pNext==pOpen );
22957
        pOpen->pPrev->pNext = pOpen->pNext;
22958
      }else{
22959
        assert( openList==pOpen );
22960
        openList = pOpen->pNext;
22961
      }
22962
      if( pOpen->pNext ){
22963
        assert( pOpen->pNext->pPrev==pOpen );
22964
        pOpen->pNext->pPrev = pOpen->pPrev;
22965
      }
22966
#if SQLITE_THREADSAFE && defined(__linux__)
22967
      assert( !pOpen->pUnused || threadsOverrideEachOthersLocks==0 );
22968
#endif
22969
22970
      /* If pOpen->pUnused is not null, then memory and file-descriptors
22971
      ** are leaked.
22972
      **
22973
      ** This will only happen if, under Linuxthreads, the user has opened
22974
      ** a transaction in one thread, then attempts to close the database
22975
      ** handle from another thread (without first unlocking the db file).
22976
      ** This is a misuse.  */
22977
      sqlite3_free(pOpen);
22978
    }
22979
  }
22980
}
22981
22982
/*
22983
** Given a file descriptor, locate unixLockInfo and unixOpenCnt structures that
22984
** describes that file descriptor.  Create new ones if necessary.  The
22985
** return values might be uninitialized if an error occurs.
22986
**
22987
** The mutex entered using the unixEnterMutex() function must be held
22988
** when this function is called.
22989
**
23426
**
22990
** Return an appropriate error code.
23427
** Return an appropriate error code.
22991
*/
23428
*/
22992
static int findLockInfo(
23429
static int findInodeInfo(
22993
  unixFile *pFile,               /* Unix file with file desc used in the key */
23430
  unixFile *pFile,               /* Unix file with file desc used in the key */
22994
  struct unixLockInfo **ppLock,  /* Return the unixLockInfo structure here */
23431
  unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
22995
  struct unixOpenCnt **ppOpen    /* Return the unixOpenCnt structure here */
22996
){
23432
){
22997
  int rc;                        /* System call return code */
23433
  int rc;                        /* System call return code */
22998
  int fd;                        /* The file descriptor for pFile */
23434
  int fd;                        /* The file descriptor for pFile */
22999
  struct unixLockKey lockKey;    /* Lookup key for the unixLockInfo structure */
23435
  struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
23000
  struct unixFileId fileId;      /* Lookup key for the unixOpenCnt struct */
23001
  struct stat statbuf;           /* Low-level file information */
23436
  struct stat statbuf;           /* Low-level file information */
23002
  struct unixLockInfo *pLock = 0;/* Candidate unixLockInfo object */
23437
  unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
23003
  struct unixOpenCnt *pOpen;     /* Candidate unixOpenCnt object */
23004
23438
23005
  assert( unixMutexHeld() );
23439
  assert( unixMutexHeld() );
23006
23440
 Lines 23042-23163   static int findLockInfo( Link Here 
23042
  }
23476
  }
23043
#endif
23477
#endif
23044
23478
23045
  memset(&lockKey, 0, sizeof(lockKey));
23479
  memset(&fileId, 0, sizeof(fileId));
23046
  lockKey.fid.dev = statbuf.st_dev;
23480
  fileId.dev = statbuf.st_dev;
23047
#if OS_VXWORKS
23481
#if OS_VXWORKS
23048
  lockKey.fid.pId = pFile->pId;
23482
  fileId.pId = pFile->pId;
23049
#else
23483
#else
23050
  lockKey.fid.ino = statbuf.st_ino;
23484
  fileId.ino = statbuf.st_ino;
23051
#endif
23485
#endif
23052
#if SQLITE_THREADSAFE && defined(__linux__)
23486
  pInode = inodeList;
23053
  if( threadsOverrideEachOthersLocks<0 ){
23487
  while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
23054
    testThreadLockingBehavior(fd);
23488
    pInode = pInode->pNext;
23055
  }
23489
  }
23056
  lockKey.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
23490
  if( pInode==0 ){
23057
#endif
23491
    pInode = sqlite3_malloc( sizeof(*pInode) );
23058
  fileId = lockKey.fid;
23492
    if( pInode==0 ){
23059
  if( ppLock!=0 ){
23493
      return SQLITE_NOMEM;
23060
    pLock = lockList;
23494
    }
23061
    while( pLock && memcmp(&lockKey, &pLock->lockKey, sizeof(lockKey)) ){
23495
    memset(pInode, 0, sizeof(*pInode));
23062
      pLock = pLock->pNext;
23496
    memcpy(&pInode->fileId, &fileId, sizeof(fileId));
23063
    }
23497
    pInode->nRef = 1;
23064
    if( pLock==0 ){
23498
    pInode->pNext = inodeList;
23065
      pLock = sqlite3_malloc( sizeof(*pLock) );
23499
    pInode->pPrev = 0;
23066
      if( pLock==0 ){
23500
    if( inodeList ) inodeList->pPrev = pInode;
23067
        rc = SQLITE_NOMEM;
23501
    inodeList = pInode;
23068
        goto exit_findlockinfo;
23502
  }else{
23069
      }
23503
    pInode->nRef++;
23070
      memcpy(&pLock->lockKey,&lockKey,sizeof(lockKey));
23504
  }
23071
      pLock->nRef = 1;
23505
  *ppInode = pInode;
23072
      pLock->cnt = 0;
23506
  return SQLITE_OK;
23073
      pLock->locktype = 0;
23507
}
23074
#if defined(SQLITE_ENABLE_LOCKING_STYLE)
23075
      pLock->sharedByte = 0;
23076
#endif
23077
      pLock->pNext = lockList;
23078
      pLock->pPrev = 0;
23079
      if( lockList ) lockList->pPrev = pLock;
23080
      lockList = pLock;
23081
    }else{
23082
      pLock->nRef++;
23083
    }
23084
    *ppLock = pLock;
23085
  }
23086
  if( ppOpen!=0 ){
23087
    pOpen = openList;
23088
    while( pOpen && memcmp(&fileId, &pOpen->fileId, sizeof(fileId)) ){
23089
      pOpen = pOpen->pNext;
23090
    }
23091
    if( pOpen==0 ){
23092
      pOpen = sqlite3_malloc( sizeof(*pOpen) );
23093
      if( pOpen==0 ){
23094
        releaseLockInfo(pLock);
23095
        rc = SQLITE_NOMEM;
23096
        goto exit_findlockinfo;
23097
      }
23098
      memset(pOpen, 0, sizeof(*pOpen));
23099
      pOpen->fileId = fileId;
23100
      pOpen->nRef = 1;
23101
      pOpen->pNext = openList;
23102
      if( openList ) openList->pPrev = pOpen;
23103
      openList = pOpen;
23104
    }else{
23105
      pOpen->nRef++;
23106
    }
23107
    *ppOpen = pOpen;
23108
  }
23109
23110
exit_findlockinfo:
23111
  return rc;
23112
}
23113
23114
/*
23115
** If we are currently in a different thread than the thread that the
23116
** unixFile argument belongs to, then transfer ownership of the unixFile
23117
** over to the current thread.
23118
**
23119
** A unixFile is only owned by a thread on systems that use LinuxThreads.
23120
**
23121
** Ownership transfer is only allowed if the unixFile is currently unlocked.
23122
** If the unixFile is locked and an ownership is wrong, then return
23123
** SQLITE_MISUSE.  SQLITE_OK is returned if everything works.
23124
*/
23125
#if SQLITE_THREADSAFE && defined(__linux__)
23126
static int transferOwnership(unixFile *pFile){
23127
  int rc;
23128
  pthread_t hSelf;
23129
  if( threadsOverrideEachOthersLocks ){
23130
    /* Ownership transfers not needed on this system */
23131
    return SQLITE_OK;
23132
  }
23133
  hSelf = pthread_self();
23134
  if( pthread_equal(pFile->tid, hSelf) ){
23135
    /* We are still in the same thread */
23136
    OSTRACE1("No-transfer, same thread\n");
23137
    return SQLITE_OK;
23138
  }
23139
  if( pFile->locktype!=NO_LOCK ){
23140
    /* We cannot change ownership while we are holding a lock! */
23141
    return SQLITE_MISUSE_BKPT;
23142
  }
23143
  OSTRACE4("Transfer ownership of %d from %d to %d\n",
23144
            pFile->h, pFile->tid, hSelf);
23145
  pFile->tid = hSelf;
23146
  if (pFile->pLock != NULL) {
23147
    releaseLockInfo(pFile->pLock);
23148
    rc = findLockInfo(pFile, &pFile->pLock, 0);
23149
    OSTRACE5("LOCK    %d is now %s(%s,%d)\n", pFile->h,
23150
           locktypeName(pFile->locktype),
23151
           locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
23152
    return rc;
23153
  } else {
23154
    return SQLITE_OK;
23155
  }
23156
}
23157
#else  /* if not SQLITE_THREADSAFE */
23158
  /* On single-threaded builds, ownership transfer is a no-op */
23159
# define transferOwnership(X) SQLITE_OK
23160
#endif /* SQLITE_THREADSAFE */
23161
23508
23162
23509
23163
/*
23510
/*
 Lines 23174-23183   static int unixCheckReservedLock(sqlite3 Link Here 
23174
  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23521
  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23175
23522
23176
  assert( pFile );
23523
  assert( pFile );
23177
  unixEnterMutex(); /* Because pFile->pLock is shared across threads */
23524
  unixEnterMutex(); /* Because pFile->pInode is shared across threads */
23178
23525
23179
  /* Check if a thread in this process holds such a lock */
23526
  /* Check if a thread in this process holds such a lock */
23180
  if( pFile->pLock->locktype>SHARED_LOCK ){
23527
  if( pFile->pInode->eFileLock>SHARED_LOCK ){
23181
    reserved = 1;
23528
    reserved = 1;
23182
  }
23529
  }
23183
23530
 Lines 23201-23214   static int unixCheckReservedLock(sqlite3 Link Here 
23201
#endif
23548
#endif
23202
  
23549
  
23203
  unixLeaveMutex();
23550
  unixLeaveMutex();
23204
  OSTRACE4("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved);
23551
  OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
23205
23552
23206
  *pResOut = reserved;
23553
  *pResOut = reserved;
23207
  return rc;
23554
  return rc;
23208
}
23555
}
23209
23556
23210
/*
23557
/*
23211
** Lock the file with the lock specified by parameter locktype - one
23558
** Lock the file with the lock specified by parameter eFileLock - one
23212
** of the following:
23559
** of the following:
23213
**
23560
**
23214
**     (1) SHARED_LOCK
23561
**     (1) SHARED_LOCK
 Lines 23231-23237   static int unixCheckReservedLock(sqlite3 Link Here 
23231
** This routine will only increase a lock.  Use the sqlite3OsUnlock()
23578
** This routine will only increase a lock.  Use the sqlite3OsUnlock()
23232
** routine to lower a locking level.
23579
** routine to lower a locking level.
23233
*/
23580
*/
23234
static int unixLock(sqlite3_file *id, int locktype){
23581
static int unixLock(sqlite3_file *id, int eFileLock){
23235
  /* The following describes the implementation of the various locks and
23582
  /* The following describes the implementation of the various locks and
23236
  ** lock transitions in terms of the POSIX advisory shared and exclusive
23583
  ** lock transitions in terms of the POSIX advisory shared and exclusive
23237
  ** lock primitives (called read-locks and write-locks below, to avoid
23584
  ** lock primitives (called read-locks and write-locks below, to avoid
 Lines 23272-23294   static int unixLock(sqlite3_file *id, in Link Here 
23272
  */
23619
  */
23273
  int rc = SQLITE_OK;
23620
  int rc = SQLITE_OK;
23274
  unixFile *pFile = (unixFile*)id;
23621
  unixFile *pFile = (unixFile*)id;
23275
  struct unixLockInfo *pLock = pFile->pLock;
23622
  unixInodeInfo *pInode = pFile->pInode;
23276
  struct flock lock;
23623
  struct flock lock;
23277
  int s = 0;
23624
  int s = 0;
23278
  int tErrno = 0;
23625
  int tErrno = 0;
23279
23626
23280
  assert( pFile );
23627
  assert( pFile );
23281
  OSTRACE7("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
23628
  OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
23282
      locktypeName(locktype), locktypeName(pFile->locktype),
23629
      azFileLock(eFileLock), azFileLock(pFile->eFileLock),
23283
      locktypeName(pLock->locktype), pLock->cnt , getpid());
23630
      azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
23284
23631
23285
  /* If there is already a lock of this type or more restrictive on the
23632
  /* If there is already a lock of this type or more restrictive on the
23286
  ** unixFile, do nothing. Don't use the end_lock: exit path, as
23633
  ** unixFile, do nothing. Don't use the end_lock: exit path, as
23287
  ** unixEnterMutex() hasn't been called yet.
23634
  ** unixEnterMutex() hasn't been called yet.
23288
  */
23635
  */
23289
  if( pFile->locktype>=locktype ){
23636
  if( pFile->eFileLock>=eFileLock ){
23290
    OSTRACE3("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
23637
    OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
23291
            locktypeName(locktype));
23638
            azFileLock(eFileLock)));
23292
    return SQLITE_OK;
23639
    return SQLITE_OK;
23293
  }
23640
  }
23294
23641
 Lines 23297-23324   static int unixLock(sqlite3_file *id, in Link Here 
23297
  **  (2) SQLite never explicitly requests a pendig lock.
23644
  **  (2) SQLite never explicitly requests a pendig lock.
23298
  **  (3) A shared lock is always held when a reserve lock is requested.
23645
  **  (3) A shared lock is always held when a reserve lock is requested.
23299
  */
23646
  */
23300
  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
23647
  assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
23301
  assert( locktype!=PENDING_LOCK );
23648
  assert( eFileLock!=PENDING_LOCK );
23302
  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
23649
  assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
23303
23650
23304
  /* This mutex is needed because pFile->pLock is shared across threads
23651
  /* This mutex is needed because pFile->pInode is shared across threads
23305
  */
23652
  */
23306
  unixEnterMutex();
23653
  unixEnterMutex();
23307
23654
  pInode = pFile->pInode;
23308
  /* Make sure the current thread owns the pFile.
23309
  */
23310
  rc = transferOwnership(pFile);
23311
  if( rc!=SQLITE_OK ){
23312
    unixLeaveMutex();
23313
    return rc;
23314
  }
23315
  pLock = pFile->pLock;
23316
23655
23317
  /* If some thread using this PID has a lock via a different unixFile*
23656
  /* If some thread using this PID has a lock via a different unixFile*
23318
  ** handle that precludes the requested lock, return BUSY.
23657
  ** handle that precludes the requested lock, return BUSY.
23319
  */
23658
  */
23320
  if( (pFile->locktype!=pLock->locktype && 
23659
  if( (pFile->eFileLock!=pInode->eFileLock && 
23321
          (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
23660
          (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
23322
  ){
23661
  ){
23323
    rc = SQLITE_BUSY;
23662
    rc = SQLITE_BUSY;
23324
    goto end_lock;
23663
    goto end_lock;
 Lines 23328-23341   static int unixLock(sqlite3_file *id, in Link Here 
23328
  ** has a SHARED or RESERVED lock, then increment reference counts and
23667
  ** has a SHARED or RESERVED lock, then increment reference counts and
23329
  ** return SQLITE_OK.
23668
  ** return SQLITE_OK.
23330
  */
23669
  */
23331
  if( locktype==SHARED_LOCK && 
23670
  if( eFileLock==SHARED_LOCK && 
23332
      (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
23671
      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
23333
    assert( locktype==SHARED_LOCK );
23672
    assert( eFileLock==SHARED_LOCK );
23334
    assert( pFile->locktype==0 );
23673
    assert( pFile->eFileLock==0 );
23335
    assert( pLock->cnt>0 );
23674
    assert( pInode->nShared>0 );
23336
    pFile->locktype = SHARED_LOCK;
23675
    pFile->eFileLock = SHARED_LOCK;
23337
    pLock->cnt++;
23676
    pInode->nShared++;
23338
    pFile->pOpen->nLock++;
23677
    pInode->nLock++;
23339
    goto end_lock;
23678
    goto end_lock;
23340
  }
23679
  }
23341
23680
 Lines 23346-23355   static int unixLock(sqlite3_file *id, in Link Here 
23346
  */
23685
  */
23347
  lock.l_len = 1L;
23686
  lock.l_len = 1L;
23348
  lock.l_whence = SEEK_SET;
23687
  lock.l_whence = SEEK_SET;
23349
  if( locktype==SHARED_LOCK 
23688
  if( eFileLock==SHARED_LOCK 
23350
      || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
23689
      || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
23351
  ){
23690
  ){
23352
    lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
23691
    lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
23353
    lock.l_start = PENDING_BYTE;
23692
    lock.l_start = PENDING_BYTE;
23354
    s = fcntl(pFile->h, F_SETLK, &lock);
23693
    s = fcntl(pFile->h, F_SETLK, &lock);
23355
    if( s==(-1) ){
23694
    if( s==(-1) ){
 Lines 23366-23374   static int unixLock(sqlite3_file *id, in Link Here 
23366
  /* If control gets to this point, then actually go ahead and make
23705
  /* If control gets to this point, then actually go ahead and make
23367
  ** operating system calls for the specified lock.
23706
  ** operating system calls for the specified lock.
23368
  */
23707
  */
23369
  if( locktype==SHARED_LOCK ){
23708
  if( eFileLock==SHARED_LOCK ){
23370
    assert( pLock->cnt==0 );
23709
    assert( pInode->nShared==0 );
23371
    assert( pLock->locktype==0 );
23710
    assert( pInode->eFileLock==0 );
23372
23711
23373
    /* Now get the read-lock */
23712
    /* Now get the read-lock */
23374
    lock.l_start = SHARED_FIRST;
23713
    lock.l_start = SHARED_FIRST;
 Lines 23397-23407   static int unixLock(sqlite3_file *id, in Link Here 
23397
        pFile->lastErrno = tErrno;
23736
        pFile->lastErrno = tErrno;
23398
      }
23737
      }
23399
    }else{
23738
    }else{
23400
      pFile->locktype = SHARED_LOCK;
23739
      pFile->eFileLock = SHARED_LOCK;
23401
      pFile->pOpen->nLock++;
23740
      pInode->nLock++;
23402
      pLock->cnt = 1;
23741
      pInode->nShared = 1;
23403
    }
23742
    }
23404
  }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
23743
  }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
23405
    /* We are trying for an exclusive lock but another thread in this
23744
    /* We are trying for an exclusive lock but another thread in this
23406
    ** same process is still holding a shared lock. */
23745
    ** same process is still holding a shared lock. */
23407
    rc = SQLITE_BUSY;
23746
    rc = SQLITE_BUSY;
 Lines 23410-23418   static int unixLock(sqlite3_file *id, in Link Here 
23410
    ** assumed that there is a SHARED or greater lock on the file
23749
    ** assumed that there is a SHARED or greater lock on the file
23411
    ** already.
23750
    ** already.
23412
    */
23751
    */
23413
    assert( 0!=pFile->locktype );
23752
    assert( 0!=pFile->eFileLock );
23414
    lock.l_type = F_WRLCK;
23753
    lock.l_type = F_WRLCK;
23415
    switch( locktype ){
23754
    switch( eFileLock ){
23416
      case RESERVED_LOCK:
23755
      case RESERVED_LOCK:
23417
        lock.l_start = RESERVED_BYTE;
23756
        lock.l_start = RESERVED_BYTE;
23418
        break;
23757
        break;
 Lines 23441-23448   static int unixLock(sqlite3_file *id, in Link Here 
23441
  ** write operation (not a hot journal rollback).
23780
  ** write operation (not a hot journal rollback).
23442
  */
23781
  */
23443
  if( rc==SQLITE_OK
23782
  if( rc==SQLITE_OK
23444
   && pFile->locktype<=SHARED_LOCK
23783
   && pFile->eFileLock<=SHARED_LOCK
23445
   && locktype==RESERVED_LOCK
23784
   && eFileLock==RESERVED_LOCK
23446
  ){
23785
  ){
23447
    pFile->transCntrChng = 0;
23786
    pFile->transCntrChng = 0;
23448
    pFile->dbUpdate = 0;
23787
    pFile->dbUpdate = 0;
 Lines 23452-23498   static int unixLock(sqlite3_file *id, in Link Here 
23452
23791
23453
23792
23454
  if( rc==SQLITE_OK ){
23793
  if( rc==SQLITE_OK ){
23455
    pFile->locktype = locktype;
23794
    pFile->eFileLock = eFileLock;
23456
    pLock->locktype = locktype;
23795
    pInode->eFileLock = eFileLock;
23457
  }else if( locktype==EXCLUSIVE_LOCK ){
23796
  }else if( eFileLock==EXCLUSIVE_LOCK ){
23458
    pFile->locktype = PENDING_LOCK;
23797
    pFile->eFileLock = PENDING_LOCK;
23459
    pLock->locktype = PENDING_LOCK;
23798
    pInode->eFileLock = PENDING_LOCK;
23460
  }
23799
  }
23461
23800
23462
end_lock:
23801
end_lock:
23463
  unixLeaveMutex();
23802
  unixLeaveMutex();
23464
  OSTRACE4("LOCK    %d %s %s (unix)\n", pFile->h, locktypeName(locktype), 
23803
  OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock), 
23465
      rc==SQLITE_OK ? "ok" : "failed");
23804
      rc==SQLITE_OK ? "ok" : "failed"));
23466
  return rc;
23467
}
23468
23469
/*
23470
** Close all file descriptors accumuated in the unixOpenCnt->pUnused list.
23471
** If all such file descriptors are closed without error, the list is
23472
** cleared and SQLITE_OK returned.
23473
**
23474
** Otherwise, if an error occurs, then successfully closed file descriptor
23475
** entries are removed from the list, and SQLITE_IOERR_CLOSE returned. 
23476
** not deleted and SQLITE_IOERR_CLOSE returned.
23477
*/ 
23478
static int closePendingFds(unixFile *pFile){
23479
  int rc = SQLITE_OK;
23480
  struct unixOpenCnt *pOpen = pFile->pOpen;
23481
  UnixUnusedFd *pError = 0;
23482
  UnixUnusedFd *p;
23483
  UnixUnusedFd *pNext;
23484
  for(p=pOpen->pUnused; p; p=pNext){
23485
    pNext = p->pNext;
23486
    if( close(p->fd) ){
23487
      pFile->lastErrno = errno;
23488
      rc = SQLITE_IOERR_CLOSE;
23489
      p->pNext = pError;
23490
      pError = p;
23491
    }else{
23492
      sqlite3_free(p);
23493
    }
23494
  }
23495
  pOpen->pUnused = pError;
23496
  return rc;
23805
  return rc;
23497
}
23806
}
23498
23807
 Lines 23501-23516   static int closePendingFds(unixFile *pFi Link Here 
23501
** pUnused list.
23810
** pUnused list.
23502
*/
23811
*/
23503
static void setPendingFd(unixFile *pFile){
23812
static void setPendingFd(unixFile *pFile){
23504
  struct unixOpenCnt *pOpen = pFile->pOpen;
23813
  unixInodeInfo *pInode = pFile->pInode;
23505
  UnixUnusedFd *p = pFile->pUnused;
23814
  UnixUnusedFd *p = pFile->pUnused;
23506
  p->pNext = pOpen->pUnused;
23815
  p->pNext = pInode->pUnused;
23507
  pOpen->pUnused = p;
23816
  pInode->pUnused = p;
23508
  pFile->h = -1;
23817
  pFile->h = -1;
23509
  pFile->pUnused = 0;
23818
  pFile->pUnused = 0;
23510
}
23819
}
23511
23820
23512
/*
23821
/*
23513
** Lower the locking level on file descriptor pFile to locktype.  locktype
23822
** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
23514
** must be either NO_LOCK or SHARED_LOCK.
23823
** must be either NO_LOCK or SHARED_LOCK.
23515
**
23824
**
23516
** If the locking level of the file descriptor is already at or below
23825
** If the locking level of the file descriptor is already at or below
 Lines 23522-23552   static void setPendingFd(unixFile *pFile Link Here 
23522
** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to 
23831
** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to 
23523
** remove the write lock on a region when a read lock is set.
23832
** remove the write lock on a region when a read lock is set.
23524
*/
23833
*/
23525
static int _posixUnlock(sqlite3_file *id, int locktype, int handleNFSUnlock){
23834
static int _posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
23526
  unixFile *pFile = (unixFile*)id;
23835
  unixFile *pFile = (unixFile*)id;
23527
  struct unixLockInfo *pLock;
23836
  unixInodeInfo *pInode;
23528
  struct flock lock;
23837
  struct flock lock;
23529
  int rc = SQLITE_OK;
23838
  int rc = SQLITE_OK;
23530
  int h;
23839
  int h;
23531
  int tErrno;                      /* Error code from system call errors */
23840
  int tErrno;                      /* Error code from system call errors */
23532
23841
23533
  assert( pFile );
23842
  assert( pFile );
23534
  OSTRACE7("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, locktype,
23843
  OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
23535
      pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
23844
      pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
23536
23845
      getpid()));
23537
  assert( locktype<=SHARED_LOCK );
23846
23538
  if( pFile->locktype<=locktype ){
23847
  assert( eFileLock<=SHARED_LOCK );
23848
  if( pFile->eFileLock<=eFileLock ){
23539
    return SQLITE_OK;
23849
    return SQLITE_OK;
23540
  }
23850
  }
23541
  if( CHECK_THREADID(pFile) ){
23542
    return SQLITE_MISUSE_BKPT;
23543
  }
23544
  unixEnterMutex();
23851
  unixEnterMutex();
23545
  h = pFile->h;
23852
  h = pFile->h;
23546
  pLock = pFile->pLock;
23853
  pInode = pFile->pInode;
23547
  assert( pLock->cnt!=0 );
23854
  assert( pInode->nShared!=0 );
23548
  if( pFile->locktype>SHARED_LOCK ){
23855
  if( pFile->eFileLock>SHARED_LOCK ){
23549
    assert( pLock->locktype==pFile->locktype );
23856
    assert( pInode->eFileLock==pFile->eFileLock );
23550
    SimulateIOErrorBenign(1);
23857
    SimulateIOErrorBenign(1);
23551
    SimulateIOError( h=(-1) )
23858
    SimulateIOError( h=(-1) )
23552
    SimulateIOErrorBenign(0);
23859
    SimulateIOErrorBenign(0);
 Lines 23560-23568   static int _posixUnlock(sqlite3_file *id Link Here 
23560
    ** the file has changed and hence might not know to flush their
23867
    ** the file has changed and hence might not know to flush their
23561
    ** cache.  The use of a stale cache can lead to database corruption.
23868
    ** cache.  The use of a stale cache can lead to database corruption.
23562
    */
23869
    */
23870
#if 0
23563
    assert( pFile->inNormalWrite==0
23871
    assert( pFile->inNormalWrite==0
23564
         || pFile->dbUpdate==0
23872
         || pFile->dbUpdate==0
23565
         || pFile->transCntrChng==1 );
23873
         || pFile->transCntrChng==1 );
23874
#endif
23566
    pFile->inNormalWrite = 0;
23875
    pFile->inNormalWrite = 0;
23567
#endif
23876
#endif
23568
23877
 Lines 23575-23581   static int _posixUnlock(sqlite3_file *id Link Here 
23575
    **  3:   [RRRRW]
23884
    **  3:   [RRRRW]
23576
    **  4:   [RRRR.]
23885
    **  4:   [RRRR.]
23577
    */
23886
    */
23578
    if( locktype==SHARED_LOCK ){
23887
    if( eFileLock==SHARED_LOCK ){
23579
      if( handleNFSUnlock ){
23888
      if( handleNFSUnlock ){
23580
        off_t divSize = SHARED_SIZE - 1;
23889
        off_t divSize = SHARED_SIZE - 1;
23581
        
23890
        
 Lines 23635-23641   static int _posixUnlock(sqlite3_file *id Link Here 
23635
    lock.l_start = PENDING_BYTE;
23944
    lock.l_start = PENDING_BYTE;
23636
    lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
23945
    lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
23637
    if( fcntl(h, F_SETLK, &lock)!=(-1) ){
23946
    if( fcntl(h, F_SETLK, &lock)!=(-1) ){
23638
      pLock->locktype = SHARED_LOCK;
23947
      pInode->eFileLock = SHARED_LOCK;
23639
    }else{
23948
    }else{
23640
      tErrno = errno;
23949
      tErrno = errno;
23641
      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23950
      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
 Lines 23645-23659   static int _posixUnlock(sqlite3_file *id Link Here 
23645
      goto end_unlock;
23954
      goto end_unlock;
23646
    }
23955
    }
23647
  }
23956
  }
23648
  if( locktype==NO_LOCK ){
23957
  if( eFileLock==NO_LOCK ){
23649
    struct unixOpenCnt *pOpen;
23650
23651
    /* Decrement the shared lock counter.  Release the lock using an
23958
    /* Decrement the shared lock counter.  Release the lock using an
23652
    ** OS call only when all threads in this same process have released
23959
    ** OS call only when all threads in this same process have released
23653
    ** the lock.
23960
    ** the lock.
23654
    */
23961
    */
23655
    pLock->cnt--;
23962
    pInode->nShared--;
23656
    if( pLock->cnt==0 ){
23963
    if( pInode->nShared==0 ){
23657
      lock.l_type = F_UNLCK;
23964
      lock.l_type = F_UNLCK;
23658
      lock.l_whence = SEEK_SET;
23965
      lock.l_whence = SEEK_SET;
23659
      lock.l_start = lock.l_len = 0L;
23966
      lock.l_start = lock.l_len = 0L;
 Lines 23661-23675   static int _posixUnlock(sqlite3_file *id Link Here 
23661
      SimulateIOError( h=(-1) )
23968
      SimulateIOError( h=(-1) )
23662
      SimulateIOErrorBenign(0);
23969
      SimulateIOErrorBenign(0);
23663
      if( fcntl(h, F_SETLK, &lock)!=(-1) ){
23970
      if( fcntl(h, F_SETLK, &lock)!=(-1) ){
23664
        pLock->locktype = NO_LOCK;
23971
        pInode->eFileLock = NO_LOCK;
23665
      }else{
23972
      }else{
23666
        tErrno = errno;
23973
        tErrno = errno;
23667
        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23974
        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23668
        if( IS_LOCK_ERROR(rc) ){
23975
        if( IS_LOCK_ERROR(rc) ){
23669
          pFile->lastErrno = tErrno;
23976
          pFile->lastErrno = tErrno;
23670
        }
23977
        }
23671
        pLock->locktype = NO_LOCK;
23978
        pInode->eFileLock = NO_LOCK;
23672
        pFile->locktype = NO_LOCK;
23979
        pFile->eFileLock = NO_LOCK;
23673
      }
23980
      }
23674
    }
23981
    }
23675
23982
 Lines 23677-23686   static int _posixUnlock(sqlite3_file *id Link Here 
23677
    ** count reaches zero, close any other file descriptors whose close
23984
    ** count reaches zero, close any other file descriptors whose close
23678
    ** was deferred because of outstanding locks.
23985
    ** was deferred because of outstanding locks.
23679
    */
23986
    */
23680
    pOpen = pFile->pOpen;
23987
    pInode->nLock--;
23681
    pOpen->nLock--;
23988
    assert( pInode->nLock>=0 );
23682
    assert( pOpen->nLock>=0 );
23989
    if( pInode->nLock==0 ){
23683
    if( pOpen->nLock==0 ){
23684
      int rc2 = closePendingFds(pFile);
23990
      int rc2 = closePendingFds(pFile);
23685
      if( rc==SQLITE_OK ){
23991
      if( rc==SQLITE_OK ){
23686
        rc = rc2;
23992
        rc = rc2;
 Lines 23690-23708   static int _posixUnlock(sqlite3_file *id Link Here 
23690
	
23996
	
23691
end_unlock:
23997
end_unlock:
23692
  unixLeaveMutex();
23998
  unixLeaveMutex();
23693
  if( rc==SQLITE_OK ) pFile->locktype = locktype;
23999
  if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
23694
  return rc;
24000
  return rc;
23695
}
24001
}
23696
24002
23697
/*
24003
/*
23698
** Lower the locking level on file descriptor pFile to locktype.  locktype
24004
** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
23699
** must be either NO_LOCK or SHARED_LOCK.
24005
** must be either NO_LOCK or SHARED_LOCK.
23700
**
24006
**
23701
** If the locking level of the file descriptor is already at or below
24007
** If the locking level of the file descriptor is already at or below
23702
** the requested locking level, this routine is a no-op.
24008
** the requested locking level, this routine is a no-op.
23703
*/
24009
*/
23704
static int unixUnlock(sqlite3_file *id, int locktype){
24010
static int unixUnlock(sqlite3_file *id, int eFileLock){
23705
  return _posixUnlock(id, locktype, 0);
24011
  return _posixUnlock(id, eFileLock, 0);
23706
}
24012
}
23707
24013
23708
/*
24014
/*
 Lines 23743-23749   static int closeUnixFile(sqlite3_file *i Link Here 
23743
      pFile->pId = 0;
24049
      pFile->pId = 0;
23744
    }
24050
    }
23745
#endif
24051
#endif
23746
    OSTRACE2("CLOSE   %-3d\n", pFile->h);
24052
    OSTRACE(("CLOSE   %-3d\n", pFile->h));
23747
    OpenCounter(-1);
24053
    OpenCounter(-1);
23748
    sqlite3_free(pFile->pUnused);
24054
    sqlite3_free(pFile->pUnused);
23749
    memset(pFile, 0, sizeof(unixFile));
24055
    memset(pFile, 0, sizeof(unixFile));
 Lines 23760-23775   static int unixClose(sqlite3_file *id){ Link Here 
23760
    unixFile *pFile = (unixFile *)id;
24066
    unixFile *pFile = (unixFile *)id;
23761
    unixUnlock(id, NO_LOCK);
24067
    unixUnlock(id, NO_LOCK);
23762
    unixEnterMutex();
24068
    unixEnterMutex();
23763
    if( pFile->pOpen && pFile->pOpen->nLock ){
24069
    if( pFile->pInode && pFile->pInode->nLock ){
23764
      /* If there are outstanding locks, do not actually close the file just
24070
      /* If there are outstanding locks, do not actually close the file just
23765
      ** yet because that would clear those locks.  Instead, add the file
24071
      ** yet because that would clear those locks.  Instead, add the file
23766
      ** descriptor to pOpen->pUnused list.  It will be automatically closed 
24072
      ** descriptor to pInode->pUnused list.  It will be automatically closed 
23767
      ** when the last lock is cleared.
24073
      ** when the last lock is cleared.
23768
      */
24074
      */
23769
      setPendingFd(pFile);
24075
      setPendingFd(pFile);
23770
    }
24076
    }
23771
    releaseLockInfo(pFile->pLock);
24077
    releaseInodeInfo(pFile);
23772
    releaseOpenCnt(pFile->pOpen);
23773
    rc = closeUnixFile(id);
24078
    rc = closeUnixFile(id);
23774
    unixLeaveMutex();
24079
    unixLeaveMutex();
23775
  }
24080
  }
 Lines 23868-23874   static int dotlockCheckReservedLock(sqli Link Here 
23868
  assert( pFile );
24173
  assert( pFile );
23869
24174
23870
  /* Check if a thread in this process holds such a lock */
24175
  /* Check if a thread in this process holds such a lock */
23871
  if( pFile->locktype>SHARED_LOCK ){
24176
  if( pFile->eFileLock>SHARED_LOCK ){
23872
    /* Either this connection or some other connection in the same process
24177
    /* Either this connection or some other connection in the same process
23873
    ** holds a lock on the file.  No need to check further. */
24178
    ** holds a lock on the file.  No need to check further. */
23874
    reserved = 1;
24179
    reserved = 1;
 Lines 23877-23889   static int dotlockCheckReservedLock(sqli Link Here 
23877
    const char *zLockFile = (const char*)pFile->lockingContext;
24182
    const char *zLockFile = (const char*)pFile->lockingContext;
23878
    reserved = access(zLockFile, 0)==0;
24183
    reserved = access(zLockFile, 0)==0;
23879
  }
24184
  }
23880
  OSTRACE4("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved);
24185
  OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
23881
  *pResOut = reserved;
24186
  *pResOut = reserved;
23882
  return rc;
24187
  return rc;
23883
}
24188
}
23884
24189
23885
/*
24190
/*
23886
** Lock the file with the lock specified by parameter locktype - one
24191
** Lock the file with the lock specified by parameter eFileLock - one
23887
** of the following:
24192
** of the following:
23888
**
24193
**
23889
**     (1) SHARED_LOCK
24194
**     (1) SHARED_LOCK
 Lines 23909-23915   static int dotlockCheckReservedLock(sqli Link Here 
23909
** With dotfile locking, we really only support state (4): EXCLUSIVE.
24214
** With dotfile locking, we really only support state (4): EXCLUSIVE.
23910
** But we track the other locking levels internally.
24215
** But we track the other locking levels internally.
23911
*/
24216
*/
23912
static int dotlockLock(sqlite3_file *id, int locktype) {
24217
static int dotlockLock(sqlite3_file *id, int eFileLock) {
23913
  unixFile *pFile = (unixFile*)id;
24218
  unixFile *pFile = (unixFile*)id;
23914
  int fd;
24219
  int fd;
23915
  char *zLockFile = (char *)pFile->lockingContext;
24220
  char *zLockFile = (char *)pFile->lockingContext;
 Lines 23919-23926   static int dotlockLock(sqlite3_file *id, Link Here 
23919
  /* If we have any lock, then the lock file already exists.  All we have
24224
  /* If we have any lock, then the lock file already exists.  All we have
23920
  ** to do is adjust our internal record of the lock level.
24225
  ** to do is adjust our internal record of the lock level.
23921
  */
24226
  */
23922
  if( pFile->locktype > NO_LOCK ){
24227
  if( pFile->eFileLock > NO_LOCK ){
23923
    pFile->locktype = locktype;
24228
    pFile->eFileLock = eFileLock;
23924
#if !OS_VXWORKS
24229
#if !OS_VXWORKS
23925
    /* Always update the timestamp on the old file */
24230
    /* Always update the timestamp on the old file */
23926
    utimes(zLockFile, NULL);
24231
    utimes(zLockFile, NULL);
 Lines 23949-23960   static int dotlockLock(sqlite3_file *id, Link Here 
23949
  }
24254
  }
23950
  
24255
  
23951
  /* got it, set the type and return ok */
24256
  /* got it, set the type and return ok */
23952
  pFile->locktype = locktype;
24257
  pFile->eFileLock = eFileLock;
23953
  return rc;
24258
  return rc;
23954
}
24259
}
23955
24260
23956
/*
24261
/*
23957
** Lower the locking level on file descriptor pFile to locktype.  locktype
24262
** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
23958
** must be either NO_LOCK or SHARED_LOCK.
24263
** must be either NO_LOCK or SHARED_LOCK.
23959
**
24264
**
23960
** If the locking level of the file descriptor is already at or below
24265
** If the locking level of the file descriptor is already at or below
 Lines 23962-23991   static int dotlockLock(sqlite3_file *id, Link Here 
23962
**
24267
**
23963
** When the locking level reaches NO_LOCK, delete the lock file.
24268
** When the locking level reaches NO_LOCK, delete the lock file.
23964
*/
24269
*/
23965
static int dotlockUnlock(sqlite3_file *id, int locktype) {
24270
static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
23966
  unixFile *pFile = (unixFile*)id;
24271
  unixFile *pFile = (unixFile*)id;
23967
  char *zLockFile = (char *)pFile->lockingContext;
24272
  char *zLockFile = (char *)pFile->lockingContext;
23968
24273
23969
  assert( pFile );
24274
  assert( pFile );
23970
  OSTRACE5("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, locktype,
24275
  OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
23971
	   pFile->locktype, getpid());
24276
	   pFile->eFileLock, getpid()));
23972
  assert( locktype<=SHARED_LOCK );
24277
  assert( eFileLock<=SHARED_LOCK );
23973
  
24278
  
23974
  /* no-op if possible */
24279
  /* no-op if possible */
23975
  if( pFile->locktype==locktype ){
24280
  if( pFile->eFileLock==eFileLock ){
23976
    return SQLITE_OK;
24281
    return SQLITE_OK;
23977
  }
24282
  }
23978
24283
23979
  /* To downgrade to shared, simply update our internal notion of the
24284
  /* To downgrade to shared, simply update our internal notion of the
23980
  ** lock state.  No need to mess with the file on disk.
24285
  ** lock state.  No need to mess with the file on disk.
23981
  */
24286
  */
23982
  if( locktype==SHARED_LOCK ){
24287
  if( eFileLock==SHARED_LOCK ){
23983
    pFile->locktype = SHARED_LOCK;
24288
    pFile->eFileLock = SHARED_LOCK;
23984
    return SQLITE_OK;
24289
    return SQLITE_OK;
23985
  }
24290
  }
23986
  
24291
  
23987
  /* To fully unlock the database, delete the lock file */
24292
  /* To fully unlock the database, delete the lock file */
23988
  assert( locktype==NO_LOCK );
24293
  assert( eFileLock==NO_LOCK );
23989
  if( unlink(zLockFile) ){
24294
  if( unlink(zLockFile) ){
23990
    int rc = 0;
24295
    int rc = 0;
23991
    int tErrno = errno;
24296
    int tErrno = errno;
 Lines 23997-24003   static int dotlockUnlock(sqlite3_file *i Link Here 
23997
    }
24302
    }
23998
    return rc; 
24303
    return rc; 
23999
  }
24304
  }
24000
  pFile->locktype = NO_LOCK;
24305
  pFile->eFileLock = NO_LOCK;
24001
  return SQLITE_OK;
24306
  return SQLITE_OK;
24002
}
24307
}
24003
24308
 Lines 24050-24056   static int flockCheckReservedLock(sqlite Link Here 
24050
  assert( pFile );
24355
  assert( pFile );
24051
  
24356
  
24052
  /* Check if a thread in this process holds such a lock */
24357
  /* Check if a thread in this process holds such a lock */
24053
  if( pFile->locktype>SHARED_LOCK ){
24358
  if( pFile->eFileLock>SHARED_LOCK ){
24054
    reserved = 1;
24359
    reserved = 1;
24055
  }
24360
  }
24056
  
24361
  
 Lines 24081-24087   static int flockCheckReservedLock(sqlite Link Here 
24081
      }
24386
      }
24082
    }
24387
    }
24083
  }
24388
  }
24084
  OSTRACE4("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved);
24389
  OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
24085
24390
24086
#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
24391
#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
24087
  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
24392
  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
 Lines 24094-24100   static int flockCheckReservedLock(sqlite Link Here 
24094
}
24399
}
24095
24400
24096
/*
24401
/*
24097
** Lock the file with the lock specified by parameter locktype - one
24402
** Lock the file with the lock specified by parameter eFileLock - one
24098
** of the following:
24403
** of the following:
24099
**
24404
**
24100
**     (1) SHARED_LOCK
24405
**     (1) SHARED_LOCK
 Lines 24122-24128   static int flockCheckReservedLock(sqlite Link Here 
24122
** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24427
** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24123
** routine to lower a locking level.
24428
** routine to lower a locking level.
24124
*/
24429
*/
24125
static int flockLock(sqlite3_file *id, int locktype) {
24430
static int flockLock(sqlite3_file *id, int eFileLock) {
24126
  int rc = SQLITE_OK;
24431
  int rc = SQLITE_OK;
24127
  unixFile *pFile = (unixFile*)id;
24432
  unixFile *pFile = (unixFile*)id;
24128
24433
 Lines 24130-24137   static int flockLock(sqlite3_file *id, i Link Here 
24130
24435
24131
  /* if we already have a lock, it is exclusive.  
24436
  /* if we already have a lock, it is exclusive.  
24132
  ** Just adjust level and punt on outta here. */
24437
  ** Just adjust level and punt on outta here. */
24133
  if (pFile->locktype > NO_LOCK) {
24438
  if (pFile->eFileLock > NO_LOCK) {
24134
    pFile->locktype = locktype;
24439
    pFile->eFileLock = eFileLock;
24135
    return SQLITE_OK;
24440
    return SQLITE_OK;
24136
  }
24441
  }
24137
  
24442
  
 Lines 24146-24155   static int flockLock(sqlite3_file *id, i Link Here 
24146
    }
24451
    }
24147
  } else {
24452
  } else {
24148
    /* got it, set the type and return ok */
24453
    /* got it, set the type and return ok */
24149
    pFile->locktype = locktype;
24454
    pFile->eFileLock = eFileLock;
24150
  }
24455
  }
24151
  OSTRACE4("LOCK    %d %s %s (flock)\n", pFile->h, locktypeName(locktype), 
24456
  OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock), 
24152
           rc==SQLITE_OK ? "ok" : "failed");
24457
           rc==SQLITE_OK ? "ok" : "failed"));
24153
#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
24458
#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
24154
  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
24459
  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
24155
    rc = SQLITE_BUSY;
24460
    rc = SQLITE_BUSY;
 Lines 24160-24187   static int flockLock(sqlite3_file *id, i Link Here 
24160
24465
24161
24466
24162
/*
24467
/*
24163
** Lower the locking level on file descriptor pFile to locktype.  locktype
24468
** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24164
** must be either NO_LOCK or SHARED_LOCK.
24469
** must be either NO_LOCK or SHARED_LOCK.
24165
**
24470
**
24166
** If the locking level of the file descriptor is already at or below
24471
** If the locking level of the file descriptor is already at or below
24167
** the requested locking level, this routine is a no-op.
24472
** the requested locking level, this routine is a no-op.
24168
*/
24473
*/
24169
static int flockUnlock(sqlite3_file *id, int locktype) {
24474
static int flockUnlock(sqlite3_file *id, int eFileLock) {
24170
  unixFile *pFile = (unixFile*)id;
24475
  unixFile *pFile = (unixFile*)id;
24171
  
24476
  
24172
  assert( pFile );
24477
  assert( pFile );
24173
  OSTRACE5("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, locktype,
24478
  OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
24174
           pFile->locktype, getpid());
24479
           pFile->eFileLock, getpid()));
24175
  assert( locktype<=SHARED_LOCK );
24480
  assert( eFileLock<=SHARED_LOCK );
24176
  
24481
  
24177
  /* no-op if possible */
24482
  /* no-op if possible */
24178
  if( pFile->locktype==locktype ){
24483
  if( pFile->eFileLock==eFileLock ){
24179
    return SQLITE_OK;
24484
    return SQLITE_OK;
24180
  }
24485
  }
24181
  
24486
  
24182
  /* shared can just be set because we always have an exclusive */
24487
  /* shared can just be set because we always have an exclusive */
24183
  if (locktype==SHARED_LOCK) {
24488
  if (eFileLock==SHARED_LOCK) {
24184
    pFile->locktype = locktype;
24489
    pFile->eFileLock = eFileLock;
24185
    return SQLITE_OK;
24490
    return SQLITE_OK;
24186
  }
24491
  }
24187
  
24492
  
 Lines 24201-24207   static int flockUnlock(sqlite3_file *id, Link Here 
24201
    
24506
    
24202
    return r;
24507
    return r;
24203
  } else {
24508
  } else {
24204
    pFile->locktype = NO_LOCK;
24509
    pFile->eFileLock = NO_LOCK;
24205
    return SQLITE_OK;
24510
    return SQLITE_OK;
24206
  }
24511
  }
24207
}
24512
}
 Lines 24249-24261   static int semCheckReservedLock(sqlite3_ Link Here 
24249
  assert( pFile );
24554
  assert( pFile );
24250
24555
24251
  /* Check if a thread in this process holds such a lock */
24556
  /* Check if a thread in this process holds such a lock */
24252
  if( pFile->locktype>SHARED_LOCK ){
24557
  if( pFile->eFileLock>SHARED_LOCK ){
24253
    reserved = 1;
24558
    reserved = 1;
24254
  }
24559
  }
24255
  
24560
  
24256
  /* Otherwise see if some other process holds it. */
24561
  /* Otherwise see if some other process holds it. */
24257
  if( !reserved ){
24562
  if( !reserved ){
24258
    sem_t *pSem = pFile->pOpen->pSem;
24563
    sem_t *pSem = pFile->pInode->pSem;
24259
    struct stat statBuf;
24564
    struct stat statBuf;
24260
24565
24261
    if( sem_trywait(pSem)==-1 ){
24566
    if( sem_trywait(pSem)==-1 ){
 Lines 24265-24285   static int semCheckReservedLock(sqlite3_ Link Here 
24265
        pFile->lastErrno = tErrno;
24570
        pFile->lastErrno = tErrno;
24266
      } else {
24571
      } else {
24267
        /* someone else has the lock when we are in NO_LOCK */
24572
        /* someone else has the lock when we are in NO_LOCK */
24268
        reserved = (pFile->locktype < SHARED_LOCK);
24573
        reserved = (pFile->eFileLock < SHARED_LOCK);
24269
      }
24574
      }
24270
    }else{
24575
    }else{
24271
      /* we could have it if we want it */
24576
      /* we could have it if we want it */
24272
      sem_post(pSem);
24577
      sem_post(pSem);
24273
    }
24578
    }
24274
  }
24579
  }
24275
  OSTRACE4("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved);
24580
  OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
24276
24581
24277
  *pResOut = reserved;
24582
  *pResOut = reserved;
24278
  return rc;
24583
  return rc;
24279
}
24584
}
24280
24585
24281
/*
24586
/*
24282
** Lock the file with the lock specified by parameter locktype - one
24587
** Lock the file with the lock specified by parameter eFileLock - one
24283
** of the following:
24588
** of the following:
24284
**
24589
**
24285
**     (1) SHARED_LOCK
24590
**     (1) SHARED_LOCK
 Lines 24307-24322   static int semCheckReservedLock(sqlite3_ Link Here 
24307
** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24612
** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24308
** routine to lower a locking level.
24613
** routine to lower a locking level.
24309
*/
24614
*/
24310
static int semLock(sqlite3_file *id, int locktype) {
24615
static int semLock(sqlite3_file *id, int eFileLock) {
24311
  unixFile *pFile = (unixFile*)id;
24616
  unixFile *pFile = (unixFile*)id;
24312
  int fd;
24617
  int fd;
24313
  sem_t *pSem = pFile->pOpen->pSem;
24618
  sem_t *pSem = pFile->pInode->pSem;
24314
  int rc = SQLITE_OK;
24619
  int rc = SQLITE_OK;
24315
24620
24316
  /* if we already have a lock, it is exclusive.  
24621
  /* if we already have a lock, it is exclusive.  
24317
  ** Just adjust level and punt on outta here. */
24622
  ** Just adjust level and punt on outta here. */
24318
  if (pFile->locktype > NO_LOCK) {
24623
  if (pFile->eFileLock > NO_LOCK) {
24319
    pFile->locktype = locktype;
24624
    pFile->eFileLock = eFileLock;
24320
    rc = SQLITE_OK;
24625
    rc = SQLITE_OK;
24321
    goto sem_end_lock;
24626
    goto sem_end_lock;
24322
  }
24627
  }
 Lines 24328-24364   static int semLock(sqlite3_file *id, int Link Here 
24328
  }
24633
  }
24329
24634
24330
  /* got it, set the type and return ok */
24635
  /* got it, set the type and return ok */
24331
  pFile->locktype = locktype;
24636
  pFile->eFileLock = eFileLock;
24332
24637
24333
 sem_end_lock:
24638
 sem_end_lock:
24334
  return rc;
24639
  return rc;
24335
}
24640
}
24336
24641
24337
/*
24642
/*
24338
** Lower the locking level on file descriptor pFile to locktype.  locktype
24643
** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24339
** must be either NO_LOCK or SHARED_LOCK.
24644
** must be either NO_LOCK or SHARED_LOCK.
24340
**
24645
**
24341
** If the locking level of the file descriptor is already at or below
24646
** If the locking level of the file descriptor is already at or below
24342
** the requested locking level, this routine is a no-op.
24647
** the requested locking level, this routine is a no-op.
24343
*/
24648
*/
24344
static int semUnlock(sqlite3_file *id, int locktype) {
24649
static int semUnlock(sqlite3_file *id, int eFileLock) {
24345
  unixFile *pFile = (unixFile*)id;
24650
  unixFile *pFile = (unixFile*)id;
24346
  sem_t *pSem = pFile->pOpen->pSem;
24651
  sem_t *pSem = pFile->pInode->pSem;
24347
24652
24348
  assert( pFile );
24653
  assert( pFile );
24349
  assert( pSem );
24654
  assert( pSem );
24350
  OSTRACE5("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, locktype,
24655
  OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
24351
	   pFile->locktype, getpid());
24656
	   pFile->eFileLock, getpid()));
24352
  assert( locktype<=SHARED_LOCK );
24657
  assert( eFileLock<=SHARED_LOCK );
24353
  
24658
  
24354
  /* no-op if possible */
24659
  /* no-op if possible */
24355
  if( pFile->locktype==locktype ){
24660
  if( pFile->eFileLock==eFileLock ){
24356
    return SQLITE_OK;
24661
    return SQLITE_OK;
24357
  }
24662
  }
24358
  
24663
  
24359
  /* shared can just be set because we always have an exclusive */
24664
  /* shared can just be set because we always have an exclusive */
24360
  if (locktype==SHARED_LOCK) {
24665
  if (eFileLock==SHARED_LOCK) {
24361
    pFile->locktype = locktype;
24666
    pFile->eFileLock = eFileLock;
24362
    return SQLITE_OK;
24667
    return SQLITE_OK;
24363
  }
24668
  }
24364
  
24669
  
 Lines 24371-24377   static int semUnlock(sqlite3_file *id, i Link Here 
24371
    }
24676
    }
24372
    return rc; 
24677
    return rc; 
24373
  }
24678
  }
24374
  pFile->locktype = NO_LOCK;
24679
  pFile->eFileLock = NO_LOCK;
24375
  return SQLITE_OK;
24680
  return SQLITE_OK;
24376
}
24681
}
24377
24682
 Lines 24384-24391   static int semClose(sqlite3_file *id) { Link Here 
24384
    semUnlock(id, NO_LOCK);
24689
    semUnlock(id, NO_LOCK);
24385
    assert( pFile );
24690
    assert( pFile );
24386
    unixEnterMutex();
24691
    unixEnterMutex();
24387
    releaseLockInfo(pFile->pLock);
24692
    releaseInodeInfo(pFile);
24388
    releaseOpenCnt(pFile->pOpen);
24389
    unixLeaveMutex();
24693
    unixLeaveMutex();
24390
    closeUnixFile(id);
24694
    closeUnixFile(id);
24391
  }
24695
  }
 Lines 24454-24468   static int afpSetLock( Link Here 
24454
  pb.length = length; 
24758
  pb.length = length; 
24455
  pb.fd = pFile->h;
24759
  pb.fd = pFile->h;
24456
  
24760
  
24457
  OSTRACE6("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n", 
24761
  OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n", 
24458
    (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
24762
    (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
24459
    offset, length);
24763
    offset, length));
24460
  err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
24764
  err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
24461
  if ( err==-1 ) {
24765
  if ( err==-1 ) {
24462
    int rc;
24766
    int rc;
24463
    int tErrno = errno;
24767
    int tErrno = errno;
24464
    OSTRACE4("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
24768
    OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
24465
             path, tErrno, strerror(tErrno));
24769
             path, tErrno, strerror(tErrno)));
24466
#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
24770
#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
24467
    rc = SQLITE_BUSY;
24771
    rc = SQLITE_BUSY;
24468
#else
24772
#else
 Lines 24497-24506   static int afpCheckReservedLock(sqlite3_ Link Here 
24497
    *pResOut = 1;
24801
    *pResOut = 1;
24498
    return SQLITE_OK;
24802
    return SQLITE_OK;
24499
  }
24803
  }
24500
  unixEnterMutex(); /* Because pFile->pLock is shared across threads */
24804
  unixEnterMutex(); /* Because pFile->pInode is shared across threads */
24501
  
24805
  
24502
  /* Check if a thread in this process holds such a lock */
24806
  /* Check if a thread in this process holds such a lock */
24503
  if( pFile->pLock->locktype>SHARED_LOCK ){
24807
  if( pFile->pInode->eFileLock>SHARED_LOCK ){
24504
    reserved = 1;
24808
    reserved = 1;
24505
  }
24809
  }
24506
  
24810
  
 Lines 24523-24536   static int afpCheckReservedLock(sqlite3_ Link Here 
24523
  }
24827
  }
24524
  
24828
  
24525
  unixLeaveMutex();
24829
  unixLeaveMutex();
24526
  OSTRACE4("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved);
24830
  OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
24527
  
24831
  
24528
  *pResOut = reserved;
24832
  *pResOut = reserved;
24529
  return rc;
24833
  return rc;
24530
}
24834
}
24531
24835
24532
/*
24836
/*
24533
** Lock the file with the lock specified by parameter locktype - one
24837
** Lock the file with the lock specified by parameter eFileLock - one
24534
** of the following:
24838
** of the following:
24535
**
24839
**
24536
**     (1) SHARED_LOCK
24840
**     (1) SHARED_LOCK
 Lines 24553-24576   static int afpCheckReservedLock(sqlite3_ Link Here 
24553
** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24857
** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24554
** routine to lower a locking level.
24858
** routine to lower a locking level.
24555
*/
24859
*/
24556
static int afpLock(sqlite3_file *id, int locktype){
24860
static int afpLock(sqlite3_file *id, int eFileLock){
24557
  int rc = SQLITE_OK;
24861
  int rc = SQLITE_OK;
24558
  unixFile *pFile = (unixFile*)id;
24862
  unixFile *pFile = (unixFile*)id;
24559
  struct unixLockInfo *pLock = pFile->pLock;
24863
  unixInodeInfo *pInode = pFile->pInode;
24560
  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
24864
  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
24561
  
24865
  
24562
  assert( pFile );
24866
  assert( pFile );
24563
  OSTRACE7("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
24867
  OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
24564
           locktypeName(locktype), locktypeName(pFile->locktype),
24868
           azFileLock(eFileLock), azFileLock(pFile->eFileLock),
24565
           locktypeName(pLock->locktype), pLock->cnt , getpid());
24869
           azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
24566
24870
24567
  /* If there is already a lock of this type or more restrictive on the
24871
  /* If there is already a lock of this type or more restrictive on the
24568
  ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
24872
  ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
24569
  ** unixEnterMutex() hasn't been called yet.
24873
  ** unixEnterMutex() hasn't been called yet.
24570
  */
24874
  */
24571
  if( pFile->locktype>=locktype ){
24875
  if( pFile->eFileLock>=eFileLock ){
24572
    OSTRACE3("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
24876
    OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
24573
           locktypeName(locktype));
24877
           azFileLock(eFileLock)));
24574
    return SQLITE_OK;
24878
    return SQLITE_OK;
24575
  }
24879
  }
24576
24880
 Lines 24579-24606   static int afpLock(sqlite3_file *id, int Link Here 
24579
  **  (2) SQLite never explicitly requests a pendig lock.
24883
  **  (2) SQLite never explicitly requests a pendig lock.
24580
  **  (3) A shared lock is always held when a reserve lock is requested.
24884
  **  (3) A shared lock is always held when a reserve lock is requested.
24581
  */
24885
  */
24582
  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
24886
  assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
24583
  assert( locktype!=PENDING_LOCK );
24887
  assert( eFileLock!=PENDING_LOCK );
24584
  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
24888
  assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
24585
  
24889
  
24586
  /* This mutex is needed because pFile->pLock is shared across threads
24890
  /* This mutex is needed because pFile->pInode is shared across threads
24587
  */
24891
  */
24588
  unixEnterMutex();
24892
  unixEnterMutex();
24589
24893
  pInode = pFile->pInode;
24590
  /* Make sure the current thread owns the pFile.
24591
  */
24592
  rc = transferOwnership(pFile);
24593
  if( rc!=SQLITE_OK ){
24594
    unixLeaveMutex();
24595
    return rc;
24596
  }
24597
  pLock = pFile->pLock;
24598
24894
24599
  /* If some thread using this PID has a lock via a different unixFile*
24895
  /* If some thread using this PID has a lock via a different unixFile*
24600
  ** handle that precludes the requested lock, return BUSY.
24896
  ** handle that precludes the requested lock, return BUSY.
24601
  */
24897
  */
24602
  if( (pFile->locktype!=pLock->locktype && 
24898
  if( (pFile->eFileLock!=pInode->eFileLock && 
24603
       (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
24899
       (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
24604
     ){
24900
     ){
24605
    rc = SQLITE_BUSY;
24901
    rc = SQLITE_BUSY;
24606
    goto afp_end_lock;
24902
    goto afp_end_lock;
 Lines 24610-24623   static int afpLock(sqlite3_file *id, int Link Here 
24610
  ** has a SHARED or RESERVED lock, then increment reference counts and
24906
  ** has a SHARED or RESERVED lock, then increment reference counts and
24611
  ** return SQLITE_OK.
24907
  ** return SQLITE_OK.
24612
  */
24908
  */
24613
  if( locktype==SHARED_LOCK && 
24909
  if( eFileLock==SHARED_LOCK && 
24614
     (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
24910
     (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
24615
    assert( locktype==SHARED_LOCK );
24911
    assert( eFileLock==SHARED_LOCK );
24616
    assert( pFile->locktype==0 );
24912
    assert( pFile->eFileLock==0 );
24617
    assert( pLock->cnt>0 );
24913
    assert( pInode->nShared>0 );
24618
    pFile->locktype = SHARED_LOCK;
24914
    pFile->eFileLock = SHARED_LOCK;
24619
    pLock->cnt++;
24915
    pInode->nShared++;
24620
    pFile->pOpen->nLock++;
24916
    pInode->nLock++;
24621
    goto afp_end_lock;
24917
    goto afp_end_lock;
24622
  }
24918
  }
24623
    
24919
    
 Lines 24625-24632   static int afpLock(sqlite3_file *id, int Link Here 
24625
  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
24921
  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
24626
  ** be released.
24922
  ** be released.
24627
  */
24923
  */
24628
  if( locktype==SHARED_LOCK 
24924
  if( eFileLock==SHARED_LOCK 
24629
      || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
24925
      || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
24630
  ){
24926
  ){
24631
    int failed;
24927
    int failed;
24632
    failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
24928
    failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
 Lines 24639-24658   static int afpLock(sqlite3_file *id, int Link Here 
24639
  /* If control gets to this point, then actually go ahead and make
24935
  /* If control gets to this point, then actually go ahead and make
24640
  ** operating system calls for the specified lock.
24936
  ** operating system calls for the specified lock.
24641
  */
24937
  */
24642
  if( locktype==SHARED_LOCK ){
24938
  if( eFileLock==SHARED_LOCK ){
24643
    int lrc1, lrc2, lrc1Errno;
24939
    int lrc1, lrc2, lrc1Errno;
24644
    long lk, mask;
24940
    long lk, mask;
24645
    
24941
    
24646
    assert( pLock->cnt==0 );
24942
    assert( pInode->nShared==0 );
24647
    assert( pLock->locktype==0 );
24943
    assert( pInode->eFileLock==0 );
24648
        
24944
        
24649
    mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
24945
    mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
24650
    /* Now get the read-lock SHARED_LOCK */
24946
    /* Now get the read-lock SHARED_LOCK */
24651
    /* note that the quality of the randomness doesn't matter that much */
24947
    /* note that the quality of the randomness doesn't matter that much */
24652
    lk = random(); 
24948
    lk = random(); 
24653
    pLock->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
24949
    pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
24654
    lrc1 = afpSetLock(context->dbPath, pFile, 
24950
    lrc1 = afpSetLock(context->dbPath, pFile, 
24655
          SHARED_FIRST+pLock->sharedByte, 1, 1);
24951
          SHARED_FIRST+pInode->sharedByte, 1, 1);
24656
    if( IS_LOCK_ERROR(lrc1) ){
24952
    if( IS_LOCK_ERROR(lrc1) ){
24657
      lrc1Errno = pFile->lastErrno;
24953
      lrc1Errno = pFile->lastErrno;
24658
    }
24954
    }
 Lines 24669-24679   static int afpLock(sqlite3_file *id, int Link Here 
24669
    } else if( lrc1 != SQLITE_OK ) {
24965
    } else if( lrc1 != SQLITE_OK ) {
24670
      rc = lrc1;
24966
      rc = lrc1;
24671
    } else {
24967
    } else {
24672
      pFile->locktype = SHARED_LOCK;
24968
      pFile->eFileLock = SHARED_LOCK;
24673
      pFile->pOpen->nLock++;
24969
      pInode->nLock++;
24674
      pLock->cnt = 1;
24970
      pInode->nShared = 1;
24675
    }
24971
    }
24676
  }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
24972
  }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
24677
    /* We are trying for an exclusive lock but another thread in this
24973
    /* We are trying for an exclusive lock but another thread in this
24678
     ** same process is still holding a shared lock. */
24974
     ** same process is still holding a shared lock. */
24679
    rc = SQLITE_BUSY;
24975
    rc = SQLITE_BUSY;
 Lines 24683-24710   static int afpLock(sqlite3_file *id, int Link Here 
24683
    ** already.
24979
    ** already.
24684
    */
24980
    */
24685
    int failed = 0;
24981
    int failed = 0;
24686
    assert( 0!=pFile->locktype );
24982
    assert( 0!=pFile->eFileLock );
24687
    if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
24983
    if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
24688
        /* Acquire a RESERVED lock */
24984
        /* Acquire a RESERVED lock */
24689
        failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
24985
        failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
24690
      if( !failed ){
24986
      if( !failed ){
24691
        context->reserved = 1;
24987
        context->reserved = 1;
24692
      }
24988
      }
24693
    }
24989
    }
24694
    if (!failed && locktype == EXCLUSIVE_LOCK) {
24990
    if (!failed && eFileLock == EXCLUSIVE_LOCK) {
24695
      /* Acquire an EXCLUSIVE lock */
24991
      /* Acquire an EXCLUSIVE lock */
24696
        
24992
        
24697
      /* Remove the shared lock before trying the range.  we'll need to 
24993
      /* Remove the shared lock before trying the range.  we'll need to 
24698
      ** reestablish the shared lock if we can't get the  afpUnlock
24994
      ** reestablish the shared lock if we can't get the  afpUnlock
24699
      */
24995
      */
24700
      if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
24996
      if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
24701
                         pLock->sharedByte, 1, 0)) ){
24997
                         pInode->sharedByte, 1, 0)) ){
24702
        int failed2 = SQLITE_OK;
24998
        int failed2 = SQLITE_OK;
24703
        /* now attemmpt to get the exclusive lock range */
24999
        /* now attemmpt to get the exclusive lock range */
24704
        failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST, 
25000
        failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST, 
24705
                               SHARED_SIZE, 1);
25001
                               SHARED_SIZE, 1);
24706
        if( failed && (failed2 = afpSetLock(context->dbPath, pFile, 
25002
        if( failed && (failed2 = afpSetLock(context->dbPath, pFile, 
24707
                       SHARED_FIRST + pLock->sharedByte, 1, 1)) ){
25003
                       SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
24708
          /* Can't reestablish the shared lock.  Sqlite can't deal, this is
25004
          /* Can't reestablish the shared lock.  Sqlite can't deal, this is
24709
          ** a critical I/O error
25005
          ** a critical I/O error
24710
          */
25006
          */
 Lines 24722-24752   static int afpLock(sqlite3_file *id, int Link Here 
24722
  }
25018
  }
24723
  
25019
  
24724
  if( rc==SQLITE_OK ){
25020
  if( rc==SQLITE_OK ){
24725
    pFile->locktype = locktype;
25021
    pFile->eFileLock = eFileLock;
24726
    pLock->locktype = locktype;
25022
    pInode->eFileLock = eFileLock;
24727
  }else if( locktype==EXCLUSIVE_LOCK ){
25023
  }else if( eFileLock==EXCLUSIVE_LOCK ){
24728
    pFile->locktype = PENDING_LOCK;
25024
    pFile->eFileLock = PENDING_LOCK;
24729
    pLock->locktype = PENDING_LOCK;
25025
    pInode->eFileLock = PENDING_LOCK;
24730
  }
25026
  }
24731
  
25027
  
24732
afp_end_lock:
25028
afp_end_lock:
24733
  unixLeaveMutex();
25029
  unixLeaveMutex();
24734
  OSTRACE4("LOCK    %d %s %s (afp)\n", pFile->h, locktypeName(locktype), 
25030
  OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock), 
24735
         rc==SQLITE_OK ? "ok" : "failed");
25031
         rc==SQLITE_OK ? "ok" : "failed"));
24736
  return rc;
25032
  return rc;
24737
}
25033
}
24738
25034
24739
/*
25035
/*
24740
** Lower the locking level on file descriptor pFile to locktype.  locktype
25036
** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24741
** must be either NO_LOCK or SHARED_LOCK.
25037
** must be either NO_LOCK or SHARED_LOCK.
24742
**
25038
**
24743
** If the locking level of the file descriptor is already at or below
25039
** If the locking level of the file descriptor is already at or below
24744
** the requested locking level, this routine is a no-op.
25040
** the requested locking level, this routine is a no-op.
24745
*/
25041
*/
24746
static int afpUnlock(sqlite3_file *id, int locktype) {
25042
static int afpUnlock(sqlite3_file *id, int eFileLock) {
24747
  int rc = SQLITE_OK;
25043
  int rc = SQLITE_OK;
24748
  unixFile *pFile = (unixFile*)id;
25044
  unixFile *pFile = (unixFile*)id;
24749
  struct unixLockInfo *pLock;
25045
  unixInodeInfo *pInode;
24750
  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
25046
  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
24751
  int skipShared = 0;
25047
  int skipShared = 0;
24752
#ifdef SQLITE_TEST
25048
#ifdef SQLITE_TEST
 Lines 24754-24774   static int afpUnlock(sqlite3_file *id, i Link Here 
24754
#endif
25050
#endif
24755
25051
24756
  assert( pFile );
25052
  assert( pFile );
24757
  OSTRACE7("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, locktype,
25053
  OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
24758
           pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
25054
           pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
24759
25055
           getpid()));
24760
  assert( locktype<=SHARED_LOCK );
25056
24761
  if( pFile->locktype<=locktype ){
25057
  assert( eFileLock<=SHARED_LOCK );
25058
  if( pFile->eFileLock<=eFileLock ){
24762
    return SQLITE_OK;
25059
    return SQLITE_OK;
24763
  }
25060
  }
24764
  if( CHECK_THREADID(pFile) ){
24765
    return SQLITE_MISUSE_BKPT;
24766
  }
24767
  unixEnterMutex();
25061
  unixEnterMutex();
24768
  pLock = pFile->pLock;
25062
  pInode = pFile->pInode;
24769
  assert( pLock->cnt!=0 );
25063
  assert( pInode->nShared!=0 );
24770
  if( pFile->locktype>SHARED_LOCK ){
25064
  if( pFile->eFileLock>SHARED_LOCK ){
24771
    assert( pLock->locktype==pFile->locktype );
25065
    assert( pInode->eFileLock==pFile->eFileLock );
24772
    SimulateIOErrorBenign(1);
25066
    SimulateIOErrorBenign(1);
24773
    SimulateIOError( h=(-1) )
25067
    SimulateIOError( h=(-1) )
24774
    SimulateIOErrorBenign(0);
25068
    SimulateIOErrorBenign(0);
 Lines 24788-24825   static int afpUnlock(sqlite3_file *id, i Link Here 
24788
    pFile->inNormalWrite = 0;
25082
    pFile->inNormalWrite = 0;
24789
#endif
25083
#endif
24790
    
25084
    
24791
    if( pFile->locktype==EXCLUSIVE_LOCK ){
25085
    if( pFile->eFileLock==EXCLUSIVE_LOCK ){
24792
      rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
25086
      rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
24793
      if( rc==SQLITE_OK && (locktype==SHARED_LOCK || pLock->cnt>1) ){
25087
      if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
24794
        /* only re-establish the shared lock if necessary */
25088
        /* only re-establish the shared lock if necessary */
24795
        int sharedLockByte = SHARED_FIRST+pLock->sharedByte;
25089
        int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
24796
        rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
25090
        rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
24797
      } else {
25091
      } else {
24798
        skipShared = 1;
25092
        skipShared = 1;
24799
      }
25093
      }
24800
    }
25094
    }
24801
    if( rc==SQLITE_OK && pFile->locktype>=PENDING_LOCK ){
25095
    if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
24802
      rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
25096
      rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
24803
    } 
25097
    } 
24804
    if( rc==SQLITE_OK && pFile->locktype>=RESERVED_LOCK && context->reserved ){
25098
    if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
24805
      rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
25099
      rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
24806
      if( !rc ){ 
25100
      if( !rc ){ 
24807
        context->reserved = 0; 
25101
        context->reserved = 0; 
24808
      }
25102
      }
24809
    }
25103
    }
24810
    if( rc==SQLITE_OK && (locktype==SHARED_LOCK || pLock->cnt>1)){
25104
    if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
24811
      pLock->locktype = SHARED_LOCK;
25105
      pInode->eFileLock = SHARED_LOCK;
24812
    }
25106
    }
24813
  }
25107
  }
24814
  if( rc==SQLITE_OK && locktype==NO_LOCK ){
25108
  if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
24815
25109
24816
    /* Decrement the shared lock counter.  Release the lock using an
25110
    /* Decrement the shared lock counter.  Release the lock using an
24817
    ** OS call only when all threads in this same process have released
25111
    ** OS call only when all threads in this same process have released
24818
    ** the lock.
25112
    ** the lock.
24819
    */
25113
    */
24820
    unsigned long long sharedLockByte = SHARED_FIRST+pLock->sharedByte;
25114
    unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
24821
    pLock->cnt--;
25115
    pInode->nShared--;
24822
    if( pLock->cnt==0 ){
25116
    if( pInode->nShared==0 ){
24823
      SimulateIOErrorBenign(1);
25117
      SimulateIOErrorBenign(1);
24824
      SimulateIOError( h=(-1) )
25118
      SimulateIOError( h=(-1) )
24825
      SimulateIOErrorBenign(0);
25119
      SimulateIOErrorBenign(0);
 Lines 24827-24849   static int afpUnlock(sqlite3_file *id, i Link Here 
24827
        rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
25121
        rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
24828
      }
25122
      }
24829
      if( !rc ){
25123
      if( !rc ){
24830
        pLock->locktype = NO_LOCK;
25124
        pInode->eFileLock = NO_LOCK;
24831
        pFile->locktype = NO_LOCK;
25125
        pFile->eFileLock = NO_LOCK;
24832
      }
25126
      }
24833
    }
25127
    }
24834
    if( rc==SQLITE_OK ){
25128
    if( rc==SQLITE_OK ){
24835
      struct unixOpenCnt *pOpen = pFile->pOpen;
25129
      pInode->nLock--;
24836
        
25130
      assert( pInode->nLock>=0 );
24837
      pOpen->nLock--;
25131
      if( pInode->nLock==0 ){
24838
      assert( pOpen->nLock>=0 );
24839
      if( pOpen->nLock==0 ){
24840
        rc = closePendingFds(pFile);
25132
        rc = closePendingFds(pFile);
24841
      }
25133
      }
24842
    }
25134
    }
24843
  }
25135
  }
24844
  
25136
  
24845
  unixLeaveMutex();
25137
  unixLeaveMutex();
24846
  if( rc==SQLITE_OK ) pFile->locktype = locktype;
25138
  if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
24847
  return rc;
25139
  return rc;
24848
}
25140
}
24849
25141
 Lines 24856-24871   static int afpClose(sqlite3_file *id) { Link Here 
24856
    unixFile *pFile = (unixFile*)id;
25148
    unixFile *pFile = (unixFile*)id;
24857
    afpUnlock(id, NO_LOCK);
25149
    afpUnlock(id, NO_LOCK);
24858
    unixEnterMutex();
25150
    unixEnterMutex();
24859
    if( pFile->pOpen && pFile->pOpen->nLock ){
25151
    if( pFile->pInode && pFile->pInode->nLock ){
24860
      /* If there are outstanding locks, do not actually close the file just
25152
      /* If there are outstanding locks, do not actually close the file just
24861
      ** yet because that would clear those locks.  Instead, add the file
25153
      ** yet because that would clear those locks.  Instead, add the file
24862
      ** descriptor to pOpen->aPending.  It will be automatically closed when
25154
      ** descriptor to pInode->aPending.  It will be automatically closed when
24863
      ** the last lock is cleared.
25155
      ** the last lock is cleared.
24864
      */
25156
      */
24865
      setPendingFd(pFile);
25157
      setPendingFd(pFile);
24866
    }
25158
    }
24867
    releaseLockInfo(pFile->pLock);
25159
    releaseInodeInfo(pFile);
24868
    releaseOpenCnt(pFile->pOpen);
24869
    sqlite3_free(pFile->lockingContext);
25160
    sqlite3_free(pFile->lockingContext);
24870
    rc = closeUnixFile(id);
25161
    rc = closeUnixFile(id);
24871
    unixLeaveMutex();
25162
    unixLeaveMutex();
 Lines 24888-24901   static int afpClose(sqlite3_file *id) { Link Here 
24888
25179
24889
#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
25180
#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
24890
/*
25181
/*
24891
 ** Lower the locking level on file descriptor pFile to locktype.  locktype
25182
 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24892
 ** must be either NO_LOCK or SHARED_LOCK.
25183
 ** must be either NO_LOCK or SHARED_LOCK.
24893
 **
25184
 **
24894
 ** If the locking level of the file descriptor is already at or below
25185
 ** If the locking level of the file descriptor is already at or below
24895
 ** the requested locking level, this routine is a no-op.
25186
 ** the requested locking level, this routine is a no-op.
24896
 */
25187
 */
24897
static int nfsUnlock(sqlite3_file *id, int locktype){
25188
static int nfsUnlock(sqlite3_file *id, int eFileLock){
24898
  return _posixUnlock(id, locktype, 1);
25189
  return _posixUnlock(id, eFileLock, 1);
24899
}
25190
}
24900
25191
24901
#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
25192
#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
 Lines 24959-24965   static int seekAndRead(unixFile *id, sql Link Here 
24959
  if( got<0 ){
25250
  if( got<0 ){
24960
    ((unixFile*)id)->lastErrno = errno;
25251
    ((unixFile*)id)->lastErrno = errno;
24961
  }
25252
  }
24962
  OSTRACE5("READ    %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
25253
  OSTRACE(("READ    %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
24963
  return got;
25254
  return got;
24964
}
25255
}
24965
25256
 Lines 24980-24989   static int unixRead( Link Here 
24980
25271
24981
  /* If this is a database file (not a journal, master-journal or temp
25272
  /* If this is a database file (not a journal, master-journal or temp
24982
  ** file), the bytes in the locking range should never be read or written. */
25273
  ** file), the bytes in the locking range should never be read or written. */
25274
#if 0
24983
  assert( pFile->pUnused==0
25275
  assert( pFile->pUnused==0
24984
       || offset>=PENDING_BYTE+512
25276
       || offset>=PENDING_BYTE+512
24985
       || offset+amt<=PENDING_BYTE 
25277
       || offset+amt<=PENDING_BYTE 
24986
  );
25278
  );
25279
#endif
24987
25280
24988
  got = seekAndRead(pFile, offset, pBuf, amt);
25281
  got = seekAndRead(pFile, offset, pBuf, amt);
24989
  if( got==amt ){
25282
  if( got==amt ){
 Lines 25033-25039   static int seekAndWrite(unixFile *id, i6 Link Here 
25033
    ((unixFile*)id)->lastErrno = errno;
25326
    ((unixFile*)id)->lastErrno = errno;
25034
  }
25327
  }
25035
25328
25036
  OSTRACE5("WRITE   %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
25329
  OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
25037
  return got;
25330
  return got;
25038
}
25331
}
25039
25332
 Lines 25052-25064   static int unixWrite( Link Here 
25052
  int wrote = 0;
25345
  int wrote = 0;
25053
  assert( id );
25346
  assert( id );
25054
  assert( amt>0 );
25347
  assert( amt>0 );
25055
25348
  struct stat buf;              /* Used to hold return values of fstat() */
25349
   
25350
  if (pFile->szChunk) {
25351
    if( fstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
25352
    off_t end_point = offset + amt;
25353
    if (buf.st_size < end_point) {
25354
      printf("Fragmenting from %ld to %ld\n", buf.st_size, end_point);
25355
    }
25356
  }
25056
  /* If this is a database file (not a journal, master-journal or temp
25357
  /* If this is a database file (not a journal, master-journal or temp
25057
  ** file), the bytes in the locking range should never be read or written. */
25358
  ** file), the bytes in the locking range should never be read or written. */
25359
#if 0
25058
  assert( pFile->pUnused==0
25360
  assert( pFile->pUnused==0
25059
       || offset>=PENDING_BYTE+512
25361
       || offset>=PENDING_BYTE+512
25060
       || offset+amt<=PENDING_BYTE 
25362
       || offset+amt<=PENDING_BYTE 
25061
  );
25363
  );
25364
#endif
25062
25365
25063
#ifndef NDEBUG
25366
#ifndef NDEBUG
25064
  /* If we are doing a normal write to a database file (as opposed to
25367
  /* If we are doing a normal write to a database file (as opposed to
 Lines 25089-25094   static int unixWrite( Link Here 
25089
  }
25392
  }
25090
  SimulateIOError(( wrote=(-1), amt=1 ));
25393
  SimulateIOError(( wrote=(-1), amt=1 ));
25091
  SimulateDiskfullError(( wrote=0, amt=1 ));
25394
  SimulateDiskfullError(( wrote=0, amt=1 ));
25395
25092
  if( amt>0 ){
25396
  if( amt>0 ){
25093
    if( wrote<0 ){
25397
    if( wrote<0 ){
25094
      /* lastErrno set by seekAndWrite */
25398
      /* lastErrno set by seekAndWrite */
 Lines 25098-25103   static int unixWrite( Link Here 
25098
      return SQLITE_FULL;
25402
      return SQLITE_FULL;
25099
    }
25403
    }
25100
  }
25404
  }
25405
25101
  return SQLITE_OK;
25406
  return SQLITE_OK;
25102
}
25407
}
25103
25408
 Lines 25257-25263   static int unixSync(sqlite3_file *id, in Link Here 
25257
  SimulateDiskfullError( return SQLITE_FULL );
25562
  SimulateDiskfullError( return SQLITE_FULL );
25258
25563
25259
  assert( pFile );
25564
  assert( pFile );
25260
  OSTRACE2("SYNC    %-3d\n", pFile->h);
25565
  OSTRACE(("SYNC    %-3d\n", pFile->h));
25261
  rc = full_fsync(pFile->h, isFullsync, isDataOnly);
25566
  rc = full_fsync(pFile->h, isFullsync, isDataOnly);
25262
  SimulateIOError( rc=1 );
25567
  SimulateIOError( rc=1 );
25263
  if( rc ){
25568
  if( rc ){
 Lines 25266-25273   static int unixSync(sqlite3_file *id, in Link Here 
25266
  }
25571
  }
25267
  if( pFile->dirfd>=0 ){
25572
  if( pFile->dirfd>=0 ){
25268
    int err;
25573
    int err;
25269
    OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
25574
    OSTRACE(("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
25270
            HAVE_FULLFSYNC, isFullsync);
25575
            HAVE_FULLFSYNC, isFullsync));
25271
#ifndef SQLITE_DISABLE_DIRSYNC
25576
#ifndef SQLITE_DISABLE_DIRSYNC
25272
    /* The directory sync is only attempted if full_fsync is
25577
    /* The directory sync is only attempted if full_fsync is
25273
    ** turned off or unavailable.  If a full_fsync occurred above,
25578
    ** turned off or unavailable.  If a full_fsync occurred above,
 Lines 25299-25310   static int unixSync(sqlite3_file *id, in Link Here 
25299
** Truncate an open file to a specified size
25604
** Truncate an open file to a specified size
25300
*/
25605
*/
25301
static int unixTruncate(sqlite3_file *id, i64 nByte){
25606
static int unixTruncate(sqlite3_file *id, i64 nByte){
25302
  int rc;
25607
  unixFile *pFile = (unixFile *)id;
25303
  assert( id );
25608
  int rc;
25609
  assert( pFile );
25304
  SimulateIOError( return SQLITE_IOERR_TRUNCATE );
25610
  SimulateIOError( return SQLITE_IOERR_TRUNCATE );
25305
  rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
25611
25612
  /* If the user has configured a chunk-size for this file, truncate the
25613
  ** file so that it consists of an integer number of chunks (i.e. the
25614
  ** actual file size after the operation may be larger than the requested
25615
  ** size).
25616
  */
25617
  if( pFile->szChunk ){
25618
    nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
25619
    printf("%p truncate to %d\n", id, nByte);
25620
  }
25621
  rc = ftruncate(pFile->h, (off_t)nByte);
25306
  if( rc ){
25622
  if( rc ){
25307
    ((unixFile*)id)->lastErrno = errno;
25623
    pFile->lastErrno = errno;
25308
    return SQLITE_IOERR_TRUNCATE;
25624
    return SQLITE_IOERR_TRUNCATE;
25309
  }else{
25625
  }else{
25310
#ifndef NDEBUG
25626
#ifndef NDEBUG
 Lines 25315-25322   static int unixTruncate(sqlite3_file *id Link Here 
25315
    ** when restoring a database using the backup API from a zero-length
25631
    ** when restoring a database using the backup API from a zero-length
25316
    ** source.
25632
    ** source.
25317
    */
25633
    */
25318
    if( ((unixFile*)id)->inNormalWrite && nByte==0 ){
25634
    if( pFile->inNormalWrite && nByte==0 ){
25319
      ((unixFile*)id)->transCntrChng = 1;
25635
      pFile->transCntrChng = 1;
25320
    }
25636
    }
25321
#endif
25637
#endif
25322
25638
 Lines 25339-25345   static int unixFileSize(sqlite3_file *id Link Here 
25339
  }
25655
  }
25340
  *pSize = buf.st_size;
25656
  *pSize = buf.st_size;
25341
25657
25342
  /* When opening a zero-size database, the findLockInfo() procedure
25658
  /* When opening a zero-size database, the findInodeInfo() procedure
25343
  ** writes a single byte into that file in order to work around a bug
25659
  ** writes a single byte into that file in order to work around a bug
25344
  ** in the OS-X msdos filesystem.  In order to avoid problems with upper
25660
  ** in the OS-X msdos filesystem.  In order to avoid problems with upper
25345
  ** layers, we need to report this file size as zero even though it is
25661
  ** layers, we need to report this file size as zero even though it is
 Lines 25359-25364   static int unixFileSize(sqlite3_file *id Link Here 
25359
static int proxyFileControl(sqlite3_file*,int,void*);
25675
static int proxyFileControl(sqlite3_file*,int,void*);
25360
#endif
25676
#endif
25361
25677
25678
/* 
25679
** This function is called to handle the SQLITE_FCNTL_SIZE_HINT 
25680
** file-control operation.
25681
**
25682
** If the user has configured a chunk-size for this file, it could be
25683
** that the file needs to be extended at this point. Otherwise, the
25684
** SQLITE_FCNTL_SIZE_HINT operation is a no-op for Unix.
25685
*/
25686
static int fcntlSizeHint(unixFile *pFile, i64 nByte){
25687
  if( pFile->szChunk ){
25688
    i64 nSize;                    /* Required file size */
25689
    struct stat buf;              /* Used to hold return values of fstat() */
25690
   
25691
    if( fstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
25692
25693
    nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
25694
    if( nSize>(i64)buf.st_size ){
25695
      printf("%p truncate to %d\n", pFile, nSize);
25696
#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
25697
      if( posix_fallocate(pFile->h, buf.st_size, nSize-buf.st_size) ){
25698
        return SQLITE_IOERR_WRITE;
25699
      }
25700
#else
25701
      /* If the OS does not have posix_fallocate(), fake it. First use
25702
      ** ftruncate() to set the file size, then write a single byte to
25703
      ** the last byte in each block within the extended region. This
25704
      ** is the same technique used by glibc to implement posix_fallocate()
25705
      ** on systems that do not have a real fallocate() system call.
25706
      */
25707
      int nBlk = buf.st_blksize;  /* File-system block size */
25708
      i64 iWrite;                 /* Next offset to write to */
25709
      int nWrite;                 /* Return value from seekAndWrite() */
25710
25711
      if( ftruncate(pFile->h, nSize) ){
25712
        pFile->lastErrno = errno;
25713
        return SQLITE_IOERR_TRUNCATE;
25714
      }
25715
      iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
25716
      do {
25717
        nWrite = seekAndWrite(pFile, iWrite, "", 1);
25718
        iWrite += nBlk;
25719
      } while( nWrite==1 && iWrite<nSize );
25720
      if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
25721
#endif
25722
    }
25723
  }
25724
25725
  return SQLITE_OK;
25726
}
25362
25727
25363
/*
25728
/*
25364
** Information and control of an open file handle.
25729
** Information and control of an open file handle.
 Lines 25366-25378   static int proxyFileControl(sqlite3_file Link Here 
25366
static int unixFileControl(sqlite3_file *id, int op, void *pArg){
25731
static int unixFileControl(sqlite3_file *id, int op, void *pArg){
25367
  switch( op ){
25732
  switch( op ){
25368
    case SQLITE_FCNTL_LOCKSTATE: {
25733
    case SQLITE_FCNTL_LOCKSTATE: {
25369
      *(int*)pArg = ((unixFile*)id)->locktype;
25734
      *(int*)pArg = ((unixFile*)id)->eFileLock;
25370
      return SQLITE_OK;
25735
      return SQLITE_OK;
25371
    }
25736
    }
25372
    case SQLITE_LAST_ERRNO: {
25737
    case SQLITE_LAST_ERRNO: {
25373
      *(int*)pArg = ((unixFile*)id)->lastErrno;
25738
      *(int*)pArg = ((unixFile*)id)->lastErrno;
25374
      return SQLITE_OK;
25739
      return SQLITE_OK;
25375
    }
25740
    }
25741
    case SQLITE_FCNTL_CHUNK_SIZE: {
25742
      ((unixFile*)id)->szChunk = *(int *)pArg;
25743
      return SQLITE_OK;
25744
    }
25745
    case SQLITE_FCNTL_SIZE_HINT: {
25746
      return fcntlSizeHint((unixFile *)id, *(i64 *)pArg);
25747
    }
25376
#ifndef NDEBUG
25748
#ifndef NDEBUG
25377
    /* The pager calls this method to signal that it has done
25749
    /* The pager calls this method to signal that it has done
25378
    ** a rollback and that the database is therefore unchanged and
25750
    ** a rollback and that the database is therefore unchanged and
 Lines 25417-25422   static int unixDeviceCharacteristics(sql Link Here 
25417
  return 0;
25789
  return 0;
25418
}
25790
}
25419
25791
25792
#ifndef SQLITE_OMIT_WAL
25793
25794
25795
/*
25796
** Object used to represent an shared memory buffer.  
25797
**
25798
** When multiple threads all reference the same wal-index, each thread
25799
** has its own unixShm object, but they all point to a single instance
25800
** of this unixShmNode object.  In other words, each wal-index is opened
25801
** only once per process.
25802
**
25803
** Each unixShmNode object is connected to a single unixInodeInfo object.
25804
** We could coalesce this object into unixInodeInfo, but that would mean
25805
** every open file that does not use shared memory (in other words, most
25806
** open files) would have to carry around this extra information.  So
25807
** the unixInodeInfo object contains a pointer to this unixShmNode object
25808
** and the unixShmNode object is created only when needed.
25809
**
25810
** unixMutexHeld() must be true when creating or destroying
25811
** this object or while reading or writing the following fields:
25812
**
25813
**      nRef
25814
**
25815
** The following fields are read-only after the object is created:
25816
** 
25817
**      fid
25818
**      zFilename
25819
**
25820
** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
25821
** unixMutexHeld() is true when reading or writing any other field
25822
** in this structure.
25823
*/
25824
struct unixShmNode {
25825
  unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
25826
  sqlite3_mutex *mutex;      /* Mutex to access this object */
25827
  char *zFilename;           /* Name of the mmapped file */
25828
  int h;                     /* Open file descriptor */
25829
  int szRegion;              /* Size of shared-memory regions */
25830
  int nRegion;               /* Size of array apRegion */
25831
  char **apRegion;           /* Array of mapped shared-memory regions */
25832
  int nRef;                  /* Number of unixShm objects pointing to this */
25833
  unixShm *pFirst;           /* All unixShm objects pointing to this */
25834
#ifdef SQLITE_DEBUG
25835
  u8 exclMask;               /* Mask of exclusive locks held */
25836
  u8 sharedMask;             /* Mask of shared locks held */
25837
  u8 nextShmId;              /* Next available unixShm.id value */
25838
#endif
25839
};
25840
25841
/*
25842
** Structure used internally by this VFS to record the state of an
25843
** open shared memory connection.
25844
**
25845
** The following fields are initialized when this object is created and
25846
** are read-only thereafter:
25847
**
25848
**    unixShm.pFile
25849
**    unixShm.id
25850
**
25851
** All other fields are read/write.  The unixShm.pFile->mutex must be held
25852
** while accessing any read/write fields.
25853
*/
25854
struct unixShm {
25855
  unixShmNode *pShmNode;     /* The underlying unixShmNode object */
25856
  unixShm *pNext;            /* Next unixShm with the same unixShmNode */
25857
  u8 hasMutex;               /* True if holding the unixShmNode mutex */
25858
  u16 sharedMask;            /* Mask of shared locks held */
25859
  u16 exclMask;              /* Mask of exclusive locks held */
25860
#ifdef SQLITE_DEBUG
25861
  u8 id;                     /* Id of this connection within its unixShmNode */
25862
#endif
25863
};
25864
25865
/*
25866
** Constants used for locking
25867
*/
25868
#define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */
25869
#define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
25870
25871
/*
25872
** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
25873
**
25874
** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
25875
** otherwise.
25876
*/
25877
static int unixShmSystemLock(
25878
  unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
25879
  int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
25880
  int ofst,              /* First byte of the locking range */
25881
  int n                  /* Number of bytes to lock */
25882
){
25883
  struct flock f;       /* The posix advisory locking structure */
25884
  int rc = SQLITE_OK;   /* Result code form fcntl() */
25885
25886
  /* Access to the unixShmNode object is serialized by the caller */
25887
  assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
25888
25889
  /* Shared locks never span more than one byte */
25890
  assert( n==1 || lockType!=F_RDLCK );
25891
25892
  /* Locks are within range */
25893
  assert( n>=1 && n<SQLITE_SHM_NLOCK );
25894
25895
  /* Initialize the locking parameters */
25896
  memset(&f, 0, sizeof(f));
25897
  f.l_type = lockType;
25898
  f.l_whence = SEEK_SET;
25899
  f.l_start = ofst;
25900
  f.l_len = n;
25901
25902
  rc = fcntl(pShmNode->h, F_SETLK, &f);
25903
  rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
25904
25905
  /* Update the global lock state and do debug tracing */
25906
#ifdef SQLITE_DEBUG
25907
  { u16 mask;
25908
  OSTRACE(("SHM-LOCK "));
25909
  mask = (1<<(ofst+n)) - (1<<ofst);
25910
  if( rc==SQLITE_OK ){
25911
    if( lockType==F_UNLCK ){
25912
      OSTRACE(("unlock %d ok", ofst));
25913
      pShmNode->exclMask &= ~mask;
25914
      pShmNode->sharedMask &= ~mask;
25915
    }else if( lockType==F_RDLCK ){
25916
      OSTRACE(("read-lock %d ok", ofst));
25917
      pShmNode->exclMask &= ~mask;
25918
      pShmNode->sharedMask |= mask;
25919
    }else{
25920
      assert( lockType==F_WRLCK );
25921
      OSTRACE(("write-lock %d ok", ofst));
25922
      pShmNode->exclMask |= mask;
25923
      pShmNode->sharedMask &= ~mask;
25924
    }
25925
  }else{
25926
    if( lockType==F_UNLCK ){
25927
      OSTRACE(("unlock %d failed", ofst));
25928
    }else if( lockType==F_RDLCK ){
25929
      OSTRACE(("read-lock failed"));
25930
    }else{
25931
      assert( lockType==F_WRLCK );
25932
      OSTRACE(("write-lock %d failed", ofst));
25933
    }
25934
  }
25935
  OSTRACE((" - afterwards %03x,%03x\n",
25936
           pShmNode->sharedMask, pShmNode->exclMask));
25937
  }
25938
#endif
25939
25940
  return rc;        
25941
}
25942
25943
25944
/*
25945
** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
25946
**
25947
** This is not a VFS shared-memory method; it is a utility function called
25948
** by VFS shared-memory methods.
25949
*/
25950
static void unixShmPurge(unixFile *pFd){
25951
  unixShmNode *p = pFd->pInode->pShmNode;
25952
  assert( unixMutexHeld() );
25953
  if( p && p->nRef==0 ){
25954
    int i;
25955
    assert( p->pInode==pFd->pInode );
25956
    if( p->mutex ) sqlite3_mutex_free(p->mutex);
25957
    for(i=0; i<p->nRegion; i++){
25958
      munmap(p->apRegion[i], p->szRegion);
25959
    }
25960
    sqlite3_free(p->apRegion);
25961
    if( p->h>=0 ) close(p->h);
25962
    p->pInode->pShmNode = 0;
25963
    sqlite3_free(p);
25964
  }
25965
}
25966
25967
/*
25968
** Open a shared-memory area associated with open database file pDbFd.  
25969
** This particular implementation uses mmapped files.
25970
**
25971
** The file used to implement shared-memory is in the same directory
25972
** as the open database file and has the same name as the open database
25973
** file with the "-shm" suffix added.  For example, if the database file
25974
** is "/home/user1/config.db" then the file that is created and mmapped
25975
** for shared memory will be called "/home/user1/config.db-shm".  
25976
**
25977
** Another approach to is to use files in /dev/shm or /dev/tmp or an
25978
** some other tmpfs mount. But if a file in a different directory
25979
** from the database file is used, then differing access permissions
25980
** or a chroot() might cause two different processes on the same
25981
** database to end up using different files for shared memory - 
25982
** meaning that their memory would not really be shared - resulting
25983
** in database corruption.  Nevertheless, this tmpfs file usage
25984
** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
25985
** or the equivalent.  The use of the SQLITE_SHM_DIRECTORY compile-time
25986
** option results in an incompatible build of SQLite;  builds of SQLite
25987
** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
25988
** same database file at the same time, database corruption will likely
25989
** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
25990
** "unsupported" and may go away in a future SQLite release.
25991
**
25992
** When opening a new shared-memory file, if no other instances of that
25993
** file are currently open, in this process or in other processes, then
25994
** the file must be truncated to zero length or have its header cleared.
25995
*/
25996
static int unixOpenSharedMemory(unixFile *pDbFd){
25997
  struct unixShm *p = 0;          /* The connection to be opened */
25998
  struct unixShmNode *pShmNode;   /* The underlying mmapped file */
25999
  int rc;                         /* Result code */
26000
  unixInodeInfo *pInode;          /* The inode of fd */
26001
  char *zShmFilename;             /* Name of the file used for SHM */
26002
  int nShmFilename;               /* Size of the SHM filename in bytes */
26003
26004
  /* Allocate space for the new unixShm object. */
26005
  p = sqlite3_malloc( sizeof(*p) );
26006
  if( p==0 ) return SQLITE_NOMEM;
26007
  memset(p, 0, sizeof(*p));
26008
  assert( pDbFd->pShm==0 );
26009
26010
  /* Check to see if a unixShmNode object already exists. Reuse an existing
26011
  ** one if present. Create a new one if necessary.
26012
  */
26013
  unixEnterMutex();
26014
  pInode = pDbFd->pInode;
26015
  pShmNode = pInode->pShmNode;
26016
  if( pShmNode==0 ){
26017
    struct stat sStat;                 /* fstat() info for database file */
26018
26019
    /* Call fstat() to figure out the permissions on the database file. If
26020
    ** a new *-shm file is created, an attempt will be made to create it
26021
    ** with the same permissions. The actual permissions the file is created
26022
    ** with are subject to the current umask setting.
26023
    */
26024
    if( fstat(pDbFd->h, &sStat) ){
26025
      rc = SQLITE_IOERR_FSTAT;
26026
      goto shm_open_err;
26027
    }
26028
26029
#ifdef SQLITE_SHM_DIRECTORY
26030
    nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
26031
#else
26032
    nShmFilename = 5 + (int)strlen(pDbFd->zPath);
26033
#endif
26034
    pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
26035
    if( pShmNode==0 ){
26036
      rc = SQLITE_NOMEM;
26037
      goto shm_open_err;
26038
    }
26039
    memset(pShmNode, 0, sizeof(*pShmNode));
26040
    zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
26041
#ifdef SQLITE_SHM_DIRECTORY
26042
    sqlite3_snprintf(nShmFilename, zShmFilename, 
26043
                     SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
26044
                     (u32)sStat.st_ino, (u32)sStat.st_dev);
26045
#else
26046
    sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
26047
#endif
26048
    pShmNode->h = -1;
26049
    pDbFd->pInode->pShmNode = pShmNode;
26050
    pShmNode->pInode = pDbFd->pInode;
26051
    pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
26052
    if( pShmNode->mutex==0 ){
26053
      rc = SQLITE_NOMEM;
26054
      goto shm_open_err;
26055
    }
26056
26057
    pShmNode->h = open(zShmFilename, O_RDWR|O_CREAT, (sStat.st_mode & 0777));
26058
    if( pShmNode->h<0 ){
26059
      rc = SQLITE_CANTOPEN_BKPT;
26060
      goto shm_open_err;
26061
    }
26062
26063
    /* Check to see if another process is holding the dead-man switch.
26064
    ** If not, truncate the file to zero length. 
26065
    */
26066
    rc = SQLITE_OK;
26067
    if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
26068
      if( ftruncate(pShmNode->h, 0) ){
26069
        rc = SQLITE_IOERR_SHMOPEN;
26070
      }
26071
    }
26072
    if( rc==SQLITE_OK ){
26073
      rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
26074
    }
26075
    if( rc ) goto shm_open_err;
26076
  }
26077
26078
  /* Make the new connection a child of the unixShmNode */
26079
  p->pShmNode = pShmNode;
26080
#ifdef SQLITE_DEBUG
26081
  p->id = pShmNode->nextShmId++;
26082
#endif
26083
  pShmNode->nRef++;
26084
  pDbFd->pShm = p;
26085
  unixLeaveMutex();
26086
26087
  /* The reference count on pShmNode has already been incremented under
26088
  ** the cover of the unixEnterMutex() mutex and the pointer from the
26089
  ** new (struct unixShm) object to the pShmNode has been set. All that is
26090
  ** left to do is to link the new object into the linked list starting
26091
  ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex 
26092
  ** mutex.
26093
  */
26094
  sqlite3_mutex_enter(pShmNode->mutex);
26095
  p->pNext = pShmNode->pFirst;
26096
  pShmNode->pFirst = p;
26097
  sqlite3_mutex_leave(pShmNode->mutex);
26098
  return SQLITE_OK;
26099
26100
  /* Jump here on any error */
26101
shm_open_err:
26102
  unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
26103
  sqlite3_free(p);
26104
  unixLeaveMutex();
26105
  return rc;
26106
}
26107
26108
/*
26109
** This function is called to obtain a pointer to region iRegion of the 
26110
** shared-memory associated with the database file fd. Shared-memory regions 
26111
** are numbered starting from zero. Each shared-memory region is szRegion 
26112
** bytes in size.
26113
**
26114
** If an error occurs, an error code is returned and *pp is set to NULL.
26115
**
26116
** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
26117
** region has not been allocated (by any client, including one running in a
26118
** separate process), then *pp is set to NULL and SQLITE_OK returned. If 
26119
** bExtend is non-zero and the requested shared-memory region has not yet 
26120
** been allocated, it is allocated by this function.
26121
**
26122
** If the shared-memory region has already been allocated or is allocated by
26123
** this call as described above, then it is mapped into this processes 
26124
** address space (if it is not already), *pp is set to point to the mapped 
26125
** memory and SQLITE_OK returned.
26126
*/
26127
static int unixShmMap(
26128
  sqlite3_file *fd,               /* Handle open on database file */
26129
  int iRegion,                    /* Region to retrieve */
26130
  int szRegion,                   /* Size of regions */
26131
  int bExtend,                    /* True to extend file if necessary */
26132
  void volatile **pp              /* OUT: Mapped memory */
26133
){
26134
  unixFile *pDbFd = (unixFile*)fd;
26135
  unixShm *p;
26136
  unixShmNode *pShmNode;
26137
  int rc = SQLITE_OK;
26138
26139
  /* If the shared-memory file has not yet been opened, open it now. */
26140
  if( pDbFd->pShm==0 ){
26141
    rc = unixOpenSharedMemory(pDbFd);
26142
    if( rc!=SQLITE_OK ) return rc;
26143
  }
26144
26145
  p = pDbFd->pShm;
26146
  pShmNode = p->pShmNode;
26147
  sqlite3_mutex_enter(pShmNode->mutex);
26148
  assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
26149
26150
  if( pShmNode->nRegion<=iRegion ){
26151
    char **apNew;                      /* New apRegion[] array */
26152
    int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
26153
    struct stat sStat;                 /* Used by fstat() */
26154
26155
    pShmNode->szRegion = szRegion;
26156
26157
    /* The requested region is not mapped into this processes address space.
26158
    ** Check to see if it has been allocated (i.e. if the wal-index file is
26159
    ** large enough to contain the requested region).
26160
    */
26161
    if( fstat(pShmNode->h, &sStat) ){
26162
      rc = SQLITE_IOERR_SHMSIZE;
26163
      goto shmpage_out;
26164
    }
26165
26166
    if( sStat.st_size<nByte ){
26167
      /* The requested memory region does not exist. If bExtend is set to
26168
      ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
26169
      **
26170
      ** Alternatively, if bExtend is true, use ftruncate() to allocate
26171
      ** the requested memory region.
26172
      */
26173
      if( !bExtend ) goto shmpage_out;
26174
      if( ftruncate(pShmNode->h, nByte) ){
26175
        rc = SQLITE_IOERR_SHMSIZE;
26176
        goto shmpage_out;
26177
      }
26178
    }
26179
26180
    /* Map the requested memory region into this processes address space. */
26181
    apNew = (char **)sqlite3_realloc(
26182
        pShmNode->apRegion, (iRegion+1)*sizeof(char *)
26183
    );
26184
    if( !apNew ){
26185
      rc = SQLITE_IOERR_NOMEM;
26186
      goto shmpage_out;
26187
    }
26188
    pShmNode->apRegion = apNew;
26189
    while(pShmNode->nRegion<=iRegion){
26190
      void *pMem = mmap(0, szRegion, PROT_READ|PROT_WRITE, 
26191
          MAP_SHARED, pShmNode->h, iRegion*szRegion
26192
      );
26193
      if( pMem==MAP_FAILED ){
26194
        rc = SQLITE_IOERR;
26195
        goto shmpage_out;
26196
      }
26197
      pShmNode->apRegion[pShmNode->nRegion] = pMem;
26198
      pShmNode->nRegion++;
26199
    }
26200
  }
26201
26202
shmpage_out:
26203
  if( pShmNode->nRegion>iRegion ){
26204
    *pp = pShmNode->apRegion[iRegion];
26205
  }else{
26206
    *pp = 0;
26207
  }
26208
  sqlite3_mutex_leave(pShmNode->mutex);
26209
  return rc;
26210
}
26211
26212
/*
26213
** Change the lock state for a shared-memory segment.
26214
**
26215
** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
26216
** different here than in posix.  In xShmLock(), one can go from unlocked
26217
** to shared and back or from unlocked to exclusive and back.  But one may
26218
** not go from shared to exclusive or from exclusive to shared.
26219
*/
26220
static int unixShmLock(
26221
  sqlite3_file *fd,          /* Database file holding the shared memory */
26222
  int ofst,                  /* First lock to acquire or release */
26223
  int n,                     /* Number of locks to acquire or release */
26224
  int flags                  /* What to do with the lock */
26225
){
26226
  unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
26227
  unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
26228
  unixShm *pX;                          /* For looping over all siblings */
26229
  unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
26230
  int rc = SQLITE_OK;                   /* Result code */
26231
  u16 mask;                             /* Mask of locks to take or release */
26232
26233
  assert( pShmNode==pDbFd->pInode->pShmNode );
26234
  assert( pShmNode->pInode==pDbFd->pInode );
26235
  assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
26236
  assert( n>=1 );
26237
  assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
26238
       || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
26239
       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
26240
       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
26241
  assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
26242
26243
  mask = (1<<(ofst+n)) - (1<<ofst);
26244
  assert( n>1 || mask==(1<<ofst) );
26245
  sqlite3_mutex_enter(pShmNode->mutex);
26246
  if( flags & SQLITE_SHM_UNLOCK ){
26247
    u16 allMask = 0; /* Mask of locks held by siblings */
26248
26249
    /* See if any siblings hold this same lock */
26250
    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
26251
      if( pX==p ) continue;
26252
      assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
26253
      allMask |= pX->sharedMask;
26254
    }
26255
26256
    /* Unlock the system-level locks */
26257
    if( (mask & allMask)==0 ){
26258
      rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
26259
    }else{
26260
      rc = SQLITE_OK;
26261
    }
26262
26263
    /* Undo the local locks */
26264
    if( rc==SQLITE_OK ){
26265
      p->exclMask &= ~mask;
26266
      p->sharedMask &= ~mask;
26267
    } 
26268
  }else if( flags & SQLITE_SHM_SHARED ){
26269
    u16 allShared = 0;  /* Union of locks held by connections other than "p" */
26270
26271
    /* Find out which shared locks are already held by sibling connections.
26272
    ** If any sibling already holds an exclusive lock, go ahead and return
26273
    ** SQLITE_BUSY.
26274
    */
26275
    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
26276
      if( (pX->exclMask & mask)!=0 ){
26277
        rc = SQLITE_BUSY;
26278
        break;
26279
      }
26280
      allShared |= pX->sharedMask;
26281
    }
26282
26283
    /* Get shared locks at the system level, if necessary */
26284
    if( rc==SQLITE_OK ){
26285
      if( (allShared & mask)==0 ){
26286
        rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
26287
      }else{
26288
        rc = SQLITE_OK;
26289
      }
26290
    }
26291
26292
    /* Get the local shared locks */
26293
    if( rc==SQLITE_OK ){
26294
      p->sharedMask |= mask;
26295
    }
26296
  }else{
26297
    /* Make sure no sibling connections hold locks that will block this
26298
    ** lock.  If any do, return SQLITE_BUSY right away.
26299
    */
26300
    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
26301
      if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
26302
        rc = SQLITE_BUSY;
26303
        break;
26304
      }
26305
    }
26306
  
26307
    /* Get the exclusive locks at the system level.  Then if successful
26308
    ** also mark the local connection as being locked.
26309
    */
26310
    if( rc==SQLITE_OK ){
26311
      rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
26312
      if( rc==SQLITE_OK ){
26313
        assert( (p->sharedMask & mask)==0 );
26314
        p->exclMask |= mask;
26315
      }
26316
    }
26317
  }
26318
  sqlite3_mutex_leave(pShmNode->mutex);
26319
  OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
26320
           p->id, getpid(), p->sharedMask, p->exclMask));
26321
  return rc;
26322
}
26323
26324
/*
26325
** Implement a memory barrier or memory fence on shared memory.  
26326
**
26327
** All loads and stores begun before the barrier must complete before
26328
** any load or store begun after the barrier.
26329
*/
26330
static void unixShmBarrier(
26331
  sqlite3_file *fd                /* Database file holding the shared memory */
26332
){
26333
  UNUSED_PARAMETER(fd);
26334
  unixEnterMutex();
26335
  unixLeaveMutex();
26336
}
26337
26338
/*
26339
** Close a connection to shared-memory.  Delete the underlying 
26340
** storage if deleteFlag is true.
26341
**
26342
** If there is no shared memory associated with the connection then this
26343
** routine is a harmless no-op.
26344
*/
26345
static int unixShmUnmap(
26346
  sqlite3_file *fd,               /* The underlying database file */
26347
  int deleteFlag                  /* Delete shared-memory if true */
26348
){
26349
  unixShm *p;                     /* The connection to be closed */
26350
  unixShmNode *pShmNode;          /* The underlying shared-memory file */
26351
  unixShm **pp;                   /* For looping over sibling connections */
26352
  unixFile *pDbFd;                /* The underlying database file */
26353
26354
  pDbFd = (unixFile*)fd;
26355
  p = pDbFd->pShm;
26356
  if( p==0 ) return SQLITE_OK;
26357
  pShmNode = p->pShmNode;
26358
26359
  assert( pShmNode==pDbFd->pInode->pShmNode );
26360
  assert( pShmNode->pInode==pDbFd->pInode );
26361
26362
  /* Remove connection p from the set of connections associated
26363
  ** with pShmNode */
26364
  sqlite3_mutex_enter(pShmNode->mutex);
26365
  for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
26366
  *pp = p->pNext;
26367
26368
  /* Free the connection p */
26369
  sqlite3_free(p);
26370
  pDbFd->pShm = 0;
26371
  sqlite3_mutex_leave(pShmNode->mutex);
26372
26373
  /* If pShmNode->nRef has reached 0, then close the underlying
26374
  ** shared-memory file, too */
26375
  unixEnterMutex();
26376
  assert( pShmNode->nRef>0 );
26377
  pShmNode->nRef--;
26378
  if( pShmNode->nRef==0 ){
26379
    if( deleteFlag ) unlink(pShmNode->zFilename);
26380
    unixShmPurge(pDbFd);
26381
  }
26382
  unixLeaveMutex();
26383
26384
  return SQLITE_OK;
26385
}
26386
26387
26388
#else
26389
# define unixShmMap     0
26390
# define unixShmLock    0
26391
# define unixShmBarrier 0
26392
# define unixShmUnmap   0
26393
#endif /* #ifndef SQLITE_OMIT_WAL */
26394
25420
/*
26395
/*
25421
** Here ends the implementation of all sqlite3_file methods.
26396
** Here ends the implementation of all sqlite3_file methods.
25422
**
26397
**
 Lines 25457-25465   static int unixDeviceCharacteristics(sql Link Here 
25457
**   *  An I/O method finder function called FINDER that returns a pointer
26432
**   *  An I/O method finder function called FINDER that returns a pointer
25458
**      to the METHOD object in the previous bullet.
26433
**      to the METHOD object in the previous bullet.
25459
*/
26434
*/
25460
#define IOMETHODS(FINDER, METHOD, CLOSE, LOCK, UNLOCK, CKLOCK)               \
26435
#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK)      \
25461
static const sqlite3_io_methods METHOD = {                                   \
26436
static const sqlite3_io_methods METHOD = {                                   \
25462
   1,                          /* iVersion */                                \
26437
   VERSION,                    /* iVersion */                                \
25463
   CLOSE,                      /* xClose */                                  \
26438
   CLOSE,                      /* xClose */                                  \
25464
   unixRead,                   /* xRead */                                   \
26439
   unixRead,                   /* xRead */                                   \
25465
   unixWrite,                  /* xWrite */                                  \
26440
   unixWrite,                  /* xWrite */                                  \
 Lines 25471-25477   static const sqlite3_io_methods METHOD = Link Here 
25471
   CKLOCK,                     /* xCheckReservedLock */                      \
26446
   CKLOCK,                     /* xCheckReservedLock */                      \
25472
   unixFileControl,            /* xFileControl */                            \
26447
   unixFileControl,            /* xFileControl */                            \
25473
   unixSectorSize,             /* xSectorSize */                             \
26448
   unixSectorSize,             /* xSectorSize */                             \
25474
   unixDeviceCharacteristics   /* xDeviceCapabilities */                     \
26449
   unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
26450
   unixShmMap,                 /* xShmMap */                                 \
26451
   unixShmLock,                /* xShmLock */                                \
26452
   unixShmBarrier,             /* xShmBarrier */                             \
26453
   unixShmUnmap                /* xShmUnmap */                               \
25475
};                                                                           \
26454
};                                                                           \
25476
static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
26455
static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
25477
  UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
26456
  UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
 Lines 25488-25493   static const sqlite3_io_methods *(*const Link Here 
25488
IOMETHODS(
26467
IOMETHODS(
25489
  posixIoFinder,            /* Finder function name */
26468
  posixIoFinder,            /* Finder function name */
25490
  posixIoMethods,           /* sqlite3_io_methods object name */
26469
  posixIoMethods,           /* sqlite3_io_methods object name */
26470
  2,                        /* shared memory is enabled */
25491
  unixClose,                /* xClose method */
26471
  unixClose,                /* xClose method */
25492
  unixLock,                 /* xLock method */
26472
  unixLock,                 /* xLock method */
25493
  unixUnlock,               /* xUnlock method */
26473
  unixUnlock,               /* xUnlock method */
 Lines 25496-25501   IOMETHODS( Link Here 
25496
IOMETHODS(
26476
IOMETHODS(
25497
  nolockIoFinder,           /* Finder function name */
26477
  nolockIoFinder,           /* Finder function name */
25498
  nolockIoMethods,          /* sqlite3_io_methods object name */
26478
  nolockIoMethods,          /* sqlite3_io_methods object name */
26479
  1,                        /* shared memory is disabled */
25499
  nolockClose,              /* xClose method */
26480
  nolockClose,              /* xClose method */
25500
  nolockLock,               /* xLock method */
26481
  nolockLock,               /* xLock method */
25501
  nolockUnlock,             /* xUnlock method */
26482
  nolockUnlock,             /* xUnlock method */
 Lines 25504-25509   IOMETHODS( Link Here 
25504
IOMETHODS(
26485
IOMETHODS(
25505
  dotlockIoFinder,          /* Finder function name */
26486
  dotlockIoFinder,          /* Finder function name */
25506
  dotlockIoMethods,         /* sqlite3_io_methods object name */
26487
  dotlockIoMethods,         /* sqlite3_io_methods object name */
26488
  1,                        /* shared memory is disabled */
25507
  dotlockClose,             /* xClose method */
26489
  dotlockClose,             /* xClose method */
25508
  dotlockLock,              /* xLock method */
26490
  dotlockLock,              /* xLock method */
25509
  dotlockUnlock,            /* xUnlock method */
26491
  dotlockUnlock,            /* xUnlock method */
 Lines 25514-25519   IOMETHODS( Link Here 
25514
IOMETHODS(
26496
IOMETHODS(
25515
  flockIoFinder,            /* Finder function name */
26497
  flockIoFinder,            /* Finder function name */
25516
  flockIoMethods,           /* sqlite3_io_methods object name */
26498
  flockIoMethods,           /* sqlite3_io_methods object name */
26499
  1,                        /* shared memory is disabled */
25517
  flockClose,               /* xClose method */
26500
  flockClose,               /* xClose method */
25518
  flockLock,                /* xLock method */
26501
  flockLock,                /* xLock method */
25519
  flockUnlock,              /* xUnlock method */
26502
  flockUnlock,              /* xUnlock method */
 Lines 25525-25530   IOMETHODS( Link Here 
25525
IOMETHODS(
26508
IOMETHODS(
25526
  semIoFinder,              /* Finder function name */
26509
  semIoFinder,              /* Finder function name */
25527
  semIoMethods,             /* sqlite3_io_methods object name */
26510
  semIoMethods,             /* sqlite3_io_methods object name */
26511
  1,                        /* shared memory is disabled */
25528
  semClose,                 /* xClose method */
26512
  semClose,                 /* xClose method */
25529
  semLock,                  /* xLock method */
26513
  semLock,                  /* xLock method */
25530
  semUnlock,                /* xUnlock method */
26514
  semUnlock,                /* xUnlock method */
 Lines 25536-25541   IOMETHODS( Link Here 
25536
IOMETHODS(
26520
IOMETHODS(
25537
  afpIoFinder,              /* Finder function name */
26521
  afpIoFinder,              /* Finder function name */
25538
  afpIoMethods,             /* sqlite3_io_methods object name */
26522
  afpIoMethods,             /* sqlite3_io_methods object name */
26523
  1,                        /* shared memory is disabled */
25539
  afpClose,                 /* xClose method */
26524
  afpClose,                 /* xClose method */
25540
  afpLock,                  /* xLock method */
26525
  afpLock,                  /* xLock method */
25541
  afpUnlock,                /* xUnlock method */
26526
  afpUnlock,                /* xUnlock method */
 Lines 25560-25565   static int proxyCheckReservedLock(sqlite Link Here 
25560
IOMETHODS(
26545
IOMETHODS(
25561
  proxyIoFinder,            /* Finder function name */
26546
  proxyIoFinder,            /* Finder function name */
25562
  proxyIoMethods,           /* sqlite3_io_methods object name */
26547
  proxyIoMethods,           /* sqlite3_io_methods object name */
26548
  1,                        /* shared memory is disabled */
25563
  proxyClose,               /* xClose method */
26549
  proxyClose,               /* xClose method */
25564
  proxyLock,                /* xLock method */
26550
  proxyLock,                /* xLock method */
25565
  proxyUnlock,              /* xUnlock method */
26551
  proxyUnlock,              /* xUnlock method */
 Lines 25572-25577   IOMETHODS( Link Here 
25572
IOMETHODS(
26558
IOMETHODS(
25573
  nfsIoFinder,               /* Finder function name */
26559
  nfsIoFinder,               /* Finder function name */
25574
  nfsIoMethods,              /* sqlite3_io_methods object name */
26560
  nfsIoMethods,              /* sqlite3_io_methods object name */
26561
  1,                         /* shared memory is disabled */
25575
  unixClose,                 /* xClose method */
26562
  unixClose,                 /* xClose method */
25576
  unixLock,                  /* xLock method */
26563
  unixLock,                  /* xLock method */
25577
  nfsUnlock,                 /* xUnlock method */
26564
  nfsUnlock,                 /* xUnlock method */
 Lines 25712-25730   static int fillInUnixFile( Link Here 
25712
  unixFile *pNew = (unixFile *)pId;
26699
  unixFile *pNew = (unixFile *)pId;
25713
  int rc = SQLITE_OK;
26700
  int rc = SQLITE_OK;
25714
26701
25715
  assert( pNew->pLock==NULL );
26702
  assert( pNew->pInode==NULL );
25716
  assert( pNew->pOpen==NULL );
25717
26703
25718
  /* Parameter isDelete is only used on vxworks. Express this explicitly 
26704
  /* Parameter isDelete is only used on vxworks. Express this explicitly 
25719
  ** here to prevent compiler warnings about unused parameters.
26705
  ** here to prevent compiler warnings about unused parameters.
25720
  */
26706
  */
25721
  UNUSED_PARAMETER(isDelete);
26707
  UNUSED_PARAMETER(isDelete);
25722
26708
25723
  OSTRACE3("OPEN    %-3d %s\n", h, zFilename);    
26709
  OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
25724
  pNew->h = h;
26710
  pNew->h = h;
25725
  pNew->dirfd = dirfd;
26711
  pNew->dirfd = dirfd;
25726
  SET_THREADID(pNew);
25727
  pNew->fileFlags = 0;
26712
  pNew->fileFlags = 0;
26713
  assert( zFilename==0 || zFilename[0]=='/' );  /* Never a relative pathname */
26714
  pNew->zPath = zFilename;
25728
26715
25729
#if OS_VXWORKS
26716
#if OS_VXWORKS
25730
  pNew->pId = vxworksFindFileId(zFilename);
26717
  pNew->pId = vxworksFindFileId(zFilename);
 Lines 25752-25761   static int fillInUnixFile( Link Here 
25752
#endif
26739
#endif
25753
  ){
26740
  ){
25754
    unixEnterMutex();
26741
    unixEnterMutex();
25755
    rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
26742
    rc = findInodeInfo(pNew, &pNew->pInode);
25756
    if( rc!=SQLITE_OK ){
26743
    if( rc!=SQLITE_OK ){
25757
      /* If an error occured in findLockInfo(), close the file descriptor
26744
      /* If an error occured in findInodeInfo(), close the file descriptor
25758
      ** immediately, before releasing the mutex. findLockInfo() may fail
26745
      ** immediately, before releasing the mutex. findInodeInfo() may fail
25759
      ** in two scenarios:
26746
      ** in two scenarios:
25760
      **
26747
      **
25761
      **   (a) A call to fstat() failed.
26748
      **   (a) A call to fstat() failed.
 Lines 25764-25770   static int fillInUnixFile( Link Here 
25764
      ** Scenario (b) may only occur if the process is holding no other
26751
      ** Scenario (b) may only occur if the process is holding no other
25765
      ** file descriptors open on the same file. If there were other file
26752
      ** file descriptors open on the same file. If there were other file
25766
      ** descriptors on this file, then no malloc would be required by
26753
      ** descriptors on this file, then no malloc would be required by
25767
      ** findLockInfo(). If this is the case, it is quite safe to close
26754
      ** findInodeInfo(). If this is the case, it is quite safe to close
25768
      ** handle h - as it is guaranteed that no posix locks will be released
26755
      ** handle h - as it is guaranteed that no posix locks will be released
25769
      ** by doing so.
26756
      ** by doing so.
25770
      **
26757
      **
 Lines 25795-25801   static int fillInUnixFile( Link Here 
25795
      pCtx->reserved = 0;
26782
      pCtx->reserved = 0;
25796
      srandomdev();
26783
      srandomdev();
25797
      unixEnterMutex();
26784
      unixEnterMutex();
25798
      rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
26785
      rc = findInodeInfo(pNew, &pNew->pInode);
25799
      if( rc!=SQLITE_OK ){
26786
      if( rc!=SQLITE_OK ){
25800
        sqlite3_free(pNew->lockingContext);
26787
        sqlite3_free(pNew->lockingContext);
25801
        close(h);
26788
        close(h);
 Lines 25828-25845   static int fillInUnixFile( Link Here 
25828
    ** included in the semLockingContext
26815
    ** included in the semLockingContext
25829
    */
26816
    */
25830
    unixEnterMutex();
26817
    unixEnterMutex();
25831
    rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
26818
    rc = findInodeInfo(pNew, &pNew->pInode);
25832
    if( (rc==SQLITE_OK) && (pNew->pOpen->pSem==NULL) ){
26819
    if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
25833
      char *zSemName = pNew->pOpen->aSemName;
26820
      char *zSemName = pNew->pInode->aSemName;
25834
      int n;
26821
      int n;
25835
      sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
26822
      sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
25836
                       pNew->pId->zCanonicalName);
26823
                       pNew->pId->zCanonicalName);
25837
      for( n=1; zSemName[n]; n++ )
26824
      for( n=1; zSemName[n]; n++ )
25838
        if( zSemName[n]=='/' ) zSemName[n] = '_';
26825
        if( zSemName[n]=='/' ) zSemName[n] = '_';
25839
      pNew->pOpen->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
26826
      pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
25840
      if( pNew->pOpen->pSem == SEM_FAILED ){
26827
      if( pNew->pInode->pSem == SEM_FAILED ){
25841
        rc = SQLITE_NOMEM;
26828
        rc = SQLITE_NOMEM;
25842
        pNew->pOpen->aSemName[0] = '\0';
26829
        pNew->pInode->aSemName[0] = '\0';
25843
      }
26830
      }
25844
    }
26831
    }
25845
    unixLeaveMutex();
26832
    unixLeaveMutex();
 Lines 25890-25896   static int openDirectory(const char *zFi Link Here 
25890
#ifdef FD_CLOEXEC
26877
#ifdef FD_CLOEXEC
25891
      fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
26878
      fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
25892
#endif
26879
#endif
25893
      OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
26880
      OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
25894
    }
26881
    }
25895
  }
26882
  }
25896
  *pFd = fd;
26883
  *pFd = fd;
 Lines 25898-25923   static int openDirectory(const char *zFi Link Here 
25898
}
26885
}
25899
26886
25900
/*
26887
/*
25901
** Create a temporary file name in zBuf.  zBuf must be allocated
26888
** Return the name of a directory in which to put temporary files.
25902
** by the calling process and must be big enough to hold at least
26889
** If no suitable temporary file directory can be found, return NULL.
25903
** pVfs->mxPathname bytes.
26890
*/
25904
*/
26891
static const char *unixTempFileDir(void){
25905
static int getTempname(int nBuf, char *zBuf){
25906
  static const char *azDirs[] = {
26892
  static const char *azDirs[] = {
25907
     0,
26893
     0,
25908
     0,
26894
     0,
25909
     "/var/tmp",
26895
     "/var/tmp",
25910
     "/usr/tmp",
26896
     "/usr/tmp",
25911
     "/tmp",
26897
     "/tmp",
25912
     ".",
26898
     0        /* List terminator */
25913
  };
26899
  };
26900
  unsigned int i;
26901
  struct stat buf;
26902
  const char *zDir = 0;
26903
26904
  azDirs[0] = sqlite3_temp_directory;
26905
  if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
26906
  for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
26907
    if( zDir==0 ) continue;
26908
    if( stat(zDir, &buf) ) continue;
26909
    if( !S_ISDIR(buf.st_mode) ) continue;
26910
    if( access(zDir, 07) ) continue;
26911
    break;
26912
  }
26913
  return zDir;
26914
}
26915
26916
/*
26917
** Create a temporary file name in zBuf.  zBuf must be allocated
26918
** by the calling process and must be big enough to hold at least
26919
** pVfs->mxPathname bytes.
26920
*/
26921
static int unixGetTempname(int nBuf, char *zBuf){
25914
  static const unsigned char zChars[] =
26922
  static const unsigned char zChars[] =
25915
    "abcdefghijklmnopqrstuvwxyz"
26923
    "abcdefghijklmnopqrstuvwxyz"
25916
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
26924
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
25917
    "0123456789";
26925
    "0123456789";
25918
  unsigned int i, j;
26926
  unsigned int i, j;
25919
  struct stat buf;
26927
  const char *zDir;
25920
  const char *zDir = ".";
25921
26928
25922
  /* It's odd to simulate an io-error here, but really this is just
26929
  /* It's odd to simulate an io-error here, but really this is just
25923
  ** using the io-error infrastructure to test that SQLite handles this
26930
  ** using the io-error infrastructure to test that SQLite handles this
 Lines 25925-25943   static int getTempname(int nBuf, char *z Link Here 
25925
  */
26932
  */
25926
  SimulateIOError( return SQLITE_IOERR );
26933
  SimulateIOError( return SQLITE_IOERR );
25927
26934
25928
  azDirs[0] = sqlite3_temp_directory;
26935
  zDir = unixTempFileDir();
25929
  if (NULL == azDirs[1]) {
26936
  if( zDir==0 ) zDir = ".";
25930
    azDirs[1] = getenv("TMPDIR");
25931
  }
25932
  
25933
  for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
25934
    if( azDirs[i]==0 ) continue;
25935
    if( stat(azDirs[i], &buf) ) continue;
25936
    if( !S_ISDIR(buf.st_mode) ) continue;
25937
    if( access(azDirs[i], 07) ) continue;
25938
    zDir = azDirs[i];
25939
    break;
25940
  }
25941
26937
25942
  /* Check that the output buffer is large enough for the temporary file 
26938
  /* Check that the output buffer is large enough for the temporary file 
25943
  ** name. If it is not, return SQLITE_ERROR.
26939
  ** name. If it is not, return SQLITE_ERROR.
 Lines 26003-26019   static UnixUnusedFd *findReusableFd(cons Link Here 
26003
  ** Even if a subsequent open() call does succeed, the consequences of
26999
  ** Even if a subsequent open() call does succeed, the consequences of
26004
  ** not searching for a resusable file descriptor are not dire.  */
27000
  ** not searching for a resusable file descriptor are not dire.  */
26005
  if( 0==stat(zPath, &sStat) ){
27001
  if( 0==stat(zPath, &sStat) ){
26006
    struct unixOpenCnt *pOpen;
27002
    unixInodeInfo *pInode;
26007
27003
26008
    unixEnterMutex();
27004
    unixEnterMutex();
26009
    pOpen = openList;
27005
    pInode = inodeList;
26010
    while( pOpen && (pOpen->fileId.dev!=sStat.st_dev
27006
    while( pInode && (pInode->fileId.dev!=sStat.st_dev
26011
                     || pOpen->fileId.ino!=sStat.st_ino) ){
27007
                     || pInode->fileId.ino!=sStat.st_ino) ){
26012
       pOpen = pOpen->pNext;
27008
       pInode = pInode->pNext;
26013
    }
27009
    }
26014
    if( pOpen ){
27010
    if( pInode ){
26015
      UnixUnusedFd **pp;
27011
      UnixUnusedFd **pp;
26016
      for(pp=&pOpen->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
27012
      for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
26017
      pUnused = *pp;
27013
      pUnused = *pp;
26018
      if( pUnused ){
27014
      if( pUnused ){
26019
        *pp = pUnused->pNext;
27015
        *pp = pUnused->pNext;
 Lines 26026-26031   static UnixUnusedFd *findReusableFd(cons Link Here 
26026
}
27022
}
26027
27023
26028
/*
27024
/*
27025
** This function is called by unixOpen() to determine the unix permissions
27026
** to create new files with. If no error occurs, then SQLITE_OK is returned
27027
** and a value suitable for passing as the third argument to open(2) is
27028
** written to *pMode. If an IO error occurs, an SQLite error code is 
27029
** returned and the value of *pMode is not modified.
27030
**
27031
** If the file being opened is a temporary file, it is always created with
27032
** the octal permissions 0600 (read/writable by owner only). If the file
27033
** is a database or master journal file, it is created with the permissions 
27034
** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
27035
**
27036
** Finally, if the file being opened is a WAL or regular journal file, then 
27037
** this function queries the file-system for the permissions on the 
27038
** corresponding database file and sets *pMode to this value. Whenever 
27039
** possible, WAL and journal files are created using the same permissions 
27040
** as the associated database file.
27041
*/
27042
static int findCreateFileMode(
27043
  const char *zPath,              /* Path of file (possibly) being created */
27044
  int flags,                      /* Flags passed as 4th argument to xOpen() */
27045
  mode_t *pMode                   /* OUT: Permissions to open file with */
27046
){
27047
  int rc = SQLITE_OK;             /* Return Code */
27048
  if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
27049
    char zDb[MAX_PATHNAME+1];     /* Database file path */
27050
    int nDb;                      /* Number of valid bytes in zDb */
27051
    struct stat sStat;            /* Output of stat() on database file */
27052
27053
    nDb = sqlite3Strlen30(zPath) - ((flags & SQLITE_OPEN_WAL) ? 4 : 8);
27054
    memcpy(zDb, zPath, nDb);
27055
    zDb[nDb] = '\0';
27056
    if( 0==stat(zDb, &sStat) ){
27057
      *pMode = sStat.st_mode & 0777;
27058
    }else{
27059
      rc = SQLITE_IOERR_FSTAT;
27060
    }
27061
  }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
27062
    *pMode = 0600;
27063
  }else{
27064
    *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
27065
  }
27066
  return rc;
27067
}
27068
27069
/*
26029
** Open the file zPath.
27070
** Open the file zPath.
26030
** 
27071
** 
26031
** Previously, the SQLite OS layer used three functions in place of this
27072
** Previously, the SQLite OS layer used three functions in place of this
 Lines 26075-26083   static int unixOpen( Link Here 
26075
  ** a file-descriptor on the directory too. The first time unixSync()
27116
  ** a file-descriptor on the directory too. The first time unixSync()
26076
  ** is called the directory file descriptor will be fsync()ed and close()d.
27117
  ** is called the directory file descriptor will be fsync()ed and close()d.
26077
  */
27118
  */
26078
  int isOpenDirectory = (isCreate && 
27119
  int isOpenDirectory = (isCreate && (
26079
      (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
27120
        eType==SQLITE_OPEN_MASTER_JOURNAL 
26080
  );
27121
     || eType==SQLITE_OPEN_MAIN_JOURNAL 
27122
     || eType==SQLITE_OPEN_WAL
27123
  ));
26081
27124
26082
  /* If argument zPath is a NULL pointer, this function is required to open
27125
  /* If argument zPath is a NULL pointer, this function is required to open
26083
  ** a temporary file. Use this buffer to store the file name in.
27126
  ** a temporary file. Use this buffer to store the file name in.
 Lines 26097-26113   static int unixOpen( Link Here 
26097
  assert(isExclusive==0 || isCreate);
27140
  assert(isExclusive==0 || isCreate);
26098
  assert(isDelete==0 || isCreate);
27141
  assert(isDelete==0 || isCreate);
26099
27142
26100
  /* The main DB, main journal, and master journal are never automatically
27143
  /* The main DB, main journal, WAL file and master journal are never 
26101
  ** deleted. Nor are they ever temporary files.  */
27144
  ** automatically deleted. Nor are they ever temporary files.  */
26102
  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
27145
  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
26103
  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
27146
  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
26104
  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
27147
  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
27148
  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
26105
27149
26106
  /* Assert that the upper layer has set one of the "file-type" flags. */
27150
  /* Assert that the upper layer has set one of the "file-type" flags. */
26107
  assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
27151
  assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
26108
       || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
27152
       || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
26109
       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
27153
       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
26110
       || eType==SQLITE_OPEN_TRANSIENT_DB
27154
       || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
26111
  );
27155
  );
26112
27156
26113
  memset(p, 0, sizeof(unixFile));
27157
  memset(p, 0, sizeof(unixFile));
 Lines 26127-26133   static int unixOpen( Link Here 
26127
  }else if( !zName ){
27171
  }else if( !zName ){
26128
    /* If zName is NULL, the upper layer is requesting a temp file. */
27172
    /* If zName is NULL, the upper layer is requesting a temp file. */
26129
    assert(isDelete && !isOpenDirectory);
27173
    assert(isDelete && !isOpenDirectory);
26130
    rc = getTempname(MAX_PATHNAME+1, zTmpname);
27174
    rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
26131
    if( rc!=SQLITE_OK ){
27175
    if( rc!=SQLITE_OK ){
26132
      return rc;
27176
      return rc;
26133
    }
27177
    }
 Lines 26145-26153   static int unixOpen( Link Here 
26145
  openFlags |= (O_LARGEFILE|O_BINARY);
27189
  openFlags |= (O_LARGEFILE|O_BINARY);
26146
27190
26147
  if( fd<0 ){
27191
  if( fd<0 ){
26148
    mode_t openMode = (isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
27192
    mode_t openMode;              /* Permissions to create file with */
27193
    rc = findCreateFileMode(zName, flags, &openMode);
27194
    if( rc!=SQLITE_OK ){
27195
      assert( !p->pUnused );
27196
      assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
27197
      return rc;
27198
    }
26149
    fd = open(zName, openFlags, openMode);
27199
    fd = open(zName, openFlags, openMode);
26150
    OSTRACE4("OPENX   %-3d %s 0%o\n", fd, zName, openFlags);
27200
    OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
26151
    if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
27201
    if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
26152
      /* Failed to open the file for read/write access. Try read-only. */
27202
      /* Failed to open the file for read/write access. Try read-only. */
26153
      flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
27203
      flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
 Lines 26288-26294   static int unixDelete( Link Here 
26288
  int rc = SQLITE_OK;
27338
  int rc = SQLITE_OK;
26289
  UNUSED_PARAMETER(NotUsed);
27339
  UNUSED_PARAMETER(NotUsed);
26290
  SimulateIOError(return SQLITE_IOERR_DELETE);
27340
  SimulateIOError(return SQLITE_IOERR_DELETE);
26291
  unlink(zPath);
27341
  if( unlink(zPath)==(-1) && errno!=ENOENT ){
27342
    return SQLITE_IOERR_DELETE;
27343
  }
26292
#ifndef SQLITE_DISABLE_DIRSYNC
27344
#ifndef SQLITE_DISABLE_DIRSYNC
26293
  if( dirSync ){
27345
  if( dirSync ){
26294
    int fd;
27346
    int fd;
 Lines 26345-26350   static int unixAccess( Link Here 
26345
      assert(!"Invalid flags argument");
27397
      assert(!"Invalid flags argument");
26346
  }
27398
  }
26347
  *pResOut = (access(zPath, amode)==0);
27399
  *pResOut = (access(zPath, amode)==0);
27400
  if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
27401
    struct stat buf;
27402
    if( 0==stat(zPath, &buf) && buf.st_size==0 ){
27403
      *pResOut = 0;
27404
    }
27405
  }
26348
  return SQLITE_OK;
27406
  return SQLITE_OK;
26349
}
27407
}
26350
27408
 Lines 26533-26567   SQLITE_API int sqlite3_current_time = 0; Link Here 
26533
#endif
27591
#endif
26534
27592
26535
/*
27593
/*
27594
** Find the current time (in Universal Coordinated Time).  Write into *piNow
27595
** the current time and date as a Julian Day number times 86_400_000.  In
27596
** other words, write into *piNow the number of milliseconds since the Julian
27597
** epoch of noon in Greenwich on November 24, 4714 B.C according to the
27598
** proleptic Gregorian calendar.
27599
**
27600
** On success, return 0.  Return 1 if the time and date cannot be found.
27601
*/
27602
static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
27603
  static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
27604
#if defined(NO_GETTOD)
27605
  time_t t;
27606
  time(&t);
27607
  *piNow = ((sqlite3_int64)i)*1000 + unixEpoch;
27608
#elif OS_VXWORKS
27609
  struct timespec sNow;
27610
  clock_gettime(CLOCK_REALTIME, &sNow);
27611
  *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
27612
#else
27613
  struct timeval sNow;
27614
  gettimeofday(&sNow, 0);
27615
  *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
27616
#endif
27617
27618
#ifdef SQLITE_TEST
27619
  if( sqlite3_current_time ){
27620
    *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
27621
  }
27622
#endif
27623
  UNUSED_PARAMETER(NotUsed);
27624
  return 0;
27625
}
27626
27627
/*
26536
** Find the current time (in Universal Coordinated Time).  Write the
27628
** Find the current time (in Universal Coordinated Time).  Write the
26537
** current time and date as a Julian Day number into *prNow and
27629
** current time and date as a Julian Day number into *prNow and
26538
** return 0.  Return 1 if the time and date cannot be found.
27630
** return 0.  Return 1 if the time and date cannot be found.
26539
*/
27631
*/
26540
static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
27632
static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
26541
#if defined(SQLITE_OMIT_FLOATING_POINT)
27633
  sqlite3_int64 i;
26542
  time_t t;
26543
  time(&t);
26544
  *prNow = (((sqlite3_int64)t)/8640 + 24405875)/10;
26545
#elif defined(NO_GETTOD)
26546
  time_t t;
26547
  time(&t);
26548
  *prNow = t/86400.0 + 2440587.5;
26549
#elif OS_VXWORKS
26550
  struct timespec sNow;
26551
  clock_gettime(CLOCK_REALTIME, &sNow);
26552
  *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_nsec/86400000000000.0;
26553
#else
26554
  struct timeval sNow;
26555
  gettimeofday(&sNow, 0);
26556
  *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
26557
#endif
26558
26559
#ifdef SQLITE_TEST
26560
  if( sqlite3_current_time ){
26561
    *prNow = sqlite3_current_time/86400.0 + 2440587.5;
26562
  }
26563
#endif
26564
  UNUSED_PARAMETER(NotUsed);
27634
  UNUSED_PARAMETER(NotUsed);
27635
  unixCurrentTimeInt64(0, &i);
27636
  *prNow = i/86400000.0;
26565
  return 0;
27637
  return 0;
26566
}
27638
}
26567
27639
 Lines 26579-26584   static int unixGetLastError(sqlite3_vfs Link Here 
26579
  return 0;
27651
  return 0;
26580
}
27652
}
26581
27653
27654
26582
/*
27655
/*
26583
************************ End of sqlite3_vfs methods ***************************
27656
************************ End of sqlite3_vfs methods ***************************
26584
******************************************************************************/
27657
******************************************************************************/
 Lines 26769-26776   static int proxyGetLockPath(const char * Link Here 
26769
# ifdef _CS_DARWIN_USER_TEMP_DIR
27842
# ifdef _CS_DARWIN_USER_TEMP_DIR
26770
  {
27843
  {
26771
    if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
27844
    if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
26772
      OSTRACE4("GETLOCKPATH  failed %s errno=%d pid=%d\n",
27845
      OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
26773
               lPath, errno, getpid());
27846
               lPath, errno, getpid()));
26774
      return SQLITE_IOERR_LOCK;
27847
      return SQLITE_IOERR_LOCK;
26775
    }
27848
    }
26776
    len = strlcat(lPath, "sqliteplocks", maxLen);    
27849
    len = strlcat(lPath, "sqliteplocks", maxLen);    
 Lines 26786-26798   static int proxyGetLockPath(const char * Link Here 
26786
  
27859
  
26787
  /* transform the db path to a unique cache name */
27860
  /* transform the db path to a unique cache name */
26788
  dbLen = (int)strlen(dbPath);
27861
  dbLen = (int)strlen(dbPath);
26789
  for( i=0; i<dbLen && (i+len+7)<maxLen; i++){
27862
  for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
26790
    char c = dbPath[i];
27863
    char c = dbPath[i];
26791
    lPath[i+len] = (c=='/')?'_':c;
27864
    lPath[i+len] = (c=='/')?'_':c;
26792
  }
27865
  }
26793
  lPath[i+len]='\0';
27866
  lPath[i+len]='\0';
26794
  strlcat(lPath, ":auto:", maxLen);
27867
  strlcat(lPath, ":auto:", maxLen);
26795
  OSTRACE3("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, getpid());
27868
  OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, getpid()));
26796
  return SQLITE_OK;
27869
  return SQLITE_OK;
26797
}
27870
}
26798
27871
 Lines 26817-26825   static int proxyCreateLockPath(const cha Link Here 
26817
        if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
27890
        if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
26818
          int err=errno;
27891
          int err=errno;
26819
          if( err!=EEXIST ) {
27892
          if( err!=EEXIST ) {
26820
            OSTRACE5("CREATELOCKPATH  FAILED creating %s, "
27893
            OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
26821
                     "'%s' proxy lock path=%s pid=%d\n",
27894
                     "'%s' proxy lock path=%s pid=%d\n",
26822
                     buf, strerror(err), lockPath, getpid());
27895
                     buf, strerror(err), lockPath, getpid()));
26823
            return err;
27896
            return err;
26824
          }
27897
          }
26825
        }
27898
        }
 Lines 26828-26834   static int proxyCreateLockPath(const cha Link Here 
26828
    }
27901
    }
26829
    buf[i] = lockPath[i];
27902
    buf[i] = lockPath[i];
26830
  }
27903
  }
26831
  OSTRACE3("CREATELOCKPATH  proxy lock path=%s pid=%d\n", lockPath, getpid());
27904
  OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n", lockPath, getpid()));
26832
  return 0;
27905
  return 0;
26833
}
27906
}
26834
27907
 Lines 26927-26932   SQLITE_API int sqlite3_hostid_num = 0; Link Here 
26927
28000
26928
#define PROXY_HOSTIDLEN    16  /* conch file host id length */
28001
#define PROXY_HOSTIDLEN    16  /* conch file host id length */
26929
28002
28003
/* Not always defined in the headers as it ought to be */
28004
extern int gethostuuid(uuid_t id, const struct timespec *wait);
28005
26930
/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN 
28006
/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN 
26931
** bytes of writable memory.
28007
** bytes of writable memory.
26932
*/
28008
*/
 Lines 26976-26981   static int proxyBreakConchLock(unixFile Link Here 
26976
  char errmsg[64] = "";
28052
  char errmsg[64] = "";
26977
  int fd = -1;
28053
  int fd = -1;
26978
  int rc = -1;
28054
  int rc = -1;
28055
  UNUSED_PARAMETER(myHostID);
26979
28056
26980
  /* create a new path by replace the trailing '-conch' with '-break' */
28057
  /* create a new path by replace the trailing '-conch' with '-break' */
26981
  pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
28058
  pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
 Lines 26996-27002   static int proxyBreakConchLock(unixFile Link Here 
26996
    sprintf(errmsg, "create failed (%d)", errno);
28073
    sprintf(errmsg, "create failed (%d)", errno);
26997
    goto end_breaklock;
28074
    goto end_breaklock;
26998
  }
28075
  }
26999
  if( pwrite(fd, buf, readLen, 0) != readLen ){
28076
  if( pwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
27000
    sprintf(errmsg, "write failed (%d)", errno);
28077
    sprintf(errmsg, "write failed (%d)", errno);
27001
    goto end_breaklock;
28078
    goto end_breaklock;
27002
  }
28079
  }
 Lines 27120-27127   static int proxyTakeConch(unixFile *pFil Link Here 
27120
    int tryOldLockPath = 0;
28197
    int tryOldLockPath = 0;
27121
    int forceNewLockPath = 0;
28198
    int forceNewLockPath = 0;
27122
    
28199
    
27123
    OSTRACE4("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
28200
    OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
27124
             (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid());
28201
             (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
27125
28202
27126
    rc = proxyGetHostID(myHostID, &pError);
28203
    rc = proxyGetHostID(myHostID, &pError);
27127
    if( (rc&0xff)==SQLITE_IOERR ){
28204
    if( (rc&0xff)==SQLITE_IOERR ){
 Lines 27201-27207   static int proxyTakeConch(unixFile *pFil Link Here 
27201
      */
28278
      */
27202
      futimes(conchFile->h, NULL);
28279
      futimes(conchFile->h, NULL);
27203
      if( hostIdMatch && !createConch ){
28280
      if( hostIdMatch && !createConch ){
27204
        if( conchFile->pLock && conchFile->pLock->cnt>1 ){
28281
        if( conchFile->pInode && conchFile->pInode->nShared>1 ){
27205
          /* We are trying for an exclusive lock but another thread in this
28282
          /* We are trying for an exclusive lock but another thread in this
27206
           ** same process is still holding a shared lock. */
28283
           ** same process is still holding a shared lock. */
27207
          rc = SQLITE_BUSY;
28284
          rc = SQLITE_BUSY;
 Lines 27257-27263   static int proxyTakeConch(unixFile *pFil Link Here 
27257
      conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
28334
      conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
27258
      
28335
      
27259
    end_takeconch:
28336
    end_takeconch:
27260
      OSTRACE2("TRANSPROXY: CLOSE  %d\n", pFile->h);
28337
      OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
27261
      if( rc==SQLITE_OK && pFile->openFlags ){
28338
      if( rc==SQLITE_OK && pFile->openFlags ){
27262
        if( pFile->h>=0 ){
28339
        if( pFile->h>=0 ){
27263
#ifdef STRICT_CLOSE_ERROR
28340
#ifdef STRICT_CLOSE_ERROR
 Lines 27272-27278   static int proxyTakeConch(unixFile *pFil Link Here 
27272
        pFile->h = -1;
28349
        pFile->h = -1;
27273
        int fd = open(pCtx->dbPath, pFile->openFlags,
28350
        int fd = open(pCtx->dbPath, pFile->openFlags,
27274
                      SQLITE_DEFAULT_FILE_PERMISSIONS);
28351
                      SQLITE_DEFAULT_FILE_PERMISSIONS);
27275
        OSTRACE2("TRANSPROXY: OPEN  %d\n", fd);
28352
        OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
27276
        if( fd>=0 ){
28353
        if( fd>=0 ){
27277
          pFile->h = fd;
28354
          pFile->h = fd;
27278
        }else{
28355
        }else{
 Lines 27314-27322   static int proxyTakeConch(unixFile *pFil Link Here 
27314
      } else {
28391
      } else {
27315
        conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
28392
        conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
27316
      }
28393
      }
27317
      OSTRACE3("TAKECONCH  %d %s\n", conchFile->h, rc==SQLITE_OK?"ok":"failed");
28394
      OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
28395
               rc==SQLITE_OK?"ok":"failed"));
27318
      return rc;
28396
      return rc;
27319
    } while (1); /* in case we need to retry the :auto: lock file - we should never get here except via the 'continue' call. */
28397
    } while (1); /* in case we need to retry the :auto: lock file - 
28398
                 ** we should never get here except via the 'continue' call. */
27320
  }
28399
  }
27321
}
28400
}
27322
28401
 Lines 27324-27344   static int proxyTakeConch(unixFile *pFil Link Here 
27324
** If pFile holds a lock on a conch file, then release that lock.
28403
** If pFile holds a lock on a conch file, then release that lock.
27325
*/
28404
*/
27326
static int proxyReleaseConch(unixFile *pFile){
28405
static int proxyReleaseConch(unixFile *pFile){
27327
  int rc;                     /* Subroutine return code */
28406
  int rc = SQLITE_OK;         /* Subroutine return code */
27328
  proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
28407
  proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
27329
  unixFile *conchFile;        /* Name of the conch file */
28408
  unixFile *conchFile;        /* Name of the conch file */
27330
28409
27331
  pCtx = (proxyLockingContext *)pFile->lockingContext;
28410
  pCtx = (proxyLockingContext *)pFile->lockingContext;
27332
  conchFile = pCtx->conchFile;
28411
  conchFile = pCtx->conchFile;
27333
  OSTRACE4("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
28412
  OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
27334
           (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), 
28413
           (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), 
27335
           getpid());
28414
           getpid()));
27336
  if( pCtx->conchHeld>0 ){
28415
  if( pCtx->conchHeld>0 ){
27337
    rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
28416
    rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
27338
  }
28417
  }
27339
  pCtx->conchHeld = 0;
28418
  pCtx->conchHeld = 0;
27340
  OSTRACE3("RELEASECONCH  %d %s\n", conchFile->h,
28419
  OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
27341
           (rc==SQLITE_OK ? "ok" : "failed"));
28420
           (rc==SQLITE_OK ? "ok" : "failed")));
27342
  return rc;
28421
  return rc;
27343
}
28422
}
27344
28423
 Lines 27395-27401   static int switchLockProxyPath(unixFile Link Here 
27395
  char *oldPath = pCtx->lockProxyPath;
28474
  char *oldPath = pCtx->lockProxyPath;
27396
  int rc = SQLITE_OK;
28475
  int rc = SQLITE_OK;
27397
28476
27398
  if( pFile->locktype!=NO_LOCK ){
28477
  if( pFile->eFileLock!=NO_LOCK ){
27399
    return SQLITE_BUSY;
28478
    return SQLITE_BUSY;
27400
  }  
28479
  }  
27401
28480
 Lines 27462-27468   static int proxyTransformUnixFile(unixFi Link Here 
27462
  char *lockPath=NULL;
28541
  char *lockPath=NULL;
27463
  int rc = SQLITE_OK;
28542
  int rc = SQLITE_OK;
27464
  
28543
  
27465
  if( pFile->locktype!=NO_LOCK ){
28544
  if( pFile->eFileLock!=NO_LOCK ){
27466
    return SQLITE_BUSY;
28545
    return SQLITE_BUSY;
27467
  }
28546
  }
27468
  proxyGetDbPathForUnixFile(pFile, dbPath);
28547
  proxyGetDbPathForUnixFile(pFile, dbPath);
 Lines 27472-27479   static int proxyTransformUnixFile(unixFi Link Here 
27472
    lockPath=(char *)path;
28551
    lockPath=(char *)path;
27473
  }
28552
  }
27474
  
28553
  
27475
  OSTRACE4("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
28554
  OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
27476
           (lockPath ? lockPath : ":auto:"), getpid());
28555
           (lockPath ? lockPath : ":auto:"), getpid()));
27477
28556
27478
  pCtx = sqlite3_malloc( sizeof(*pCtx) );
28557
  pCtx = sqlite3_malloc( sizeof(*pCtx) );
27479
  if( pCtx==0 ){
28558
  if( pCtx==0 ){
 Lines 27529-27540   static int proxyTransformUnixFile(unixFi Link Here 
27529
      pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
28608
      pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
27530
      sqlite3_free(pCtx->conchFile);
28609
      sqlite3_free(pCtx->conchFile);
27531
    }
28610
    }
27532
    sqlite3_free(pCtx->lockProxyPath);
28611
    sqlite3DbFree(0, pCtx->lockProxyPath);
27533
    sqlite3_free(pCtx->conchFilePath); 
28612
    sqlite3_free(pCtx->conchFilePath); 
27534
    sqlite3_free(pCtx);
28613
    sqlite3_free(pCtx);
27535
  }
28614
  }
27536
  OSTRACE3("TRANSPROXY  %d %s\n", pFile->h,
28615
  OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
27537
           (rc==SQLITE_OK ? "ok" : "failed"));
28616
           (rc==SQLITE_OK ? "ok" : "failed")));
27538
  return rc;
28617
  return rc;
27539
}
28618
}
27540
28619
 Lines 27629-27635   static int proxyCheckReservedLock(sqlite Link Here 
27629
}
28708
}
27630
28709
27631
/*
28710
/*
27632
** Lock the file with the lock specified by parameter locktype - one
28711
** Lock the file with the lock specified by parameter eFileLock - one
27633
** of the following:
28712
** of the following:
27634
**
28713
**
27635
**     (1) SHARED_LOCK
28714
**     (1) SHARED_LOCK
 Lines 27652-27666   static int proxyCheckReservedLock(sqlite Link Here 
27652
** This routine will only increase a lock.  Use the sqlite3OsUnlock()
28731
** This routine will only increase a lock.  Use the sqlite3OsUnlock()
27653
** routine to lower a locking level.
28732
** routine to lower a locking level.
27654
*/
28733
*/
27655
static int proxyLock(sqlite3_file *id, int locktype) {
28734
static int proxyLock(sqlite3_file *id, int eFileLock) {
27656
  unixFile *pFile = (unixFile*)id;
28735
  unixFile *pFile = (unixFile*)id;
27657
  int rc = proxyTakeConch(pFile);
28736
  int rc = proxyTakeConch(pFile);
27658
  if( rc==SQLITE_OK ){
28737
  if( rc==SQLITE_OK ){
27659
    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
28738
    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
27660
    if( pCtx->conchHeld>0 ){
28739
    if( pCtx->conchHeld>0 ){
27661
      unixFile *proxy = pCtx->lockProxy;
28740
      unixFile *proxy = pCtx->lockProxy;
27662
      rc = proxy->pMethod->xLock((sqlite3_file*)proxy, locktype);
28741
      rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
27663
      pFile->locktype = proxy->locktype;
28742
      pFile->eFileLock = proxy->eFileLock;
27664
    }else{
28743
    }else{
27665
      /* conchHeld < 0 is lockless */
28744
      /* conchHeld < 0 is lockless */
27666
    }
28745
    }
 Lines 27670-27690   static int proxyLock(sqlite3_file *id, i Link Here 
27670
28749
27671
28750
27672
/*
28751
/*
27673
** Lower the locking level on file descriptor pFile to locktype.  locktype
28752
** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
27674
** must be either NO_LOCK or SHARED_LOCK.
28753
** must be either NO_LOCK or SHARED_LOCK.
27675
**
28754
**
27676
** If the locking level of the file descriptor is already at or below
28755
** If the locking level of the file descriptor is already at or below
27677
** the requested locking level, this routine is a no-op.
28756
** the requested locking level, this routine is a no-op.
27678
*/
28757
*/
27679
static int proxyUnlock(sqlite3_file *id, int locktype) {
28758
static int proxyUnlock(sqlite3_file *id, int eFileLock) {
27680
  unixFile *pFile = (unixFile*)id;
28759
  unixFile *pFile = (unixFile*)id;
27681
  int rc = proxyTakeConch(pFile);
28760
  int rc = proxyTakeConch(pFile);
27682
  if( rc==SQLITE_OK ){
28761
  if( rc==SQLITE_OK ){
27683
    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
28762
    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
27684
    if( pCtx->conchHeld>0 ){
28763
    if( pCtx->conchHeld>0 ){
27685
      unixFile *proxy = pCtx->lockProxy;
28764
      unixFile *proxy = pCtx->lockProxy;
27686
      rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, locktype);
28765
      rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
27687
      pFile->locktype = proxy->locktype;
28766
      pFile->eFileLock = proxy->eFileLock;
27688
    }else{
28767
    }else{
27689
      /* conchHeld < 0 is lockless */
28768
      /* conchHeld < 0 is lockless */
27690
    }
28769
    }
 Lines 27720-27728   static int proxyClose(sqlite3_file *id) Link Here 
27720
      if( rc ) return rc;
28799
      if( rc ) return rc;
27721
      sqlite3_free(conchFile);
28800
      sqlite3_free(conchFile);
27722
    }
28801
    }
27723
    sqlite3_free(pCtx->lockProxyPath);
28802
    sqlite3DbFree(0, pCtx->lockProxyPath);
27724
    sqlite3_free(pCtx->conchFilePath);
28803
    sqlite3_free(pCtx->conchFilePath);
27725
    sqlite3_free(pCtx->dbPath);
28804
    sqlite3DbFree(0, pCtx->dbPath);
27726
    /* restore the original locking context and pMethod then close it */
28805
    /* restore the original locking context and pMethod then close it */
27727
    pFile->lockingContext = pCtx->oldLockingContext;
28806
    pFile->lockingContext = pCtx->oldLockingContext;
27728
    pFile->pMethod = pCtx->pOldMethod;
28807
    pFile->pMethod = pCtx->pOldMethod;
 Lines 27779-27785   SQLITE_API int sqlite3_os_init(void){ Link Here 
27779
  ** that filesystem time.
28858
  ** that filesystem time.
27780
  */
28859
  */
27781
  #define UNIXVFS(VFSNAME, FINDER) {                        \
28860
  #define UNIXVFS(VFSNAME, FINDER) {                        \
27782
    1,                    /* iVersion */                    \
28861
    2,                    /* iVersion */                    \
27783
    sizeof(unixFile),     /* szOsFile */                    \
28862
    sizeof(unixFile),     /* szOsFile */                    \
27784
    MAX_PATHNAME,         /* mxPathname */                  \
28863
    MAX_PATHNAME,         /* mxPathname */                  \
27785
    0,                    /* pNext */                       \
28864
    0,                    /* pNext */                       \
 Lines 27796-27802   SQLITE_API int sqlite3_os_init(void){ Link Here 
27796
    unixRandomness,       /* xRandomness */                 \
28875
    unixRandomness,       /* xRandomness */                 \
27797
    unixSleep,            /* xSleep */                      \
28876
    unixSleep,            /* xSleep */                      \
27798
    unixCurrentTime,      /* xCurrentTime */                \
28877
    unixCurrentTime,      /* xCurrentTime */                \
27799
    unixGetLastError      /* xGetLastError */               \
28878
    unixGetLastError,     /* xGetLastError */               \
28879
    unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
27800
  }
28880
  }
27801
28881
27802
  /*
28882
  /*
 Lines 27947-27969   SQLITE_API int sqlite3_os_end(void){ Link Here 
27947
29027
27948
#ifdef SQLITE_DEBUG
29028
#ifdef SQLITE_DEBUG
27949
SQLITE_PRIVATE int sqlite3OSTrace = 0;
29029
SQLITE_PRIVATE int sqlite3OSTrace = 0;
27950
#define OSTRACE1(X)         if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
29030
#define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
27951
#define OSTRACE2(X,Y)       if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
29031
#else
27952
#define OSTRACE3(X,Y,Z)     if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
29032
#define OSTRACE(X)
27953
#define OSTRACE4(X,Y,Z,A)   if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
27954
#define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
27955
#define OSTRACE6(X,Y,Z,A,B,C) \
27956
    if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
27957
#define OSTRACE7(X,Y,Z,A,B,C,D) \
27958
    if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
27959
#else
27960
#define OSTRACE1(X)
27961
#define OSTRACE2(X,Y)
27962
#define OSTRACE3(X,Y,Z)
27963
#define OSTRACE4(X,Y,Z,A)
27964
#define OSTRACE5(X,Y,Z,A,B)
27965
#define OSTRACE6(X,Y,Z,A,B,C)
27966
#define OSTRACE7(X,Y,Z,A,B,C,D)
27967
#endif
29033
#endif
27968
29034
27969
/*
29035
/*
 Lines 28149-28154   SQLITE_API int sqlite3_open_file_count = Link Here 
28149
# define FormatMessageW(a,b,c,d,e,f,g) 0
29215
# define FormatMessageW(a,b,c,d,e,f,g) 0
28150
#endif
29216
#endif
28151
29217
29218
/* Forward references */
29219
typedef struct winShm winShm;           /* A connection to shared-memory */
29220
typedef struct winShmNode winShmNode;   /* A region of shared-memory */
29221
28152
/*
29222
/*
28153
** WinCE lacks native support for file locking so we have to fake it
29223
** WinCE lacks native support for file locking so we have to fake it
28154
** with some code of our own.
29224
** with some code of our own.
 Lines 28168-28179   typedef struct winceLock { Link Here 
28168
*/
29238
*/
28169
typedef struct winFile winFile;
29239
typedef struct winFile winFile;
28170
struct winFile {
29240
struct winFile {
28171
  const sqlite3_io_methods *pMethod;/* Must be first */
29241
  const sqlite3_io_methods *pMethod; /*** Must be first ***/
29242
  sqlite3_vfs *pVfs;      /* The VFS used to open this file */
28172
  HANDLE h;               /* Handle for accessing the file */
29243
  HANDLE h;               /* Handle for accessing the file */
28173
  unsigned char locktype; /* Type of lock currently held on this file */
29244
  unsigned char locktype; /* Type of lock currently held on this file */
28174
  short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
29245
  short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
28175
  DWORD lastErrno;        /* The Windows errno from the last I/O error */
29246
  DWORD lastErrno;        /* The Windows errno from the last I/O error */
28176
  DWORD sectorSize;       /* Sector size of the device file is on */
29247
  DWORD sectorSize;       /* Sector size of the device file is on */
29248
  winShm *pShm;           /* Instance of shared memory on this file */
29249
  const char *zPath;      /* Full pathname of this file */
29250
  int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
28177
#if SQLITE_OS_WINCE
29251
#if SQLITE_OS_WINCE
28178
  WCHAR *zDeleteOnClose;  /* Name of file to delete when closing */
29252
  WCHAR *zDeleteOnClose;  /* Name of file to delete when closing */
28179
  HANDLE hMutex;          /* Mutex used to control access to shared lock */  
29253
  HANDLE hMutex;          /* Mutex used to control access to shared lock */  
 Lines 28686-28691   static BOOL winceLockFileEx( Link Here 
28686
******************************************************************************/
29760
******************************************************************************/
28687
29761
28688
/*
29762
/*
29763
** Some microsoft compilers lack this definition.
29764
*/
29765
#ifndef INVALID_SET_FILE_POINTER
29766
# define INVALID_SET_FILE_POINTER ((DWORD)-1)
29767
#endif
29768
29769
/*
29770
** Move the current position of the file handle passed as the first 
29771
** argument to offset iOffset within the file. If successful, return 0. 
29772
** Otherwise, set pFile->lastErrno and return non-zero.
29773
*/
29774
static int seekWinFile(winFile *pFile, sqlite3_int64 iOffset){
29775
  LONG upperBits;                 /* Most sig. 32 bits of new offset */
29776
  LONG lowerBits;                 /* Least sig. 32 bits of new offset */
29777
  DWORD dwRet;                    /* Value returned by SetFilePointer() */
29778
29779
  upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
29780
  lowerBits = (LONG)(iOffset & 0xffffffff);
29781
29782
  /* API oddity: If successful, SetFilePointer() returns a dword 
29783
  ** containing the lower 32-bits of the new file-offset. Or, if it fails,
29784
  ** it returns INVALID_SET_FILE_POINTER. However according to MSDN, 
29785
  ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine 
29786
  ** whether an error has actually occured, it is also necessary to call 
29787
  ** GetLastError().
29788
  */
29789
  dwRet = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
29790
  if( (dwRet==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR) ){
29791
    pFile->lastErrno = GetLastError();
29792
    return 1;
29793
  }
29794
29795
  return 0;
29796
}
29797
29798
/*
28689
** Close a file.
29799
** Close a file.
28690
**
29800
**
28691
** It is reported that an attempt to close a handle might sometimes
29801
** It is reported that an attempt to close a handle might sometimes
 Lines 28701-28709   static int winClose(sqlite3_file *id){ Link Here 
28701
  winFile *pFile = (winFile*)id;
29811
  winFile *pFile = (winFile*)id;
28702
29812
28703
  assert( id!=0 );
29813
  assert( id!=0 );
28704
  OSTRACE2("CLOSE %d\n", pFile->h);
29814
  assert( pFile->pShm==0 );
29815
  OSTRACE(("CLOSE %d\n", pFile->h));
28705
  do{
29816
  do{
28706
    rc = CloseHandle(pFile->h);
29817
    rc = CloseHandle(pFile->h);
29818
    /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
28707
  }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
29819
  }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
28708
#if SQLITE_OS_WINCE
29820
#if SQLITE_OS_WINCE
28709
#define WINCE_DELETION_ATTEMPTS 3
29821
#define WINCE_DELETION_ATTEMPTS 3
 Lines 28720-28737   static int winClose(sqlite3_file *id){ Link Here 
28720
    free(pFile->zDeleteOnClose);
29832
    free(pFile->zDeleteOnClose);
28721
  }
29833
  }
28722
#endif
29834
#endif
29835
  OSTRACE(("CLOSE %d %s\n", pFile->h, rc ? "ok" : "failed"));
28723
  OpenCounter(-1);
29836
  OpenCounter(-1);
28724
  return rc ? SQLITE_OK : SQLITE_IOERR;
29837
  return rc ? SQLITE_OK : SQLITE_IOERR;
28725
}
29838
}
28726
29839
28727
/*
29840
/*
28728
** Some microsoft compilers lack this definition.
28729
*/
28730
#ifndef INVALID_SET_FILE_POINTER
28731
# define INVALID_SET_FILE_POINTER ((DWORD)-1)
28732
#endif
28733
28734
/*
28735
** Read data from a file into a buffer.  Return SQLITE_OK if all
29841
** Read data from a file into a buffer.  Return SQLITE_OK if all
28736
** bytes were read successfully and SQLITE_IOERR if anything goes
29842
** bytes were read successfully and SQLITE_IOERR if anything goes
28737
** wrong.
29843
** wrong.
 Lines 28742-28773   static int winRead( Link Here 
28742
  int amt,                   /* Number of bytes to read */
29848
  int amt,                   /* Number of bytes to read */
28743
  sqlite3_int64 offset       /* Begin reading at this offset */
29849
  sqlite3_int64 offset       /* Begin reading at this offset */
28744
){
29850
){
28745
  LONG upperBits = (LONG)((offset>>32) & 0x7fffffff);
29851
  winFile *pFile = (winFile*)id;  /* file handle */
28746
  LONG lowerBits = (LONG)(offset & 0xffffffff);
29852
  DWORD nRead;                    /* Number of bytes actually read from file */
28747
  DWORD rc;
28748
  winFile *pFile = (winFile*)id;
28749
  DWORD error;
28750
  DWORD got;
28751
29853
28752
  assert( id!=0 );
29854
  assert( id!=0 );
28753
  SimulateIOError(return SQLITE_IOERR_READ);
29855
  SimulateIOError(return SQLITE_IOERR_READ);
28754
  OSTRACE3("READ %d lock=%d\n", pFile->h, pFile->locktype);
29856
  OSTRACE(("READ %d lock=%d\n", pFile->h, pFile->locktype));
28755
  rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
29857
28756
  if( rc==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ){
29858
  if( seekWinFile(pFile, offset) ){
28757
    pFile->lastErrno = error;
28758
    return SQLITE_FULL;
29859
    return SQLITE_FULL;
28759
  }
29860
  }
28760
  if( !ReadFile(pFile->h, pBuf, amt, &got, 0) ){
29861
  if( !ReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
28761
    pFile->lastErrno = GetLastError();
29862
    pFile->lastErrno = GetLastError();
28762
    return SQLITE_IOERR_READ;
29863
    return SQLITE_IOERR_READ;
28763
  }
29864
  }
28764
  if( got==(DWORD)amt ){
29865
  if( nRead<(DWORD)amt ){
28765
    return SQLITE_OK;
28766
  }else{
28767
    /* Unread parts of the buffer must be zero-filled */
29866
    /* Unread parts of the buffer must be zero-filled */
28768
    memset(&((char*)pBuf)[got], 0, amt-got);
29867
    memset(&((char*)pBuf)[nRead], 0, amt-nRead);
28769
    return SQLITE_IOERR_SHORT_READ;
29868
    return SQLITE_IOERR_SHORT_READ;
28770
  }
29869
  }
29870
29871
  return SQLITE_OK;
28771
}
29872
}
28772
29873
28773
/*
29874
/*
 Lines 28775-28841   static int winRead( Link Here 
28775
** or some other error code on failure.
29876
** or some other error code on failure.
28776
*/
29877
*/
28777
static int winWrite(
29878
static int winWrite(
28778
  sqlite3_file *id,         /* File to write into */
29879
  sqlite3_file *id,               /* File to write into */
28779
  const void *pBuf,         /* The bytes to be written */
29880
  const void *pBuf,               /* The bytes to be written */
28780
  int amt,                  /* Number of bytes to write */
29881
  int amt,                        /* Number of bytes to write */
28781
  sqlite3_int64 offset      /* Offset into the file to begin writing at */
29882
  sqlite3_int64 offset            /* Offset into the file to begin writing at */
28782
){
29883
){
28783
  LONG upperBits = (LONG)((offset>>32) & 0x7fffffff);
29884
  int rc;                         /* True if error has occured, else false */
28784
  LONG lowerBits = (LONG)(offset & 0xffffffff);
29885
  winFile *pFile = (winFile*)id;  /* File handle */
28785
  DWORD rc;
29886
28786
  winFile *pFile = (winFile*)id;
29887
  assert( amt>0 );
28787
  DWORD error;
29888
  assert( pFile );
28788
  DWORD wrote = 0;
28789
28790
  assert( id!=0 );
28791
  SimulateIOError(return SQLITE_IOERR_WRITE);
29889
  SimulateIOError(return SQLITE_IOERR_WRITE);
28792
  SimulateDiskfullError(return SQLITE_FULL);
29890
  SimulateDiskfullError(return SQLITE_FULL);
28793
  OSTRACE3("WRITE %d lock=%d\n", pFile->h, pFile->locktype);
29891
28794
  rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
29892
  OSTRACE(("WRITE %d lock=%d\n", pFile->h, pFile->locktype));
28795
  if( rc==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ){
29893
28796
    pFile->lastErrno = error;
29894
  rc = seekWinFile(pFile, offset);
28797
    return SQLITE_FULL;
29895
  if( rc==0 ){
28798
  }
29896
    u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */
28799
  assert( amt>0 );
29897
    int nRem = amt;               /* Number of bytes yet to be written */
28800
  while(
29898
    DWORD nWrite;                 /* Bytes written by each WriteFile() call */
28801
     amt>0
29899
28802
     && (rc = WriteFile(pFile->h, pBuf, amt, &wrote, 0))!=0
29900
    while( nRem>0 && WriteFile(pFile->h, aRem, nRem, &nWrite, 0) && nWrite>0 ){
28803
     && wrote>0
29901
      aRem += nWrite;
28804
  ){
29902
      nRem -= nWrite;
28805
    amt -= wrote;
29903
    }
28806
    pBuf = &((char*)pBuf)[wrote];
29904
    if( nRem>0 ){
28807
  }
29905
      pFile->lastErrno = GetLastError();
28808
  if( !rc || amt>(int)wrote ){
29906
      rc = 1;
29907
    }
29908
  }
29909
29910
  if( rc ){
29911
    if( pFile->lastErrno==ERROR_HANDLE_DISK_FULL ){
29912
      return SQLITE_FULL;
29913
    }
29914
    return SQLITE_IOERR_WRITE;
29915
  }
29916
  return SQLITE_OK;
29917
}
29918
29919
/*
29920
** Truncate an open file to a specified size
29921
*/
29922
static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
29923
  winFile *pFile = (winFile*)id;  /* File handle object */
29924
  int rc = SQLITE_OK;             /* Return code for this function */
29925
29926
  assert( pFile );
29927
29928
  OSTRACE(("TRUNCATE %d %lld\n", pFile->h, nByte));
29929
  SimulateIOError(return SQLITE_IOERR_TRUNCATE);
29930
29931
  /* If the user has configured a chunk-size for this file, truncate the
29932
  ** file so that it consists of an integer number of chunks (i.e. the
29933
  ** actual file size after the operation may be larger than the requested
29934
  ** size).
29935
  */
29936
  if( pFile->szChunk ){
29937
    nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
29938
  }
29939
29940
  /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
29941
  if( seekWinFile(pFile, nByte) ){
29942
    rc = SQLITE_IOERR_TRUNCATE;
29943
  }else if( 0==SetEndOfFile(pFile->h) ){
28809
    pFile->lastErrno = GetLastError();
29944
    pFile->lastErrno = GetLastError();
28810
    return SQLITE_FULL;
29945
    rc = SQLITE_IOERR_TRUNCATE;
28811
  }
29946
  }
28812
  return SQLITE_OK;
29947
28813
}
29948
  OSTRACE(("TRUNCATE %d %lld %s\n", pFile->h, nByte, rc ? "failed" : "ok"));
28814
29949
  return rc;
28815
/*
28816
** Truncate an open file to a specified size
28817
*/
28818
static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
28819
  LONG upperBits = (LONG)((nByte>>32) & 0x7fffffff);
28820
  LONG lowerBits = (LONG)(nByte & 0xffffffff);
28821
  DWORD rc;
28822
  winFile *pFile = (winFile*)id;
28823
  DWORD error;
28824
28825
  assert( id!=0 );
28826
  OSTRACE3("TRUNCATE %d %lld\n", pFile->h, nByte);
28827
  SimulateIOError(return SQLITE_IOERR_TRUNCATE);
28828
  rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
28829
  if( rc==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ){
28830
    pFile->lastErrno = error;
28831
    return SQLITE_IOERR_TRUNCATE;
28832
  }
28833
  /* SetEndOfFile will fail if nByte is negative */
28834
  if( !SetEndOfFile(pFile->h) ){
28835
    pFile->lastErrno = GetLastError();
28836
    return SQLITE_IOERR_TRUNCATE;
28837
  }
28838
  return SQLITE_OK;
28839
}
29950
}
28840
29951
28841
#ifdef SQLITE_TEST
29952
#ifdef SQLITE_TEST
 Lines 28851-28864   SQLITE_API int sqlite3_fullsync_count = Link Here 
28851
** Make sure all writes to a particular file are committed to disk.
29962
** Make sure all writes to a particular file are committed to disk.
28852
*/
29963
*/
28853
static int winSync(sqlite3_file *id, int flags){
29964
static int winSync(sqlite3_file *id, int flags){
28854
#ifndef SQLITE_NO_SYNC
29965
#if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || defined(SQLITE_DEBUG)
28855
  winFile *pFile = (winFile*)id;
29966
  winFile *pFile = (winFile*)id;
28856
28857
  assert( id!=0 );
28858
  OSTRACE3("SYNC %d lock=%d\n", pFile->h, pFile->locktype);
28859
#else
29967
#else
28860
  UNUSED_PARAMETER(id);
29968
  UNUSED_PARAMETER(id);
28861
#endif
29969
#endif
29970
29971
  assert( pFile );
29972
  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
29973
  assert((flags&0x0F)==SQLITE_SYNC_NORMAL
29974
      || (flags&0x0F)==SQLITE_SYNC_FULL
29975
  );
29976
29977
  OSTRACE(("SYNC %d lock=%d\n", pFile->h, pFile->locktype));
29978
28862
#ifndef SQLITE_TEST
29979
#ifndef SQLITE_TEST
28863
  UNUSED_PARAMETER(flags);
29980
  UNUSED_PARAMETER(flags);
28864
#else
29981
#else
 Lines 28867-28877   static int winSync(sqlite3_file *id, int Link Here 
28867
  }
29984
  }
28868
  sqlite3_sync_count++;
29985
  sqlite3_sync_count++;
28869
#endif
29986
#endif
29987
29988
  /* Unix cannot, but some systems may return SQLITE_FULL from here. This
29989
  ** line is to test that doing so does not cause any problems.
29990
  */
29991
  SimulateDiskfullError( return SQLITE_FULL );
29992
  SimulateIOError( return SQLITE_IOERR; );
29993
28870
  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
29994
  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
28871
  ** no-op
29995
  ** no-op
28872
  */
29996
  */
28873
#ifdef SQLITE_NO_SYNC
29997
#ifdef SQLITE_NO_SYNC
28874
    return SQLITE_OK;
29998
  return SQLITE_OK;
28875
#else
29999
#else
28876
  if( FlushFileBuffers(pFile->h) ){
30000
  if( FlushFileBuffers(pFile->h) ){
28877
    return SQLITE_OK;
30001
    return SQLITE_OK;
 Lines 28996-29003   static int winLock(sqlite3_file *id, int Link Here 
28996
  DWORD error = NO_ERROR;
30120
  DWORD error = NO_ERROR;
28997
30121
28998
  assert( id!=0 );
30122
  assert( id!=0 );
28999
  OSTRACE5("LOCK %d %d was %d(%d)\n",
30123
  OSTRACE(("LOCK %d %d was %d(%d)\n",
29000
          pFile->h, locktype, pFile->locktype, pFile->sharedLockByte);
30124
           pFile->h, locktype, pFile->locktype, pFile->sharedLockByte));
29001
30125
29002
  /* If there is already a lock of this type or more restrictive on the
30126
  /* If there is already a lock of this type or more restrictive on the
29003
  ** OsFile, do nothing. Don't use the end_lock: exit path, as
30127
  ** OsFile, do nothing. Don't use the end_lock: exit path, as
 Lines 29027-29033   static int winLock(sqlite3_file *id, int Link Here 
29027
      /* Try 3 times to get the pending lock.  The pending lock might be
30151
      /* Try 3 times to get the pending lock.  The pending lock might be
29028
      ** held by another reader process who will release it momentarily.
30152
      ** held by another reader process who will release it momentarily.
29029
      */
30153
      */
29030
      OSTRACE2("could not get a PENDING lock. cnt=%d\n", cnt);
30154
      OSTRACE(("could not get a PENDING lock. cnt=%d\n", cnt));
29031
      Sleep(1);
30155
      Sleep(1);
29032
    }
30156
    }
29033
    gotPendingLock = res;
30157
    gotPendingLock = res;
 Lines 29072-29084   static int winLock(sqlite3_file *id, int Link Here 
29072
  if( locktype==EXCLUSIVE_LOCK && res ){
30196
  if( locktype==EXCLUSIVE_LOCK && res ){
29073
    assert( pFile->locktype>=SHARED_LOCK );
30197
    assert( pFile->locktype>=SHARED_LOCK );
29074
    res = unlockReadLock(pFile);
30198
    res = unlockReadLock(pFile);
29075
    OSTRACE2("unreadlock = %d\n", res);
30199
    OSTRACE(("unreadlock = %d\n", res));
29076
    res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
30200
    res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
29077
    if( res ){
30201
    if( res ){
29078
      newLocktype = EXCLUSIVE_LOCK;
30202
      newLocktype = EXCLUSIVE_LOCK;
29079
    }else{
30203
    }else{
29080
      error = GetLastError();
30204
      error = GetLastError();
29081
      OSTRACE2("error-code = %d\n", error);
30205
      OSTRACE(("error-code = %d\n", error));
29082
      getReadLock(pFile);
30206
      getReadLock(pFile);
29083
    }
30207
    }
29084
  }
30208
  }
 Lines 29096-29103   static int winLock(sqlite3_file *id, int Link Here 
29096
  if( res ){
30220
  if( res ){
29097
    rc = SQLITE_OK;
30221
    rc = SQLITE_OK;
29098
  }else{
30222
  }else{
29099
    OSTRACE4("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
30223
    OSTRACE(("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
29100
           locktype, newLocktype);
30224
           locktype, newLocktype));
29101
    pFile->lastErrno = error;
30225
    pFile->lastErrno = error;
29102
    rc = SQLITE_BUSY;
30226
    rc = SQLITE_BUSY;
29103
  }
30227
  }
 Lines 29114-29130   static int winCheckReservedLock(sqlite3_ Link Here 
29114
  int rc;
30238
  int rc;
29115
  winFile *pFile = (winFile*)id;
30239
  winFile *pFile = (winFile*)id;
29116
30240
30241
  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
30242
29117
  assert( id!=0 );
30243
  assert( id!=0 );
29118
  if( pFile->locktype>=RESERVED_LOCK ){
30244
  if( pFile->locktype>=RESERVED_LOCK ){
29119
    rc = 1;
30245
    rc = 1;
29120
    OSTRACE3("TEST WR-LOCK %d %d (local)\n", pFile->h, rc);
30246
    OSTRACE(("TEST WR-LOCK %d %d (local)\n", pFile->h, rc));
29121
  }else{
30247
  }else{
29122
    rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
30248
    rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
29123
    if( rc ){
30249
    if( rc ){
29124
      UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
30250
      UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
29125
    }
30251
    }
29126
    rc = !rc;
30252
    rc = !rc;
29127
    OSTRACE3("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc);
30253
    OSTRACE(("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc));
29128
  }
30254
  }
29129
  *pResOut = rc;
30255
  *pResOut = rc;
29130
  return SQLITE_OK;
30256
  return SQLITE_OK;
 Lines 29147-29154   static int winUnlock(sqlite3_file *id, i Link Here 
29147
  int rc = SQLITE_OK;
30273
  int rc = SQLITE_OK;
29148
  assert( pFile!=0 );
30274
  assert( pFile!=0 );
29149
  assert( locktype<=SHARED_LOCK );
30275
  assert( locktype<=SHARED_LOCK );
29150
  OSTRACE5("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
30276
  OSTRACE(("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
29151
          pFile->locktype, pFile->sharedLockByte);
30277
          pFile->locktype, pFile->sharedLockByte));
29152
  type = pFile->locktype;
30278
  type = pFile->locktype;
29153
  if( type>=EXCLUSIVE_LOCK ){
30279
  if( type>=EXCLUSIVE_LOCK ){
29154
    UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
30280
    UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
 Lines 29184-29189   static int winFileControl(sqlite3_file * Link Here 
29184
      *(int*)pArg = (int)((winFile*)id)->lastErrno;
30310
      *(int*)pArg = (int)((winFile*)id)->lastErrno;
29185
      return SQLITE_OK;
30311
      return SQLITE_OK;
29186
    }
30312
    }
30313
    case SQLITE_FCNTL_CHUNK_SIZE: {
30314
      ((winFile*)id)->szChunk = *(int *)pArg;
30315
      return SQLITE_OK;
30316
    }
30317
    case SQLITE_FCNTL_SIZE_HINT: {
30318
      sqlite3_int64 sz = *(sqlite3_int64*)pArg;
30319
      SimulateIOErrorBenign(1);
30320
      winTruncate(id, sz);
30321
      SimulateIOErrorBenign(0);
30322
      return SQLITE_OK;
30323
    }
29187
  }
30324
  }
29188
  return SQLITE_ERROR;
30325
  return SQLITE_ERROR;
29189
}
30326
}
 Lines 29208-29241   static int winSectorSize(sqlite3_file *i Link Here 
29208
*/
30345
*/
29209
static int winDeviceCharacteristics(sqlite3_file *id){
30346
static int winDeviceCharacteristics(sqlite3_file *id){
29210
  UNUSED_PARAMETER(id);
30347
  UNUSED_PARAMETER(id);
29211
  return 0;
30348
  return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;
29212
}
30349
}
30350
30351
#ifndef SQLITE_OMIT_WAL
30352
30353
/*
30354
** Helper functions to obtain and relinquish the global mutex. The
30355
** global mutex is used to protect the winLockInfo objects used by 
30356
** this file, all of which may be shared by multiple threads.
30357
**
30358
** Function winShmMutexHeld() is used to assert() that the global mutex 
30359
** is held when required. This function is only used as part of assert() 
30360
** statements. e.g.
30361
**
30362
**   winShmEnterMutex()
30363
**     assert( winShmMutexHeld() );
30364
**   winShmLeaveMutex()
30365
*/
30366
static void winShmEnterMutex(void){
30367
  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
30368
}
30369
static void winShmLeaveMutex(void){
30370
  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
30371
}
30372
#ifdef SQLITE_DEBUG
30373
static int winShmMutexHeld(void) {
30374
  return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
30375
}
30376
#endif
30377
30378
/*
30379
** Object used to represent a single file opened and mmapped to provide
30380
** shared memory.  When multiple threads all reference the same
30381
** log-summary, each thread has its own winFile object, but they all
30382
** point to a single instance of this object.  In other words, each
30383
** log-summary is opened only once per process.
30384
**
30385
** winShmMutexHeld() must be true when creating or destroying
30386
** this object or while reading or writing the following fields:
30387
**
30388
**      nRef
30389
**      pNext 
30390
**
30391
** The following fields are read-only after the object is created:
30392
** 
30393
**      fid
30394
**      zFilename
30395
**
30396
** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
30397
** winShmMutexHeld() is true when reading or writing any other field
30398
** in this structure.
30399
**
30400
*/
30401
struct winShmNode {
30402
  sqlite3_mutex *mutex;      /* Mutex to access this object */
30403
  char *zFilename;           /* Name of the file */
30404
  winFile hFile;             /* File handle from winOpen */
30405
30406
  int szRegion;              /* Size of shared-memory regions */
30407
  int nRegion;               /* Size of array apRegion */
30408
  struct ShmRegion {
30409
    HANDLE hMap;             /* File handle from CreateFileMapping */
30410
    void *pMap;
30411
  } *aRegion;
30412
  DWORD lastErrno;           /* The Windows errno from the last I/O error */
30413
30414
  int nRef;                  /* Number of winShm objects pointing to this */
30415
  winShm *pFirst;            /* All winShm objects pointing to this */
30416
  winShmNode *pNext;         /* Next in list of all winShmNode objects */
30417
#ifdef SQLITE_DEBUG
30418
  u8 nextShmId;              /* Next available winShm.id value */
30419
#endif
30420
};
30421
30422
/*
30423
** A global array of all winShmNode objects.
30424
**
30425
** The winShmMutexHeld() must be true while reading or writing this list.
30426
*/
30427
static winShmNode *winShmNodeList = 0;
30428
30429
/*
30430
** Structure used internally by this VFS to record the state of an
30431
** open shared memory connection.
30432
**
30433
** The following fields are initialized when this object is created and
30434
** are read-only thereafter:
30435
**
30436
**    winShm.pShmNode
30437
**    winShm.id
30438
**
30439
** All other fields are read/write.  The winShm.pShmNode->mutex must be held
30440
** while accessing any read/write fields.
30441
*/
30442
struct winShm {
30443
  winShmNode *pShmNode;      /* The underlying winShmNode object */
30444
  winShm *pNext;             /* Next winShm with the same winShmNode */
30445
  u8 hasMutex;               /* True if holding the winShmNode mutex */
30446
  u16 sharedMask;            /* Mask of shared locks held */
30447
  u16 exclMask;              /* Mask of exclusive locks held */
30448
#ifdef SQLITE_DEBUG
30449
  u8 id;                     /* Id of this connection with its winShmNode */
30450
#endif
30451
};
30452
30453
/*
30454
** Constants used for locking
30455
*/
30456
#define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
30457
#define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
30458
30459
/*
30460
** Apply advisory locks for all n bytes beginning at ofst.
30461
*/
30462
#define _SHM_UNLCK  1
30463
#define _SHM_RDLCK  2
30464
#define _SHM_WRLCK  3
30465
static int winShmSystemLock(
30466
  winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
30467
  int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
30468
  int ofst,             /* Offset to first byte to be locked/unlocked */
30469
  int nByte             /* Number of bytes to lock or unlock */
30470
){
30471
  OVERLAPPED ovlp;
30472
  DWORD dwFlags;
30473
  int rc = 0;           /* Result code form Lock/UnlockFileEx() */
30474
30475
  /* Access to the winShmNode object is serialized by the caller */
30476
  assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
30477
30478
  /* Initialize the locking parameters */
30479
  dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
30480
  if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
30481
30482
  memset(&ovlp, 0, sizeof(OVERLAPPED));
30483
  ovlp.Offset = ofst;
30484
30485
  /* Release/Acquire the system-level lock */
30486
  if( lockType==_SHM_UNLCK ){
30487
    rc = UnlockFileEx(pFile->hFile.h, 0, nByte, 0, &ovlp);
30488
  }else{
30489
    rc = LockFileEx(pFile->hFile.h, dwFlags, 0, nByte, 0, &ovlp);
30490
  }
30491
  
30492
  if( rc!= 0 ){
30493
    rc = SQLITE_OK;
30494
  }else{
30495
    pFile->lastErrno =  GetLastError();
30496
    rc = SQLITE_BUSY;
30497
  }
30498
30499
  OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n", 
30500
           pFile->hFile.h,
30501
           rc==SQLITE_OK ? "ok" : "failed",
30502
           lockType==_SHM_UNLCK ? "UnlockFileEx" : "LockFileEx",
30503
           pFile->lastErrno));
30504
30505
  return rc;
30506
}
30507
30508
/* Forward references to VFS methods */
30509
static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
30510
static int winDelete(sqlite3_vfs *,const char*,int);
30511
30512
/*
30513
** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
30514
**
30515
** This is not a VFS shared-memory method; it is a utility function called
30516
** by VFS shared-memory methods.
30517
*/
30518
static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
30519
  winShmNode **pp;
30520
  winShmNode *p;
30521
  assert( winShmMutexHeld() );
30522
  pp = &winShmNodeList;
30523
  while( (p = *pp)!=0 ){
30524
    if( p->nRef==0 ){
30525
      int i;
30526
      if( p->mutex ) sqlite3_mutex_free(p->mutex);
30527
      for(i=0; i<p->nRegion; i++){
30528
        UnmapViewOfFile(p->aRegion[i].pMap);
30529
        CloseHandle(p->aRegion[i].hMap);
30530
      }
30531
      if( p->hFile.h != INVALID_HANDLE_VALUE ){
30532
        SimulateIOErrorBenign(1);
30533
        winClose((sqlite3_file *)&p->hFile);
30534
        SimulateIOErrorBenign(0);
30535
      }
30536
      if( deleteFlag ){
30537
        SimulateIOErrorBenign(1);
30538
        winDelete(pVfs, p->zFilename, 0);
30539
        SimulateIOErrorBenign(0);
30540
      }
30541
      *pp = p->pNext;
30542
      sqlite3_free(p->aRegion);
30543
      sqlite3_free(p);
30544
    }else{
30545
      pp = &p->pNext;
30546
    }
30547
  }
30548
}
30549
30550
/*
30551
** Open the shared-memory area associated with database file pDbFd.
30552
**
30553
** When opening a new shared-memory file, if no other instances of that
30554
** file are currently open, in this process or in other processes, then
30555
** the file must be truncated to zero length or have its header cleared.
30556
*/
30557
static int winOpenSharedMemory(winFile *pDbFd){
30558
  struct winShm *p;                  /* The connection to be opened */
30559
  struct winShmNode *pShmNode = 0;   /* The underlying mmapped file */
30560
  int rc;                            /* Result code */
30561
  struct winShmNode *pNew;           /* Newly allocated winShmNode */
30562
  int nName;                         /* Size of zName in bytes */
30563
30564
  assert( pDbFd->pShm==0 );    /* Not previously opened */
30565
30566
  /* Allocate space for the new sqlite3_shm object.  Also speculatively
30567
  ** allocate space for a new winShmNode and filename.
30568
  */
30569
  p = sqlite3_malloc( sizeof(*p) );
30570
  if( p==0 ) return SQLITE_NOMEM;
30571
  memset(p, 0, sizeof(*p));
30572
  nName = sqlite3Strlen30(pDbFd->zPath);
30573
  pNew = sqlite3_malloc( sizeof(*pShmNode) + nName + 15 );
30574
  if( pNew==0 ){
30575
    sqlite3_free(p);
30576
    return SQLITE_NOMEM;
30577
  }
30578
  memset(pNew, 0, sizeof(*pNew));
30579
  pNew->zFilename = (char*)&pNew[1];
30580
  sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
30581
30582
  /* Look to see if there is an existing winShmNode that can be used.
30583
  ** If no matching winShmNode currently exists, create a new one.
30584
  */
30585
  winShmEnterMutex();
30586
  for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
30587
    /* TBD need to come up with better match here.  Perhaps
30588
    ** use FILE_ID_BOTH_DIR_INFO Structure.
30589
    */
30590
    if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
30591
  }
30592
  if( pShmNode ){
30593
    sqlite3_free(pNew);
30594
  }else{
30595
    pShmNode = pNew;
30596
    pNew = 0;
30597
    ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
30598
    pShmNode->pNext = winShmNodeList;
30599
    winShmNodeList = pShmNode;
30600
30601
    pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
30602
    if( pShmNode->mutex==0 ){
30603
      rc = SQLITE_NOMEM;
30604
      goto shm_open_err;
30605
    }
30606
    rc = winOpen(pDbFd->pVfs,
30607
                 pShmNode->zFilename,             /* Name of the file (UTF-8) */
30608
                 (sqlite3_file*)&pShmNode->hFile,  /* File handle here */
30609
                 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, /* Mode flags */
30610
                 0);
30611
    if( SQLITE_OK!=rc ){
30612
      rc = SQLITE_CANTOPEN_BKPT;
30613
      goto shm_open_err;
30614
    }
30615
30616
    /* Check to see if another process is holding the dead-man switch.
30617
    ** If not, truncate the file to zero length. 
30618
    */
30619
    if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
30620
      rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
30621
      if( rc!=SQLITE_OK ){
30622
        rc = SQLITE_IOERR_SHMOPEN;
30623
      }
30624
    }
30625
    if( rc==SQLITE_OK ){
30626
      winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
30627
      rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
30628
    }
30629
    if( rc ) goto shm_open_err;
30630
  }
30631
30632
  /* Make the new connection a child of the winShmNode */
30633
  p->pShmNode = pShmNode;
30634
#ifdef SQLITE_DEBUG
30635
  p->id = pShmNode->nextShmId++;
30636
#endif
30637
  pShmNode->nRef++;
30638
  pDbFd->pShm = p;
30639
  winShmLeaveMutex();
30640
30641
  /* The reference count on pShmNode has already been incremented under
30642
  ** the cover of the winShmEnterMutex() mutex and the pointer from the
30643
  ** new (struct winShm) object to the pShmNode has been set. All that is
30644
  ** left to do is to link the new object into the linked list starting
30645
  ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex 
30646
  ** mutex.
30647
  */
30648
  sqlite3_mutex_enter(pShmNode->mutex);
30649
  p->pNext = pShmNode->pFirst;
30650
  pShmNode->pFirst = p;
30651
  sqlite3_mutex_leave(pShmNode->mutex);
30652
  return SQLITE_OK;
30653
30654
  /* Jump here on any error */
30655
shm_open_err:
30656
  winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
30657
  winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
30658
  sqlite3_free(p);
30659
  sqlite3_free(pNew);
30660
  winShmLeaveMutex();
30661
  return rc;
30662
}
30663
30664
/*
30665
** Close a connection to shared-memory.  Delete the underlying 
30666
** storage if deleteFlag is true.
30667
*/
30668
static int winShmUnmap(
30669
  sqlite3_file *fd,          /* Database holding shared memory */
30670
  int deleteFlag             /* Delete after closing if true */
30671
){
30672
  winFile *pDbFd;       /* Database holding shared-memory */
30673
  winShm *p;            /* The connection to be closed */
30674
  winShmNode *pShmNode; /* The underlying shared-memory file */
30675
  winShm **pp;          /* For looping over sibling connections */
30676
30677
  pDbFd = (winFile*)fd;
30678
  p = pDbFd->pShm;
30679
  if( p==0 ) return SQLITE_OK;
30680
  pShmNode = p->pShmNode;
30681
30682
  /* Remove connection p from the set of connections associated
30683
  ** with pShmNode */
30684
  sqlite3_mutex_enter(pShmNode->mutex);
30685
  for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
30686
  *pp = p->pNext;
30687
30688
  /* Free the connection p */
30689
  sqlite3_free(p);
30690
  pDbFd->pShm = 0;
30691
  sqlite3_mutex_leave(pShmNode->mutex);
30692
30693
  /* If pShmNode->nRef has reached 0, then close the underlying
30694
  ** shared-memory file, too */
30695
  winShmEnterMutex();
30696
  assert( pShmNode->nRef>0 );
30697
  pShmNode->nRef--;
30698
  if( pShmNode->nRef==0 ){
30699
    winShmPurge(pDbFd->pVfs, deleteFlag);
30700
  }
30701
  winShmLeaveMutex();
30702
30703
  return SQLITE_OK;
30704
}
30705
30706
/*
30707
** Change the lock state for a shared-memory segment.
30708
*/
30709
static int winShmLock(
30710
  sqlite3_file *fd,          /* Database file holding the shared memory */
30711
  int ofst,                  /* First lock to acquire or release */
30712
  int n,                     /* Number of locks to acquire or release */
30713
  int flags                  /* What to do with the lock */
30714
){
30715
  winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
30716
  winShm *p = pDbFd->pShm;              /* The shared memory being locked */
30717
  winShm *pX;                           /* For looping over all siblings */
30718
  winShmNode *pShmNode = p->pShmNode;
30719
  int rc = SQLITE_OK;                   /* Result code */
30720
  u16 mask;                             /* Mask of locks to take or release */
30721
30722
  assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
30723
  assert( n>=1 );
30724
  assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
30725
       || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
30726
       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
30727
       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
30728
  assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
30729
30730
  mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
30731
  assert( n>1 || mask==(1<<ofst) );
30732
  sqlite3_mutex_enter(pShmNode->mutex);
30733
  if( flags & SQLITE_SHM_UNLOCK ){
30734
    u16 allMask = 0; /* Mask of locks held by siblings */
30735
30736
    /* See if any siblings hold this same lock */
30737
    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
30738
      if( pX==p ) continue;
30739
      assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
30740
      allMask |= pX->sharedMask;
30741
    }
30742
30743
    /* Unlock the system-level locks */
30744
    if( (mask & allMask)==0 ){
30745
      rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
30746
    }else{
30747
      rc = SQLITE_OK;
30748
    }
30749
30750
    /* Undo the local locks */
30751
    if( rc==SQLITE_OK ){
30752
      p->exclMask &= ~mask;
30753
      p->sharedMask &= ~mask;
30754
    } 
30755
  }else if( flags & SQLITE_SHM_SHARED ){
30756
    u16 allShared = 0;  /* Union of locks held by connections other than "p" */
30757
30758
    /* Find out which shared locks are already held by sibling connections.
30759
    ** If any sibling already holds an exclusive lock, go ahead and return
30760
    ** SQLITE_BUSY.
30761
    */
30762
    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
30763
      if( (pX->exclMask & mask)!=0 ){
30764
        rc = SQLITE_BUSY;
30765
        break;
30766
      }
30767
      allShared |= pX->sharedMask;
30768
    }
30769
30770
    /* Get shared locks at the system level, if necessary */
30771
    if( rc==SQLITE_OK ){
30772
      if( (allShared & mask)==0 ){
30773
        rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
30774
      }else{
30775
        rc = SQLITE_OK;
30776
      }
30777
    }
30778
30779
    /* Get the local shared locks */
30780
    if( rc==SQLITE_OK ){
30781
      p->sharedMask |= mask;
30782
    }
30783
  }else{
30784
    /* Make sure no sibling connections hold locks that will block this
30785
    ** lock.  If any do, return SQLITE_BUSY right away.
30786
    */
30787
    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
30788
      if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
30789
        rc = SQLITE_BUSY;
30790
        break;
30791
      }
30792
    }
30793
  
30794
    /* Get the exclusive locks at the system level.  Then if successful
30795
    ** also mark the local connection as being locked.
30796
    */
30797
    if( rc==SQLITE_OK ){
30798
      rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
30799
      if( rc==SQLITE_OK ){
30800
        assert( (p->sharedMask & mask)==0 );
30801
        p->exclMask |= mask;
30802
      }
30803
    }
30804
  }
30805
  sqlite3_mutex_leave(pShmNode->mutex);
30806
  OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
30807
           p->id, (int)GetCurrentProcessId(), p->sharedMask, p->exclMask,
30808
           rc ? "failed" : "ok"));
30809
  return rc;
30810
}
30811
30812
/*
30813
** Implement a memory barrier or memory fence on shared memory.  
30814
**
30815
** All loads and stores begun before the barrier must complete before
30816
** any load or store begun after the barrier.
30817
*/
30818
static void winShmBarrier(
30819
  sqlite3_file *fd          /* Database holding the shared memory */
30820
){
30821
  UNUSED_PARAMETER(fd);
30822
  /* MemoryBarrier(); // does not work -- do not know why not */
30823
  winShmEnterMutex();
30824
  winShmLeaveMutex();
30825
}
30826
30827
/*
30828
** This function is called to obtain a pointer to region iRegion of the 
30829
** shared-memory associated with the database file fd. Shared-memory regions 
30830
** are numbered starting from zero. Each shared-memory region is szRegion 
30831
** bytes in size.
30832
**
30833
** If an error occurs, an error code is returned and *pp is set to NULL.
30834
**
30835
** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
30836
** region has not been allocated (by any client, including one running in a
30837
** separate process), then *pp is set to NULL and SQLITE_OK returned. If 
30838
** isWrite is non-zero and the requested shared-memory region has not yet 
30839
** been allocated, it is allocated by this function.
30840
**
30841
** If the shared-memory region has already been allocated or is allocated by
30842
** this call as described above, then it is mapped into this processes 
30843
** address space (if it is not already), *pp is set to point to the mapped 
30844
** memory and SQLITE_OK returned.
30845
*/
30846
static int winShmMap(
30847
  sqlite3_file *fd,               /* Handle open on database file */
30848
  int iRegion,                    /* Region to retrieve */
30849
  int szRegion,                   /* Size of regions */
30850
  int isWrite,                    /* True to extend file if necessary */
30851
  void volatile **pp              /* OUT: Mapped memory */
30852
){
30853
  winFile *pDbFd = (winFile*)fd;
30854
  winShm *p = pDbFd->pShm;
30855
  winShmNode *pShmNode;
30856
  int rc = SQLITE_OK;
30857
30858
  if( !p ){
30859
    rc = winOpenSharedMemory(pDbFd);
30860
    if( rc!=SQLITE_OK ) return rc;
30861
    p = pDbFd->pShm;
30862
  }
30863
  pShmNode = p->pShmNode;
30864
30865
  sqlite3_mutex_enter(pShmNode->mutex);
30866
  assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
30867
30868
  if( pShmNode->nRegion<=iRegion ){
30869
    struct ShmRegion *apNew;           /* New aRegion[] array */
30870
    int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
30871
    sqlite3_int64 sz;                  /* Current size of wal-index file */
30872
30873
    pShmNode->szRegion = szRegion;
30874
30875
    /* The requested region is not mapped into this processes address space.
30876
    ** Check to see if it has been allocated (i.e. if the wal-index file is
30877
    ** large enough to contain the requested region).
30878
    */
30879
    rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
30880
    if( rc!=SQLITE_OK ){
30881
      rc = SQLITE_IOERR_SHMSIZE;
30882
      goto shmpage_out;
30883
    }
30884
30885
    if( sz<nByte ){
30886
      /* The requested memory region does not exist. If isWrite is set to
30887
      ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
30888
      **
30889
      ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
30890
      ** the requested memory region.
30891
      */
30892
      if( !isWrite ) goto shmpage_out;
30893
      rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
30894
      if( rc!=SQLITE_OK ){
30895
        rc = SQLITE_IOERR_SHMSIZE;
30896
        goto shmpage_out;
30897
      }
30898
    }
30899
30900
    /* Map the requested memory region into this processes address space. */
30901
    apNew = (struct ShmRegion *)sqlite3_realloc(
30902
        pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
30903
    );
30904
    if( !apNew ){
30905
      rc = SQLITE_IOERR_NOMEM;
30906
      goto shmpage_out;
30907
    }
30908
    pShmNode->aRegion = apNew;
30909
30910
    while( pShmNode->nRegion<=iRegion ){
30911
      HANDLE hMap;                /* file-mapping handle */
30912
      void *pMap = 0;             /* Mapped memory region */
30913
     
30914
      hMap = CreateFileMapping(pShmNode->hFile.h, 
30915
          NULL, PAGE_READWRITE, 0, nByte, NULL
30916
      );
30917
      if( hMap ){
30918
        pMap = MapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
30919
            0, 0, nByte
30920
        );
30921
      }
30922
      if( !pMap ){
30923
        pShmNode->lastErrno = GetLastError();
30924
        rc = SQLITE_IOERR;
30925
        if( hMap ) CloseHandle(hMap);
30926
        goto shmpage_out;
30927
      }
30928
30929
      pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
30930
      pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
30931
      pShmNode->nRegion++;
30932
    }
30933
  }
30934
30935
shmpage_out:
30936
  if( pShmNode->nRegion>iRegion ){
30937
    char *p = (char *)pShmNode->aRegion[iRegion].pMap;
30938
    *pp = (void *)&p[iRegion*szRegion];
30939
  }else{
30940
    *pp = 0;
30941
  }
30942
  sqlite3_mutex_leave(pShmNode->mutex);
30943
  return rc;
30944
}
30945
30946
#else
30947
# define winShmMap     0
30948
# define winShmLock    0
30949
# define winShmBarrier 0
30950
# define winShmUnmap   0
30951
#endif /* #ifndef SQLITE_OMIT_WAL */
30952
30953
/*
30954
** Here ends the implementation of all sqlite3_file methods.
30955
**
30956
********************** End sqlite3_file Methods *******************************
30957
******************************************************************************/
29213
30958
29214
/*
30959
/*
29215
** This vector defines all the methods that can operate on an
30960
** This vector defines all the methods that can operate on an
29216
** sqlite3_file for win32.
30961
** sqlite3_file for win32.
29217
*/
30962
*/
29218
static const sqlite3_io_methods winIoMethod = {
30963
static const sqlite3_io_methods winIoMethod = {
29219
  1,                        /* iVersion */
30964
  2,                              /* iVersion */
29220
  winClose,
30965
  winClose,                       /* xClose */
29221
  winRead,
30966
  winRead,                        /* xRead */
29222
  winWrite,
30967
  winWrite,                       /* xWrite */
29223
  winTruncate,
30968
  winTruncate,                    /* xTruncate */
29224
  winSync,
30969
  winSync,                        /* xSync */
29225
  winFileSize,
30970
  winFileSize,                    /* xFileSize */
29226
  winLock,
30971
  winLock,                        /* xLock */
29227
  winUnlock,
30972
  winUnlock,                      /* xUnlock */
29228
  winCheckReservedLock,
30973
  winCheckReservedLock,           /* xCheckReservedLock */
29229
  winFileControl,
30974
  winFileControl,                 /* xFileControl */
29230
  winSectorSize,
30975
  winSectorSize,                  /* xSectorSize */
29231
  winDeviceCharacteristics
30976
  winDeviceCharacteristics,       /* xDeviceCharacteristics */
29232
};
30977
  winShmMap,                      /* xShmMap */
29233
30978
  winShmLock,                     /* xShmLock */
29234
/***************************************************************************
30979
  winShmBarrier,                  /* xShmBarrier */
29235
** Here ends the I/O methods that form the sqlite3_io_methods object.
30980
  winShmUnmap                     /* xShmUnmap */
29236
**
30981
};
29237
** The next block of code implements the VFS methods.
30982
29238
****************************************************************************/
30983
/****************************************************************************
30984
**************************** sqlite3_vfs methods ****************************
30985
**
30986
** This division contains the implementation of methods on the
30987
** sqlite3_vfs object.
30988
*/
29239
30989
29240
/*
30990
/*
29241
** Convert a UTF-8 filename into whatever form the underlying
30991
** Convert a UTF-8 filename into whatever form the underlying
 Lines 29269-29274   static int getTempname(int nBuf, char *z Link Here 
29269
    "0123456789";
31019
    "0123456789";
29270
  size_t i, j;
31020
  size_t i, j;
29271
  char zTempPath[MAX_PATH+1];
31021
  char zTempPath[MAX_PATH+1];
31022
31023
  /* It's odd to simulate an io-error here, but really this is just
31024
  ** using the io-error infrastructure to test that SQLite handles this
31025
  ** function failing. 
31026
  */
31027
  SimulateIOError( return SQLITE_IOERR );
31028
29272
  if( sqlite3_temp_directory ){
31029
  if( sqlite3_temp_directory ){
29273
    sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
31030
    sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
29274
  }else if( isNT() ){
31031
  }else if( isNT() ){
 Lines 29300-29316   static int getTempname(int nBuf, char *z Link Here 
29300
    }
31057
    }
29301
#endif
31058
#endif
29302
  }
31059
  }
31060
31061
  /* Check that the output buffer is large enough for the temporary file 
31062
  ** name. If it is not, return SQLITE_ERROR.
31063
  */
31064
  if( (sqlite3Strlen30(zTempPath) + sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX) + 17) >= nBuf ){
31065
    return SQLITE_ERROR;
31066
  }
31067
29303
  for(i=sqlite3Strlen30(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
31068
  for(i=sqlite3Strlen30(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
29304
  zTempPath[i] = 0;
31069
  zTempPath[i] = 0;
29305
  sqlite3_snprintf(nBuf-30, zBuf,
31070
31071
  sqlite3_snprintf(nBuf-17, zBuf,
29306
                   "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
31072
                   "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
29307
  j = sqlite3Strlen30(zBuf);
31073
  j = sqlite3Strlen30(zBuf);
29308
  sqlite3_randomness(20, &zBuf[j]);
31074
  sqlite3_randomness(15, &zBuf[j]);
29309
  for(i=0; i<20; i++, j++){
31075
  for(i=0; i<15; i++, j++){
29310
    zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
31076
    zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
29311
  }
31077
  }
29312
  zBuf[j] = 0;
31078
  zBuf[j] = 0;
29313
  OSTRACE2("TEMP FILENAME: %s\n", zBuf);
31079
31080
  OSTRACE(("TEMP FILENAME: %s\n", zBuf));
29314
  return SQLITE_OK; 
31081
  return SQLITE_OK; 
29315
}
31082
}
29316
31083
 Lines 29402-29407   static int winOpen( Link Here 
29402
  assert( id!=0 );
31169
  assert( id!=0 );
29403
  UNUSED_PARAMETER(pVfs);
31170
  UNUSED_PARAMETER(pVfs);
29404
31171
31172
  pFile->h = INVALID_HANDLE_VALUE;
31173
29405
  /* If the second argument to this function is NULL, generate a 
31174
  /* If the second argument to this function is NULL, generate a 
29406
  ** temporary file name to use 
31175
  ** temporary file name to use 
29407
  */
31176
  */
 Lines 29483-29489   static int winOpen( Link Here 
29483
    );
31252
    );
29484
#endif
31253
#endif
29485
  }
31254
  }
31255
  OSTRACE(("OPEN %d %s 0x%lx %s\n", 
31256
           h, zName, dwDesiredAccess, 
31257
           h==INVALID_HANDLE_VALUE ? "failed" : "ok"));
29486
  if( h==INVALID_HANDLE_VALUE ){
31258
  if( h==INVALID_HANDLE_VALUE ){
31259
    pFile->lastErrno = GetLastError();
29487
    free(zConverted);
31260
    free(zConverted);
29488
    if( flags & SQLITE_OPEN_READWRITE ){
31261
    if( flags & SQLITE_OPEN_READWRITE ){
29489
      return winOpen(pVfs, zName, id, 
31262
      return winOpen(pVfs, zName, id, 
 Lines 29503-29508   static int winOpen( Link Here 
29503
  pFile->pMethod = &winIoMethod;
31276
  pFile->pMethod = &winIoMethod;
29504
  pFile->h = h;
31277
  pFile->h = h;
29505
  pFile->lastErrno = NO_ERROR;
31278
  pFile->lastErrno = NO_ERROR;
31279
  pFile->pVfs = pVfs;
31280
  pFile->pShm = 0;
31281
  pFile->zPath = zName;
29506
  pFile->sectorSize = getSectorSize(pVfs, zUtf8Name);
31282
  pFile->sectorSize = getSectorSize(pVfs, zUtf8Name);
29507
#if SQLITE_OS_WINCE
31283
#if SQLITE_OS_WINCE
29508
  if( (flags & (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)) ==
31284
  if( (flags & (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)) ==
 Lines 29545-29557   static int winDelete( Link Here 
29545
  int cnt = 0;
31321
  int cnt = 0;
29546
  DWORD rc;
31322
  DWORD rc;
29547
  DWORD error = 0;
31323
  DWORD error = 0;
29548
  void *zConverted = convertUtf8Filename(zFilename);
31324
  void *zConverted;
29549
  UNUSED_PARAMETER(pVfs);
31325
  UNUSED_PARAMETER(pVfs);
29550
  UNUSED_PARAMETER(syncDir);
31326
  UNUSED_PARAMETER(syncDir);
31327
31328
  SimulateIOError(return SQLITE_IOERR_DELETE);
31329
  zConverted = convertUtf8Filename(zFilename);
29551
  if( zConverted==0 ){
31330
  if( zConverted==0 ){
29552
    return SQLITE_NOMEM;
31331
    return SQLITE_NOMEM;
29553
  }
31332
  }
29554
  SimulateIOError(return SQLITE_IOERR_DELETE);
29555
  if( isNT() ){
31333
  if( isNT() ){
29556
    do{
31334
    do{
29557
      DeleteFileW(zConverted);
31335
      DeleteFileW(zConverted);
 Lines 29574-29580   static int winDelete( Link Here 
29574
#endif
31352
#endif
29575
  }
31353
  }
29576
  free(zConverted);
31354
  free(zConverted);
29577
  OSTRACE2("DELETE \"%s\"\n", zFilename);
31355
  OSTRACE(("DELETE \"%s\" %s\n", zFilename,
31356
       ( (rc==INVALID_FILE_ATTRIBUTES) && (error==ERROR_FILE_NOT_FOUND)) ?
31357
         "ok" : "failed" ));
31358
 
29578
  return (   (rc == INVALID_FILE_ATTRIBUTES) 
31359
  return (   (rc == INVALID_FILE_ATTRIBUTES) 
29579
          && (error == ERROR_FILE_NOT_FOUND)) ? SQLITE_OK : SQLITE_IOERR_DELETE;
31360
          && (error == ERROR_FILE_NOT_FOUND)) ? SQLITE_OK : SQLITE_IOERR_DELETE;
29580
}
31361
}
 Lines 29590-29602   static int winAccess( Link Here 
29590
){
31371
){
29591
  DWORD attr;
31372
  DWORD attr;
29592
  int rc = 0;
31373
  int rc = 0;
29593
  void *zConverted = convertUtf8Filename(zFilename);
31374
  void *zConverted;
29594
  UNUSED_PARAMETER(pVfs);
31375
  UNUSED_PARAMETER(pVfs);
31376
31377
  SimulateIOError( return SQLITE_IOERR_ACCESS; );
31378
  zConverted = convertUtf8Filename(zFilename);
29595
  if( zConverted==0 ){
31379
  if( zConverted==0 ){
29596
    return SQLITE_NOMEM;
31380
    return SQLITE_NOMEM;
29597
  }
31381
  }
29598
  if( isNT() ){
31382
  if( isNT() ){
29599
    attr = GetFileAttributesW((WCHAR*)zConverted);
31383
    WIN32_FILE_ATTRIBUTE_DATA sAttrData;
31384
    memset(&sAttrData, 0, sizeof(sAttrData));
31385
    if( GetFileAttributesExW((WCHAR*)zConverted,
31386
                             GetFileExInfoStandard, 
31387
                             &sAttrData) ){
31388
      /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
31389
      ** as if it does not exist.
31390
      */
31391
      if(    flags==SQLITE_ACCESS_EXISTS
31392
          && sAttrData.nFileSizeHigh==0 
31393
          && sAttrData.nFileSizeLow==0 ){
31394
        attr = INVALID_FILE_ATTRIBUTES;
31395
      }else{
31396
        attr = sAttrData.dwFileAttributes;
31397
      }
31398
    }else{
31399
      if( GetLastError()!=ERROR_FILE_NOT_FOUND ){
31400
        free(zConverted);
31401
        return SQLITE_IOERR_ACCESS;
31402
      }else{
31403
        attr = INVALID_FILE_ATTRIBUTES;
31404
      }
31405
    }
29600
/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
31406
/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
29601
** Since the ASCII version of these Windows API do not exist for WINCE,
31407
** Since the ASCII version of these Windows API do not exist for WINCE,
29602
** it's important to not reference them for WINCE builds.
31408
** it's important to not reference them for WINCE builds.
 Lines 29636-29647   static int winFullPathname( Link Here 
29636
){
31442
){
29637
  
31443
  
29638
#if defined(__CYGWIN__)
31444
#if defined(__CYGWIN__)
31445
  SimulateIOError( return SQLITE_ERROR );
29639
  UNUSED_PARAMETER(nFull);
31446
  UNUSED_PARAMETER(nFull);
29640
  cygwin_conv_to_full_win32_path(zRelative, zFull);
31447
  cygwin_conv_to_full_win32_path(zRelative, zFull);
29641
  return SQLITE_OK;
31448
  return SQLITE_OK;
29642
#endif
31449
#endif
29643
31450
29644
#if SQLITE_OS_WINCE
31451
#if SQLITE_OS_WINCE
31452
  SimulateIOError( return SQLITE_ERROR );
29645
  UNUSED_PARAMETER(nFull);
31453
  UNUSED_PARAMETER(nFull);
29646
  /* WinCE has no concept of a relative pathname, or so I am told. */
31454
  /* WinCE has no concept of a relative pathname, or so I am told. */
29647
  sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
31455
  sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
 Lines 29652-29657   static int winFullPathname( Link Here 
29652
  int nByte;
31460
  int nByte;
29653
  void *zConverted;
31461
  void *zConverted;
29654
  char *zOut;
31462
  char *zOut;
31463
31464
  /* It's odd to simulate an io-error here, but really this is just
31465
  ** using the io-error infrastructure to test that SQLite handles this
31466
  ** function failing. This function could fail if, for example, the
31467
  ** current working directory has been unlinked.
31468
  */
31469
  SimulateIOError( return SQLITE_ERROR );
29655
  UNUSED_PARAMETER(nFull);
31470
  UNUSED_PARAMETER(nFull);
29656
  zConverted = convertUtf8Filename(zRelative);
31471
  zConverted = convertUtf8Filename(zRelative);
29657
  if( isNT() ){
31472
  if( isNT() ){
 Lines 29719-29725   static int getSectorSize( Link Here 
29719
  ** to get the drive letter to look up the sector
31534
  ** to get the drive letter to look up the sector
29720
  ** size.
31535
  ** size.
29721
  */
31536
  */
31537
  SimulateIOErrorBenign(1);
29722
  rc = winFullPathname(pVfs, zRelative, MAX_PATH, zFullpath);
31538
  rc = winFullPathname(pVfs, zRelative, MAX_PATH, zFullpath);
31539
  SimulateIOErrorBenign(0);
29723
  if( rc == SQLITE_OK )
31540
  if( rc == SQLITE_OK )
29724
  {
31541
  {
29725
    void *zConverted = convertUtf8Filename(zFullpath);
31542
    void *zConverted = convertUtf8Filename(zFullpath);
 Lines 29867-29900   static int winSleep(sqlite3_vfs *pVfs, i Link Here 
29867
}
31684
}
29868
31685
29869
/*
31686
/*
29870
** The following variable, if set to a non-zero value, becomes the result
31687
** The following variable, if set to a non-zero value, is interpreted as
29871
** returned from sqlite3OsCurrentTime().  This is used for testing.
31688
** the number of seconds since 1970 and is used to set the result of
31689
** sqlite3OsCurrentTime() during testing.
29872
*/
31690
*/
29873
#ifdef SQLITE_TEST
31691
#ifdef SQLITE_TEST
29874
SQLITE_API int sqlite3_current_time = 0;
31692
SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
29875
#endif
31693
#endif
29876
31694
29877
/*
31695
/*
29878
** Find the current time (in Universal Coordinated Time).  Write the
31696
** Find the current time (in Universal Coordinated Time).  Write into *piNow
29879
** current time and date as a Julian Day number into *prNow and
31697
** the current time and date as a Julian Day number times 86_400_000.  In
29880
** return 0.  Return 1 if the time and date cannot be found.
31698
** other words, write into *piNow the number of milliseconds since the Julian
29881
*/
31699
** epoch of noon in Greenwich on November 24, 4714 B.C according to the
29882
int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
31700
** proleptic Gregorian calendar.
29883
  FILETIME ft;
31701
**
31702
** On success, return 0.  Return 1 if the time and date cannot be found.
31703
*/
31704
static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
29884
  /* FILETIME structure is a 64-bit value representing the number of 
31705
  /* FILETIME structure is a 64-bit value representing the number of 
29885
     100-nanosecond intervals since January 1, 1601 (= JD 2305813.5). 
31706
     100-nanosecond intervals since January 1, 1601 (= JD 2305813.5). 
29886
  */
31707
  */
29887
  sqlite3_int64 timeW;   /* Whole days */
31708
  FILETIME ft;
29888
  sqlite3_int64 timeF;   /* Fractional Days */
31709
  static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
29889
31710
#ifdef SQLITE_TEST
29890
  /* Number of 100-nanosecond intervals in a single day */
31711
  static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
29891
  static const sqlite3_int64 ntuPerDay = 
31712
#endif
29892
      10000000*(sqlite3_int64)86400;
29893
29894
  /* Number of 100-nanosecond intervals in half of a day */
29895
  static const sqlite3_int64 ntuPerHalfDay = 
29896
      10000000*(sqlite3_int64)43200;
29897
29898
  /* 2^32 - to avoid use of LL and warnings in gcc */
31713
  /* 2^32 - to avoid use of LL and warnings in gcc */
29899
  static const sqlite3_int64 max32BitValue = 
31714
  static const sqlite3_int64 max32BitValue = 
29900
      (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296;
31715
      (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296;
 Lines 29909-29932   int winCurrentTime(sqlite3_vfs *pVfs, do Link Here 
29909
#else
31724
#else
29910
  GetSystemTimeAsFileTime( &ft );
31725
  GetSystemTimeAsFileTime( &ft );
29911
#endif
31726
#endif
29912
  UNUSED_PARAMETER(pVfs);
31727
29913
  timeW = (((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) + (sqlite3_int64)ft.dwLowDateTime;
31728
  *piNow = winFiletimeEpoch +
29914
  timeF = timeW % ntuPerDay;          /* fractional days (100-nanoseconds) */
31729
            ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) + 
29915
  timeW = timeW / ntuPerDay;          /* whole days */
31730
               (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
29916
  timeW = timeW + 2305813;            /* add whole days (from 2305813.5) */
31731
29917
  timeF = timeF + ntuPerHalfDay;      /* add half a day (from 2305813.5) */
29918
  timeW = timeW + (timeF/ntuPerDay);  /* add whole day if half day made one */
29919
  timeF = timeF % ntuPerDay;          /* compute new fractional days */
29920
  *prNow = (double)timeW + ((double)timeF / (double)ntuPerDay);
29921
#ifdef SQLITE_TEST
31732
#ifdef SQLITE_TEST
29922
  if( sqlite3_current_time ){
31733
  if( sqlite3_current_time ){
29923
    *prNow = ((double)sqlite3_current_time + (double)43200) / (double)86400 + (double)2440587;
31734
    *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
29924
  }
31735
  }
29925
#endif
31736
#endif
31737
  UNUSED_PARAMETER(pVfs);
29926
  return 0;
31738
  return 0;
29927
}
31739
}
29928
31740
29929
/*
31741
/*
31742
** Find the current time (in Universal Coordinated Time).  Write the
31743
** current time and date as a Julian Day number into *prNow and
31744
** return 0.  Return 1 if the time and date cannot be found.
31745
*/
31746
int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
31747
  int rc;
31748
  sqlite3_int64 i;
31749
  rc = winCurrentTimeInt64(pVfs, &i);
31750
  if( !rc ){
31751
    *prNow = i/86400000.0;
31752
  }
31753
  return rc;
31754
}
31755
31756
/*
29930
** The idea is that this function works like a combination of
31757
** The idea is that this function works like a combination of
29931
** GetLastError() and FormatMessage() on windows (or errno and
31758
** GetLastError() and FormatMessage() on windows (or errno and
29932
** strerror_r() on unix). After an error is returned by an OS
31759
** strerror_r() on unix). After an error is returned by an OS
 Lines 29961-29990   static int winGetLastError(sqlite3_vfs * Link Here 
29961
  return getLastErrorMsg(nBuf, zBuf);
31788
  return getLastErrorMsg(nBuf, zBuf);
29962
}
31789
}
29963
31790
31791
31792
29964
/*
31793
/*
29965
** Initialize and deinitialize the operating system interface.
31794
** Initialize and deinitialize the operating system interface.
29966
*/
31795
*/
29967
SQLITE_API int sqlite3_os_init(void){
31796
SQLITE_API int sqlite3_os_init(void){
29968
  static sqlite3_vfs winVfs = {
31797
  static sqlite3_vfs winVfs = {
29969
    1,                 /* iVersion */
31798
    2,                   /* iVersion */
29970
    sizeof(winFile),   /* szOsFile */
31799
    sizeof(winFile),     /* szOsFile */
29971
    MAX_PATH,          /* mxPathname */
31800
    MAX_PATH,            /* mxPathname */
29972
    0,                 /* pNext */
31801
    0,                   /* pNext */
29973
    "win32",           /* zName */
31802
    "win32",             /* zName */
29974
    0,                 /* pAppData */
31803
    0,                   /* pAppData */
29975
 
31804
    winOpen,             /* xOpen */
29976
    winOpen,           /* xOpen */
31805
    winDelete,           /* xDelete */
29977
    winDelete,         /* xDelete */
31806
    winAccess,           /* xAccess */
29978
    winAccess,         /* xAccess */
31807
    winFullPathname,     /* xFullPathname */
29979
    winFullPathname,   /* xFullPathname */
31808
    winDlOpen,           /* xDlOpen */
29980
    winDlOpen,         /* xDlOpen */
31809
    winDlError,          /* xDlError */
29981
    winDlError,        /* xDlError */
31810
    winDlSym,            /* xDlSym */
29982
    winDlSym,          /* xDlSym */
31811
    winDlClose,          /* xDlClose */
29983
    winDlClose,        /* xDlClose */
31812
    winRandomness,       /* xRandomness */
29984
    winRandomness,     /* xRandomness */
31813
    winSleep,            /* xSleep */
29985
    winSleep,          /* xSleep */
31814
    winCurrentTime,      /* xCurrentTime */
29986
    winCurrentTime,    /* xCurrentTime */
31815
    winGetLastError,     /* xGetLastError */
29987
    winGetLastError    /* xGetLastError */
31816
    winCurrentTimeInt64, /* xCurrentTimeInt64 */
29988
  };
31817
  };
29989
31818
29990
  sqlite3_vfs_register(&winVfs, 1);
31819
  sqlite3_vfs_register(&winVfs, 1);
 Lines 30036-30042   SQLITE_API int sqlite3_os_end(void){ Link Here 
30036
*/
31865
*/
30037
31866
30038
/* Size of the Bitvec structure in bytes. */
31867
/* Size of the Bitvec structure in bytes. */
30039
#define BITVEC_SZ        (sizeof(void*)*128)  /* 512 on 32bit.  1024 on 64bit */
31868
#define BITVEC_SZ        512
30040
31869
30041
/* Round the union size down to the nearest pointer boundary, since that's how 
31870
/* Round the union size down to the nearest pointer boundary, since that's how 
30042
** it will be aligned within the Bitvec struct. */
31871
** it will be aligned within the Bitvec struct. */
 Lines 30669-30683   SQLITE_PRIVATE int sqlite3PcacheFetch( Link Here 
30669
32498
30670
  if( pPage ){
32499
  if( pPage ){
30671
    if( !pPage->pData ){
32500
    if( !pPage->pData ){
30672
      memset(pPage, 0, sizeof(PgHdr) + pCache->szExtra);
32501
      memset(pPage, 0, sizeof(PgHdr));
30673
      pPage->pExtra = (void*)&pPage[1];
32502
      pPage->pData = (void *)&pPage[1];
30674
      pPage->pData = (void *)&((char *)pPage)[sizeof(PgHdr) + pCache->szExtra];
32503
      pPage->pExtra = (void*)&((char *)pPage->pData)[pCache->szPage];
32504
      memset(pPage->pExtra, 0, pCache->szExtra);
30675
      pPage->pCache = pCache;
32505
      pPage->pCache = pCache;
30676
      pPage->pgno = pgno;
32506
      pPage->pgno = pgno;
30677
    }
32507
    }
30678
    assert( pPage->pCache==pCache );
32508
    assert( pPage->pCache==pCache );
30679
    assert( pPage->pgno==pgno );
32509
    assert( pPage->pgno==pgno );
30680
    assert( pPage->pExtra==(void *)&pPage[1] );
32510
    assert( pPage->pData==(void *)&pPage[1] );
32511
    assert( pPage->pExtra==(void *)&((char *)&pPage[1])[pCache->szPage] );
30681
32512
30682
    if( 0==pPage->nRef ){
32513
    if( 0==pPage->nRef ){
30683
      pCache->nRef++;
32514
      pCache->nRef++;
 Lines 30816-30822   SQLITE_PRIVATE void sqlite3PcacheTruncat Link Here 
30816
    PgHdr *pNext;
32647
    PgHdr *pNext;
30817
    for(p=pCache->pDirty; p; p=pNext){
32648
    for(p=pCache->pDirty; p; p=pNext){
30818
      pNext = p->pDirtyNext;
32649
      pNext = p->pDirtyNext;
30819
      if( p->pgno>pgno ){
32650
      /* This routine never gets call with a positive pgno except right
32651
      ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
32652
      ** it must be that pgno==0.
32653
      */
32654
      assert( p->pgno>0 );
32655
      if( ALWAYS(p->pgno>pgno) ){
30820
        assert( p->flags&PGHDR_DIRTY );
32656
        assert( p->flags&PGHDR_DIRTY );
30821
        sqlite3PcacheMakeClean(p);
32657
        sqlite3PcacheMakeClean(p);
30822
      }
32658
      }
 Lines 31139-31149   SQLITE_PRIVATE void sqlite3PCacheBufferS Link Here 
31139
static void *pcache1Alloc(int nByte){
32975
static void *pcache1Alloc(int nByte){
31140
  void *p;
32976
  void *p;
31141
  assert( sqlite3_mutex_held(pcache1.mutex) );
32977
  assert( sqlite3_mutex_held(pcache1.mutex) );
32978
  sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
31142
  if( nByte<=pcache1.szSlot && pcache1.pFree ){
32979
  if( nByte<=pcache1.szSlot && pcache1.pFree ){
31143
    assert( pcache1.isInit );
32980
    assert( pcache1.isInit );
31144
    p = (PgHdr1 *)pcache1.pFree;
32981
    p = (PgHdr1 *)pcache1.pFree;
31145
    pcache1.pFree = pcache1.pFree->pNext;
32982
    pcache1.pFree = pcache1.pFree->pNext;
31146
    sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
31147
    sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
32983
    sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
31148
  }else{
32984
  }else{
31149
32985
 Lines 31160-31165   static void *pcache1Alloc(int nByte){ Link Here 
31160
      int sz = sqlite3MallocSize(p);
32996
      int sz = sqlite3MallocSize(p);
31161
      sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
32997
      sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
31162
    }
32998
    }
32999
    sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
31163
  }
33000
  }
31164
  return p;
33001
  return p;
31165
}
33002
}
 Lines 31177-31183   static void pcache1Free(void *p){ Link Here 
31177
    pSlot->pNext = pcache1.pFree;
33014
    pSlot->pNext = pcache1.pFree;
31178
    pcache1.pFree = pSlot;
33015
    pcache1.pFree = pSlot;
31179
  }else{
33016
  }else{
31180
    int iSize = sqlite3MallocSize(p);
33017
    int iSize;
33018
    assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
33019
    sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
33020
    iSize = sqlite3MallocSize(p);
31181
    sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -iSize);
33021
    sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -iSize);
31182
    sqlite3_free(p);
33022
    sqlite3_free(p);
31183
  }
33023
  }
 Lines 31699-31705   static void pcache1Destroy(sqlite3_pcach Link Here 
31699
** already provided an alternative.
33539
** already provided an alternative.
31700
*/
33540
*/
31701
SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
33541
SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
31702
  static sqlite3_pcache_methods defaultMethods = {
33542
  static const sqlite3_pcache_methods defaultMethods = {
31703
    0,                       /* pArg */
33543
    0,                       /* pArg */
31704
    pcache1Init,             /* xInit */
33544
    pcache1Init,             /* xInit */
31705
    pcache1Shutdown,         /* xShutdown */
33545
    pcache1Shutdown,         /* xShutdown */
 Lines 32212-32217   SQLITE_PRIVATE int sqlite3RowSetTest(Row Link Here 
32212
** another is writing.
34052
** another is writing.
32213
*/
34053
*/
32214
#ifndef SQLITE_OMIT_DISKIO
34054
#ifndef SQLITE_OMIT_DISKIO
34055
/************** Include wal.h in the middle of pager.c ***********************/
34056
/************** Begin file wal.h *********************************************/
34057
/*
34058
** 2010 February 1
34059
**
34060
** The author disclaims copyright to this source code.  In place of
34061
** a legal notice, here is a blessing:
34062
**
34063
**    May you do good and not evil.
34064
**    May you find forgiveness for yourself and forgive others.
34065
**    May you share freely, never taking more than you give.
34066
**
34067
*************************************************************************
34068
** This header file defines the interface to the write-ahead logging 
34069
** system. Refer to the comments below and the header comment attached to 
34070
** the implementation of each function in log.c for further details.
34071
*/
34072
34073
#ifndef _WAL_H_
34074
#define _WAL_H_
34075
34076
34077
#ifdef SQLITE_OMIT_WAL
34078
# define sqlite3WalOpen(x,y,z)                 0
34079
# define sqlite3WalClose(w,x,y,z)              0
34080
# define sqlite3WalBeginReadTransaction(y,z)   0
34081
# define sqlite3WalEndReadTransaction(z)
34082
# define sqlite3WalRead(v,w,x,y,z)             0
34083
# define sqlite3WalDbsize(y)                   0
34084
# define sqlite3WalBeginWriteTransaction(y)    0
34085
# define sqlite3WalEndWriteTransaction(x)      0
34086
# define sqlite3WalUndo(x,y,z)                 0
34087
# define sqlite3WalSavepoint(y,z)
34088
# define sqlite3WalSavepointUndo(y,z)          0
34089
# define sqlite3WalFrames(u,v,w,x,y,z)         0
34090
# define sqlite3WalCheckpoint(u,v,w,x)         0
34091
# define sqlite3WalCallback(z)                 0
34092
# define sqlite3WalExclusiveMode(y,z)          0
34093
#else
34094
34095
#define WAL_SAVEPOINT_NDATA 4
34096
34097
/* Connection to a write-ahead log (WAL) file. 
34098
** There is one object of this type for each pager. 
34099
*/
34100
typedef struct Wal Wal;
34101
34102
/* Open and close a connection to a write-ahead log. */
34103
SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *zName, Wal**);
34104
SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
34105
34106
/* Used by readers to open (lock) and close (unlock) a snapshot.  A 
34107
** snapshot is like a read-transaction.  It is the state of the database
34108
** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and
34109
** preserves the current state even if the other threads or processes
34110
** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the
34111
** transaction and releases the lock.
34112
*/
34113
SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
34114
SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
34115
34116
/* Read a page from the write-ahead log, if it is present. */
34117
SQLITE_PRIVATE int sqlite3WalRead(Wal *pWal, Pgno pgno, int *pInWal, int nOut, u8 *pOut);
34118
34119
/* If the WAL is not empty, return the size of the database. */
34120
SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
34121
34122
/* Obtain or release the WRITER lock. */
34123
SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
34124
SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
34125
34126
/* Undo any frames written (but not committed) to the log */
34127
SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
34128
34129
/* Return an integer that records the current (uncommitted) write
34130
** position in the WAL */
34131
SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
34132
34133
/* Move the write position of the WAL back to iFrame.  Called in
34134
** response to a ROLLBACK TO command. */
34135
SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
34136
34137
/* Write a frame or frames to the log. */
34138
SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
34139
34140
/* Copy pages from the log to the database file */ 
34141
SQLITE_PRIVATE int sqlite3WalCheckpoint(
34142
  Wal *pWal,                      /* Write-ahead log connection */
34143
  int sync_flags,                 /* Flags to sync db file with (or 0) */
34144
  int nBuf,                       /* Size of buffer nBuf */
34145
  u8 *zBuf                        /* Temporary buffer to use */
34146
);
34147
34148
/* Return the value to pass to a sqlite3_wal_hook callback, the
34149
** number of frames in the WAL at the point of the last commit since
34150
** sqlite3WalCallback() was called.  If no commits have occurred since
34151
** the last call, then return 0.
34152
*/
34153
SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
34154
34155
/* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
34156
** by the pager layer on the database file.
34157
*/
34158
SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
34159
34160
#endif /* ifndef SQLITE_OMIT_WAL */
34161
#endif /* _WAL_H_ */
34162
34163
/************** End of wal.h *************************************************/
34164
/************** Continuing where we left off in pager.c **********************/
34165
34166
34167
/******************* NOTES ON THE DESIGN OF THE PAGER ************************
34168
**
34169
** This comment block describes invariants that hold when using a rollback
34170
** journal.  These invariants do not apply for journal_mode=WAL,
34171
** journal_mode=MEMORY, or journal_mode=OFF.
34172
**
34173
** Within this comment block, a page is deemed to have been synced
34174
** automatically as soon as it is written when PRAGMA synchronous=OFF.
34175
** Otherwise, the page is not synced until the xSync method of the VFS
34176
** is called successfully on the file containing the page.
34177
**
34178
** Definition:  A page of the database file is said to be "overwriteable" if
34179
** one or more of the following are true about the page:
34180
** 
34181
**     (a)  The original content of the page as it was at the beginning of
34182
**          the transaction has been written into the rollback journal and
34183
**          synced.
34184
** 
34185
**     (b)  The page was a freelist leaf page at the start of the transaction.
34186
** 
34187
**     (c)  The page number is greater than the largest page that existed in
34188
**          the database file at the start of the transaction.
34189
** 
34190
** (1) A page of the database file is never overwritten unless one of the
34191
**     following are true:
34192
** 
34193
**     (a) The page and all other pages on the same sector are overwriteable.
34194
** 
34195
**     (b) The atomic page write optimization is enabled, and the entire
34196
**         transaction other than the update of the transaction sequence
34197
**         number consists of a single page change.
34198
** 
34199
** (2) The content of a page written into the rollback journal exactly matches
34200
**     both the content in the database when the rollback journal was written
34201
**     and the content in the database at the beginning of the current
34202
**     transaction.
34203
** 
34204
** (3) Writes to the database file are an integer multiple of the page size
34205
**     in length and are aligned on a page boundary.
34206
** 
34207
** (4) Reads from the database file are either aligned on a page boundary and
34208
**     an integer multiple of the page size in length or are taken from the
34209
**     first 100 bytes of the database file.
34210
** 
34211
** (5) All writes to the database file are synced prior to the rollback journal
34212
**     being deleted, truncated, or zeroed.
34213
** 
34214
** (6) If a master journal file is used, then all writes to the database file
34215
**     are synced prior to the master journal being deleted.
34216
** 
34217
** Definition: Two databases (or the same database at two points it time)
34218
** are said to be "logically equivalent" if they give the same answer to
34219
** all queries.  Note in particular the the content of freelist leaf
34220
** pages can be changed arbitarily without effecting the logical equivalence
34221
** of the database.
34222
** 
34223
** (7) At any time, if any subset, including the empty set and the total set,
34224
**     of the unsynced changes to a rollback journal are removed and the 
34225
**     journal is rolled back, the resulting database file will be logical
34226
**     equivalent to the database file at the beginning of the transaction.
34227
** 
34228
** (8) When a transaction is rolled back, the xTruncate method of the VFS
34229
**     is called to restore the database file to the same size it was at
34230
**     the beginning of the transaction.  (In some VFSes, the xTruncate
34231
**     method is a no-op, but that does not change the fact the SQLite will
34232
**     invoke it.)
34233
** 
34234
** (9) Whenever the database file is modified, at least one bit in the range
34235
**     of bytes from 24 through 39 inclusive will be changed prior to releasing
34236
**     the EXCLUSIVE lock, thus signaling other connections on the same
34237
**     database to flush their caches.
34238
**
34239
** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
34240
**      than one billion transactions.
34241
**
34242
** (11) A database file is well-formed at the beginning and at the conclusion
34243
**      of every transaction.
34244
**
34245
** (12) An EXCLUSIVE lock is held on the database file when writing to
34246
**      the database file.
34247
**
34248
** (13) A SHARED lock is held on the database file while reading any
34249
**      content out of the database file.
34250
**
34251
******************************************************************************/
32215
34252
32216
/*
34253
/*
32217
** Macros for troubleshooting.  Normally turned off
34254
** Macros for troubleshooting.  Normally turned off
 Lines 32236-32293   int sqlite3PagerTrace=1; /* True to ena Link Here 
32236
#define FILEHANDLEID(fd) ((int)fd)
34273
#define FILEHANDLEID(fd) ((int)fd)
32237
34274
32238
/*
34275
/*
32239
** The page cache as a whole is always in one of the following
34276
** The Pager.eState variable stores the current 'state' of a pager. A
32240
** states:
34277
** pager may be in any one of the seven states shown in the following
32241
**
34278
** state diagram.
32242
**   PAGER_UNLOCK        The page cache is not currently reading or 
34279
**
32243
**                       writing the database file.  There is no
34280
**                            OPEN <------+------+
32244
**                       data held in memory.  This is the initial
34281
**                              |         |      |
32245
**                       state.
34282
**                              V         |      |
32246
**
34283
**               +---------> READER-------+      |
32247
**   PAGER_SHARED        The page cache is reading the database.
34284
**               |              |                |
32248
**                       Writing is not permitted.  There can be
34285
**               |              V                |
32249
**                       multiple readers accessing the same database
34286
**               |<-------WRITER_LOCKED------> ERROR
32250
**                       file at the same time.
34287
**               |              |                ^  
32251
**
34288
**               |              V                |
32252
**   PAGER_RESERVED      This process has reserved the database for writing
34289
**               |<------WRITER_CACHEMOD-------->|
32253
**                       but has not yet made any changes.  Only one process
34290
**               |              |                |
32254
**                       at a time can reserve the database.  The original
34291
**               |              V                |
32255
**                       database file has not been modified so other
34292
**               |<-------WRITER_DBMOD---------->|
32256
**                       processes may still be reading the on-disk
34293
**               |              |                |
32257
**                       database file.
34294
**               |              V                |
32258
**
34295
**               +<------WRITER_FINISHED-------->+
32259
**   PAGER_EXCLUSIVE     The page cache is writing the database.
34296
**
32260
**                       Access is exclusive.  No other processes or
34297
**
32261
**                       threads can be reading or writing while one
34298
** List of state transitions and the C [function] that performs each:
32262
**                       process is writing.
34299
** 
32263
**
34300
**   OPEN              -> READER              [sqlite3PagerSharedLock]
32264
**   PAGER_SYNCED        The pager moves to this state from PAGER_EXCLUSIVE
34301
**   READER            -> OPEN                [pager_unlock]
32265
**                       after all dirty pages have been written to the
34302
**
32266
**                       database file and the file has been synced to
34303
**   READER            -> WRITER_LOCKED       [sqlite3PagerBegin]
32267
**                       disk. All that remains to do is to remove or
34304
**   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]
32268
**                       truncate the journal file and the transaction 
34305
**   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]
32269
**                       will be committed.
34306
**   WRITER_DBMOD      -> WRITER_FINISHED     [sqlite3PagerCommitPhaseOne]
32270
**
34307
**   WRITER_***        -> READER              [pager_end_transaction]
32271
** The page cache comes up in PAGER_UNLOCK.  The first time a
34308
**
32272
** sqlite3PagerGet() occurs, the state transitions to PAGER_SHARED.
34309
**   WRITER_***        -> ERROR               [pager_error]
32273
** After all pages have been released using sqlite_page_unref(),
34310
**   ERROR             -> OPEN                [pager_unlock]
32274
** the state transitions back to PAGER_UNLOCK.  The first time
34311
** 
32275
** that sqlite3PagerWrite() is called, the state transitions to
34312
**
32276
** PAGER_RESERVED.  (Note that sqlite3PagerWrite() can only be
34313
**  OPEN:
32277
** called on an outstanding page which means that the pager must
34314
**
32278
** be in PAGER_SHARED before it transitions to PAGER_RESERVED.)
34315
**    The pager starts up in this state. Nothing is guaranteed in this
32279
** PAGER_RESERVED means that there is an open rollback journal.
34316
**    state - the file may or may not be locked and the database size is
32280
** The transition to PAGER_EXCLUSIVE occurs before any changes
34317
**    unknown. The database may not be read or written.
32281
** are made to the database file, though writes to the rollback
34318
**
32282
** journal occurs with just PAGER_RESERVED.  After an sqlite3PagerRollback()
34319
**    * No read or write transaction is active.
32283
** or sqlite3PagerCommitPhaseTwo(), the state can go back to PAGER_SHARED,
34320
**    * Any lock, or no lock at all, may be held on the database file.
32284
** or it can stay at PAGER_EXCLUSIVE if we are in exclusive access mode.
34321
**    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
32285
*/
34322
**
32286
#define PAGER_UNLOCK      0
34323
**  READER:
32287
#define PAGER_SHARED      1   /* same as SHARED_LOCK */
34324
**
32288
#define PAGER_RESERVED    2   /* same as RESERVED_LOCK */
34325
**    In this state all the requirements for reading the database in 
32289
#define PAGER_EXCLUSIVE   4   /* same as EXCLUSIVE_LOCK */
34326
**    rollback (non-WAL) mode are met. Unless the pager is (or recently
32290
#define PAGER_SYNCED      5
34327
**    was) in exclusive-locking mode, a user-level read transaction is 
34328
**    open. The database size is known in this state.
34329
**
34330
**    A connection running with locking_mode=normal enters this state when
34331
**    it opens a read-transaction on the database and returns to state
34332
**    OPEN after the read-transaction is completed. However a connection
34333
**    running in locking_mode=exclusive (including temp databases) remains in
34334
**    this state even after the read-transaction is closed. The only way
34335
**    a locking_mode=exclusive connection can transition from READER to OPEN
34336
**    is via the ERROR state (see below).
34337
** 
34338
**    * A read transaction may be active (but a write-transaction cannot).
34339
**    * A SHARED or greater lock is held on the database file.
34340
**    * The dbSize variable may be trusted (even if a user-level read 
34341
**      transaction is not active). The dbOrigSize and dbFileSize variables
34342
**      may not be trusted at this point.
34343
**    * If the database is a WAL database, then the WAL connection is open.
34344
**    * Even if a read-transaction is not open, it is guaranteed that 
34345
**      there is no hot-journal in the file-system.
34346
**
34347
**  WRITER_LOCKED:
34348
**
34349
**    The pager moves to this state from READER when a write-transaction
34350
**    is first opened on the database. In WRITER_LOCKED state, all locks 
34351
**    required to start a write-transaction are held, but no actual 
34352
**    modifications to the cache or database have taken place.
34353
**
34354
**    In rollback mode, a RESERVED or (if the transaction was opened with 
34355
**    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
34356
**    moving to this state, but the journal file is not written to or opened 
34357
**    to in this state. If the transaction is committed or rolled back while 
34358
**    in WRITER_LOCKED state, all that is required is to unlock the database 
34359
**    file.
34360
**
34361
**    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
34362
**    If the connection is running with locking_mode=exclusive, an attempt
34363
**    is made to obtain an EXCLUSIVE lock on the database file.
34364
**
34365
**    * A write transaction is active.
34366
**    * If the connection is open in rollback-mode, a RESERVED or greater 
34367
**      lock is held on the database file.
34368
**    * If the connection is open in WAL-mode, a WAL write transaction
34369
**      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
34370
**      called).
34371
**    * The dbSize, dbOrigSize and dbFileSize variables are all valid.
34372
**    * The contents of the pager cache have not been modified.
34373
**    * The journal file may or may not be open.
34374
**    * Nothing (not even the first header) has been written to the journal.
34375
**
34376
**  WRITER_CACHEMOD:
34377
**
34378
**    A pager moves from WRITER_LOCKED state to this state when a page is
34379
**    first modified by the upper layer. In rollback mode the journal file
34380
**    is opened (if it is not already open) and a header written to the
34381
**    start of it. The database file on disk has not been modified.
34382
**
34383
**    * A write transaction is active.
34384
**    * A RESERVED or greater lock is held on the database file.
34385
**    * The journal file is open and the first header has been written 
34386
**      to it, but the header has not been synced to disk.
34387
**    * The contents of the page cache have been modified.
34388
**
34389
**  WRITER_DBMOD:
34390
**
34391
**    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
34392
**    when it modifies the contents of the database file. WAL connections
34393
**    never enter this state (since they do not modify the database file,
34394
**    just the log file).
34395
**
34396
**    * A write transaction is active.
34397
**    * An EXCLUSIVE or greater lock is held on the database file.
34398
**    * The journal file is open and the first header has been written 
34399
**      and synced to disk.
34400
**    * The contents of the page cache have been modified (and possibly
34401
**      written to disk).
34402
**
34403
**  WRITER_FINISHED:
34404
**
34405
**    It is not possible for a WAL connection to enter this state.
34406
**
34407
**    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
34408
**    state after the entire transaction has been successfully written into the
34409
**    database file. In this state the transaction may be committed simply
34410
**    by finalizing the journal file. Once in WRITER_FINISHED state, it is 
34411
**    not possible to modify the database further. At this point, the upper 
34412
**    layer must either commit or rollback the transaction.
34413
**
34414
**    * A write transaction is active.
34415
**    * An EXCLUSIVE or greater lock is held on the database file.
34416
**    * All writing and syncing of journal and database data has finished.
34417
**      If no error occured, all that remains is to finalize the journal to
34418
**      commit the transaction. If an error did occur, the caller will need
34419
**      to rollback the transaction. 
34420
**
34421
**  ERROR:
34422
**
34423
**    The ERROR state is entered when an IO or disk-full error (including
34424
**    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it 
34425
**    difficult to be sure that the in-memory pager state (cache contents, 
34426
**    db size etc.) are consistent with the contents of the file-system.
34427
**
34428
**    Temporary pager files may enter the ERROR state, but in-memory pagers
34429
**    cannot.
34430
**
34431
**    For example, if an IO error occurs while performing a rollback, 
34432
**    the contents of the page-cache may be left in an inconsistent state.
34433
**    At this point it would be dangerous to change back to READER state
34434
**    (as usually happens after a rollback). Any subsequent readers might
34435
**    report database corruption (due to the inconsistent cache), and if
34436
**    they upgrade to writers, they may inadvertently corrupt the database
34437
**    file. To avoid this hazard, the pager switches into the ERROR state
34438
**    instead of READER following such an error.
34439
**
34440
**    Once it has entered the ERROR state, any attempt to use the pager
34441
**    to read or write data returns an error. Eventually, once all 
34442
**    outstanding transactions have been abandoned, the pager is able to
34443
**    transition back to OPEN state, discarding the contents of the 
34444
**    page-cache and any other in-memory state at the same time. Everything
34445
**    is reloaded from disk (and, if necessary, hot-journal rollback peformed)
34446
**    when a read-transaction is next opened on the pager (transitioning
34447
**    the pager into READER state). At that point the system has recovered 
34448
**    from the error.
34449
**
34450
**    Specifically, the pager jumps into the ERROR state if:
34451
**
34452
**      1. An error occurs while attempting a rollback. This happens in
34453
**         function sqlite3PagerRollback().
34454
**
34455
**      2. An error occurs while attempting to finalize a journal file
34456
**         following a commit in function sqlite3PagerCommitPhaseTwo().
34457
**
34458
**      3. An error occurs while attempting to write to the journal or
34459
**         database file in function pagerStress() in order to free up
34460
**         memory.
34461
**
34462
**    In other cases, the error is returned to the b-tree layer. The b-tree
34463
**    layer then attempts a rollback operation. If the error condition 
34464
**    persists, the pager enters the ERROR state via condition (1) above.
34465
**
34466
**    Condition (3) is necessary because it can be triggered by a read-only
34467
**    statement executed within a transaction. In this case, if the error
34468
**    code were simply returned to the user, the b-tree layer would not
34469
**    automatically attempt a rollback, as it assumes that an error in a
34470
**    read-only statement cannot leave the pager in an internally inconsistent 
34471
**    state.
34472
**
34473
**    * The Pager.errCode variable is set to something other than SQLITE_OK.
34474
**    * There are one or more outstanding references to pages (after the
34475
**      last reference is dropped the pager should move back to OPEN state).
34476
**    * The pager is not an in-memory pager.
34477
**    
34478
**
34479
** Notes:
34480
**
34481
**   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
34482
**     connection is open in WAL mode. A WAL connection is always in one
34483
**     of the first four states.
34484
**
34485
**   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
34486
**     state. There are two exceptions: immediately after exclusive-mode has
34487
**     been turned on (and before any read or write transactions are 
34488
**     executed), and when the pager is leaving the "error state".
34489
**
34490
**   * See also: assert_pager_state().
34491
*/
34492
#define PAGER_OPEN                  0
34493
#define PAGER_READER                1
34494
#define PAGER_WRITER_LOCKED         2
34495
#define PAGER_WRITER_CACHEMOD       3
34496
#define PAGER_WRITER_DBMOD          4
34497
#define PAGER_WRITER_FINISHED       5
34498
#define PAGER_ERROR                 6
34499
34500
/*
34501
** The Pager.eLock variable is almost always set to one of the 
34502
** following locking-states, according to the lock currently held on
34503
** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
34504
** This variable is kept up to date as locks are taken and released by
34505
** the pagerLockDb() and pagerUnlockDb() wrappers.
34506
**
34507
** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
34508
** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
34509
** the operation was successful. In these circumstances pagerLockDb() and
34510
** pagerUnlockDb() take a conservative approach - eLock is always updated
34511
** when unlocking the file, and only updated when locking the file if the
34512
** VFS call is successful. This way, the Pager.eLock variable may be set
34513
** to a less exclusive (lower) value than the lock that is actually held
34514
** at the system level, but it is never set to a more exclusive value.
34515
**
34516
** This is usually safe. If an xUnlock fails or appears to fail, there may 
34517
** be a few redundant xLock() calls or a lock may be held for longer than
34518
** required, but nothing really goes wrong.
34519
**
34520
** The exception is when the database file is unlocked as the pager moves
34521
** from ERROR to OPEN state. At this point there may be a hot-journal file 
34522
** in the file-system that needs to be rolled back (as part of a OPEN->SHARED
34523
** transition, by the same pager or any other). If the call to xUnlock()
34524
** fails at this point and the pager is left holding an EXCLUSIVE lock, this
34525
** can confuse the call to xCheckReservedLock() call made later as part
34526
** of hot-journal detection.
34527
**
34528
** xCheckReservedLock() is defined as returning true "if there is a RESERVED 
34529
** lock held by this process or any others". So xCheckReservedLock may 
34530
** return true because the caller itself is holding an EXCLUSIVE lock (but
34531
** doesn't know it because of a previous error in xUnlock). If this happens
34532
** a hot-journal may be mistaken for a journal being created by an active
34533
** transaction in another process, causing SQLite to read from the database
34534
** without rolling it back.
34535
**
34536
** To work around this, if a call to xUnlock() fails when unlocking the
34537
** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
34538
** is only changed back to a real locking state after a successful call
34539
** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
34540
** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK 
34541
** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
34542
** lock on the database file before attempting to roll it back. See function
34543
** PagerSharedLock() for more detail.
34544
**
34545
** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in 
34546
** PAGER_OPEN state.
34547
*/
34548
#define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
32291
34549
32292
/*
34550
/*
32293
** A macro used for invoking the codec if there is one
34551
** A macro used for invoking the codec if there is one
 Lines 32331-32366   struct PagerSavepoint { Link Here 
32331
  Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
34589
  Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
32332
  Pgno nOrig;                  /* Original number of pages in file */
34590
  Pgno nOrig;                  /* Original number of pages in file */
32333
  Pgno iSubRec;                /* Index of first record in sub-journal */
34591
  Pgno iSubRec;                /* Index of first record in sub-journal */
32334
};
34592
#ifndef SQLITE_OMIT_WAL
32335
34593
  u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
32336
/*
34594
#endif
32337
** A open page cache is an instance of the following structure.
34595
};
32338
**
34596
32339
** errCode
34597
/*
32340
**
34598
** A open page cache is an instance of struct Pager. A description of
32341
**   Pager.errCode may be set to SQLITE_IOERR, SQLITE_CORRUPT, or
34599
** some of the more important member variables follows:
32342
**   or SQLITE_FULL. Once one of the first three errors occurs, it persists
34600
**
32343
**   and is returned as the result of every major pager API call.  The
34601
** eState
32344
**   SQLITE_FULL return code is slightly different. It persists only until the
34602
**
32345
**   next successful rollback is performed on the pager cache. Also,
34603
**   The current 'state' of the pager object. See the comment and state
32346
**   SQLITE_FULL does not affect the sqlite3PagerGet() and sqlite3PagerLookup()
34604
**   diagram above for a description of the pager state.
32347
**   APIs, they may still be used successfully.
34605
**
32348
**
34606
** eLock
32349
** dbSizeValid, dbSize, dbOrigSize, dbFileSize
34607
**
32350
**
34608
**   For a real on-disk database, the current lock held on the database file -
32351
**   Managing the size of the database file in pages is a little complicated.
34609
**   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
32352
**   The variable Pager.dbSize contains the number of pages that the database
34610
**
32353
**   image currently contains. As the database image grows or shrinks this
34611
**   For a temporary or in-memory database (neither of which require any
32354
**   variable is updated. The variable Pager.dbFileSize contains the number
34612
**   locks), this variable is always set to EXCLUSIVE_LOCK. Since such
32355
**   of pages in the database file. This may be different from Pager.dbSize
34613
**   databases always have Pager.exclusiveMode==1, this tricks the pager
32356
**   if some pages have been appended to the database image but not yet written
34614
**   logic into thinking that it already has all the locks it will ever
32357
**   out from the cache to the actual file on disk. Or if the image has been
34615
**   need (and no reason to release them).
32358
**   truncated by an incremental-vacuum operation. The Pager.dbOrigSize variable
34616
**
32359
**   contains the number of pages in the database image when the current
34617
**   In some (obscure) circumstances, this variable may also be set to
32360
**   transaction was opened. The contents of all three of these variables is
34618
**   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
32361
**   only guaranteed to be correct if the boolean Pager.dbSizeValid is true.
34619
**   details.
32362
**
32363
**   TODO: Under what conditions is dbSizeValid set? Cleared?
32364
**
34620
**
32365
** changeCountDone
34621
** changeCountDone
32366
**
34622
**
 Lines 32379-32438   struct PagerSavepoint { Link Here 
32379
**   need only update the change-counter once, for the first transaction
34635
**   need only update the change-counter once, for the first transaction
32380
**   committed.
34636
**   committed.
32381
**
34637
**
32382
** dbModified
32383
**
32384
**   The dbModified flag is set whenever a database page is dirtied.
32385
**   It is cleared at the end of each transaction.
32386
**
32387
**   It is used when committing or otherwise ending a transaction. If
32388
**   the dbModified flag is clear then less work has to be done.
32389
**
32390
** journalStarted
32391
**
32392
**   This flag is set whenever the the main journal is synced. 
32393
**
32394
**   The point of this flag is that it must be set after the 
32395
**   first journal header in a journal file has been synced to disk.
32396
**   After this has happened, new pages appended to the database 
32397
**   do not need the PGHDR_NEED_SYNC flag set, as they do not need
32398
**   to wait for a journal sync before they can be written out to
32399
**   the database file (see function pager_write()).
32400
**   
32401
** setMaster
34638
** setMaster
32402
**
34639
**
32403
**   This variable is used to ensure that the master journal file name
34640
**   When PagerCommitPhaseOne() is called to commit a transaction, it may
32404
**   (if any) is only written into the journal file once.
34641
**   (or may not) specify a master-journal name to be written into the 
32405
**
34642
**   journal file before it is synced to disk.
32406
**   When committing a transaction, the master journal file name (if any)
34643
**
32407
**   may be written into the journal file while the pager is still in
34644
**   Whether or not a journal file contains a master-journal pointer affects 
32408
**   PAGER_RESERVED state (see CommitPhaseOne() for the action). It
34645
**   the way in which the journal file is finalized after the transaction is 
32409
**   then attempts to upgrade to an exclusive lock. If this attempt
34646
**   committed or rolled back when running in "journal_mode=PERSIST" mode.
32410
**   fails, then SQLITE_BUSY may be returned to the user and the user
34647
**   If a journal file does not contain a master-journal pointer, it is
32411
**   may attempt to commit the transaction again later (calling
34648
**   finalized by overwriting the first journal header with zeroes. If
32412
**   CommitPhaseOne() again). This flag is used to ensure that the 
34649
**   it does contain a master-journal pointer the journal file is finalized 
32413
**   master journal name is only written to the journal file the first
34650
**   by truncating it to zero bytes, just as if the connection were 
32414
**   time CommitPhaseOne() is called.
34651
**   running in "journal_mode=truncate" mode.
32415
**
34652
**
32416
** doNotSync
34653
**   Journal files that contain master journal pointers cannot be finalized
32417
**
34654
**   simply by overwriting the first journal-header with zeroes, as the
32418
**   This variable is set and cleared by sqlite3PagerWrite().
34655
**   master journal pointer could interfere with hot-journal rollback of any
32419
**
34656
**   subsequently interrupted transaction that reuses the journal file.
32420
** needSync
34657
**
32421
**
34658
**   The flag is cleared as soon as the journal file is finalized (either
32422
**   TODO: It might be easier to set this variable in writeJournalHdr()
34659
**   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
32423
**   and writeMasterJournal() only. Change its meaning to "unsynced data
34660
**   journal file from being successfully finalized, the setMaster flag
32424
**   has been written to the journal".
34661
**   is cleared anyway (and the pager will move to ERROR state).
34662
**
34663
** doNotSpill, doNotSyncSpill
34664
**
34665
**   These two boolean variables control the behaviour of cache-spills
34666
**   (calls made by the pcache module to the pagerStress() routine to
34667
**   write cached data to the file-system in order to free up memory).
34668
**
34669
**   When doNotSpill is non-zero, writing to the database from pagerStress()
34670
**   is disabled altogether. This is done in a very obscure case that
34671
**   comes up during savepoint rollback that requires the pcache module
34672
**   to allocate a new page to prevent the journal file from being written
34673
**   while it is being traversed by code in pager_playback().
34674
** 
34675
**   If doNotSyncSpill is non-zero, writing to the database from pagerStress()
34676
**   is permitted, but syncing the journal file is not. This flag is set
34677
**   by sqlite3PagerWrite() when the file-system sector-size is larger than
34678
**   the database page-size in order to prevent a journal sync from happening 
34679
**   in between the journalling of two pages on the same sector. 
32425
**
34680
**
32426
** subjInMemory
34681
** subjInMemory
32427
**
34682
**
32428
**   This is a boolean variable. If true, then any required sub-journal
34683
**   This is a boolean variable. If true, then any required sub-journal
32429
**   is opened as an in-memory journal file. If false, then in-memory
34684
**   is opened as an in-memory journal file. If false, then in-memory
32430
**   sub-journals are only used for in-memory pager files.
34685
**   sub-journals are only used for in-memory pager files.
34686
**
34687
**   This variable is updated by the upper layer each time a new 
34688
**   write-transaction is opened.
34689
**
34690
** dbSize, dbOrigSize, dbFileSize
34691
**
34692
**   Variable dbSize is set to the number of pages in the database file.
34693
**   It is valid in PAGER_READER and higher states (all states except for
34694
**   OPEN and ERROR). 
34695
**
34696
**   dbSize is set based on the size of the database file, which may be 
34697
**   larger than the size of the database (the value stored at offset
34698
**   28 of the database header by the btree). If the size of the file
34699
**   is not an integer multiple of the page-size, the value stored in
34700
**   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
34701
**   Except, any file that is greater than 0 bytes in size is considered
34702
**   to have at least one page. (i.e. a 1KB file with 2K page-size leads
34703
**   to dbSize==1).
34704
**
34705
**   During a write-transaction, if pages with page-numbers greater than
34706
**   dbSize are modified in the cache, dbSize is updated accordingly.
34707
**   Similarly, if the database is truncated using PagerTruncateImage(), 
34708
**   dbSize is updated.
34709
**
34710
**   Variables dbOrigSize and dbFileSize are valid in states 
34711
**   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
34712
**   variable at the start of the transaction. It is used during rollback,
34713
**   and to determine whether or not pages need to be journalled before
34714
**   being modified.
34715
**
34716
**   Throughout a write-transaction, dbFileSize contains the size of
34717
**   the file on disk in pages. It is set to a copy of dbSize when the
34718
**   write-transaction is first opened, and updated when VFS calls are made
34719
**   to write or truncate the database file on disk. 
34720
**
34721
**   The only reason the dbFileSize variable is required is to suppress 
34722
**   unnecessary calls to xTruncate() after committing a transaction. If, 
34723
**   when a transaction is committed, the dbFileSize variable indicates 
34724
**   that the database file is larger than the database image (Pager.dbSize), 
34725
**   pager_truncate() is called. The pager_truncate() call uses xFilesize()
34726
**   to measure the database file on disk, and then truncates it if required.
34727
**   dbFileSize is not used when rolling back a transaction. In this case
34728
**   pager_truncate() is called unconditionally (which means there may be
34729
**   a call to xFilesize() that is not strictly required). In either case,
34730
**   pager_truncate() may cause the file to become smaller or larger.
34731
**
34732
** dbHintSize
34733
**
34734
**   The dbHintSize variable is used to limit the number of calls made to
34735
**   the VFS xFileControl(FCNTL_SIZE_HINT) method. 
34736
**
34737
**   dbHintSize is set to a copy of the dbSize variable when a
34738
**   write-transaction is opened (at the same time as dbFileSize and
34739
**   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
34740
**   dbHintSize is increased to the number of pages that correspond to the
34741
**   size-hint passed to the method call. See pager_write_pagelist() for 
34742
**   details.
34743
**
34744
** errCode
34745
**
34746
**   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
34747
**   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode 
34748
**   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX 
34749
**   sub-codes.
32431
*/
34750
*/
32432
struct Pager {
34751
struct Pager {
32433
  sqlite3_vfs *pVfs;          /* OS functions to use for IO */
34752
  sqlite3_vfs *pVfs;          /* OS functions to use for IO */
32434
  u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
34753
  u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
32435
  u8 journalMode;             /* On of the PAGER_JOURNALMODE_* values */
34754
  u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
32436
  u8 useJournal;              /* Use a rollback journal on this file */
34755
  u8 useJournal;              /* Use a rollback journal on this file */
32437
  u8 noReadlock;              /* Do not bother to obtain readlocks */
34756
  u8 noReadlock;              /* Do not bother to obtain readlocks */
32438
  u8 noSync;                  /* Do not sync the journal if true */
34757
  u8 noSync;                  /* Do not sync the journal if true */
 Lines 32442-32470   struct Pager { Link Here 
32442
  u8 readOnly;                /* True for a read-only database */
34761
  u8 readOnly;                /* True for a read-only database */
32443
  u8 memDb;                   /* True to inhibit all file I/O */
34762
  u8 memDb;                   /* True to inhibit all file I/O */
32444
34763
32445
  /* The following block contains those class members that are dynamically
34764
  /**************************************************************************
32446
  ** modified during normal operations. The other variables in this structure
34765
  ** The following block contains those class members that change during
32447
  ** are either constant throughout the lifetime of the pager, or else
34766
  ** routine opertion.  Class members not in this block are either fixed
32448
  ** used to store configuration parameters that affect the way the pager 
34767
  ** when the pager is first created or else only change when there is a
32449
  ** operates.
34768
  ** significant mode change (such as changing the page_size, locking_mode,
32450
  **
34769
  ** or the journal_mode).  From another view, these class members describe
32451
  ** The 'state' variable is described in more detail along with the
34770
  ** the "state" of the pager, while other class members describe the
32452
  ** descriptions of the values it may take - PAGER_UNLOCK etc. Many of the
34771
  ** "configuration" of the pager.
32453
  ** other variables in this block are described in the comment directly 
34772
  */
32454
  ** above this class definition.
34773
  u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
32455
  */
34774
  u8 eLock;                   /* Current lock held on database file */
32456
  u8 state;                   /* PAGER_UNLOCK, _SHARED, _RESERVED, etc. */
32457
  u8 dbModified;              /* True if there are any changes to the Db */
32458
  u8 needSync;                /* True if an fsync() is needed on the journal */
32459
  u8 journalStarted;          /* True if header of journal is synced */
32460
  u8 changeCountDone;         /* Set after incrementing the change-counter */
34775
  u8 changeCountDone;         /* Set after incrementing the change-counter */
32461
  u8 setMaster;               /* True if a m-j name has been written to jrnl */
34776
  u8 setMaster;               /* True if a m-j name has been written to jrnl */
32462
  u8 doNotSync;               /* Boolean. While true, do not spill the cache */
34777
  u8 doNotSpill;              /* Do not spill the cache when non-zero */
32463
  u8 dbSizeValid;             /* Set when dbSize is correct */
34778
  u8 doNotSyncSpill;          /* Do not do a spill that requires jrnl sync */
32464
  u8 subjInMemory;            /* True to use in-memory sub-journals */
34779
  u8 subjInMemory;            /* True to use in-memory sub-journals */
32465
  Pgno dbSize;                /* Number of pages in the database */
34780
  Pgno dbSize;                /* Number of pages in the database */
32466
  Pgno dbOrigSize;            /* dbSize before the current transaction */
34781
  Pgno dbOrigSize;            /* dbSize before the current transaction */
32467
  Pgno dbFileSize;            /* Number of pages in the database file */
34782
  Pgno dbFileSize;            /* Number of pages in the database file */
34783
  Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */
32468
  int errCode;                /* One of several kinds of errors */
34784
  int errCode;                /* One of several kinds of errors */
32469
  int nRec;                   /* Pages journalled since last j-header written */
34785
  int nRec;                   /* Pages journalled since last j-header written */
32470
  u32 cksumInit;              /* Quasi-random value added to every checksum */
34786
  u32 cksumInit;              /* Quasi-random value added to every checksum */
 Lines 32475-32490   struct Pager { Link Here 
32475
  sqlite3_file *sjfd;         /* File descriptor for sub-journal */
34791
  sqlite3_file *sjfd;         /* File descriptor for sub-journal */
32476
  i64 journalOff;             /* Current write offset in the journal file */
34792
  i64 journalOff;             /* Current write offset in the journal file */
32477
  i64 journalHdr;             /* Byte offset to previous journal header */
34793
  i64 journalHdr;             /* Byte offset to previous journal header */
34794
  sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
32478
  PagerSavepoint *aSavepoint; /* Array of active savepoints */
34795
  PagerSavepoint *aSavepoint; /* Array of active savepoints */
32479
  int nSavepoint;             /* Number of elements in aSavepoint[] */
34796
  int nSavepoint;             /* Number of elements in aSavepoint[] */
32480
  char dbFileVers[16];        /* Changes whenever database file changes */
34797
  char dbFileVers[16];        /* Changes whenever database file changes */
32481
  u32 sectorSize;             /* Assumed sector size during rollback */
34798
  /*
34799
  ** End of the routinely-changing class members
34800
  ***************************************************************************/
32482
34801
32483
  u16 nExtra;                 /* Add this many bytes to each in-memory page */
34802
  u16 nExtra;                 /* Add this many bytes to each in-memory page */
32484
  i16 nReserve;               /* Number of unused bytes at end of each page */
34803
  i16 nReserve;               /* Number of unused bytes at end of each page */
32485
  u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
34804
  u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
34805
  u32 sectorSize;             /* Assumed sector size during rollback */
32486
  int pageSize;               /* Number of bytes in a page */
34806
  int pageSize;               /* Number of bytes in a page */
32487
  Pgno mxPgno;                /* Maximum allowed size of the database */
34807
  Pgno mxPgno;                /* Maximum allowed size of the database */
34808
  i64 journalSizeLimit;       /* Size limit for persistent journal files */
32488
  char *zFilename;            /* Name of the database file */
34809
  char *zFilename;            /* Name of the database file */
32489
  char *zJournal;             /* Name of the journal file */
34810
  char *zJournal;             /* Name of the journal file */
32490
  int (*xBusyHandler)(void*); /* Function to call when busy */
34811
  int (*xBusyHandler)(void*); /* Function to call when busy */
 Lines 32501-32509   struct Pager { Link Here 
32501
  void *pCodec;               /* First argument to xCodec... methods */
34822
  void *pCodec;               /* First argument to xCodec... methods */
32502
#endif
34823
#endif
32503
  char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
34824
  char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
32504
  i64 journalSizeLimit;       /* Size limit for persistent journal files */
32505
  PCache *pPCache;            /* Pointer to page cache object */
34825
  PCache *pPCache;            /* Pointer to page cache object */
32506
  sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
34826
#ifndef SQLITE_OMIT_WAL
34827
  Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
34828
  char *zWal;                 /* File name for write-ahead log */
34829
#endif
32507
};
34830
};
32508
34831
32509
/*
34832
/*
 Lines 32578-32599   static const unsigned char aJournalMagic Link Here 
32578
*/
34901
*/
32579
#define PAGER_MAX_PGNO 2147483647
34902
#define PAGER_MAX_PGNO 2147483647
32580
34903
34904
/*
34905
** The argument to this macro is a file descriptor (type sqlite3_file*).
34906
** Return 0 if it is not open, or non-zero (but not 1) if it is.
34907
**
34908
** This is so that expressions can be written as:
34909
**
34910
**   if( isOpen(pPager->jfd) ){ ...
34911
**
34912
** instead of
34913
**
34914
**   if( pPager->jfd->pMethods ){ ...
34915
*/
34916
#define isOpen(pFd) ((pFd)->pMethods)
34917
34918
/*
34919
** Return true if this pager uses a write-ahead log instead of the usual
34920
** rollback journal. Otherwise false.
34921
*/
34922
#ifndef SQLITE_OMIT_WAL
34923
static int pagerUseWal(Pager *pPager){
34924
  return (pPager->pWal!=0);
34925
}
34926
#else
34927
# define pagerUseWal(x) 0
34928
# define pagerRollbackWal(x) 0
34929
# define pagerWalFrames(v,w,x,y,z) 0
34930
# define pagerOpenWalIfPresent(z) SQLITE_OK
34931
# define pagerBeginReadTransaction(z) SQLITE_OK
34932
#endif
34933
32581
#ifndef NDEBUG 
34934
#ifndef NDEBUG 
32582
/*
34935
/*
32583
** Usage:
34936
** Usage:
32584
**
34937
**
32585
**   assert( assert_pager_state(pPager) );
34938
**   assert( assert_pager_state(pPager) );
32586
*/
34939
**
32587
static int assert_pager_state(Pager *pPager){
34940
** This function runs many asserts to try to find inconsistencies in
32588
34941
** the internal state of the Pager object.
32589
  /* A temp-file is always in PAGER_EXCLUSIVE or PAGER_SYNCED state. */
34942
*/
32590
  assert( pPager->tempFile==0 || pPager->state>=PAGER_EXCLUSIVE );
34943
static int assert_pager_state(Pager *p){
32591
34944
  Pager *pPager = p;
32592
  /* The changeCountDone flag is always set for temp-files */
34945
32593
  assert( pPager->tempFile==0 || pPager->changeCountDone );
34946
  /* State must be valid. */
34947
  assert( p->eState==PAGER_OPEN
34948
       || p->eState==PAGER_READER
34949
       || p->eState==PAGER_WRITER_LOCKED
34950
       || p->eState==PAGER_WRITER_CACHEMOD
34951
       || p->eState==PAGER_WRITER_DBMOD
34952
       || p->eState==PAGER_WRITER_FINISHED
34953
       || p->eState==PAGER_ERROR
34954
  );
34955
34956
  /* Regardless of the current state, a temp-file connection always behaves
34957
  ** as if it has an exclusive lock on the database file. It never updates
34958
  ** the change-counter field, so the changeCountDone flag is always set.
34959
  */
34960
  assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
34961
  assert( p->tempFile==0 || pPager->changeCountDone );
34962
34963
  /* If the useJournal flag is clear, the journal-mode must be "OFF". 
34964
  ** And if the journal-mode is "OFF", the journal file must not be open.
34965
  */
34966
  assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
34967
  assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
34968
34969
  /* Check that MEMDB implies noSync. And an in-memory journal. Since 
34970
  ** this means an in-memory pager performs no IO at all, it cannot encounter 
34971
  ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing 
34972
  ** a journal file. (although the in-memory journal implementation may 
34973
  ** return SQLITE_IOERR_NOMEM while the journal file is being written). It 
34974
  ** is therefore not possible for an in-memory pager to enter the ERROR 
34975
  ** state.
34976
  */
34977
  if( MEMDB ){
34978
    assert( p->noSync );
34979
    assert( p->journalMode==PAGER_JOURNALMODE_OFF 
34980
         || p->journalMode==PAGER_JOURNALMODE_MEMORY 
34981
    );
34982
    assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
34983
    assert( pagerUseWal(p)==0 );
34984
  }
34985
34986
  /* If changeCountDone is set, a RESERVED lock or greater must be held
34987
  ** on the file.
34988
  */
34989
  assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
34990
  assert( p->eLock!=PENDING_LOCK );
34991
34992
  switch( p->eState ){
34993
    case PAGER_OPEN:
34994
      assert( !MEMDB );
34995
      assert( pPager->errCode==SQLITE_OK );
34996
      assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
34997
      break;
34998
34999
    case PAGER_READER:
35000
      assert( pPager->errCode==SQLITE_OK );
35001
      assert( p->eLock!=UNKNOWN_LOCK );
35002
      assert( p->eLock>=SHARED_LOCK || p->noReadlock );
35003
      break;
35004
35005
    case PAGER_WRITER_LOCKED:
35006
      assert( p->eLock!=UNKNOWN_LOCK );
35007
      assert( pPager->errCode==SQLITE_OK );
35008
      if( !pagerUseWal(pPager) ){
35009
        assert( p->eLock>=RESERVED_LOCK );
35010
      }
35011
      assert( pPager->dbSize==pPager->dbOrigSize );
35012
      assert( pPager->dbOrigSize==pPager->dbFileSize );
35013
      assert( pPager->dbOrigSize==pPager->dbHintSize );
35014
      assert( pPager->setMaster==0 );
35015
      break;
35016
35017
    case PAGER_WRITER_CACHEMOD:
35018
      assert( p->eLock!=UNKNOWN_LOCK );
35019
      assert( pPager->errCode==SQLITE_OK );
35020
      if( !pagerUseWal(pPager) ){
35021
        /* It is possible that if journal_mode=wal here that neither the
35022
        ** journal file nor the WAL file are open. This happens during
35023
        ** a rollback transaction that switches from journal_mode=off
35024
        ** to journal_mode=wal.
35025
        */
35026
        assert( p->eLock>=RESERVED_LOCK );
35027
        assert( isOpen(p->jfd) 
35028
             || p->journalMode==PAGER_JOURNALMODE_OFF 
35029
             || p->journalMode==PAGER_JOURNALMODE_WAL 
35030
        );
35031
      }
35032
      assert( pPager->dbOrigSize==pPager->dbFileSize );
35033
      assert( pPager->dbOrigSize==pPager->dbHintSize );
35034
      break;
35035
35036
    case PAGER_WRITER_DBMOD:
35037
      assert( p->eLock==EXCLUSIVE_LOCK );
35038
      assert( pPager->errCode==SQLITE_OK );
35039
      assert( !pagerUseWal(pPager) );
35040
      assert( p->eLock>=EXCLUSIVE_LOCK );
35041
      assert( isOpen(p->jfd) 
35042
           || p->journalMode==PAGER_JOURNALMODE_OFF 
35043
           || p->journalMode==PAGER_JOURNALMODE_WAL 
35044
      );
35045
      assert( pPager->dbOrigSize<=pPager->dbHintSize );
35046
      break;
35047
35048
    case PAGER_WRITER_FINISHED:
35049
      assert( p->eLock==EXCLUSIVE_LOCK );
35050
      assert( pPager->errCode==SQLITE_OK );
35051
      assert( !pagerUseWal(pPager) );
35052
      assert( isOpen(p->jfd) 
35053
           || p->journalMode==PAGER_JOURNALMODE_OFF 
35054
           || p->journalMode==PAGER_JOURNALMODE_WAL 
35055
      );
35056
      break;
35057
35058
    case PAGER_ERROR:
35059
      /* There must be at least one outstanding reference to the pager if
35060
      ** in ERROR state. Otherwise the pager should have already dropped
35061
      ** back to OPEN state.
35062
      */
35063
      assert( pPager->errCode!=SQLITE_OK );
35064
      assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
35065
      break;
35066
  }
32594
35067
32595
  return 1;
35068
  return 1;
32596
}
35069
}
35070
35071
/*
35072
** Return a pointer to a human readable string in a static buffer
35073
** containing the state of the Pager object passed as an argument. This
35074
** is intended to be used within debuggers. For example, as an alternative
35075
** to "print *pPager" in gdb:
35076
**
35077
** (gdb) printf "%s", print_pager_state(pPager)
35078
*/
35079
static char *print_pager_state(Pager *p){
35080
  static char zRet[1024];
35081
35082
  sqlite3_snprintf(1024, zRet,
35083
      "Filename:      %s\n"
35084
      "State:         %s errCode=%d\n"
35085
      "Lock:          %s\n"
35086
      "Locking mode:  locking_mode=%s\n"
35087
      "Journal mode:  journal_mode=%s\n"
35088
      "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
35089
      "Journal:       journalOff=%lld journalHdr=%lld\n"
35090
      "Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
35091
      , p->zFilename
35092
      , p->eState==PAGER_OPEN            ? "OPEN" :
35093
        p->eState==PAGER_READER          ? "READER" :
35094
        p->eState==PAGER_WRITER_LOCKED   ? "WRITER_LOCKED" :
35095
        p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
35096
        p->eState==PAGER_WRITER_DBMOD    ? "WRITER_DBMOD" :
35097
        p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
35098
        p->eState==PAGER_ERROR           ? "ERROR" : "?error?"
35099
      , (int)p->errCode
35100
      , p->eLock==NO_LOCK         ? "NO_LOCK" :
35101
        p->eLock==RESERVED_LOCK   ? "RESERVED" :
35102
        p->eLock==EXCLUSIVE_LOCK  ? "EXCLUSIVE" :
35103
        p->eLock==SHARED_LOCK     ? "SHARED" :
35104
        p->eLock==UNKNOWN_LOCK    ? "UNKNOWN" : "?error?"
35105
      , p->exclusiveMode ? "exclusive" : "normal"
35106
      , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? "memory" :
35107
        p->journalMode==PAGER_JOURNALMODE_OFF      ? "off" :
35108
        p->journalMode==PAGER_JOURNALMODE_DELETE   ? "delete" :
35109
        p->journalMode==PAGER_JOURNALMODE_PERSIST  ? "persist" :
35110
        p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
35111
        p->journalMode==PAGER_JOURNALMODE_WAL      ? "wal" : "?error?"
35112
      , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
35113
      , p->journalOff, p->journalHdr
35114
      , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
35115
  );
35116
35117
  return zRet;
35118
}
32597
#endif
35119
#endif
32598
35120
32599
/*
35121
/*
 Lines 32646-32651   static int read32bits(sqlite3_file *fd, Link Here 
32646
*/
35168
*/
32647
#define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
35169
#define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
32648
35170
35171
32649
/*
35172
/*
32650
** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
35173
** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
32651
** on success or an error code is something goes wrong.
35174
** on success or an error code is something goes wrong.
 Lines 32657-32683   static int write32bits(sqlite3_file *fd, Link Here 
32657
}
35180
}
32658
35181
32659
/*
35182
/*
32660
** The argument to this macro is a file descriptor (type sqlite3_file*).
35183
** Unlock the database file to level eLock, which must be either NO_LOCK
32661
** Return 0 if it is not open, or non-zero (but not 1) if it is.
35184
** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
32662
**
35185
** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
32663
** This is so that expressions can be written as:
35186
**
32664
**
35187
** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
32665
**   if( isOpen(pPager->jfd) ){ ...
35188
** called, do not modify it. See the comment above the #define of 
32666
**
35189
** UNKNOWN_LOCK for an explanation of this.
32667
** instead of
35190
*/
32668
**
35191
static int pagerUnlockDb(Pager *pPager, int eLock){
32669
**   if( pPager->jfd->pMethods ){ ...
35192
  int rc = SQLITE_OK;
32670
*/
35193
32671
#define isOpen(pFd) ((pFd)->pMethods)
35194
  assert( !pPager->exclusiveMode );
32672
35195
  assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
32673
/*
35196
  assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
32674
** If file pFd is open, call sqlite3OsUnlock() on it.
35197
  if( isOpen(pPager->fd) ){
32675
*/
35198
    assert( pPager->eLock>=eLock );
32676
static int osUnlock(sqlite3_file *pFd, int eLock){
35199
    rc = sqlite3OsUnlock(pPager->fd, eLock);
32677
  if( !isOpen(pFd) ){
35200
    if( pPager->eLock!=UNKNOWN_LOCK ){
32678
    return SQLITE_OK;
35201
      pPager->eLock = (u8)eLock;
32679
  }
35202
    }
32680
  return sqlite3OsUnlock(pFd, eLock);
35203
    IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
35204
  }
35205
  return rc;
35206
}
35207
35208
/*
35209
** Lock the database file to level eLock, which must be either SHARED_LOCK,
35210
** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
35211
** Pager.eLock variable to the new locking state. 
35212
**
35213
** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is 
35214
** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK. 
35215
** See the comment above the #define of UNKNOWN_LOCK for an explanation 
35216
** of this.
35217
*/
35218
static int pagerLockDb(Pager *pPager, int eLock){
35219
  int rc = SQLITE_OK;
35220
35221
  assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
35222
  if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
35223
    rc = sqlite3OsLock(pPager->fd, eLock);
35224
    if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
35225
      pPager->eLock = (u8)eLock;
35226
      IOTRACE(("LOCK %p %d\n", pPager, eLock))
35227
    }
35228
  }
35229
  return rc;
32681
}
35230
}
32682
35231
32683
/*
35232
/*
 Lines 32926-32932   static int zeroJournalHdr(Pager *pPager, Link Here 
32926
static int writeJournalHdr(Pager *pPager){
35475
static int writeJournalHdr(Pager *pPager){
32927
  int rc = SQLITE_OK;                 /* Return code */
35476
  int rc = SQLITE_OK;                 /* Return code */
32928
  char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
35477
  char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
32929
  u32 nHeader = pPager->pageSize;     /* Size of buffer pointed to by zHeader */
35478
  u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
32930
  u32 nWrite;                         /* Bytes of header sector written */
35479
  u32 nWrite;                         /* Bytes of header sector written */
32931
  int ii;                             /* Loop counter */
35480
  int ii;                             /* Loop counter */
32932
35481
 Lines 32969-32975   static int writeJournalHdr(Pager *pPager Link Here 
32969
  **     that garbage data is never appended to the journal file.
35518
  **     that garbage data is never appended to the journal file.
32970
  */
35519
  */
32971
  assert( isOpen(pPager->fd) || pPager->noSync );
35520
  assert( isOpen(pPager->fd) || pPager->noSync );
32972
  if( (pPager->noSync) || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
35521
  if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
32973
   || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND) 
35522
   || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND) 
32974
  ){
35523
  ){
32975
    memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
35524
    memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
 Lines 33017-33022   static int writeJournalHdr(Pager *pPager Link Here 
33017
  for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
35566
  for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
33018
    IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
35567
    IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
33019
    rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
35568
    rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
35569
    assert( pPager->journalHdr <= pPager->journalOff );
33020
    pPager->journalOff += nHeader;
35570
    pPager->journalOff += nHeader;
33021
  }
35571
  }
33022
35572
 Lines 33092-33098   static int readJournalHdr( Link Here 
33092
  if( pPager->journalOff==0 ){
35642
  if( pPager->journalOff==0 ){
33093
    u32 iPageSize;               /* Page-size field of journal header */
35643
    u32 iPageSize;               /* Page-size field of journal header */
33094
    u32 iSectorSize;             /* Sector-size field of journal header */
35644
    u32 iSectorSize;             /* Sector-size field of journal header */
33095
    u16 iPageSize16;             /* Copy of iPageSize in 16-bit variable */
33096
35645
33097
    /* Read the page-size and sector-size journal header fields. */
35646
    /* Read the page-size and sector-size journal header fields. */
33098
    if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
35647
    if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
 Lines 33101-33106   static int readJournalHdr( Link Here 
33101
      return rc;
35650
      return rc;
33102
    }
35651
    }
33103
35652
35653
    /* Versions of SQLite prior to 3.5.8 set the page-size field of the
35654
    ** journal header to zero. In this case, assume that the Pager.pageSize
35655
    ** variable is already set to the correct page size.
35656
    */
35657
    if( iPageSize==0 ){
35658
      iPageSize = pPager->pageSize;
35659
    }
35660
33104
    /* Check that the values read from the page-size and sector-size fields
35661
    /* Check that the values read from the page-size and sector-size fields
33105
    ** are within range. To be 'in range', both values need to be a power
35662
    ** are within range. To be 'in range', both values need to be a power
33106
    ** of two greater than or equal to 512 or 32, and not greater than their 
35663
    ** of two greater than or equal to 512 or 32, and not greater than their 
 Lines 33122-33131   static int readJournalHdr( Link Here 
33122
    ** Use a testcase() macro to make sure that malloc failure within 
35679
    ** Use a testcase() macro to make sure that malloc failure within 
33123
    ** PagerSetPagesize() is tested.
35680
    ** PagerSetPagesize() is tested.
33124
    */
35681
    */
33125
    iPageSize16 = (u16)iPageSize;
35682
    rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
33126
    rc = sqlite3PagerSetPagesize(pPager, &iPageSize16, -1);
33127
    testcase( rc!=SQLITE_OK );
35683
    testcase( rc!=SQLITE_OK );
33128
    assert( rc!=SQLITE_OK || iPageSize16==(u16)iPageSize );
33129
35684
33130
    /* Update the assumed sector-size to match the value used by 
35685
    /* Update the assumed sector-size to match the value used by 
33131
    ** the process that created this journal. If this journal was
35686
    ** the process that created this journal. If this journal was
 Lines 33167-33173   static int writeMasterJournal(Pager *pPa Link Here 
33167
  i64 jrnlSize;                    /* Size of journal file on disk */
35722
  i64 jrnlSize;                    /* Size of journal file on disk */
33168
  u32 cksum = 0;                   /* Checksum of string zMaster */
35723
  u32 cksum = 0;                   /* Checksum of string zMaster */
33169
35724
33170
  if( !zMaster || pPager->setMaster
35725
  assert( pPager->setMaster==0 );
35726
  assert( !pagerUseWal(pPager) );
35727
35728
  if( !zMaster 
33171
   || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
35729
   || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
33172
   || pPager->journalMode==PAGER_JOURNALMODE_OFF 
35730
   || pPager->journalMode==PAGER_JOURNALMODE_OFF 
33173
  ){
35731
  ){
 Lines 33175-33180   static int writeMasterJournal(Pager *pPa Link Here 
33175
  }
35733
  }
33176
  pPager->setMaster = 1;
35734
  pPager->setMaster = 1;
33177
  assert( isOpen(pPager->jfd) );
35735
  assert( isOpen(pPager->jfd) );
35736
  assert( pPager->journalHdr <= pPager->journalOff );
33178
35737
33179
  /* Calculate the length in bytes and the checksum of zMaster */
35738
  /* Calculate the length in bytes and the checksum of zMaster */
33180
  for(nMaster=0; zMaster[nMaster]; nMaster++){
35739
  for(nMaster=0; zMaster[nMaster]; nMaster++){
 Lines 33202-33208   static int writeMasterJournal(Pager *pPa Link Here 
33202
    return rc;
35761
    return rc;
33203
  }
35762
  }
33204
  pPager->journalOff += (nMaster+20);
35763
  pPager->journalOff += (nMaster+20);
33205
  pPager->needSync = !pPager->noSync;
33206
35764
33207
  /* If the pager is in peristent-journal mode, then the physical 
35765
  /* If the pager is in peristent-journal mode, then the physical 
33208
  ** journal-file may extend past the end of the master-journal name
35766
  ** journal-file may extend past the end of the master-journal name
 Lines 33238-33254   static PgHdr *pager_lookup(Pager *pPager Link Here 
33238
}
35796
}
33239
35797
33240
/*
35798
/*
33241
** Unless the pager is in error-state, discard all in-memory pages. If
35799
** Discard the entire contents of the in-memory page-cache.
33242
** the pager is in error-state, then this call is a no-op.
33243
**
33244
** TODO: Why can we not reset the pager while in error state?
33245
*/
35800
*/
33246
static void pager_reset(Pager *pPager){
35801
static void pager_reset(Pager *pPager){
33247
  if( SQLITE_OK==pPager->errCode ){
35802
  sqlite3BackupRestart(pPager->pBackup);
33248
    sqlite3BackupRestart(pPager->pBackup);
35803
  sqlite3PcacheClear(pPager->pPCache);
33249
    sqlite3PcacheClear(pPager->pPCache);
33250
    pPager->dbSizeValid = 0;
33251
  }
33252
}
35804
}
33253
35805
33254
/*
35806
/*
 Lines 33291-33361   static int addToSavepointBitvecs(Pager * Link Here 
33291
}
35843
}
33292
35844
33293
/*
35845
/*
33294
** Unlock the database file. This function is a no-op if the pager
35846
** This function is a no-op if the pager is in exclusive mode and not
33295
** is in exclusive mode.
35847
** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
33296
**
35848
** state.
33297
** If the pager is currently in error state, discard the contents of 
35849
**
33298
** the cache and reset the Pager structure internal state. If there is
35850
** If the pager is not in exclusive-access mode, the database file is
33299
** an open journal-file, then the next time a shared-lock is obtained
35851
** completely unlocked. If the file is unlocked and the file-system does
33300
** on the pager file (by this or any other process), it will be
35852
** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
33301
** treated as a hot-journal and rolled back.
35853
** closed (if it is open).
35854
**
35855
** If the pager is in ERROR state when this function is called, the 
35856
** contents of the pager cache are discarded before switching back to 
35857
** the OPEN state. Regardless of whether the pager is in exclusive-mode
35858
** or not, any journal file left in the file-system will be treated
35859
** as a hot-journal and rolled back the next time a read-transaction
35860
** is opened (by this or by any other connection).
33302
*/
35861
*/
33303
static void pager_unlock(Pager *pPager){
35862
static void pager_unlock(Pager *pPager){
33304
  if( !pPager->exclusiveMode ){
35863
33305
    int rc;                      /* Return code */
35864
  assert( pPager->eState==PAGER_READER 
33306
35865
       || pPager->eState==PAGER_OPEN 
33307
    /* Always close the journal file when dropping the database lock.
35866
       || pPager->eState==PAGER_ERROR 
33308
    ** Otherwise, another connection with journal_mode=delete might
35867
  );
33309
    ** delete the file out from under us.
35868
33310
    */
35869
  sqlite3BitvecDestroy(pPager->pInJournal);
33311
    sqlite3OsClose(pPager->jfd);
35870
  pPager->pInJournal = 0;
33312
    sqlite3BitvecDestroy(pPager->pInJournal);
35871
  releaseAllSavepoints(pPager);
33313
    pPager->pInJournal = 0;
35872
33314
    releaseAllSavepoints(pPager);
35873
  if( pagerUseWal(pPager) ){
33315
35874
    assert( !isOpen(pPager->jfd) );
33316
    /* If the file is unlocked, somebody else might change it. The
35875
    sqlite3WalEndReadTransaction(pPager->pWal);
33317
    ** values stored in Pager.dbSize etc. might become invalid if
35876
    pPager->eState = PAGER_OPEN;
33318
    ** this happens. TODO: Really, this doesn't need to be cleared
35877
  }else if( !pPager->exclusiveMode ){
33319
    ** until the change-counter check fails in PagerSharedLock().
35878
    int rc;                       /* Error code returned by pagerUnlockDb() */
33320
    */
35879
    int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
33321
    pPager->dbSizeValid = 0;
35880
33322
35881
    /* If the operating system support deletion of open files, then
33323
    rc = osUnlock(pPager->fd, NO_LOCK);
35882
    ** close the journal file when dropping the database lock.  Otherwise
33324
    if( rc ){
35883
    ** another connection with journal_mode=delete might delete the file
33325
      pPager->errCode = rc;
35884
    ** out from under us.
33326
    }
35885
    */
33327
    IOTRACE(("UNLOCK %p\n", pPager))
35886
    assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
33328
35887
    assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
33329
    /* If Pager.errCode is set, the contents of the pager cache cannot be
35888
    assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
33330
    ** trusted. Now that the pager file is unlocked, the contents of the
35889
    assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
33331
    ** cache can be discarded and the error code safely cleared.
35890
    assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
33332
    */
35891
    assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
33333
    if( pPager->errCode ){
35892
    if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
33334
      if( rc==SQLITE_OK ){
35893
     || 1!=(pPager->journalMode & 5)
33335
        pPager->errCode = SQLITE_OK;
35894
    ){
33336
      }
35895
      sqlite3OsClose(pPager->jfd);
33337
      pager_reset(pPager);
35896
    }
33338
    }
35897
33339
35898
    /* If the pager is in the ERROR state and the call to unlock the database
35899
    ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
35900
    ** above the #define for UNKNOWN_LOCK for an explanation of why this
35901
    ** is necessary.
35902
    */
35903
    rc = pagerUnlockDb(pPager, NO_LOCK);
35904
    if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
35905
      pPager->eLock = UNKNOWN_LOCK;
35906
    }
35907
35908
    /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
35909
    ** without clearing the error code. This is intentional - the error
35910
    ** code is cleared and the cache reset in the block below.
35911
    */
35912
    assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
33340
    pPager->changeCountDone = 0;
35913
    pPager->changeCountDone = 0;
33341
    pPager->state = PAGER_UNLOCK;
35914
    pPager->eState = PAGER_OPEN;
33342
    pPager->dbModified = 0;
35915
  }
33343
  }
35916
33344
}
35917
  /* If Pager.errCode is set, the contents of the pager cache cannot be
33345
35918
  ** trusted. Now that there are no outstanding references to the pager,
33346
/*
35919
  ** it can safely move back to PAGER_OPEN state. This happens in both
33347
** This function should be called when an IOERR, CORRUPT or FULL error
35920
  ** normal and exclusive-locking mode.
33348
** may have occurred. The first argument is a pointer to the pager 
35921
  */
33349
** structure, the second the error-code about to be returned by a pager 
35922
  if( pPager->errCode ){
33350
** API function. The value returned is a copy of the second argument 
35923
    assert( !MEMDB );
33351
** to this function. 
35924
    pager_reset(pPager);
33352
**
35925
    pPager->changeCountDone = pPager->tempFile;
33353
** If the second argument is SQLITE_IOERR, SQLITE_CORRUPT, or SQLITE_FULL
35926
    pPager->eState = PAGER_OPEN;
33354
** the error becomes persistent. Until the persisten error is cleared,
35927
    pPager->errCode = SQLITE_OK;
33355
** subsequent API calls on this Pager will immediately return the same 
35928
  }
33356
** error code.
35929
33357
**
35930
  pPager->journalOff = 0;
33358
** A persistent error indicates that the contents of the pager-cache 
35931
  pPager->journalHdr = 0;
35932
  pPager->setMaster = 0;
35933
}
35934
35935
/*
35936
** This function is called whenever an IOERR or FULL error that requires
35937
** the pager to transition into the ERROR state may ahve occurred.
35938
** The first argument is a pointer to the pager structure, the second 
35939
** the error-code about to be returned by a pager API function. The 
35940
** value returned is a copy of the second argument to this function. 
35941
**
35942
** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
35943
** IOERR sub-codes, the pager enters the ERROR state and the error code
35944
** is stored in Pager.errCode. While the pager remains in the ERROR state,
35945
** all major API calls on the Pager will immediately return Pager.errCode.
35946
**
35947
** The ERROR state indicates that the contents of the pager-cache 
33359
** cannot be trusted. This state can be cleared by completely discarding 
35948
** cannot be trusted. This state can be cleared by completely discarding 
33360
** the contents of the pager-cache. If a transaction was active when
35949
** the contents of the pager-cache. If a transaction was active when
33361
** the persistent error occurred, then the rollback journal may need
35950
** the persistent error occurred, then the rollback journal may need
 Lines 33372-33405   static int pager_error(Pager *pPager, in Link Here 
33372
  );
35961
  );
33373
  if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
35962
  if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
33374
    pPager->errCode = rc;
35963
    pPager->errCode = rc;
33375
  }
35964
    pPager->eState = PAGER_ERROR;
33376
  return rc;
35965
  }
33377
}
35966
  return rc;
33378
33379
/*
33380
** Execute a rollback if a transaction is active and unlock the 
33381
** database file. 
33382
**
33383
** If the pager has already entered the error state, do not attempt 
33384
** the rollback at this time. Instead, pager_unlock() is called. The
33385
** call to pager_unlock() will discard all in-memory pages, unlock
33386
** the database file and clear the error state. If this means that
33387
** there is a hot-journal left in the file-system, the next connection
33388
** to obtain a shared lock on the pager (which may be this one) will
33389
** roll it back.
33390
**
33391
** If the pager has not already entered the error state, but an IO or
33392
** malloc error occurs during a rollback, then this will itself cause 
33393
** the pager to enter the error state. Which will be cleared by the
33394
** call to pager_unlock(), as described above.
33395
*/
33396
static void pagerUnlockAndRollback(Pager *pPager){
33397
  if( pPager->errCode==SQLITE_OK && pPager->state>=PAGER_RESERVED ){
33398
    sqlite3BeginBenignMalloc();
33399
    sqlite3PagerRollback(pPager);
33400
    sqlite3EndBenignMalloc();
33401
  }
33402
  pager_unlock(pPager);
33403
}
35967
}
33404
35968
33405
/*
35969
/*
 Lines 33409-33416   static void pagerUnlockAndRollback(Pager Link Here 
33409
** the journal file or writing the very first journal-header of a
35973
** the journal file or writing the very first journal-header of a
33410
** database transaction.
35974
** database transaction.
33411
** 
35975
** 
33412
** If the pager is in PAGER_SHARED or PAGER_UNLOCK state when this
35976
** This routine is never called in PAGER_ERROR state. If it is called
33413
** routine is called, it is a no-op (returns SQLITE_OK).
35977
** in PAGER_NONE or PAGER_SHARED state and the lock held is less
35978
** exclusive than a RESERVED lock, it is a no-op.
33414
**
35979
**
33415
** Otherwise, any active savepoints are released.
35980
** Otherwise, any active savepoints are released.
33416
**
35981
**
 Lines 33441-33453   static void pagerUnlockAndRollback(Pager Link Here 
33441
**     DELETE and the pager is in exclusive mode, the method described under
36006
**     DELETE and the pager is in exclusive mode, the method described under
33442
**     journalMode==PERSIST is used instead.
36007
**     journalMode==PERSIST is used instead.
33443
**
36008
**
33444
** After the journal is finalized, if running in non-exclusive mode, the
36009
** After the journal is finalized, the pager moves to PAGER_READER state.
33445
** pager moves to PAGER_SHARED state (and downgrades the lock on the
36010
** If running in non-exclusive rollback mode, the lock on the file is 
33446
** database file accordingly).
36011
** downgraded to a SHARED_LOCK.
33447
**
33448
** If the pager is running in exclusive mode and is in PAGER_SYNCED state,
33449
** it moves to PAGER_EXCLUSIVE. No locks are downgraded when running in
33450
** exclusive mode.
33451
**
36012
**
33452
** SQLITE_OK is returned if no error occurs. If an error occurs during
36013
** SQLITE_OK is returned if no error occurs. If an error occurs during
33453
** any of the IO operations to finalize the journal file or unlock the
36014
** any of the IO operations to finalize the journal file or unlock the
 Lines 33462-33474   static int pager_end_transaction(Pager * Link Here 
33462
  int rc = SQLITE_OK;      /* Error code from journal finalization operation */
36023
  int rc = SQLITE_OK;      /* Error code from journal finalization operation */
33463
  int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
36024
  int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
33464
36025
33465
  if( pPager->state<PAGER_RESERVED ){
36026
  /* Do nothing if the pager does not have an open write transaction
36027
  ** or at least a RESERVED lock. This function may be called when there
36028
  ** is no write-transaction active but a RESERVED or greater lock is
36029
  ** held under two circumstances:
36030
  **
36031
  **   1. After a successful hot-journal rollback, it is called with
36032
  **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
36033
  **
36034
  **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE 
36035
  **      lock switches back to locking_mode=normal and then executes a
36036
  **      read-transaction, this function is called with eState==PAGER_READER 
36037
  **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
36038
  */
36039
  assert( assert_pager_state(pPager) );
36040
  assert( pPager->eState!=PAGER_ERROR );
36041
  if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
33466
    return SQLITE_OK;
36042
    return SQLITE_OK;
33467
  }
36043
  }
36044
33468
  releaseAllSavepoints(pPager);
36045
  releaseAllSavepoints(pPager);
33469
33470
  assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
36046
  assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
33471
  if( isOpen(pPager->jfd) ){
36047
  if( isOpen(pPager->jfd) ){
36048
    assert( !pagerUseWal(pPager) );
33472
36049
33473
    /* Finalize the journal file. */
36050
    /* Finalize the journal file. */
33474
    if( sqlite3IsMemJournal(pPager->jfd) ){
36051
    if( sqlite3IsMemJournal(pPager->jfd) ){
 Lines 33481-33501   static int pager_end_transaction(Pager * Link Here 
33481
        rc = sqlite3OsTruncate(pPager->jfd, 0);
36058
        rc = sqlite3OsTruncate(pPager->jfd, 0);
33482
      }
36059
      }
33483
      pPager->journalOff = 0;
36060
      pPager->journalOff = 0;
33484
      pPager->journalStarted = 0;
36061
    }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
33485
    }else if( pPager->exclusiveMode 
36062
      || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
33486
     || pPager->journalMode==PAGER_JOURNALMODE_PERSIST
33487
    ){
36063
    ){
33488
      rc = zeroJournalHdr(pPager, hasMaster);
36064
      rc = zeroJournalHdr(pPager, hasMaster);
33489
      pager_error(pPager, rc);
33490
      pPager->journalOff = 0;
36065
      pPager->journalOff = 0;
33491
      pPager->journalStarted = 0;
33492
    }else{
36066
    }else{
33493
      /* This branch may be executed with Pager.journalMode==MEMORY if
36067
      /* This branch may be executed with Pager.journalMode==MEMORY if
33494
      ** a hot-journal was just rolled back. In this case the journal
36068
      ** a hot-journal was just rolled back. In this case the journal
33495
      ** file should be closed and deleted. If this connection writes to
36069
      ** file should be closed and deleted. If this connection writes to
33496
      ** the database file, it will do so using an in-memory journal.  */
36070
      ** the database file, it will do so using an in-memory journal. 
36071
      */
33497
      assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE 
36072
      assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE 
33498
           || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
36073
           || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
36074
           || pPager->journalMode==PAGER_JOURNALMODE_WAL 
33499
      );
36075
      );
33500
      sqlite3OsClose(pPager->jfd);
36076
      sqlite3OsClose(pPager->jfd);
33501
      if( !pPager->tempFile ){
36077
      if( !pPager->tempFile ){
 Lines 33506-33541   static int pager_end_transaction(Pager * Link Here 
33506
#ifdef SQLITE_CHECK_PAGES
36082
#ifdef SQLITE_CHECK_PAGES
33507
    sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
36083
    sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
33508
#endif
36084
#endif
33509
36085
  }
33510
    sqlite3PcacheCleanAll(pPager->pPCache);
36086
  sqlite3BitvecDestroy(pPager->pInJournal);
33511
    sqlite3BitvecDestroy(pPager->pInJournal);
36087
  pPager->pInJournal = 0;
33512
    pPager->pInJournal = 0;
36088
  pPager->nRec = 0;
33513
    pPager->nRec = 0;
36089
  sqlite3PcacheCleanAll(pPager->pPCache);
33514
  }
36090
  sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
33515
36091
33516
  if( !pPager->exclusiveMode ){
36092
  if( pagerUseWal(pPager) ){
33517
    rc2 = osUnlock(pPager->fd, SHARED_LOCK);
36093
    /* Drop the WAL write-lock, if any. Also, if the connection was in 
33518
    pPager->state = PAGER_SHARED;
36094
    ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE 
36095
    ** lock held on the database file.
36096
    */
36097
    rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
36098
    assert( rc2==SQLITE_OK );
36099
  }
36100
  if( !pPager->exclusiveMode 
36101
   && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
36102
  ){
36103
    rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
33519
    pPager->changeCountDone = 0;
36104
    pPager->changeCountDone = 0;
33520
  }else if( pPager->state==PAGER_SYNCED ){
36105
  }
33521
    pPager->state = PAGER_EXCLUSIVE;
36106
  pPager->eState = PAGER_READER;
33522
  }
33523
  pPager->setMaster = 0;
36107
  pPager->setMaster = 0;
33524
  pPager->needSync = 0;
33525
  pPager->dbModified = 0;
33526
33527
  /* TODO: Is this optimal? Why is the db size invalidated here 
33528
  ** when the database file is not unlocked? */
33529
  pPager->dbOrigSize = 0;
33530
  sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
33531
  if( !MEMDB ){
33532
    pPager->dbSizeValid = 0;
33533
  }
33534
36108
33535
  return (rc==SQLITE_OK?rc2:rc);
36109
  return (rc==SQLITE_OK?rc2:rc);
33536
}
36110
}
33537
36111
33538
/*
36112
/*
36113
** Execute a rollback if a transaction is active and unlock the 
36114
** database file. 
36115
**
36116
** If the pager has already entered the ERROR state, do not attempt 
36117
** the rollback at this time. Instead, pager_unlock() is called. The
36118
** call to pager_unlock() will discard all in-memory pages, unlock
36119
** the database file and move the pager back to OPEN state. If this 
36120
** means that there is a hot-journal left in the file-system, the next 
36121
** connection to obtain a shared lock on the pager (which may be this one) 
36122
** will roll it back.
36123
**
36124
** If the pager has not already entered the ERROR state, but an IO or
36125
** malloc error occurs during a rollback, then this will itself cause 
36126
** the pager to enter the ERROR state. Which will be cleared by the
36127
** call to pager_unlock(), as described above.
36128
*/
36129
static void pagerUnlockAndRollback(Pager *pPager){
36130
  if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
36131
    assert( assert_pager_state(pPager) );
36132
    if( pPager->eState>=PAGER_WRITER_LOCKED ){
36133
      sqlite3BeginBenignMalloc();
36134
      sqlite3PagerRollback(pPager);
36135
      sqlite3EndBenignMalloc();
36136
    }else if( !pPager->exclusiveMode ){
36137
      assert( pPager->eState==PAGER_READER );
36138
      pager_end_transaction(pPager, 0);
36139
    }
36140
  }
36141
  pager_unlock(pPager);
36142
}
36143
36144
/*
33539
** Parameter aData must point to a buffer of pPager->pageSize bytes
36145
** Parameter aData must point to a buffer of pPager->pageSize bytes
33540
** of data. Compute and return a checksum based ont the contents of the 
36146
** of data. Compute and return a checksum based ont the contents of the 
33541
** page of data and the current value of pPager->cksumInit.
36147
** page of data and the current value of pPager->cksumInit.
 Lines 33565-33578   static u32 pager_cksum(Pager *pPager, co Link Here 
33565
}
36171
}
33566
36172
33567
/*
36173
/*
36174
** Report the current page size and number of reserved bytes back
36175
** to the codec.
36176
*/
36177
#ifdef SQLITE_HAS_CODEC
36178
static void pagerReportSize(Pager *pPager){
36179
  if( pPager->xCodecSizeChng ){
36180
    pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
36181
                           (int)pPager->nReserve);
36182
  }
36183
}
36184
#else
36185
# define pagerReportSize(X)     /* No-op if we do not support a codec */
36186
#endif
36187
36188
/*
33568
** Read a single page from either the journal file (if isMainJrnl==1) or
36189
** Read a single page from either the journal file (if isMainJrnl==1) or
33569
** from the sub-journal (if isMainJrnl==0) and playback that page.
36190
** from the sub-journal (if isMainJrnl==0) and playback that page.
33570
** The page begins at offset *pOffset into the file. The *pOffset
36191
** The page begins at offset *pOffset into the file. The *pOffset
33571
** value is increased to the start of the next page in the journal.
36192
** value is increased to the start of the next page in the journal.
33572
**
36193
**
33573
** The isMainJrnl flag is true if this is the main rollback journal and
36194
** The main rollback journal uses checksums - the statement journal does 
33574
** false for the statement journal.  The main rollback journal uses
36195
** not.
33575
** checksums - the statement journal does not.
33576
**
36196
**
33577
** If the page number of the page record read from the (sub-)journal file
36197
** If the page number of the page record read from the (sub-)journal file
33578
** is greater than the current value of Pager.dbSize, then playback is
36198
** is greater than the current value of Pager.dbSize, then playback is
 Lines 33604-33614   static u32 pager_cksum(Pager *pPager, co Link Here 
33604
*/
36224
*/
33605
static int pager_playback_one_page(
36225
static int pager_playback_one_page(
33606
  Pager *pPager,                /* The pager being played back */
36226
  Pager *pPager,                /* The pager being played back */
36227
  i64 *pOffset,                 /* Offset of record to playback */
36228
  Bitvec *pDone,                /* Bitvec of pages already played back */
33607
  int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
36229
  int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
33608
  int isUnsync,                 /* True if reading from unsynced main journal */
36230
  int isSavepnt                 /* True for a savepoint rollback */
33609
  i64 *pOffset,                 /* Offset of record to playback */
33610
  int isSavepnt,                /* True for a savepoint rollback */
33611
  Bitvec *pDone                 /* Bitvec of pages already played back */
33612
){
36231
){
33613
  int rc;
36232
  int rc;
33614
  PgHdr *pPg;                   /* An existing page in the cache */
36233
  PgHdr *pPg;                   /* An existing page in the cache */
 Lines 33616-33621   static int pager_playback_one_page( Link Here 
33616
  u32 cksum;                    /* Checksum used for sanity checking */
36235
  u32 cksum;                    /* Checksum used for sanity checking */
33617
  char *aData;                  /* Temporary storage for the page */
36236
  char *aData;                  /* Temporary storage for the page */
33618
  sqlite3_file *jfd;            /* The file descriptor for the journal file */
36237
  sqlite3_file *jfd;            /* The file descriptor for the journal file */
36238
  int isSynced;                 /* True if journal page is synced */
33619
36239
33620
  assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
36240
  assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
33621
  assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
36241
  assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
 Lines 33624-33629   static int pager_playback_one_page( Link Here 
33624
36244
33625
  aData = pPager->pTmpSpace;
36245
  aData = pPager->pTmpSpace;
33626
  assert( aData );         /* Temp storage must have already been allocated */
36246
  assert( aData );         /* Temp storage must have already been allocated */
36247
  assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
36248
36249
  /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction 
36250
  ** or savepoint rollback done at the request of the caller) or this is
36251
  ** a hot-journal rollback. If it is a hot-journal rollback, the pager
36252
  ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
36253
  ** only reads from the main journal, not the sub-journal.
36254
  */
36255
  assert( pPager->eState>=PAGER_WRITER_CACHEMOD
36256
       || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
36257
  );
36258
  assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
33627
36259
33628
  /* Read the page number and page data from the journal or sub-journal
36260
  /* Read the page number and page data from the journal or sub-journal
33629
  ** file. Return an error code to the caller if an IO error occurs.
36261
  ** file. Return an error code to the caller if an IO error occurs.
 Lines 33655-33667   static int pager_playback_one_page( Link Here 
33655
    }
36287
    }
33656
  }
36288
  }
33657
36289
36290
  /* If this page has already been played by before during the current
36291
  ** rollback, then don't bother to play it back again.
36292
  */
33658
  if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
36293
  if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
33659
    return rc;
36294
    return rc;
33660
  }
36295
  }
33661
36296
33662
  assert( pPager->state==PAGER_RESERVED || pPager->state>=PAGER_EXCLUSIVE );
36297
  /* When playing back page 1, restore the nReserve setting
33663
36298
  */
33664
  /* If the pager is in RESERVED state, then there must be a copy of this
36299
  if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
36300
    pPager->nReserve = ((u8*)aData)[20];
36301
    pagerReportSize(pPager);
36302
  }
36303
36304
  /* If the pager is in CACHEMOD state, then there must be a copy of this
33665
  ** page in the pager cache. In this case just update the pager cache,
36305
  ** page in the pager cache. In this case just update the pager cache,
33666
  ** not the database file. The page is left marked dirty in this case.
36306
  ** not the database file. The page is left marked dirty in this case.
33667
  **
36307
  **
 Lines 33672-33679   static int pager_playback_one_page( Link Here 
33672
  ** either. So the condition described in the above paragraph is not
36312
  ** either. So the condition described in the above paragraph is not
33673
  ** assert()able.
36313
  ** assert()able.
33674
  **
36314
  **
33675
  ** If in EXCLUSIVE state, then we update the pager cache if it exists
36315
  ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
33676
  ** and the main file. The page is then marked not dirty.
36316
  ** pager cache if it exists and the main file. The page is then marked 
36317
  ** not dirty. Since this code is only executed in PAGER_OPEN state for
36318
  ** a hot-journal rollback, it is guaranteed that the page-cache is empty
36319
  ** if the pager is in OPEN state.
33677
  **
36320
  **
33678
  ** Ticket #1171:  The statement journal might contain page content that is
36321
  ** Ticket #1171:  The statement journal might contain page content that is
33679
  ** different from the page content at the start of the transaction.
36322
  ** different from the page content at the start of the transaction.
 Lines 33693-33710   static int pager_playback_one_page( Link Here 
33693
  ** is possible to fail a statement on a database that does not yet exist.
36336
  ** is possible to fail a statement on a database that does not yet exist.
33694
  ** Do not attempt to write if database file has never been opened.
36337
  ** Do not attempt to write if database file has never been opened.
33695
  */
36338
  */
33696
  pPg = pager_lookup(pPager, pgno);
36339
  if( pagerUseWal(pPager) ){
36340
    pPg = 0;
36341
  }else{
36342
    pPg = pager_lookup(pPager, pgno);
36343
  }
33697
  assert( pPg || !MEMDB );
36344
  assert( pPg || !MEMDB );
36345
  assert( pPager->eState!=PAGER_OPEN || pPg==0 );
33698
  PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
36346
  PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
33699
           PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
36347
           PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
33700
           (isMainJrnl?"main-journal":"sub-journal")
36348
           (isMainJrnl?"main-journal":"sub-journal")
33701
  ));
36349
  ));
33702
  if( (pPager->state>=PAGER_EXCLUSIVE)
36350
  if( isMainJrnl ){
33703
   && (pPg==0 || 0==(pPg->flags&PGHDR_NEED_SYNC))
36351
    isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
33704
   && isOpen(pPager->fd)
36352
  }else{
33705
   && !isUnsync
36353
    isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
36354
  }
36355
  if( isOpen(pPager->fd)
36356
   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
36357
   && isSynced
33706
  ){
36358
  ){
33707
    i64 ofst = (pgno-1)*(i64)pPager->pageSize;
36359
    i64 ofst = (pgno-1)*(i64)pPager->pageSize;
36360
    testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
36361
    assert( !pagerUseWal(pPager) );
33708
    rc = sqlite3OsWrite(pPager->fd, (u8*)aData, pPager->pageSize, ofst);
36362
    rc = sqlite3OsWrite(pPager->fd, (u8*)aData, pPager->pageSize, ofst);
33709
    if( pgno>pPager->dbFileSize ){
36363
    if( pgno>pPager->dbFileSize ){
33710
      pPager->dbFileSize = pgno;
36364
      pPager->dbFileSize = pgno;
 Lines 33732-33740   static int pager_playback_one_page( Link Here 
33732
    ** requiring a journal-sync before it is written.
36386
    ** requiring a journal-sync before it is written.
33733
    */
36387
    */
33734
    assert( isSavepnt );
36388
    assert( isSavepnt );
33735
    if( (rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1))!=SQLITE_OK ){
36389
    assert( pPager->doNotSpill==0 );
33736
      return rc;
36390
    pPager->doNotSpill++;
33737
    }
36391
    rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
36392
    assert( pPager->doNotSpill==1 );
36393
    pPager->doNotSpill--;
36394
    if( rc!=SQLITE_OK ) return rc;
33738
    pPg->flags &= ~PGHDR_NEED_READ;
36395
    pPg->flags &= ~PGHDR_NEED_READ;
33739
    sqlite3PcacheMakeDirty(pPg);
36396
    sqlite3PcacheMakeDirty(pPg);
33740
  }
36397
  }
 Lines 33753-33759   static int pager_playback_one_page( Link Here 
33753
      /* If the contents of this page were just restored from the main 
36410
      /* If the contents of this page were just restored from the main 
33754
      ** journal file, then its content must be as they were when the 
36411
      ** journal file, then its content must be as they were when the 
33755
      ** transaction was first opened. In this case we can mark the page
36412
      ** transaction was first opened. In this case we can mark the page
33756
      ** as clean, since there will be no need to write it out to the.
36413
      ** as clean, since there will be no need to write it out to the
36414
      ** database.
33757
      **
36415
      **
33758
      ** There is one exception to this rule. If the page is being rolled
36416
      ** There is one exception to this rule. If the page is being rolled
33759
      ** back as part of a savepoint (or statement) rollback from an 
36417
      ** back as part of a savepoint (or statement) rollback from an 
 Lines 33768-33773   static int pager_playback_one_page( Link Here 
33768
      ** segment is synced. If a crash occurs during or following this,
36426
      ** segment is synced. If a crash occurs during or following this,
33769
      ** database corruption may ensue.
36427
      ** database corruption may ensue.
33770
      */
36428
      */
36429
      assert( !pagerUseWal(pPager) );
33771
      sqlite3PcacheMakeClean(pPg);
36430
      sqlite3PcacheMakeClean(pPg);
33772
    }
36431
    }
33773
#ifdef SQLITE_CHECK_PAGES
36432
#ifdef SQLITE_CHECK_PAGES
 Lines 33836-33841   static int pager_delmaster(Pager *pPager Link Here 
33836
  sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
36495
  sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
33837
  char *zMasterJournal = 0; /* Contents of master journal file */
36496
  char *zMasterJournal = 0; /* Contents of master journal file */
33838
  i64 nMasterJournal;       /* Size of master journal file */
36497
  i64 nMasterJournal;       /* Size of master journal file */
36498
  char *zJournal;           /* Pointer to one journal within MJ file */
36499
  char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
36500
  int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
33839
36501
33840
  /* Allocate space for both the pJournal and pMaster file descriptors.
36502
  /* Allocate space for both the pJournal and pMaster file descriptors.
33841
  ** If successful, open the master journal file for reading.
36503
  ** If successful, open the master journal file for reading.
 Lines 33850-33922   static int pager_delmaster(Pager *pPager Link Here 
33850
  }
36512
  }
33851
  if( rc!=SQLITE_OK ) goto delmaster_out;
36513
  if( rc!=SQLITE_OK ) goto delmaster_out;
33852
36514
36515
  /* Load the entire master journal file into space obtained from
36516
  ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain
36517
  ** sufficient space (in zMasterPtr) to hold the names of master
36518
  ** journal files extracted from regular rollback-journals.
36519
  */
33853
  rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
36520
  rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
33854
  if( rc!=SQLITE_OK ) goto delmaster_out;
36521
  if( rc!=SQLITE_OK ) goto delmaster_out;
33855
36522
  nMasterPtr = pVfs->mxPathname+1;
33856
  if( nMasterJournal>0 ){
36523
  zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
33857
    char *zJournal;
36524
  if( !zMasterJournal ){
33858
    char *zMasterPtr = 0;
36525
    rc = SQLITE_NOMEM;
33859
    int nMasterPtr = pVfs->mxPathname+1;
36526
    goto delmaster_out;
33860
36527
  }
33861
    /* Load the entire master journal file into space obtained from
36528
  zMasterPtr = &zMasterJournal[nMasterJournal+1];
33862
    ** sqlite3_malloc() and pointed to by zMasterJournal. 
36529
  rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
33863
    */
36530
  if( rc!=SQLITE_OK ) goto delmaster_out;
33864
    zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
36531
  zMasterJournal[nMasterJournal] = 0;
33865
    if( !zMasterJournal ){
36532
33866
      rc = SQLITE_NOMEM;
36533
  zJournal = zMasterJournal;
36534
  while( (zJournal-zMasterJournal)<nMasterJournal ){
36535
    int exists;
36536
    rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
36537
    if( rc!=SQLITE_OK ){
33867
      goto delmaster_out;
36538
      goto delmaster_out;
33868
    }
36539
    }
33869
    zMasterPtr = &zMasterJournal[nMasterJournal+1];
36540
    if( exists ){
33870
    rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
36541
      /* One of the journals pointed to by the master journal exists.
33871
    if( rc!=SQLITE_OK ) goto delmaster_out;
36542
      ** Open it and check if it points at the master journal. If
33872
    zMasterJournal[nMasterJournal] = 0;
36543
      ** so, return without deleting the master journal file.
33873
36544
      */
33874
    zJournal = zMasterJournal;
36545
      int c;
33875
    while( (zJournal-zMasterJournal)<nMasterJournal ){
36546
      int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
33876
      int exists;
36547
      rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
33877
      rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
33878
      if( rc!=SQLITE_OK ){
36548
      if( rc!=SQLITE_OK ){
33879
        goto delmaster_out;
36549
        goto delmaster_out;
33880
      }
36550
      }
33881
      if( exists ){
36551
33882
        /* One of the journals pointed to by the master journal exists.
36552
      rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
33883
        ** Open it and check if it points at the master journal. If
36553
      sqlite3OsClose(pJournal);
33884
        ** so, return without deleting the master journal file.
36554
      if( rc!=SQLITE_OK ){
33885
        */
36555
        goto delmaster_out;
33886
        int c;
36556
      }
33887
        int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
36557
33888
        rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
36558
      c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
33889
        if( rc!=SQLITE_OK ){
36559
      if( c ){
33890
          goto delmaster_out;
36560
        /* We have a match. Do not delete the master journal file. */
33891
        }
36561
        goto delmaster_out;
33892
36562
      }
33893
        rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
36563
    }
33894
        sqlite3OsClose(pJournal);
36564
    zJournal += (sqlite3Strlen30(zJournal)+1);
33895
        if( rc!=SQLITE_OK ){
36565
  }
33896
          goto delmaster_out;
36566
 
33897
        }
36567
  sqlite3OsClose(pMaster);
33898
33899
        c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
33900
        if( c ){
33901
          /* We have a match. Do not delete the master journal file. */
33902
          goto delmaster_out;
33903
        }
33904
      }
33905
      zJournal += (sqlite3Strlen30(zJournal)+1);
33906
    }
33907
  }
33908
  
33909
  rc = sqlite3OsDelete(pVfs, zMaster, 0);
36568
  rc = sqlite3OsDelete(pVfs, zMaster, 0);
33910
36569
33911
delmaster_out:
36570
delmaster_out:
33912
  if( zMasterJournal ){
36571
  sqlite3_free(zMasterJournal);
33913
    sqlite3_free(zMasterJournal);
33914
  }  
33915
  if( pMaster ){
36572
  if( pMaster ){
33916
    sqlite3OsClose(pMaster);
36573
    sqlite3OsClose(pMaster);
33917
    assert( !isOpen(pJournal) );
36574
    assert( !isOpen(pJournal) );
33918
  }
36575
    sqlite3_free(pMaster);
33919
  sqlite3_free(pMaster);
36576
  }
33920
  return rc;
36577
  return rc;
33921
}
36578
}
33922
36579
 Lines 33926-33935   delmaster_out: Link Here 
33926
** file in the file-system. This only happens when committing a transaction,
36583
** file in the file-system. This only happens when committing a transaction,
33927
** or rolling back a transaction (including rolling back a hot-journal).
36584
** or rolling back a transaction (including rolling back a hot-journal).
33928
**
36585
**
33929
** If the main database file is not open, or an exclusive lock is not
36586
** If the main database file is not open, or the pager is not in either
33930
** held, this function is a no-op. Otherwise, the size of the file is
36587
** DBMOD or OPEN state, this function is a no-op. Otherwise, the size 
33931
** changed to nPage pages (nPage*pPager->pageSize bytes). If the file
36588
** of the file is changed to nPage pages (nPage*pPager->pageSize bytes). 
33932
** on disk is currently larger than nPage pages, then use the VFS
36589
** If the file on disk is currently larger than nPage pages, then use the VFS
33933
** xTruncate() method to truncate it.
36590
** xTruncate() method to truncate it.
33934
**
36591
**
33935
** Or, it might might be the case that the file on disk is smaller than 
36592
** Or, it might might be the case that the file on disk is smaller than 
 Lines 33943-33950   delmaster_out: Link Here 
33943
*/
36600
*/
33944
static int pager_truncate(Pager *pPager, Pgno nPage){
36601
static int pager_truncate(Pager *pPager, Pgno nPage){
33945
  int rc = SQLITE_OK;
36602
  int rc = SQLITE_OK;
33946
  if( pPager->state>=PAGER_EXCLUSIVE && isOpen(pPager->fd) ){
36603
  assert( pPager->eState!=PAGER_ERROR );
36604
  assert( pPager->eState!=PAGER_READER );
36605
  
36606
  if( isOpen(pPager->fd) 
36607
   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN) 
36608
  ){
33947
    i64 currentSize, newSize;
36609
    i64 currentSize, newSize;
36610
    assert( pPager->eLock==EXCLUSIVE_LOCK );
33948
    /* TODO: Is it safe to use Pager.dbFileSize here? */
36611
    /* TODO: Is it safe to use Pager.dbFileSize here? */
33949
    rc = sqlite3OsFileSize(pPager->fd, &currentSize);
36612
    rc = sqlite3OsFileSize(pPager->fd, &currentSize);
33950
    newSize = pPager->pageSize*(i64)nPage;
36613
    newSize = pPager->pageSize*(i64)nPage;
 Lines 34068-34074   static int pager_playback(Pager *pPager, Link Here 
34068
  */
36731
  */
34069
  assert( isOpen(pPager->jfd) );
36732
  assert( isOpen(pPager->jfd) );
34070
  rc = sqlite3OsFileSize(pPager->jfd, &szJ);
36733
  rc = sqlite3OsFileSize(pPager->jfd, &szJ);
34071
  if( rc!=SQLITE_OK || szJ==0 ){
36734
  if( rc!=SQLITE_OK ){
34072
    goto end_playback;
36735
    goto end_playback;
34073
  }
36736
  }
34074
36737
 Lines 34100-34110   static int pager_playback(Pager *pPager, Link Here 
34100
  ** occurs. 
36763
  ** occurs. 
34101
  */
36764
  */
34102
  while( 1 ){
36765
  while( 1 ){
34103
    int isUnsync = 0;
34104
34105
    /* Read the next journal header from the journal file.  If there are
36766
    /* Read the next journal header from the journal file.  If there are
34106
    ** not enough bytes left in the journal file for a complete header, or
36767
    ** not enough bytes left in the journal file for a complete header, or
34107
    ** it is corrupted, then a process must of failed while writing it.
36768
    ** it is corrupted, then a process must have failed while writing it.
34108
    ** This indicates nothing more needs to be rolled back.
36769
    ** This indicates nothing more needs to be rolled back.
34109
    */
36770
    */
34110
    rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
36771
    rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
 Lines 34142-34148   static int pager_playback(Pager *pPager, Link Here 
34142
    if( nRec==0 && !isHot &&
36803
    if( nRec==0 && !isHot &&
34143
        pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
36804
        pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
34144
      nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
36805
      nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
34145
      isUnsync = 1;
34146
    }
36806
    }
34147
36807
34148
    /* If this is the first header read from the journal, truncate the
36808
    /* If this is the first header read from the journal, truncate the
 Lines 34164-34175   static int pager_playback(Pager *pPager, Link Here 
34164
        pager_reset(pPager);
36824
        pager_reset(pPager);
34165
        needPagerReset = 0;
36825
        needPagerReset = 0;
34166
      }
36826
      }
34167
      rc = pager_playback_one_page(pPager,1,isUnsync,&pPager->journalOff,0,0);
36827
      rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
34168
      if( rc!=SQLITE_OK ){
36828
      if( rc!=SQLITE_OK ){
34169
        if( rc==SQLITE_DONE ){
36829
        if( rc==SQLITE_DONE ){
34170
          rc = SQLITE_OK;
36830
          rc = SQLITE_OK;
34171
          pPager->journalOff = szJ;
36831
          pPager->journalOff = szJ;
34172
          break;
36832
          break;
36833
        }else if( rc==SQLITE_IOERR_SHORT_READ ){
36834
          /* If the journal has been truncated, simply stop reading and
36835
          ** processing the journal. This might happen if the journal was
36836
          ** not completely written and synced prior to a crash.  In that
36837
          ** case, the database should have never been written in the
36838
          ** first place so it is OK to simply abandon the rollback. */
36839
          rc = SQLITE_OK;
36840
          goto end_playback;
34173
        }else{
36841
        }else{
34174
          /* If we are unable to rollback, quit and return the error
36842
          /* If we are unable to rollback, quit and return the error
34175
          ** code.  This will cause the pager to enter the error state
36843
          ** code.  This will cause the pager to enter the error state
 Lines 34211-34217   end_playback: Link Here 
34211
    rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
36879
    rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
34212
    testcase( rc!=SQLITE_OK );
36880
    testcase( rc!=SQLITE_OK );
34213
  }
36881
  }
34214
  if( rc==SQLITE_OK && pPager->noSync==0 && pPager->state>=PAGER_EXCLUSIVE ){
36882
  if( rc==SQLITE_OK && !pPager->noSync 
36883
   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
36884
  ){
34215
    rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
36885
    rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
34216
  }
36886
  }
34217
  if( rc==SQLITE_OK ){
36887
  if( rc==SQLITE_OK ){
 Lines 34234-34239   end_playback: Link Here 
34234
  return rc;
36904
  return rc;
34235
}
36905
}
34236
36906
36907
36908
/*
36909
** Read the content for page pPg out of the database file and into 
36910
** pPg->pData. A shared lock or greater must be held on the database
36911
** file before this function is called.
36912
**
36913
** If page 1 is read, then the value of Pager.dbFileVers[] is set to
36914
** the value read from the database file.
36915
**
36916
** If an IO error occurs, then the IO error is returned to the caller.
36917
** Otherwise, SQLITE_OK is returned.
36918
*/
36919
static int readDbPage(PgHdr *pPg){
36920
  Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
36921
  Pgno pgno = pPg->pgno;       /* Page number to read */
36922
  int rc = SQLITE_OK;          /* Return code */
36923
  int isInWal = 0;             /* True if page is in log file */
36924
  int pgsz = pPager->pageSize; /* Number of bytes to read */
36925
36926
  assert( pPager->eState>=PAGER_READER && !MEMDB );
36927
  assert( isOpen(pPager->fd) );
36928
36929
  if( NEVER(!isOpen(pPager->fd)) ){
36930
    assert( pPager->tempFile );
36931
    memset(pPg->pData, 0, pPager->pageSize);
36932
    return SQLITE_OK;
36933
  }
36934
36935
  if( pagerUseWal(pPager) ){
36936
    /* Try to pull the page from the write-ahead log. */
36937
    rc = sqlite3WalRead(pPager->pWal, pgno, &isInWal, pgsz, pPg->pData);
36938
  }
36939
  if( rc==SQLITE_OK && !isInWal ){
36940
    i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
36941
    rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
36942
    if( rc==SQLITE_IOERR_SHORT_READ ){
36943
      rc = SQLITE_OK;
36944
    }
36945
  }
36946
36947
  if( pgno==1 ){
36948
    if( rc ){
36949
      /* If the read is unsuccessful, set the dbFileVers[] to something
36950
      ** that will never be a valid file version.  dbFileVers[] is a copy
36951
      ** of bytes 24..39 of the database.  Bytes 28..31 should always be
36952
      ** zero or the size of the database in page. Bytes 32..35 and 35..39
36953
      ** should be page numbers which are never 0xffffffff.  So filling
36954
      ** pPager->dbFileVers[] with all 0xff bytes should suffice.
36955
      **
36956
      ** For an encrypted database, the situation is more complex:  bytes
36957
      ** 24..39 of the database are white noise.  But the probability of
36958
      ** white noising equaling 16 bytes of 0xff is vanishingly small so
36959
      ** we should still be ok.
36960
      */
36961
      memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
36962
    }else{
36963
      u8 *dbFileVers = &((u8*)pPg->pData)[24];
36964
      memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
36965
    }
36966
  }
36967
  CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
36968
36969
  PAGER_INCR(sqlite3_pager_readdb_count);
36970
  PAGER_INCR(pPager->nRead);
36971
  IOTRACE(("PGIN %p %d\n", pPager, pgno));
36972
  PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
36973
               PAGERID(pPager), pgno, pager_pagehash(pPg)));
36974
36975
  return rc;
36976
}
36977
36978
#ifndef SQLITE_OMIT_WAL
36979
/*
36980
** This function is invoked once for each page that has already been 
36981
** written into the log file when a WAL transaction is rolled back.
36982
** Parameter iPg is the page number of said page. The pCtx argument 
36983
** is actually a pointer to the Pager structure.
36984
**
36985
** If page iPg is present in the cache, and has no outstanding references,
36986
** it is discarded. Otherwise, if there are one or more outstanding
36987
** references, the page content is reloaded from the database. If the
36988
** attempt to reload content from the database is required and fails, 
36989
** return an SQLite error code. Otherwise, SQLITE_OK.
36990
*/
36991
static int pagerUndoCallback(void *pCtx, Pgno iPg){
36992
  int rc = SQLITE_OK;
36993
  Pager *pPager = (Pager *)pCtx;
36994
  PgHdr *pPg;
36995
36996
  pPg = sqlite3PagerLookup(pPager, iPg);
36997
  if( pPg ){
36998
    if( sqlite3PcachePageRefcount(pPg)==1 ){
36999
      sqlite3PcacheDrop(pPg);
37000
    }else{
37001
      rc = readDbPage(pPg);
37002
      if( rc==SQLITE_OK ){
37003
        pPager->xReiniter(pPg);
37004
      }
37005
      sqlite3PagerUnref(pPg);
37006
    }
37007
  }
37008
37009
  /* Normally, if a transaction is rolled back, any backup processes are
37010
  ** updated as data is copied out of the rollback journal and into the
37011
  ** database. This is not generally possible with a WAL database, as
37012
  ** rollback involves simply truncating the log file. Therefore, if one
37013
  ** or more frames have already been written to the log (and therefore 
37014
  ** also copied into the backup databases) as part of this transaction,
37015
  ** the backups must be restarted.
37016
  */
37017
  sqlite3BackupRestart(pPager->pBackup);
37018
37019
  return rc;
37020
}
37021
37022
/*
37023
** This function is called to rollback a transaction on a WAL database.
37024
*/
37025
static int pagerRollbackWal(Pager *pPager){
37026
  int rc;                         /* Return Code */
37027
  PgHdr *pList;                   /* List of dirty pages to revert */
37028
37029
  /* For all pages in the cache that are currently dirty or have already
37030
  ** been written (but not committed) to the log file, do one of the 
37031
  ** following:
37032
  **
37033
  **   + Discard the cached page (if refcount==0), or
37034
  **   + Reload page content from the database (if refcount>0).
37035
  */
37036
  pPager->dbSize = pPager->dbOrigSize;
37037
  rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
37038
  pList = sqlite3PcacheDirtyList(pPager->pPCache);
37039
  while( pList && rc==SQLITE_OK ){
37040
    PgHdr *pNext = pList->pDirty;
37041
    rc = pagerUndoCallback((void *)pPager, pList->pgno);
37042
    pList = pNext;
37043
  }
37044
37045
  return rc;
37046
}
37047
37048
/*
37049
** This function is a wrapper around sqlite3WalFrames(). As well as logging
37050
** the contents of the list of pages headed by pList (connected by pDirty),
37051
** this function notifies any active backup processes that the pages have
37052
** changed. 
37053
*/ 
37054
static int pagerWalFrames(
37055
  Pager *pPager,                  /* Pager object */
37056
  PgHdr *pList,                   /* List of frames to log */
37057
  Pgno nTruncate,                 /* Database size after this commit */
37058
  int isCommit,                   /* True if this is a commit */
37059
  int sync_flags                  /* Flags to pass to OsSync() (or 0) */
37060
){
37061
  int rc;                         /* Return code */
37062
37063
  assert( pPager->pWal );
37064
  rc = sqlite3WalFrames(pPager->pWal, 
37065
      pPager->pageSize, pList, nTruncate, isCommit, sync_flags
37066
  );
37067
  if( rc==SQLITE_OK && pPager->pBackup ){
37068
    PgHdr *p;
37069
    for(p=pList; p; p=p->pDirty){
37070
      sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
37071
    }
37072
  }
37073
  return rc;
37074
}
37075
37076
/*
37077
** Begin a read transaction on the WAL.
37078
**
37079
** This routine used to be called "pagerOpenSnapshot()" because it essentially
37080
** makes a snapshot of the database at the current point in time and preserves
37081
** that snapshot for use by the reader in spite of concurrently changes by
37082
** other writers or checkpointers.
37083
*/
37084
static int pagerBeginReadTransaction(Pager *pPager){
37085
  int rc;                         /* Return code */
37086
  int changed = 0;                /* True if cache must be reset */
37087
37088
  assert( pagerUseWal(pPager) );
37089
  assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
37090
37091
  /* sqlite3WalEndReadTransaction() was not called for the previous
37092
  ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
37093
  ** are in locking_mode=NORMAL and EndRead() was previously called,
37094
  ** the duplicate call is harmless.
37095
  */
37096
  sqlite3WalEndReadTransaction(pPager->pWal);
37097
37098
  rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
37099
  if( rc==SQLITE_OK && changed ){
37100
    pager_reset(pPager);
37101
  }
37102
37103
  return rc;
37104
}
37105
37106
/*
37107
** This function is called as part of the transition from PAGER_OPEN
37108
** to PAGER_READER state to determine the size of the database file
37109
** in pages (assuming the page size currently stored in Pager.pageSize).
37110
**
37111
** If no error occurs, SQLITE_OK is returned and the size of the database
37112
** in pages is stored in *pnPage. Otherwise, an error code (perhaps
37113
** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
37114
*/
37115
static int pagerPagecount(Pager *pPager, Pgno *pnPage){
37116
  Pgno nPage;                     /* Value to return via *pnPage */
37117
37118
  /* Query the WAL sub-system for the database size. The WalDbsize()
37119
  ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
37120
  ** if the database size is not available. The database size is not
37121
  ** available from the WAL sub-system if the log file is empty or
37122
  ** contains no valid committed transactions.
37123
  */
37124
  assert( pPager->eState==PAGER_OPEN );
37125
  assert( pPager->eLock>=SHARED_LOCK || pPager->noReadlock );
37126
  nPage = sqlite3WalDbsize(pPager->pWal);
37127
37128
  /* If the database size was not available from the WAL sub-system,
37129
  ** determine it based on the size of the database file. If the size
37130
  ** of the database file is not an integer multiple of the page-size,
37131
  ** round down to the nearest page. Except, any file larger than 0
37132
  ** bytes in size is considered to contain at least one page.
37133
  */
37134
  if( nPage==0 ){
37135
    i64 n = 0;                    /* Size of db file in bytes */
37136
    assert( isOpen(pPager->fd) || pPager->tempFile );
37137
    if( isOpen(pPager->fd) ){
37138
      int rc = sqlite3OsFileSize(pPager->fd, &n);
37139
      if( rc!=SQLITE_OK ){
37140
        return rc;
37141
      }
37142
    }
37143
    nPage = (Pgno)(n / pPager->pageSize);
37144
    if( nPage==0 && n>0 ){
37145
      nPage = 1;
37146
    }
37147
  }
37148
37149
  /* If the current number of pages in the file is greater than the
37150
  ** configured maximum pager number, increase the allowed limit so
37151
  ** that the file can be read.
37152
  */
37153
  if( nPage>pPager->mxPgno ){
37154
    pPager->mxPgno = (Pgno)nPage;
37155
  }
37156
37157
  *pnPage = nPage;
37158
  return SQLITE_OK;
37159
}
37160
37161
37162
/*
37163
** Check if the *-wal file that corresponds to the database opened by pPager
37164
** exists if the database is not empy, or verify that the *-wal file does
37165
** not exist (by deleting it) if the database file is empty.
37166
**
37167
** If the database is not empty and the *-wal file exists, open the pager
37168
** in WAL mode.  If the database is empty or if no *-wal file exists and
37169
** if no error occurs, make sure Pager.journalMode is not set to
37170
** PAGER_JOURNALMODE_WAL.
37171
**
37172
** Return SQLITE_OK or an error code.
37173
**
37174
** The caller must hold a SHARED lock on the database file to call this
37175
** function. Because an EXCLUSIVE lock on the db file is required to delete 
37176
** a WAL on a none-empty database, this ensures there is no race condition 
37177
** between the xAccess() below and an xDelete() being executed by some 
37178
** other connection.
37179
*/
37180
static int pagerOpenWalIfPresent(Pager *pPager){
37181
  int rc = SQLITE_OK;
37182
  assert( pPager->eState==PAGER_OPEN );
37183
  assert( pPager->eLock>=SHARED_LOCK || pPager->noReadlock );
37184
37185
  if( !pPager->tempFile ){
37186
    int isWal;                    /* True if WAL file exists */
37187
    Pgno nPage;                   /* Size of the database file */
37188
37189
    rc = pagerPagecount(pPager, &nPage);
37190
    if( rc ) return rc;
37191
    if( nPage==0 ){
37192
      rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
37193
      isWal = 0;
37194
    }else{
37195
      rc = sqlite3OsAccess(
37196
          pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
37197
      );
37198
    }
37199
    if( rc==SQLITE_OK ){
37200
      if( isWal ){
37201
        testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
37202
        rc = sqlite3PagerOpenWal(pPager, 0);
37203
      }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
37204
        pPager->journalMode = PAGER_JOURNALMODE_DELETE;
37205
      }
37206
    }
37207
  }
37208
  return rc;
37209
}
37210
#endif
37211
34237
/*
37212
/*
34238
** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
37213
** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
34239
** the entire master journal file. The case pSavepoint==NULL occurs when 
37214
** the entire master journal file. The case pSavepoint==NULL occurs when 
 Lines 34276-34282   static int pagerPlaybackSavepoint(Pager Link Here 
34276
  int rc = SQLITE_OK;      /* Return code */
37251
  int rc = SQLITE_OK;      /* Return code */
34277
  Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
37252
  Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
34278
37253
34279
  assert( pPager->state>=PAGER_SHARED );
37254
  assert( pPager->eState!=PAGER_ERROR );
37255
  assert( pPager->eState>=PAGER_WRITER_LOCKED );
34280
37256
34281
  /* Allocate a bitvec to use to store the set of pages rolled back */
37257
  /* Allocate a bitvec to use to store the set of pages rolled back */
34282
  if( pSavepoint ){
37258
  if( pSavepoint ){
 Lines 34290-34295   static int pagerPlaybackSavepoint(Pager Link Here 
34290
  ** being reverted was opened.
37266
  ** being reverted was opened.
34291
  */
37267
  */
34292
  pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
37268
  pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
37269
  pPager->changeCountDone = pPager->tempFile;
37270
37271
  if( !pSavepoint && pagerUseWal(pPager) ){
37272
    return pagerRollbackWal(pPager);
37273
  }
34293
37274
34294
  /* Use pPager->journalOff as the effective size of the main rollback
37275
  /* Use pPager->journalOff as the effective size of the main rollback
34295
  ** journal.  The actual file might be larger than this in
37276
  ** journal.  The actual file might be larger than this in
 Lines 34297-34302   static int pagerPlaybackSavepoint(Pager Link Here 
34297
  ** past pPager->journalOff is off-limits to us.
37278
  ** past pPager->journalOff is off-limits to us.
34298
  */
37279
  */
34299
  szJ = pPager->journalOff;
37280
  szJ = pPager->journalOff;
37281
  assert( pagerUseWal(pPager)==0 || szJ==0 );
34300
37282
34301
  /* Begin by rolling back records from the main journal starting at
37283
  /* Begin by rolling back records from the main journal starting at
34302
  ** PagerSavepoint.iOffset and continuing to the next journal header.
37284
  ** PagerSavepoint.iOffset and continuing to the next journal header.
 Lines 34305-34315   static int pagerPlaybackSavepoint(Pager Link Here 
34305
  ** will be skipped automatically.  Pages are added to pDone as they
37287
  ** will be skipped automatically.  Pages are added to pDone as they
34306
  ** are played back.
37288
  ** are played back.
34307
  */
37289
  */
34308
  if( pSavepoint ){
37290
  if( pSavepoint && !pagerUseWal(pPager) ){
34309
    iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
37291
    iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
34310
    pPager->journalOff = pSavepoint->iOffset;
37292
    pPager->journalOff = pSavepoint->iOffset;
34311
    while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
37293
    while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
34312
      rc = pager_playback_one_page(pPager, 1, 0, &pPager->journalOff, 1, pDone);
37294
      rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
34313
    }
37295
    }
34314
    assert( rc!=SQLITE_DONE );
37296
    assert( rc!=SQLITE_DONE );
34315
  }else{
37297
  }else{
 Lines 34339-34349   static int pagerPlaybackSavepoint(Pager Link Here 
34339
      nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
37321
      nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
34340
    }
37322
    }
34341
    for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
37323
    for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
34342
      rc = pager_playback_one_page(pPager, 1, 0, &pPager->journalOff, 1, pDone);
37324
      rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
34343
    }
37325
    }
34344
    assert( rc!=SQLITE_DONE );
37326
    assert( rc!=SQLITE_DONE );
34345
  }
37327
  }
34346
  assert( rc!=SQLITE_OK || pPager->journalOff==szJ );
37328
  assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
34347
37329
34348
  /* Finally,  rollback pages from the sub-journal.  Page that were
37330
  /* Finally,  rollback pages from the sub-journal.  Page that were
34349
  ** previously rolled back out of the main journal (and are hence in pDone)
37331
  ** previously rolled back out of the main journal (and are hence in pDone)
 Lines 34352-34360   static int pagerPlaybackSavepoint(Pager Link Here 
34352
  if( pSavepoint ){
37334
  if( pSavepoint ){
34353
    u32 ii;            /* Loop counter */
37335
    u32 ii;            /* Loop counter */
34354
    i64 offset = pSavepoint->iSubRec*(4+pPager->pageSize);
37336
    i64 offset = pSavepoint->iSubRec*(4+pPager->pageSize);
37337
37338
    if( pagerUseWal(pPager) ){
37339
      rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
37340
    }
34355
    for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
37341
    for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
34356
      assert( offset==ii*(4+pPager->pageSize) );
37342
      assert( offset==ii*(4+pPager->pageSize) );
34357
      rc = pager_playback_one_page(pPager, 0, 0, &offset, 1, pDone);
37343
      rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
34358
    }
37344
    }
34359
    assert( rc!=SQLITE_DONE );
37345
    assert( rc!=SQLITE_DONE );
34360
  }
37346
  }
 Lines 34363-34368   static int pagerPlaybackSavepoint(Pager Link Here 
34363
  if( rc==SQLITE_OK ){
37349
  if( rc==SQLITE_OK ){
34364
    pPager->journalOff = szJ;
37350
    pPager->journalOff = szJ;
34365
  }
37351
  }
37352
34366
  return rc;
37353
  return rc;
34367
}
37354
}
34368
37355
 Lines 34404-34410   SQLITE_PRIVATE void sqlite3PagerSetSafet Link Here 
34404
  pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
37391
  pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
34405
  pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
37392
  pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
34406
  pPager->sync_flags = (bFullFsync?SQLITE_SYNC_FULL:SQLITE_SYNC_NORMAL);
37393
  pPager->sync_flags = (bFullFsync?SQLITE_SYNC_FULL:SQLITE_SYNC_NORMAL);
34407
  if( pPager->noSync ) pPager->needSync = 0;
34408
}
37394
}
34409
#endif
37395
#endif
34410
37396
 Lines 34481-34507   SQLITE_PRIVATE void sqlite3PagerSetBusyh Link Here 
34481
}
37467
}
34482
37468
34483
/*
37469
/*
34484
** Report the current page size and number of reserved bytes back
34485
** to the codec.
34486
*/
34487
#ifdef SQLITE_HAS_CODEC
34488
static void pagerReportSize(Pager *pPager){
34489
  if( pPager->xCodecSizeChng ){
34490
    pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
34491
                           (int)pPager->nReserve);
34492
  }
34493
}
34494
#else
34495
# define pagerReportSize(X)     /* No-op if we do not support a codec */
34496
#endif
34497
34498
/*
34499
** Change the page size used by the Pager object. The new page size 
37470
** Change the page size used by the Pager object. The new page size 
34500
** is passed in *pPageSize.
37471
** is passed in *pPageSize.
34501
**
37472
**
34502
** If the pager is in the error state when this function is called, it
37473
** If the pager is in the error state when this function is called, it
34503
** is a no-op. The value returned is the error state error code (i.e. 
37474
** is a no-op. The value returned is the error state error code (i.e. 
34504
** one of SQLITE_IOERR, SQLITE_CORRUPT or SQLITE_FULL).
37475
** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
34505
**
37476
**
34506
** Otherwise, if all of the following are true:
37477
** Otherwise, if all of the following are true:
34507
**
37478
**
 Lines 34525-34552   static void pagerReportSize(Pager *pPage Link Here 
34525
** function was called, or because the memory allocation attempt failed, 
37496
** function was called, or because the memory allocation attempt failed, 
34526
** then *pPageSize is set to the old, retained page size before returning.
37497
** then *pPageSize is set to the old, retained page size before returning.
34527
*/
37498
*/
34528
SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u16 *pPageSize, int nReserve){
37499
SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
34529
  int rc = pPager->errCode;
37500
  int rc = SQLITE_OK;
34530
37501
37502
  /* It is not possible to do a full assert_pager_state() here, as this
37503
  ** function may be called from within PagerOpen(), before the state
37504
  ** of the Pager object is internally consistent.
37505
  **
37506
  ** At one point this function returned an error if the pager was in 
37507
  ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
37508
  ** there is at least one outstanding page reference, this function
37509
  ** is a no-op for that case anyhow.
37510
  */
37511
37512
  u32 pageSize = *pPageSize;
37513
  assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
37514
  if( (pPager->memDb==0 || pPager->dbSize==0)
37515
   && sqlite3PcacheRefCount(pPager->pPCache)==0 
37516
   && pageSize && pageSize!=(u32)pPager->pageSize 
37517
  ){
37518
    char *pNew = NULL;             /* New temp space */
37519
    i64 nByte = 0;
37520
37521
    if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
37522
      rc = sqlite3OsFileSize(pPager->fd, &nByte);
37523
    }
37524
    if( rc==SQLITE_OK ){
37525
      pNew = (char *)sqlite3PageMalloc(pageSize);
37526
      if( !pNew ) rc = SQLITE_NOMEM;
37527
    }
37528
37529
    if( rc==SQLITE_OK ){
37530
      pager_reset(pPager);
37531
      pPager->dbSize = (Pgno)(nByte/pageSize);
37532
      pPager->pageSize = pageSize;
37533
      sqlite3PageFree(pPager->pTmpSpace);
37534
      pPager->pTmpSpace = pNew;
37535
      sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
37536
    }
37537
  }
37538
37539
  *pPageSize = pPager->pageSize;
34531
  if( rc==SQLITE_OK ){
37540
  if( rc==SQLITE_OK ){
34532
    u16 pageSize = *pPageSize;
34533
    assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
34534
    if( (pPager->memDb==0 || pPager->dbSize==0)
34535
     && sqlite3PcacheRefCount(pPager->pPCache)==0 
34536
     && pageSize && pageSize!=pPager->pageSize 
34537
    ){
34538
      char *pNew = (char *)sqlite3PageMalloc(pageSize);
34539
      if( !pNew ){
34540
        rc = SQLITE_NOMEM;
34541
      }else{
34542
        pager_reset(pPager);
34543
        pPager->pageSize = pageSize;
34544
        sqlite3PageFree(pPager->pTmpSpace);
34545
        pPager->pTmpSpace = pNew;
34546
        sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
34547
      }
34548
    }
34549
    *pPageSize = (u16)pPager->pageSize;
34550
    if( nReserve<0 ) nReserve = pPager->nReserve;
37541
    if( nReserve<0 ) nReserve = pPager->nReserve;
34551
    assert( nReserve>=0 && nReserve<1000 );
37542
    assert( nReserve>=0 && nReserve<1000 );
34552
    pPager->nReserve = (i16)nReserve;
37543
    pPager->nReserve = (i16)nReserve;
 Lines 34578-34584   SQLITE_PRIVATE int sqlite3PagerMaxPageCo Link Here 
34578
  if( mxPage>0 ){
37569
  if( mxPage>0 ){
34579
    pPager->mxPgno = mxPage;
37570
    pPager->mxPgno = mxPage;
34580
  }
37571
  }
34581
  sqlite3PagerPagecount(pPager, 0);
37572
  if( pPager->eState!=PAGER_OPEN && pPager->mxPgno<pPager->dbSize ){
37573
    pPager->mxPgno = pPager->dbSize;
37574
  }
34582
  return pPager->mxPgno;
37575
  return pPager->mxPgno;
34583
}
37576
}
34584
37577
 Lines 34624-34629   SQLITE_PRIVATE int sqlite3PagerReadFileh Link Here 
34624
  int rc = SQLITE_OK;
37617
  int rc = SQLITE_OK;
34625
  memset(pDest, 0, N);
37618
  memset(pDest, 0, N);
34626
  assert( isOpen(pPager->fd) || pPager->tempFile );
37619
  assert( isOpen(pPager->fd) || pPager->tempFile );
37620
37621
  /* This routine is only called by btree immediately after creating
37622
  ** the Pager object.  There has not been an opportunity to transition
37623
  ** to WAL mode yet.
37624
  */
37625
  assert( !pagerUseWal(pPager) );
37626
34627
  if( isOpen(pPager->fd) ){
37627
  if( isOpen(pPager->fd) ){
34628
    IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
37628
    IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
34629
    rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
37629
    rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
 Lines 34635-34699   SQLITE_PRIVATE int sqlite3PagerReadFileh Link Here 
34635
}
37635
}
34636
37636
34637
/*
37637
/*
34638
** Return the total number of pages in the database file associated 
37638
** This function may only be called when a read-transaction is open on
34639
** with pPager. Normally, this is calculated as (<db file size>/<page-size>).
37639
** the pager. It returns the total number of pages in the database.
37640
**
34640
** However, if the file is between 1 and <page-size> bytes in size, then 
37641
** However, if the file is between 1 and <page-size> bytes in size, then 
34641
** this is considered a 1 page file.
37642
** this is considered a 1 page file.
34642
**
37643
*/
34643
** If the pager is in error state when this function is called, then the
37644
SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
34644
** error state error code is returned and *pnPage left unchanged. Or,
37645
  assert( pPager->eState>=PAGER_READER );
34645
** if the file system has to be queried for the size of the file and
37646
  assert( pPager->eState!=PAGER_WRITER_FINISHED );
34646
** the query attempt returns an IO error, the IO error code is returned
37647
  *pnPage = (int)pPager->dbSize;
34647
** and *pnPage is left unchanged.
34648
**
34649
** Otherwise, if everything is successful, then SQLITE_OK is returned
34650
** and *pnPage is set to the number of pages in the database.
34651
*/
34652
SQLITE_PRIVATE int sqlite3PagerPagecount(Pager *pPager, int *pnPage){
34653
  Pgno nPage;               /* Value to return via *pnPage */
34654
34655
  /* If the pager is already in the error state, return the error code. */
34656
  if( pPager->errCode ){
34657
    return pPager->errCode;
34658
  }
34659
34660
  /* Determine the number of pages in the file. Store this in nPage. */
34661
  if( pPager->dbSizeValid ){
34662
    nPage = pPager->dbSize;
34663
  }else{
34664
    int rc;                 /* Error returned by OsFileSize() */
34665
    i64 n = 0;              /* File size in bytes returned by OsFileSize() */
34666
34667
    assert( isOpen(pPager->fd) || pPager->tempFile );
34668
    if( isOpen(pPager->fd) && (0 != (rc = sqlite3OsFileSize(pPager->fd, &n))) ){
34669
      pager_error(pPager, rc);
34670
      return rc;
34671
    }
34672
    if( n>0 && n<pPager->pageSize ){
34673
      nPage = 1;
34674
    }else{
34675
      nPage = (Pgno)(n / pPager->pageSize);
34676
    }
34677
    if( pPager->state!=PAGER_UNLOCK ){
34678
      pPager->dbSize = nPage;
34679
      pPager->dbFileSize = nPage;
34680
      pPager->dbSizeValid = 1;
34681
    }
34682
  }
34683
34684
  /* If the current number of pages in the file is greater than the 
34685
  ** configured maximum pager number, increase the allowed limit so
34686
  ** that the file can be read.
34687
  */
34688
  if( nPage>pPager->mxPgno ){
34689
    pPager->mxPgno = (Pgno)nPage;
34690
  }
34691
34692
  /* Set the output variable and return SQLITE_OK */
34693
  if( pnPage ){
34694
    *pnPage = nPage;
34695
  }
34696
  return SQLITE_OK;
34697
}
37648
}
34698
37649
34699
37650
 Lines 34714-34751   SQLITE_PRIVATE int sqlite3PagerPagecount Link Here 
34714
static int pager_wait_on_lock(Pager *pPager, int locktype){
37665
static int pager_wait_on_lock(Pager *pPager, int locktype){
34715
  int rc;                              /* Return code */
37666
  int rc;                              /* Return code */
34716
37667
34717
  /* The OS lock values must be the same as the Pager lock values */
34718
  assert( PAGER_SHARED==SHARED_LOCK );
34719
  assert( PAGER_RESERVED==RESERVED_LOCK );
34720
  assert( PAGER_EXCLUSIVE==EXCLUSIVE_LOCK );
34721
34722
  /* If the file is currently unlocked then the size must be unknown. It
34723
  ** must not have been modified at this point.
34724
  */
34725
  assert( pPager->state>=PAGER_SHARED || pPager->dbSizeValid==0 );
34726
  assert( pPager->state>=PAGER_SHARED || pPager->dbModified==0 );
34727
34728
  /* Check that this is either a no-op (because the requested lock is 
37668
  /* Check that this is either a no-op (because the requested lock is 
34729
  ** already held, or one of the transistions that the busy-handler
37669
  ** already held, or one of the transistions that the busy-handler
34730
  ** may be invoked during, according to the comment above
37670
  ** may be invoked during, according to the comment above
34731
  ** sqlite3PagerSetBusyhandler().
37671
  ** sqlite3PagerSetBusyhandler().
34732
  */
37672
  */
34733
  assert( (pPager->state>=locktype)
37673
  assert( (pPager->eLock>=locktype)
34734
       || (pPager->state==PAGER_UNLOCK && locktype==PAGER_SHARED)
37674
       || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
34735
       || (pPager->state==PAGER_RESERVED && locktype==PAGER_EXCLUSIVE)
37675
       || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
34736
  );
37676
  );
34737
37677
34738
  if( pPager->state>=locktype ){
37678
  do {
34739
    rc = SQLITE_OK;
37679
    rc = pagerLockDb(pPager, locktype);
34740
  }else{
37680
  }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
34741
    do {
34742
      rc = sqlite3OsLock(pPager->fd, locktype);
34743
    }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
34744
    if( rc==SQLITE_OK ){
34745
      pPager->state = (u8)locktype;
34746
      IOTRACE(("LOCK %p %d\n", pPager, locktype))
34747
    }
34748
  }
34749
  return rc;
37681
  return rc;
34750
}
37682
}
34751
37683
 Lines 34790-34802   static void assertTruncateConstraint(Pag Link Here 
34790
** truncation will be done when the current transaction is committed.
37722
** truncation will be done when the current transaction is committed.
34791
*/
37723
*/
34792
SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
37724
SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
34793
  assert( pPager->dbSizeValid );
34794
  assert( pPager->dbSize>=nPage );
37725
  assert( pPager->dbSize>=nPage );
34795
  assert( pPager->state>=PAGER_RESERVED );
37726
  assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
34796
  pPager->dbSize = nPage;
37727
  pPager->dbSize = nPage;
34797
  assertTruncateConstraint(pPager);
37728
  assertTruncateConstraint(pPager);
34798
}
37729
}
34799
37730
37731
37732
/*
37733
** This function is called before attempting a hot-journal rollback. It
37734
** syncs the journal file to disk, then sets pPager->journalHdr to the
37735
** size of the journal file so that the pager_playback() routine knows
37736
** that the entire journal file has been synced.
37737
**
37738
** Syncing a hot-journal to disk before attempting to roll it back ensures 
37739
** that if a power-failure occurs during the rollback, the process that
37740
** attempts rollback following system recovery sees the same journal
37741
** content as this process.
37742
**
37743
** If everything goes as planned, SQLITE_OK is returned. Otherwise, 
37744
** an SQLite error code.
37745
*/
37746
static int pagerSyncHotJournal(Pager *pPager){
37747
  int rc = SQLITE_OK;
37748
  if( !pPager->noSync ){
37749
    rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
37750
  }
37751
  if( rc==SQLITE_OK ){
37752
    rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
37753
  }
37754
  return rc;
37755
}
37756
34800
/*
37757
/*
34801
** Shutdown the page cache.  Free all memory and close all files.
37758
** Shutdown the page cache.  Free all memory and close all files.
34802
**
37759
**
 Lines 34812-34840   SQLITE_PRIVATE void sqlite3PagerTruncate Link Here 
34812
** to the caller.
37769
** to the caller.
34813
*/
37770
*/
34814
SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
37771
SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
37772
  u8 *pTmp = (u8 *)pPager->pTmpSpace;
37773
34815
  disable_simulated_io_errors();
37774
  disable_simulated_io_errors();
34816
  sqlite3BeginBenignMalloc();
37775
  sqlite3BeginBenignMalloc();
34817
  pPager->errCode = 0;
37776
  /* pPager->errCode = 0; */
34818
  pPager->exclusiveMode = 0;
37777
  pPager->exclusiveMode = 0;
37778
#ifndef SQLITE_OMIT_WAL
37779
  sqlite3WalClose(pPager->pWal,
37780
    (pPager->noSync ? 0 : pPager->sync_flags), 
37781
    pPager->pageSize, pTmp
37782
  );
37783
  pPager->pWal = 0;
37784
#endif
34819
  pager_reset(pPager);
37785
  pager_reset(pPager);
34820
  if( MEMDB ){
37786
  if( MEMDB ){
34821
    pager_unlock(pPager);
37787
    pager_unlock(pPager);
34822
  }else{
37788
  }else{
34823
    /* Set Pager.journalHdr to -1 for the benefit of the pager_playback() 
37789
    /* If it is open, sync the journal file before calling UnlockAndRollback.
34824
    ** call which may be made from within pagerUnlockAndRollback(). If it
37790
    ** If this is not done, then an unsynced portion of the open journal 
34825
    ** is not -1, then the unsynced portion of an open journal file may
37791
    ** file may be played back into the database. If a power failure occurs 
34826
    ** be played back into the database. If a power failure occurs while
37792
    ** while this is happening, the database could become corrupt.
34827
    ** this is happening, the database may become corrupt.
37793
    **
34828
    */
37794
    ** If an error occurs while trying to sync the journal, shift the pager
34829
    pPager->journalHdr = -1;
37795
    ** into the ERROR state. This causes UnlockAndRollback to unlock the
37796
    ** database and close the journal file without attempting to roll it
37797
    ** back or finalize it. The next database user will have to do hot-journal
37798
    ** rollback before accessing the database file.
37799
    */
37800
    if( isOpen(pPager->jfd) ){
37801
      pager_error(pPager, pagerSyncHotJournal(pPager));
37802
    }
34830
    pagerUnlockAndRollback(pPager);
37803
    pagerUnlockAndRollback(pPager);
34831
  }
37804
  }
34832
  sqlite3EndBenignMalloc();
37805
  sqlite3EndBenignMalloc();
34833
  enable_simulated_io_errors();
37806
  enable_simulated_io_errors();
34834
  PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
37807
  PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
34835
  IOTRACE(("CLOSE %p\n", pPager))
37808
  IOTRACE(("CLOSE %p\n", pPager))
37809
  sqlite3OsClose(pPager->jfd);
34836
  sqlite3OsClose(pPager->fd);
37810
  sqlite3OsClose(pPager->fd);
34837
  sqlite3PageFree(pPager->pTmpSpace);
37811
  sqlite3PageFree(pTmp);
34838
  sqlite3PcacheClose(pPager->pPCache);
37812
  sqlite3PcacheClose(pPager->pPCache);
34839
37813
34840
#ifdef SQLITE_HAS_CODEC
37814
#ifdef SQLITE_HAS_CODEC
 Lines 34869-34877   SQLITE_PRIVATE void sqlite3PagerRef(DbPa Link Here 
34869
** been written to the journal have actually reached the surface of the
37843
** been written to the journal have actually reached the surface of the
34870
** disk and can be restored in the event of a hot-journal rollback.
37844
** disk and can be restored in the event of a hot-journal rollback.
34871
**
37845
**
34872
** If the Pager.needSync flag is not set, then this function is a
37846
** If the Pager.noSync flag is set, then this function is a no-op.
34873
** no-op. Otherwise, the actions required depend on the journal-mode
37847
** Otherwise, the actions required depend on the journal-mode and the 
34874
** and the device characteristics of the the file-system, as follows:
37848
** device characteristics of the the file-system, as follows:
34875
**
37849
**
34876
**   * If the journal file is an in-memory journal file, no action need
37850
**   * If the journal file is an in-memory journal file, no action need
34877
**     be taken.
37851
**     be taken.
 Lines 34895-34912   SQLITE_PRIVATE void sqlite3PagerRef(DbPa Link Here 
34895
**     if( NOT SEQUENTIAL ) xSync(<journal file>);
37869
**     if( NOT SEQUENTIAL ) xSync(<journal file>);
34896
**   }
37870
**   }
34897
**
37871
**
34898
** The Pager.needSync flag is never be set for temporary files, or any
34899
** file operating in no-sync mode (Pager.noSync set to non-zero).
34900
**
34901
** If successful, this routine clears the PGHDR_NEED_SYNC flag of every 
37872
** If successful, this routine clears the PGHDR_NEED_SYNC flag of every 
34902
** page currently held in memory before returning SQLITE_OK. If an IO
37873
** page currently held in memory before returning SQLITE_OK. If an IO
34903
** error is encountered, then the IO error code is returned to the caller.
37874
** error is encountered, then the IO error code is returned to the caller.
34904
*/
37875
*/
34905
static int syncJournal(Pager *pPager){
37876
static int syncJournal(Pager *pPager, int newHdr){
34906
  if( pPager->needSync ){
37877
  int rc;                         /* Return code */
37878
37879
  assert( pPager->eState==PAGER_WRITER_CACHEMOD
37880
       || pPager->eState==PAGER_WRITER_DBMOD
37881
  );
37882
  assert( assert_pager_state(pPager) );
37883
  assert( !pagerUseWal(pPager) );
37884
37885
  rc = sqlite3PagerExclusiveLock(pPager);
37886
  if( rc!=SQLITE_OK ) return rc;
37887
37888
  if( !pPager->noSync ){
34907
    assert( !pPager->tempFile );
37889
    assert( !pPager->tempFile );
34908
    if( pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
37890
    if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
34909
      int rc;                              /* Return code */
34910
      const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
37891
      const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
34911
      assert( isOpen(pPager->jfd) );
37892
      assert( isOpen(pPager->jfd) );
34912
37893
 Lines 34916-34922   static int syncJournal(Pager *pPager){ Link Here 
34916
        ** mode, then the journal file may at this point actually be larger
37897
        ** mode, then the journal file may at this point actually be larger
34917
        ** than Pager.journalOff bytes. If the next thing in the journal
37898
        ** than Pager.journalOff bytes. If the next thing in the journal
34918
        ** file happens to be a journal-header (written as part of the
37899
        ** file happens to be a journal-header (written as part of the
34919
        ** previous connections transaction), and a crash or power-failure 
37900
        ** previous connection's transaction), and a crash or power-failure 
34920
        ** occurs after nRec is updated but before this connection writes 
37901
        ** occurs after nRec is updated but before this connection writes 
34921
        ** anything else to the journal file (or commits/rolls back its 
37902
        ** anything else to the journal file (or commits/rolls back its 
34922
        ** transaction), then SQLite may become confused when doing the 
37903
        ** transaction), then SQLite may become confused when doing the 
 Lines 34935-34944   static int syncJournal(Pager *pPager){ Link Here 
34935
        */
37916
        */
34936
        i64 iNextHdrOffset;
37917
        i64 iNextHdrOffset;
34937
        u8 aMagic[8];
37918
        u8 aMagic[8];
34938
	u8 zHeader[sizeof(aJournalMagic)+4];
37919
        u8 zHeader[sizeof(aJournalMagic)+4];
34939
37920
34940
	memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
37921
        memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
34941
	put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
37922
        put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
34942
37923
34943
        iNextHdrOffset = journalHdrOffset(pPager);
37924
        iNextHdrOffset = journalHdrOffset(pPager);
34944
        rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
37925
        rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
 Lines 34970-34976   static int syncJournal(Pager *pPager){ Link Here 
34970
        IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
37951
        IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
34971
        rc = sqlite3OsWrite(
37952
        rc = sqlite3OsWrite(
34972
            pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
37953
            pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
34973
	);
37954
        );
34974
        if( rc!=SQLITE_OK ) return rc;
37955
        if( rc!=SQLITE_OK ) return rc;
34975
      }
37956
      }
34976
      if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
37957
      if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
 Lines 34981-34996   static int syncJournal(Pager *pPager){ Link Here 
34981
        );
37962
        );
34982
        if( rc!=SQLITE_OK ) return rc;
37963
        if( rc!=SQLITE_OK ) return rc;
34983
      }
37964
      }
34984
    }
37965
34985
37966
      pPager->journalHdr = pPager->journalOff;
34986
    /* The journal file was just successfully synced. Set Pager.needSync 
37967
      if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
34987
    ** to zero and clear the PGHDR_NEED_SYNC flag on all pagess.
37968
        pPager->nRec = 0;
34988
    */
37969
        rc = writeJournalHdr(pPager);
34989
    pPager->needSync = 0;
37970
        if( rc!=SQLITE_OK ) return rc;
34990
    pPager->journalStarted = 1;
37971
      }
34991
    sqlite3PcacheClearSyncFlags(pPager->pPCache);
37972
    }else{
34992
  }
37973
      pPager->journalHdr = pPager->journalOff;
34993
37974
    }
37975
  }
37976
37977
  /* Unless the pager is in noSync mode, the journal file was just 
37978
  ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on 
37979
  ** all pages.
37980
  */
37981
  sqlite3PcacheClearSyncFlags(pPager->pPCache);
37982
  pPager->eState = PAGER_WRITER_DBMOD;
37983
  assert( assert_pager_state(pPager) );
34994
  return SQLITE_OK;
37984
  return SQLITE_OK;
34995
}
37985
}
34996
37986
 Lines 35026-35056   static int syncJournal(Pager *pPager){ Link Here 
35026
** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
38016
** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
35027
** be obtained, SQLITE_BUSY is returned.
38017
** be obtained, SQLITE_BUSY is returned.
35028
*/
38018
*/
35029
static int pager_write_pagelist(PgHdr *pList){
38019
static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
35030
  Pager *pPager;                       /* Pager object */
38020
  int rc = SQLITE_OK;                  /* Return code */
35031
  int rc;                              /* Return code */
38021
35032
38022
  /* This function is only called for rollback pagers in WRITER_DBMOD state. */
35033
  if( NEVER(pList==0) ) return SQLITE_OK;
38023
  assert( !pagerUseWal(pPager) );
35034
  pPager = pList->pPager;
38024
  assert( pPager->eState==PAGER_WRITER_DBMOD );
35035
38025
  assert( pPager->eLock==EXCLUSIVE_LOCK );
35036
  /* At this point there may be either a RESERVED or EXCLUSIVE lock on the
35037
  ** database file. If there is already an EXCLUSIVE lock, the following
35038
  ** call is a no-op.
35039
  **
35040
  ** Moving the lock from RESERVED to EXCLUSIVE actually involves going
35041
  ** through an intermediate state PENDING.   A PENDING lock prevents new
35042
  ** readers from attaching to the database but is unsufficient for us to
35043
  ** write.  The idea of a PENDING lock is to prevent new readers from
35044
  ** coming in while we wait for existing readers to clear.
35045
  **
35046
  ** While the pager is in the RESERVED state, the original database file
35047
  ** is unchanged and we can rollback without having to playback the
35048
  ** journal into the original database file.  Once we transition to
35049
  ** EXCLUSIVE, it means the database file has been changed and any rollback
35050
  ** will require a journal playback.
35051
  */
35052
  assert( pPager->state>=PAGER_RESERVED );
35053
  rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
35054
38026
35055
  /* If the file is a temp-file has not yet been opened, open it now. It
38027
  /* If the file is a temp-file has not yet been opened, open it now. It
35056
  ** is not possible for rc to be other than SQLITE_OK if this branch
38028
  ** is not possible for rc to be other than SQLITE_OK if this branch
 Lines 35061-35066   static int pager_write_pagelist(PgHdr *p Link Here 
35061
    rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
38033
    rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
35062
  }
38034
  }
35063
38035
38036
  /* Before the first write, give the VFS a hint of what the final
38037
  ** file size will be.
38038
  */
38039
  assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
38040
  if( rc==SQLITE_OK && pPager->dbSize>pPager->dbHintSize ){
38041
    sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
38042
    sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
38043
    pPager->dbHintSize = pPager->dbSize;
38044
  }
38045
35064
  while( rc==SQLITE_OK && pList ){
38046
  while( rc==SQLITE_OK && pList ){
35065
    Pgno pgno = pList->pgno;
38047
    Pgno pgno = pList->pgno;
35066
38048
 Lines 35076-35081   static int pager_write_pagelist(PgHdr *p Link Here 
35076
      i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
38058
      i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
35077
      char *pData;                                   /* Data to write */    
38059
      char *pData;                                   /* Data to write */    
35078
38060
38061
      assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
38062
35079
      /* Encode the database */
38063
      /* Encode the database */
35080
      CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
38064
      CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
35081
38065
 Lines 35114-35119   static int pager_write_pagelist(PgHdr *p Link Here 
35114
}
38098
}
35115
38099
35116
/*
38100
/*
38101
** Ensure that the sub-journal file is open. If it is already open, this 
38102
** function is a no-op.
38103
**
38104
** SQLITE_OK is returned if everything goes according to plan. An 
38105
** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen() 
38106
** fails.
38107
*/
38108
static int openSubJournal(Pager *pPager){
38109
  int rc = SQLITE_OK;
38110
  if( !isOpen(pPager->sjfd) ){
38111
    if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
38112
      sqlite3MemJournalOpen(pPager->sjfd);
38113
    }else{
38114
      rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
38115
    }
38116
  }
38117
  return rc;
38118
}
38119
38120
/*
35117
** Append a record of the current state of page pPg to the sub-journal. 
38121
** Append a record of the current state of page pPg to the sub-journal. 
35118
** It is the callers responsibility to use subjRequiresPage() to check 
38122
** It is the callers responsibility to use subjRequiresPage() to check 
35119
** that it is really required before calling this function.
38123
** that it is really required before calling this function.
 Lines 35129-35146   static int pager_write_pagelist(PgHdr *p Link Here 
35129
static int subjournalPage(PgHdr *pPg){
38133
static int subjournalPage(PgHdr *pPg){
35130
  int rc = SQLITE_OK;
38134
  int rc = SQLITE_OK;
35131
  Pager *pPager = pPg->pPager;
38135
  Pager *pPager = pPg->pPager;
35132
  if( isOpen(pPager->sjfd) ){
38136
  if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
35133
    void *pData = pPg->pData;
38137
35134
    i64 offset = pPager->nSubRec*(4+pPager->pageSize);
38138
    /* Open the sub-journal, if it has not already been opened */
35135
    char *pData2;
38139
    assert( pPager->useJournal );
35136
38140
    assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
35137
    CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
38141
    assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
35138
    PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
38142
    assert( pagerUseWal(pPager) 
35139
  
38143
         || pageInJournal(pPg) 
35140
    assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
38144
         || pPg->pgno>pPager->dbOrigSize 
35141
    rc = write32bits(pPager->sjfd, offset, pPg->pgno);
38145
    );
38146
    rc = openSubJournal(pPager);
38147
38148
    /* If the sub-journal was opened successfully (or was already open),
38149
    ** write the journal record into the file.  */
35142
    if( rc==SQLITE_OK ){
38150
    if( rc==SQLITE_OK ){
35143
      rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
38151
      void *pData = pPg->pData;
38152
      i64 offset = pPager->nSubRec*(4+pPager->pageSize);
38153
      char *pData2;
38154
  
38155
      CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
38156
      PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
38157
      rc = write32bits(pPager->sjfd, offset, pPg->pgno);
38158
      if( rc==SQLITE_OK ){
38159
        rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
38160
      }
35144
    }
38161
    }
35145
  }
38162
  }
35146
  if( rc==SQLITE_OK ){
38163
  if( rc==SQLITE_OK ){
 Lines 35151-35157   static int subjournalPage(PgHdr *pPg){ Link Here 
35151
  return rc;
38168
  return rc;
35152
}
38169
}
35153
38170
35154
35155
/*
38171
/*
35156
** This function is called by the pcache layer when it has reached some
38172
** This function is called by the pcache layer when it has reached some
35157
** soft memory limit. The first argument is a pointer to a Pager object
38173
** soft memory limit. The first argument is a pointer to a Pager object
 Lines 35178-35251   static int pagerStress(void *p, PgHdr *p Link Here 
35178
  assert( pPg->pPager==pPager );
38194
  assert( pPg->pPager==pPager );
35179
  assert( pPg->flags&PGHDR_DIRTY );
38195
  assert( pPg->flags&PGHDR_DIRTY );
35180
38196
35181
  /* The doNotSync flag is set by the sqlite3PagerWrite() function while it
38197
  /* The doNotSyncSpill flag is set during times when doing a sync of
35182
  ** is journalling a set of two or more database pages that are stored
38198
  ** journal (and adding a new header) is not allowed.  This occurs
35183
  ** on the same disk sector. Syncing the journal is not allowed while
38199
  ** during calls to sqlite3PagerWrite() while trying to journal multiple
35184
  ** this is happening as it is important that all members of such a
38200
  ** pages belonging to the same sector.
35185
  ** set of pages are synced to disk together. So, if the page this function
38201
  **
35186
  ** is trying to make clean will require a journal sync and the doNotSync
38202
  ** The doNotSpill flag inhibits all cache spilling regardless of whether
35187
  ** flag is set, return without doing anything. The pcache layer will
38203
  ** or not a sync is required.  This is set during a rollback.
35188
  ** just have to go ahead and allocate a new page buffer instead of
38204
  **
35189
  ** reusing pPg.
38205
  ** Spilling is also prohibited when in an error state since that could
35190
  **
38206
  ** lead to database corruption.   In the current implementaton it 
35191
  ** Similarly, if the pager has already entered the error state, do not
38207
  ** is impossible for sqlite3PCacheFetch() to be called with createFlag==1
35192
  ** try to write the contents of pPg to disk.
38208
  ** while in the error state, hence it is impossible for this routine to
35193
  */
38209
  ** be called in the error state.  Nevertheless, we include a NEVER()
35194
  if( NEVER(pPager->errCode)
38210
  ** test for the error state as a safeguard against future changes.
35195
   || (pPager->doNotSync && pPg->flags&PGHDR_NEED_SYNC)
38211
  */
35196
  ){
38212
  if( NEVER(pPager->errCode) ) return SQLITE_OK;
38213
  if( pPager->doNotSpill ) return SQLITE_OK;
38214
  if( pPager->doNotSyncSpill && (pPg->flags & PGHDR_NEED_SYNC)!=0 ){
35197
    return SQLITE_OK;
38215
    return SQLITE_OK;
35198
  }
38216
  }
35199
38217
35200
  /* Sync the journal file if required. */
38218
  pPg->pDirty = 0;
35201
  if( pPg->flags&PGHDR_NEED_SYNC ){
38219
  if( pagerUseWal(pPager) ){
35202
    rc = syncJournal(pPager);
38220
    /* Write a single frame for this page to the log. */
35203
    if( rc==SQLITE_OK && pPager->fullSync && 
38221
    if( subjRequiresPage(pPg) ){ 
35204
      !(pPager->journalMode==PAGER_JOURNALMODE_MEMORY) &&
38222
      rc = subjournalPage(pPg); 
35205
      !(sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
38223
    }
38224
    if( rc==SQLITE_OK ){
38225
      rc = pagerWalFrames(pPager, pPg, 0, 0, 0);
38226
    }
38227
  }else{
38228
  
38229
    /* Sync the journal file if required. */
38230
    if( pPg->flags&PGHDR_NEED_SYNC 
38231
     || pPager->eState==PAGER_WRITER_CACHEMOD
35206
    ){
38232
    ){
35207
      pPager->nRec = 0;
38233
      rc = syncJournal(pPager, 1);
35208
      rc = writeJournalHdr(pPager);
38234
    }
35209
    }
38235
  
35210
  }
38236
    /* If the page number of this page is larger than the current size of
35211
38237
    ** the database image, it may need to be written to the sub-journal.
35212
  /* If the page number of this page is larger than the current size of
38238
    ** This is because the call to pager_write_pagelist() below will not
35213
  ** the database image, it may need to be written to the sub-journal.
38239
    ** actually write data to the file in this case.
35214
  ** This is because the call to pager_write_pagelist() below will not
38240
    **
35215
  ** actually write data to the file in this case.
38241
    ** Consider the following sequence of events:
35216
  **
38242
    **
35217
  ** Consider the following sequence of events:
38243
    **   BEGIN;
35218
  **
38244
    **     <journal page X>
35219
  **   BEGIN;
38245
    **     <modify page X>
35220
  **     <journal page X>
38246
    **     SAVEPOINT sp;
35221
  **     <modify page X>
38247
    **       <shrink database file to Y pages>
35222
  **     SAVEPOINT sp;
38248
    **       pagerStress(page X)
35223
  **       <shrink database file to Y pages>
38249
    **     ROLLBACK TO sp;
35224
  **       pagerStress(page X)
38250
    **
35225
  **     ROLLBACK TO sp;
38251
    ** If (X>Y), then when pagerStress is called page X will not be written
35226
  **
38252
    ** out to the database file, but will be dropped from the cache. Then,
35227
  ** If (X>Y), then when pagerStress is called page X will not be written
38253
    ** following the "ROLLBACK TO sp" statement, reading page X will read
35228
  ** out to the database file, but will be dropped from the cache. Then,
38254
    ** data from the database file. This will be the copy of page X as it
35229
  ** following the "ROLLBACK TO sp" statement, reading page X will read
38255
    ** was when the transaction started, not as it was when "SAVEPOINT sp"
35230
  ** data from the database file. This will be the copy of page X as it
38256
    ** was executed.
35231
  ** was when the transaction started, not as it was when "SAVEPOINT sp"
38257
    **
35232
  ** was executed.
38258
    ** The solution is to write the current data for page X into the 
35233
  **
38259
    ** sub-journal file now (if it is not already there), so that it will
35234
  ** The solution is to write the current data for page X into the 
38260
    ** be restored to its current value when the "ROLLBACK TO sp" is 
35235
  ** sub-journal file now (if it is not already there), so that it will
38261
    ** executed.
35236
  ** be restored to its current value when the "ROLLBACK TO sp" is 
38262
    */
35237
  ** executed.
38263
    if( NEVER(
35238
  */
38264
        rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
35239
  if( NEVER(
38265
    ) ){
35240
      rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
38266
      rc = subjournalPage(pPg);
35241
  ) ){
38267
    }
35242
    rc = subjournalPage(pPg);
38268
  
35243
  }
38269
    /* Write the contents of the page out to the database file. */
35244
38270
    if( rc==SQLITE_OK ){
35245
  /* Write the contents of the page out to the database file. */
38271
      assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
35246
  if( rc==SQLITE_OK ){
38272
      rc = pager_write_pagelist(pPager, pPg);
35247
    pPg->pDirty = 0;
38273
    }
35248
    rc = pager_write_pagelist(pPg);
35249
  }
38274
  }
35250
38275
35251
  /* Mark the page as clean. */
38276
  /* Mark the page as clean. */
 Lines 35254-35260   static int pagerStress(void *p, PgHdr *p Link Here 
35254
    sqlite3PcacheMakeClean(pPg);
38279
    sqlite3PcacheMakeClean(pPg);
35255
  }
38280
  }
35256
38281
35257
  return pager_error(pPager, rc);
38282
  return pager_error(pPager, rc); 
35258
}
38283
}
35259
38284
35260
38285
 Lines 35309-35315   SQLITE_PRIVATE int sqlite3PagerOpen( Link Here 
35309
  int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
38334
  int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
35310
  int noReadlock = (flags & PAGER_NO_READLOCK)!=0;  /* True to omit read-lock */
38335
  int noReadlock = (flags & PAGER_NO_READLOCK)!=0;  /* True to omit read-lock */
35311
  int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
38336
  int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
35312
  u16 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
38337
  u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
35313
38338
35314
  /* Figure out how much space is required for each journal file-handle
38339
  /* Figure out how much space is required for each journal file-handle
35315
  ** (there are two of them, the main journal and the sub-journal). This
38340
  ** (there are two of them, the main journal and the sub-journal). This
 Lines 35384-35389   SQLITE_PRIVATE int sqlite3PagerOpen( Link Here 
35384
    journalFileSize * 2 +          /* The two journal files */ 
38409
    journalFileSize * 2 +          /* The two journal files */ 
35385
    nPathname + 1 +                /* zFilename */
38410
    nPathname + 1 +                /* zFilename */
35386
    nPathname + 8 + 1              /* zJournal */
38411
    nPathname + 8 + 1              /* zJournal */
38412
#ifndef SQLITE_OMIT_WAL
38413
    + nPathname + 4 + 1              /* zWal */
38414
#endif
35387
  );
38415
  );
35388
  assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
38416
  assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
35389
  if( !pPtr ){
38417
  if( !pPtr ){
 Lines 35404-35410   SQLITE_PRIVATE int sqlite3PagerOpen( Link Here 
35404
    memcpy(pPager->zFilename, zPathname, nPathname);
38432
    memcpy(pPager->zFilename, zPathname, nPathname);
35405
    memcpy(pPager->zJournal, zPathname, nPathname);
38433
    memcpy(pPager->zJournal, zPathname, nPathname);
35406
    memcpy(&pPager->zJournal[nPathname], "-journal", 8);
38434
    memcpy(&pPager->zJournal[nPathname], "-journal", 8);
35407
    if( pPager->zFilename[0]==0 ) pPager->zJournal[0] = 0;
38435
    if( pPager->zFilename[0]==0 ){
38436
      pPager->zJournal[0] = 0;
38437
    }
38438
#ifndef SQLITE_OMIT_WAL
38439
    else{
38440
      pPager->zWal = &pPager->zJournal[nPathname+8+1];
38441
      memcpy(pPager->zWal, zPathname, nPathname);
38442
      memcpy(&pPager->zWal[nPathname], "-wal", 4);
38443
    }
38444
#endif
35408
    sqlite3_free(zPathname);
38445
    sqlite3_free(zPathname);
35409
  }
38446
  }
35410
  pPager->pVfs = pVfs;
38447
  pPager->pVfs = pVfs;
 Lines 35432-35438   SQLITE_PRIVATE int sqlite3PagerOpen( Link Here 
35432
        if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
38469
        if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
35433
          szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
38470
          szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
35434
        }else{
38471
        }else{
35435
          szPageDflt = (u16)pPager->sectorSize;
38472
          szPageDflt = (u32)pPager->sectorSize;
35436
        }
38473
        }
35437
      }
38474
      }
35438
#ifdef SQLITE_ENABLE_ATOMIC_WRITE
38475
#ifdef SQLITE_ENABLE_ATOMIC_WRITE
 Lines 35460-35466   SQLITE_PRIVATE int sqlite3PagerOpen( Link Here 
35460
    ** disk and uses an in-memory rollback journal.
38497
    ** disk and uses an in-memory rollback journal.
35461
    */ 
38498
    */ 
35462
    tempFile = 1;
38499
    tempFile = 1;
35463
    pPager->state = PAGER_EXCLUSIVE;
38500
    pPager->eState = PAGER_READER;
38501
    pPager->eLock = EXCLUSIVE_LOCK;
35464
    readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
38502
    readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
35465
  }
38503
  }
35466
38504
 Lines 35497-35509   SQLITE_PRIVATE int sqlite3PagerOpen( Link Here 
35497
  /* pPager->stmtOpen = 0; */
38535
  /* pPager->stmtOpen = 0; */
35498
  /* pPager->stmtInUse = 0; */
38536
  /* pPager->stmtInUse = 0; */
35499
  /* pPager->nRef = 0; */
38537
  /* pPager->nRef = 0; */
35500
  pPager->dbSizeValid = (u8)memDb;
35501
  /* pPager->stmtSize = 0; */
38538
  /* pPager->stmtSize = 0; */
35502
  /* pPager->stmtJSize = 0; */
38539
  /* pPager->stmtJSize = 0; */
35503
  /* pPager->nPage = 0; */
38540
  /* pPager->nPage = 0; */
35504
  pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
38541
  pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
35505
  /* pPager->state = PAGER_UNLOCK; */
38542
  /* pPager->state = PAGER_UNLOCK; */
38543
#if 0
35506
  assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
38544
  assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
38545
#endif
35507
  /* pPager->errMask = 0; */
38546
  /* pPager->errMask = 0; */
35508
  pPager->tempFile = (u8)tempFile;
38547
  pPager->tempFile = (u8)tempFile;
35509
  assert( tempFile==PAGER_LOCKINGMODE_NORMAL 
38548
  assert( tempFile==PAGER_LOCKINGMODE_NORMAL 
 Lines 35513-35519   SQLITE_PRIVATE int sqlite3PagerOpen( Link Here 
35513
  pPager->changeCountDone = pPager->tempFile;
38552
  pPager->changeCountDone = pPager->tempFile;
35514
  pPager->memDb = (u8)memDb;
38553
  pPager->memDb = (u8)memDb;
35515
  pPager->readOnly = (u8)readOnly;
38554
  pPager->readOnly = (u8)readOnly;
35516
  /* pPager->needSync = 0; */
35517
  assert( useJournal || pPager->tempFile );
38555
  assert( useJournal || pPager->tempFile );
35518
  pPager->noSync = pPager->tempFile;
38556
  pPager->noSync = pPager->tempFile;
35519
  pPager->fullSync = pPager->noSync ?0:1;
38557
  pPager->fullSync = pPager->noSync ?0:1;
 Lines 35574-35592   SQLITE_PRIVATE int sqlite3PagerOpen( Link Here 
35574
*/
38612
*/
35575
static int hasHotJournal(Pager *pPager, int *pExists){
38613
static int hasHotJournal(Pager *pPager, int *pExists){
35576
  sqlite3_vfs * const pVfs = pPager->pVfs;
38614
  sqlite3_vfs * const pVfs = pPager->pVfs;
35577
  int rc;                       /* Return code */
38615
  int rc = SQLITE_OK;           /* Return code */
35578
  int exists;                   /* True if a journal file is present */
38616
  int exists = 1;               /* True if a journal file is present */
35579
38617
  int jrnlOpen = !!isOpen(pPager->jfd);
35580
  assert( pPager!=0 );
38618
35581
  assert( pPager->useJournal );
38619
  assert( pPager->useJournal );
35582
  assert( isOpen(pPager->fd) );
38620
  assert( isOpen(pPager->fd) );
35583
  assert( !isOpen(pPager->jfd) );
38621
  assert( pPager->eState==PAGER_OPEN );
35584
  assert( pPager->state <= PAGER_SHARED );
38622
38623
  assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
38624
    SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
38625
  ));
35585
38626
35586
  *pExists = 0;
38627
  *pExists = 0;
35587
  rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
38628
  if( !jrnlOpen ){
38629
    rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
38630
  }
35588
  if( rc==SQLITE_OK && exists ){
38631
  if( rc==SQLITE_OK && exists ){
35589
    int locked;                 /* True if some process holds a RESERVED lock */
38632
    int locked = 0;             /* True if some process holds a RESERVED lock */
35590
38633
35591
    /* Race condition here:  Another process might have been holding the
38634
    /* Race condition here:  Another process might have been holding the
35592
    ** the RESERVED lock and have a journal open at the sqlite3OsAccess() 
38635
    ** the RESERVED lock and have a journal open at the sqlite3OsAccess() 
 Lines 35598-35604   static int hasHotJournal(Pager *pPager, Link Here 
35598
    */
38641
    */
35599
    rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
38642
    rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
35600
    if( rc==SQLITE_OK && !locked ){
38643
    if( rc==SQLITE_OK && !locked ){
35601
      int nPage;
38644
      Pgno nPage;                 /* Number of pages in database file */
35602
38645
35603
      /* Check the size of the database file. If it consists of 0 pages,
38646
      /* Check the size of the database file. If it consists of 0 pages,
35604
      ** then delete the journal file. See the header comment above for 
38647
      ** then delete the journal file. See the header comment above for 
 Lines 35606-35618   static int hasHotJournal(Pager *pPager, Link Here 
35606
      ** a RESERVED lock to avoid race conditions and to avoid violating
38649
      ** a RESERVED lock to avoid race conditions and to avoid violating
35607
      ** [H33020].
38650
      ** [H33020].
35608
      */
38651
      */
35609
      rc = sqlite3PagerPagecount(pPager, &nPage);
38652
      rc = pagerPagecount(pPager, &nPage);
35610
      if( rc==SQLITE_OK ){
38653
      if( rc==SQLITE_OK ){
35611
        if( nPage==0 ){
38654
        if( nPage==0 ){
35612
          sqlite3BeginBenignMalloc();
38655
          sqlite3BeginBenignMalloc();
35613
          if( sqlite3OsLock(pPager->fd, RESERVED_LOCK)==SQLITE_OK ){
38656
          if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
35614
            sqlite3OsDelete(pVfs, pPager->zJournal, 0);
38657
            sqlite3OsDelete(pVfs, pPager->zJournal, 0);
35615
            sqlite3OsUnlock(pPager->fd, SHARED_LOCK);
38658
            pagerUnlockDb(pPager, SHARED_LOCK);
35616
          }
38659
          }
35617
          sqlite3EndBenignMalloc();
38660
          sqlite3EndBenignMalloc();
35618
        }else{
38661
        }else{
 Lines 35622-35636   static int hasHotJournal(Pager *pPager, Link Here 
35622
          ** If there is, then we consider this journal to be hot. If not, 
38665
          ** If there is, then we consider this journal to be hot. If not, 
35623
          ** it can be ignored.
38666
          ** it can be ignored.
35624
          */
38667
          */
35625
          int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
38668
          if( !jrnlOpen ){
35626
          rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
38669
            int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
38670
            rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
38671
          }
35627
          if( rc==SQLITE_OK ){
38672
          if( rc==SQLITE_OK ){
35628
            u8 first = 0;
38673
            u8 first = 0;
35629
            rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
38674
            rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
35630
            if( rc==SQLITE_IOERR_SHORT_READ ){
38675
            if( rc==SQLITE_IOERR_SHORT_READ ){
35631
              rc = SQLITE_OK;
38676
              rc = SQLITE_OK;
35632
            }
38677
            }
35633
            sqlite3OsClose(pPager->jfd);
38678
            if( !jrnlOpen ){
38679
              sqlite3OsClose(pPager->jfd);
38680
            }
35634
            *pExists = (first!=0);
38681
            *pExists = (first!=0);
35635
          }else if( rc==SQLITE_CANTOPEN ){
38682
          }else if( rc==SQLITE_CANTOPEN ){
35636
            /* If we cannot open the rollback journal file in order to see if
38683
            /* If we cannot open the rollback journal file in order to see if
 Lines 35654-35720   static int hasHotJournal(Pager *pPager, Link Here 
35654
}
38701
}
35655
38702
35656
/*
38703
/*
35657
** Read the content for page pPg out of the database file and into 
35658
** pPg->pData. A shared lock or greater must be held on the database
35659
** file before this function is called.
35660
**
35661
** If page 1 is read, then the value of Pager.dbFileVers[] is set to
35662
** the value read from the database file.
35663
**
35664
** If an IO error occurs, then the IO error is returned to the caller.
35665
** Otherwise, SQLITE_OK is returned.
35666
*/
35667
static int readDbPage(PgHdr *pPg){
35668
  Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
35669
  Pgno pgno = pPg->pgno;       /* Page number to read */
35670
  int rc;                      /* Return code */
35671
  i64 iOffset;                 /* Byte offset of file to read from */
35672
35673
  assert( pPager->state>=PAGER_SHARED && !MEMDB );
35674
  assert( isOpen(pPager->fd) );
35675
35676
  if( NEVER(!isOpen(pPager->fd)) ){
35677
    assert( pPager->tempFile );
35678
    memset(pPg->pData, 0, pPager->pageSize);
35679
    return SQLITE_OK;
35680
  }
35681
  iOffset = (pgno-1)*(i64)pPager->pageSize;
35682
  rc = sqlite3OsRead(pPager->fd, pPg->pData, pPager->pageSize, iOffset);
35683
  if( rc==SQLITE_IOERR_SHORT_READ ){
35684
    rc = SQLITE_OK;
35685
  }
35686
  if( pgno==1 ){
35687
    if( rc ){
35688
      /* If the read is unsuccessful, set the dbFileVers[] to something
35689
      ** that will never be a valid file version.  dbFileVers[] is a copy
35690
      ** of bytes 24..39 of the database.  Bytes 28..31 should always be
35691
      ** zero.  Bytes 32..35 and 35..39 should be page numbers which are
35692
      ** never 0xffffffff.  So filling pPager->dbFileVers[] with all 0xff
35693
      ** bytes should suffice.
35694
      **
35695
      ** For an encrypted database, the situation is more complex:  bytes
35696
      ** 24..39 of the database are white noise.  But the probability of
35697
      ** white noising equaling 16 bytes of 0xff is vanishingly small so
35698
      ** we should still be ok.
35699
      */
35700
      memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
35701
    }else{
35702
      u8 *dbFileVers = &((u8*)pPg->pData)[24];
35703
      memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
35704
    }
35705
  }
35706
  CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
35707
35708
  PAGER_INCR(sqlite3_pager_readdb_count);
35709
  PAGER_INCR(pPager->nRead);
35710
  IOTRACE(("PGIN %p %d\n", pPager, pgno));
35711
  PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
35712
               PAGERID(pPager), pgno, pager_pagehash(pPg)));
35713
35714
  return rc;
35715
}
35716
35717
/*
35718
** This function is called to obtain a shared lock on the database file.
38704
** This function is called to obtain a shared lock on the database file.
35719
** It is illegal to call sqlite3PagerAcquire() until after this function
38705
** It is illegal to call sqlite3PagerAcquire() until after this function
35720
** has been successfully called. If a shared-lock is already held when
38706
** has been successfully called. If a shared-lock is already held when
 Lines 35722-35728   static int readDbPage(PgHdr *pPg){ Link Here 
35722
**
38708
**
35723
** The following operations are also performed by this function.
38709
** The following operations are also performed by this function.
35724
**
38710
**
35725
**   1) If the pager is currently in PAGER_UNLOCK state (no lock held
38711
**   1) If the pager is currently in PAGER_OPEN state (no lock held
35726
**      on the database file), then an attempt is made to obtain a
38712
**      on the database file), then an attempt is made to obtain a
35727
**      SHARED lock on the database file. Immediately after obtaining
38713
**      SHARED lock on the database file. Immediately after obtaining
35728
**      the SHARED lock, the file-system is checked for a hot-journal,
38714
**      the SHARED lock, the file-system is checked for a hot-journal,
 Lines 35737-35800   static int readDbPage(PgHdr *pPg){ Link Here 
35737
**      the contents of the page cache and rolling back any open journal
38723
**      the contents of the page cache and rolling back any open journal
35738
**      file.
38724
**      file.
35739
**
38725
**
35740
** If the operation described by (2) above is not attempted, and if the
38726
** If everything is successful, SQLITE_OK is returned. If an IO error 
35741
** pager is in an error state other than SQLITE_FULL when this is called,
38727
** occurs while locking the database, checking for a hot-journal file or 
35742
** the error state error code is returned. It is permitted to read the
38728
** rolling back a journal file, the IO error code is returned.
35743
** database when in SQLITE_FULL error state.
35744
**
35745
** Otherwise, if everything is successful, SQLITE_OK is returned. If an
35746
** IO error occurs while locking the database, checking for a hot-journal
35747
** file or rolling back a journal file, the IO error code is returned.
35748
*/
38729
*/
35749
SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
38730
SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
35750
  int rc = SQLITE_OK;                /* Return code */
38731
  int rc = SQLITE_OK;                /* Return code */
35751
  int isErrorReset = 0;              /* True if recovering from error state */
35752
38732
35753
  /* This routine is only called from b-tree and only when there are no
38733
  /* This routine is only called from b-tree and only when there are no
35754
  ** outstanding pages */
38734
  ** outstanding pages. This implies that the pager state should either
38735
  ** be OPEN or READER. READER is only possible if the pager is or was in 
38736
  ** exclusive access mode.
38737
  */
35755
  assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
38738
  assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
38739
  assert( assert_pager_state(pPager) );
38740
  assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
35756
  if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
38741
  if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
35757
38742
35758
  /* If this database is in an error-state, now is a chance to clear
38743
  if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
35759
  ** the error. Discard the contents of the pager-cache and rollback
38744
    int bHotJournal = 1;          /* True if there exists a hot journal-file */
35760
  ** any hot journal in the file-system.
38745
35761
  */
35762
  if( pPager->errCode ){
35763
    if( isOpen(pPager->jfd) || pPager->zJournal ){
35764
      isErrorReset = 1;
35765
    }
35766
    pPager->errCode = SQLITE_OK;
35767
    pager_reset(pPager);
35768
  }
35769
35770
  if( pPager->state==PAGER_UNLOCK || isErrorReset ){
35771
    sqlite3_vfs * const pVfs = pPager->pVfs;
35772
    int isHotJournal = 0;
35773
    assert( !MEMDB );
38746
    assert( !MEMDB );
35774
    assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
38747
    assert( pPager->noReadlock==0 || pPager->readOnly );
35775
    if( pPager->noReadlock ){
38748
35776
      assert( pPager->readOnly );
38749
    if( pPager->noReadlock==0 ){
35777
      pPager->state = PAGER_SHARED;
35778
    }else{
35779
      rc = pager_wait_on_lock(pPager, SHARED_LOCK);
38750
      rc = pager_wait_on_lock(pPager, SHARED_LOCK);
35780
      if( rc!=SQLITE_OK ){
38751
      if( rc!=SQLITE_OK ){
35781
        assert( pPager->state==PAGER_UNLOCK );
38752
        assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
35782
        return pager_error(pPager, rc);
38753
        goto failed;
35783
      }
38754
      }
35784
    }
38755
    }
35785
    assert( pPager->state>=SHARED_LOCK );
35786
38756
35787
    /* If a journal file exists, and there is no RESERVED lock on the
38757
    /* If a journal file exists, and there is no RESERVED lock on the
35788
    ** database file, then it either needs to be played back or deleted.
38758
    ** database file, then it either needs to be played back or deleted.
35789
    */
38759
    */
35790
    if( !isErrorReset ){
38760
    if( pPager->eLock<=SHARED_LOCK ){
35791
      assert( pPager->state <= PAGER_SHARED );
38761
      rc = hasHotJournal(pPager, &bHotJournal);
35792
      rc = hasHotJournal(pPager, &isHotJournal);
38762
    }
35793
      if( rc!=SQLITE_OK ){
38763
    if( rc!=SQLITE_OK ){
35794
        goto failed;
38764
      goto failed;
35795
      }
38765
    }
35796
    }
38766
    if( bHotJournal ){
35797
    if( isErrorReset || isHotJournal ){
35798
      /* Get an EXCLUSIVE lock on the database file. At this point it is
38767
      /* Get an EXCLUSIVE lock on the database file. At this point it is
35799
      ** important that a RESERVED lock is not obtained on the way to the
38768
      ** important that a RESERVED lock is not obtained on the way to the
35800
      ** EXCLUSIVE lock. If it were, another process might open the
38769
      ** EXCLUSIVE lock. If it were, another process might open the
 Lines 35806-35879   SQLITE_PRIVATE int sqlite3PagerSharedLoc Link Here 
35806
      ** other process attempting to access the database file will get to 
38775
      ** other process attempting to access the database file will get to 
35807
      ** this point in the code and fail to obtain its own EXCLUSIVE lock 
38776
      ** this point in the code and fail to obtain its own EXCLUSIVE lock 
35808
      ** on the database file.
38777
      ** on the database file.
35809
      */
38778
      **
35810
      if( pPager->state<EXCLUSIVE_LOCK ){
38779
      ** Unless the pager is in locking_mode=exclusive mode, the lock is
35811
        rc = sqlite3OsLock(pPager->fd, EXCLUSIVE_LOCK);
38780
      ** downgraded to SHARED_LOCK before this function returns.
35812
        if( rc!=SQLITE_OK ){
38781
      */
35813
          rc = pager_error(pPager, rc);
38782
      rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
35814
          goto failed;
35815
        }
35816
        pPager->state = PAGER_EXCLUSIVE;
35817
      }
35818
 
35819
      /* Open the journal for read/write access. This is because in 
35820
      ** exclusive-access mode the file descriptor will be kept open and
35821
      ** possibly used for a transaction later on. On some systems, the
35822
      ** OsTruncate() call used in exclusive-access mode also requires
35823
      ** a read/write file handle.
35824
      */
35825
      if( !isOpen(pPager->jfd) ){
35826
        int res;
35827
        rc = sqlite3OsAccess(pVfs,pPager->zJournal,SQLITE_ACCESS_EXISTS,&res);
35828
        if( rc==SQLITE_OK ){
35829
          if( res ){
35830
            int fout = 0;
35831
            int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
35832
            assert( !pPager->tempFile );
35833
            rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
35834
            assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
35835
            if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
35836
              rc = SQLITE_CANTOPEN_BKPT;
35837
              sqlite3OsClose(pPager->jfd);
35838
            }
35839
          }else{
35840
            /* If the journal does not exist, it usually means that some 
35841
            ** other connection managed to get in and roll it back before 
35842
            ** this connection obtained the exclusive lock above. Or, it 
35843
            ** may mean that the pager was in the error-state when this
35844
            ** function was called and the journal file does not exist.  */
35845
            rc = pager_end_transaction(pPager, 0);
35846
          }
35847
        }
35848
      }
35849
      if( rc!=SQLITE_OK ){
38783
      if( rc!=SQLITE_OK ){
35850
        goto failed;
38784
        goto failed;
35851
      }
38785
      }
35852
38786
 
35853
      /* TODO: Why are these cleared here? Is it necessary? */
38787
      /* If it is not already open and the file exists on disk, open the 
35854
      pPager->journalStarted = 0;
38788
      ** journal for read/write access. Write access is required because 
35855
      pPager->journalOff = 0;
38789
      ** in exclusive-access mode the file descriptor will be kept open 
35856
      pPager->setMaster = 0;
38790
      ** and possibly used for a transaction later on. Also, write-access 
35857
      pPager->journalHdr = 0;
38791
      ** is usually required to finalize the journal in journal_mode=persist 
38792
      ** mode (and also for journal_mode=truncate on some systems).
38793
      **
38794
      ** If the journal does not exist, it usually means that some 
38795
      ** other connection managed to get in and roll it back before 
38796
      ** this connection obtained the exclusive lock above. Or, it 
38797
      ** may mean that the pager was in the error-state when this
38798
      ** function was called and the journal file does not exist.
38799
      */
38800
      if( !isOpen(pPager->jfd) ){
38801
        sqlite3_vfs * const pVfs = pPager->pVfs;
38802
        int bExists;              /* True if journal file exists */
38803
        rc = sqlite3OsAccess(
38804
            pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
38805
        if( rc==SQLITE_OK && bExists ){
38806
          int fout = 0;
38807
          int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
38808
          assert( !pPager->tempFile );
38809
          rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
38810
          assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
38811
          if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
38812
            rc = SQLITE_CANTOPEN_BKPT;
38813
            sqlite3OsClose(pPager->jfd);
38814
          }
38815
        }
38816
      }
35858
 
38817
 
35859
      /* Playback and delete the journal.  Drop the database write
38818
      /* Playback and delete the journal.  Drop the database write
35860
      ** lock and reacquire the read lock. Purge the cache before
38819
      ** lock and reacquire the read lock. Purge the cache before
35861
      ** playing back the hot-journal so that we don't end up with
38820
      ** playing back the hot-journal so that we don't end up with
35862
      ** an inconsistent cache.
38821
      ** an inconsistent cache.  Sync the hot journal before playing
38822
      ** it back since the process that crashed and left the hot journal
38823
      ** probably did not sync it and we are required to always sync
38824
      ** the journal before playing it back.
35863
      */
38825
      */
35864
      if( isOpen(pPager->jfd) ){
38826
      if( isOpen(pPager->jfd) ){
35865
        rc = pager_playback(pPager, 1);
38827
        assert( rc==SQLITE_OK );
35866
        if( rc!=SQLITE_OK ){
38828
        rc = pagerSyncHotJournal(pPager);
35867
          rc = pager_error(pPager, rc);
38829
        if( rc==SQLITE_OK ){
35868
          goto failed;
38830
          rc = pager_playback(pPager, 1);
35869
        }
38831
          pPager->eState = PAGER_OPEN;
35870
      }
38832
        }
35871
      assert( (pPager->state==PAGER_SHARED)
38833
      }else if( !pPager->exclusiveMode ){
35872
           || (pPager->exclusiveMode && pPager->state>PAGER_SHARED)
38834
        pagerUnlockDb(pPager, SHARED_LOCK);
38835
      }
38836
38837
      if( rc!=SQLITE_OK ){
38838
        /* This branch is taken if an error occurs while trying to open
38839
        ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
38840
        ** pager_unlock() routine will be called before returning to unlock
38841
        ** the file. If the unlock attempt fails, then Pager.eLock must be
38842
        ** set to UNKNOWN_LOCK (see the comment above the #define for 
38843
        ** UNKNOWN_LOCK above for an explanation). 
38844
        **
38845
        ** In order to get pager_unlock() to do this, set Pager.eState to
38846
        ** PAGER_ERROR now. This is not actually counted as a transition
38847
        ** to ERROR state in the state diagram at the top of this file,
38848
        ** since we know that the same call to pager_unlock() will very
38849
        ** shortly transition the pager object to the OPEN state. Calling
38850
        ** assert_pager_state() would fail now, as it should not be possible
38851
        ** to be in ERROR state when there are zero outstanding page 
38852
        ** references.
38853
        */
38854
        pager_error(pPager, rc);
38855
        goto failed;
38856
      }
38857
38858
      assert( pPager->eState==PAGER_OPEN );
38859
      assert( (pPager->eLock==SHARED_LOCK)
38860
           || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
35873
      );
38861
      );
35874
    }
38862
    }
35875
38863
35876
    if( pPager->pBackup || sqlite3PcachePagecount(pPager->pPCache)>0 ){
38864
    if( !pPager->tempFile 
38865
     && (pPager->pBackup || sqlite3PcachePagecount(pPager->pPCache)>0) 
38866
    ){
35877
      /* The shared-lock has just been acquired on the database file
38867
      /* The shared-lock has just been acquired on the database file
35878
      ** and there are already pages in the cache (from a previous
38868
      ** and there are already pages in the cache (from a previous
35879
      ** read or write transaction).  Check to see if the database
38869
      ** read or write transaction).  Check to see if the database
 Lines 35890-35905   SQLITE_PRIVATE int sqlite3PagerSharedLoc Link Here 
35890
      ** detected.  The chance of an undetected change is so small that
38880
      ** detected.  The chance of an undetected change is so small that
35891
      ** it can be neglected.
38881
      ** it can be neglected.
35892
      */
38882
      */
38883
      Pgno nPage = 0;
35893
      char dbFileVers[sizeof(pPager->dbFileVers)];
38884
      char dbFileVers[sizeof(pPager->dbFileVers)];
35894
      sqlite3PagerPagecount(pPager, 0);
38885
35895
38886
      rc = pagerPagecount(pPager, &nPage);
35896
      if( pPager->errCode ){
38887
      if( rc ) goto failed;
35897
        rc = pPager->errCode;
38888
35898
        goto failed;
38889
      if( nPage>0 ){
35899
      }
35900
35901
      assert( pPager->dbSizeValid );
35902
      if( pPager->dbSize>0 ){
35903
        IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
38890
        IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
35904
        rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
38891
        rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
35905
        if( rc!=SQLITE_OK ){
38892
        if( rc!=SQLITE_OK ){
 Lines 35913-35925   SQLITE_PRIVATE int sqlite3PagerSharedLoc Link Here 
35913
        pager_reset(pPager);
38900
        pager_reset(pPager);
35914
      }
38901
      }
35915
    }
38902
    }
35916
    assert( pPager->exclusiveMode || pPager->state==PAGER_SHARED );
38903
38904
    /* If there is a WAL file in the file-system, open this database in WAL
38905
    ** mode. Otherwise, the following function call is a no-op.
38906
    */
38907
    rc = pagerOpenWalIfPresent(pPager);
38908
    assert( pPager->pWal==0 || rc==SQLITE_OK );
38909
  }
38910
38911
  if( pagerUseWal(pPager) ){
38912
    assert( rc==SQLITE_OK );
38913
    rc = pagerBeginReadTransaction(pPager);
38914
  }
38915
38916
  if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
38917
    rc = pagerPagecount(pPager, &pPager->dbSize);
35917
  }
38918
  }
35918
38919
35919
 failed:
38920
 failed:
35920
  if( rc!=SQLITE_OK ){
38921
  if( rc!=SQLITE_OK ){
35921
    /* pager_unlock() is a no-op for exclusive mode and in-memory databases. */
38922
    assert( !MEMDB );
35922
    pager_unlock(pPager);
38923
    pager_unlock(pPager);
38924
    assert( pPager->eState==PAGER_OPEN );
38925
  }else{
38926
    pPager->eState = PAGER_READER;
35923
  }
38927
  }
35924
  return rc;
38928
  return rc;
35925
}
38929
}
 Lines 35933-35941   SQLITE_PRIVATE int sqlite3PagerSharedLoc Link Here 
35933
** nothing to rollback, so this routine is a no-op.
38937
** nothing to rollback, so this routine is a no-op.
35934
*/ 
38938
*/ 
35935
static void pagerUnlockIfUnused(Pager *pPager){
38939
static void pagerUnlockIfUnused(Pager *pPager){
35936
  if( (sqlite3PcacheRefCount(pPager->pPCache)==0)
38940
  if( (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
35937
   && (!pPager->exclusiveMode || pPager->journalOff>0) 
35938
  ){
35939
    pagerUnlockAndRollback(pPager);
38941
    pagerUnlockAndRollback(pPager);
35940
  }
38942
  }
35941
}
38943
}
 Lines 35968-35974   static void pagerUnlockIfUnused(Pager *p Link Here 
35968
**   a) When reading a free-list leaf page from the database, and
38970
**   a) When reading a free-list leaf page from the database, and
35969
**
38971
**
35970
**   b) When a savepoint is being rolled back and we need to load
38972
**   b) When a savepoint is being rolled back and we need to load
35971
**      a new page into the cache to populate with the data read
38973
**      a new page into the cache to be filled with the data read
35972
**      from the savepoint journal.
38974
**      from the savepoint journal.
35973
**
38975
**
35974
** If noContent is true, then the data returned is zeroed instead of
38976
** If noContent is true, then the data returned is zeroed instead of
 Lines 35999-36006   SQLITE_PRIVATE int sqlite3PagerAcquire( Link Here 
35999
  int rc;
39001
  int rc;
36000
  PgHdr *pPg;
39002
  PgHdr *pPg;
36001
39003
39004
  assert( pPager->eState>=PAGER_READER );
36002
  assert( assert_pager_state(pPager) );
39005
  assert( assert_pager_state(pPager) );
36003
  assert( pPager->state>PAGER_UNLOCK );
36004
39006
36005
  if( pgno==0 ){
39007
  if( pgno==0 ){
36006
    return SQLITE_CORRUPT_BKPT;
39008
    return SQLITE_CORRUPT_BKPT;
 Lines 36008-36014   SQLITE_PRIVATE int sqlite3PagerAcquire( Link Here 
36008
39010
36009
  /* If the pager is in the error state, return an error immediately. 
39011
  /* If the pager is in the error state, return an error immediately. 
36010
  ** Otherwise, request the page from the PCache layer. */
39012
  ** Otherwise, request the page from the PCache layer. */
36011
  if( pPager->errCode!=SQLITE_OK && pPager->errCode!=SQLITE_FULL ){
39013
  if( pPager->errCode!=SQLITE_OK ){
36012
    rc = pPager->errCode;
39014
    rc = pPager->errCode;
36013
  }else{
39015
  }else{
36014
    rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
39016
    rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
 Lines 36024-36030   SQLITE_PRIVATE int sqlite3PagerAcquire( Link Here 
36024
  assert( (*ppPage)->pgno==pgno );
39026
  assert( (*ppPage)->pgno==pgno );
36025
  assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
39027
  assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
36026
39028
36027
  if( (*ppPage)->pPager ){
39029
  if( (*ppPage)->pPager && !noContent ){
36028
    /* In this case the pcache already contains an initialized copy of
39030
    /* In this case the pcache already contains an initialized copy of
36029
    ** the page. Return without further ado.  */
39031
    ** the page. Return without further ado.  */
36030
    assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
39032
    assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
 Lines 36034-36040   SQLITE_PRIVATE int sqlite3PagerAcquire( Link Here 
36034
  }else{
39036
  }else{
36035
    /* The pager cache has created a new page. Its content needs to 
39037
    /* The pager cache has created a new page. Its content needs to 
36036
    ** be initialized.  */
39038
    ** be initialized.  */
36037
    int nMax;
36038
39039
36039
    PAGER_INCR(pPager->nMiss);
39040
    PAGER_INCR(pPager->nMiss);
36040
    pPg = *ppPage;
39041
    pPg = *ppPage;
 Lines 36047-36061   SQLITE_PRIVATE int sqlite3PagerAcquire( Link Here 
36047
      goto pager_acquire_err;
39048
      goto pager_acquire_err;
36048
    }
39049
    }
36049
39050
36050
    rc = sqlite3PagerPagecount(pPager, &nMax);
39051
    if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
36051
    if( rc!=SQLITE_OK ){
36052
      goto pager_acquire_err;
36053
    }
36054
36055
    if( MEMDB || nMax<(int)pgno || noContent || !isOpen(pPager->fd) ){
36056
      if( pgno>pPager->mxPgno ){
39052
      if( pgno>pPager->mxPgno ){
36057
	rc = SQLITE_FULL;
39053
        rc = SQLITE_FULL;
36058
	goto pager_acquire_err;
39054
        goto pager_acquire_err;
36059
      }
39055
      }
36060
      if( noContent ){
39056
      if( noContent ){
36061
        /* Failure to set the bits in the InJournal bit-vectors is benign.
39057
        /* Failure to set the bits in the InJournal bit-vectors is benign.
 Lines 36103-36111   pager_acquire_err: Link Here 
36103
/*
39099
/*
36104
** Acquire a page if it is already in the in-memory cache.  Do
39100
** Acquire a page if it is already in the in-memory cache.  Do
36105
** not read the page from disk.  Return a pointer to the page,
39101
** not read the page from disk.  Return a pointer to the page,
36106
** or 0 if the page is not in cache. Also, return 0 if the 
39102
** or 0 if the page is not in cache. 
36107
** pager is in PAGER_UNLOCK state when this function is called,
36108
** or if the pager is in an error state other than SQLITE_FULL.
36109
**
39103
**
36110
** See also sqlite3PagerGet().  The difference between this routine
39104
** See also sqlite3PagerGet().  The difference between this routine
36111
** and sqlite3PagerGet() is that _get() will go to the disk and read
39105
** and sqlite3PagerGet() is that _get() will go to the disk and read
 Lines 36118-36124   SQLITE_PRIVATE DbPage *sqlite3PagerLooku Link Here 
36118
  assert( pPager!=0 );
39112
  assert( pPager!=0 );
36119
  assert( pgno!=0 );
39113
  assert( pgno!=0 );
36120
  assert( pPager->pPCache!=0 );
39114
  assert( pPager->pPCache!=0 );
36121
  assert( pPager->state > PAGER_UNLOCK );
39115
  assert( pPager->eState>=PAGER_READER && pPager->eState!=PAGER_ERROR );
36122
  sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
39116
  sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
36123
  return pPg;
39117
  return pPg;
36124
}
39118
}
 Lines 36140-36166   SQLITE_PRIVATE void sqlite3PagerUnref(Db Link Here 
36140
}
39134
}
36141
39135
36142
/*
39136
/*
36143
** If the main journal file has already been opened, ensure that the
36144
** sub-journal file is open too. If the main journal is not open,
36145
** this function is a no-op.
36146
**
36147
** SQLITE_OK is returned if everything goes according to plan. 
36148
** An SQLITE_IOERR_XXX error code is returned if a call to 
36149
** sqlite3OsOpen() fails.
36150
*/
36151
static int openSubJournal(Pager *pPager){
36152
  int rc = SQLITE_OK;
36153
  if( isOpen(pPager->jfd) && !isOpen(pPager->sjfd) ){
36154
    if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
36155
      sqlite3MemJournalOpen(pPager->sjfd);
36156
    }else{
36157
      rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
36158
    }
36159
  }
36160
  return rc;
36161
}
36162
36163
/*
36164
** This function is called at the start of every write transaction.
39137
** This function is called at the start of every write transaction.
36165
** There must already be a RESERVED or EXCLUSIVE lock on the database 
39138
** There must already be a RESERVED or EXCLUSIVE lock on the database 
36166
** file when this routine is called.
39139
** file when this routine is called.
 Lines 36186-36194   static int pager_open_journal(Pager *pPa Link Here 
36186
  int rc = SQLITE_OK;                        /* Return code */
39159
  int rc = SQLITE_OK;                        /* Return code */
36187
  sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
39160
  sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
36188
39161
36189
  assert( pPager->state>=PAGER_RESERVED );
39162
  assert( pPager->eState==PAGER_WRITER_LOCKED );
36190
  assert( pPager->useJournal );
39163
  assert( assert_pager_state(pPager) );
36191
  assert( pPager->journalMode!=PAGER_JOURNALMODE_OFF );
36192
  assert( pPager->pInJournal==0 );
39164
  assert( pPager->pInJournal==0 );
36193
  
39165
  
36194
  /* If already in the error state, this function is a no-op.  But on
39166
  /* If already in the error state, this function is a no-op.  But on
 Lines 36196-36257   static int pager_open_journal(Pager *pPa Link Here 
36196
  ** an error state. */
39168
  ** an error state. */
36197
  if( NEVER(pPager->errCode) ) return pPager->errCode;
39169
  if( NEVER(pPager->errCode) ) return pPager->errCode;
36198
39170
36199
  /* TODO: Is it really possible to get here with dbSizeValid==0? If not,
39171
  if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
36200
  ** the call to PagerPagecount() can be removed.
39172
    pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
36201
  */
39173
    if( pPager->pInJournal==0 ){
36202
  testcase( pPager->dbSizeValid==0 );
39174
      return SQLITE_NOMEM;
36203
  sqlite3PagerPagecount(pPager, 0);
39175
    }
36204
39176
  
36205
  pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
39177
    /* Open the journal file if it is not already open. */
36206
  if( pPager->pInJournal==0 ){
39178
    if( !isOpen(pPager->jfd) ){
36207
    return SQLITE_NOMEM;
39179
      if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
36208
  }
39180
        sqlite3MemJournalOpen(pPager->jfd);
36209
39181
      }else{
36210
  /* Open the journal file if it is not already open. */
39182
        const int flags =                   /* VFS flags to open journal file */
36211
  if( !isOpen(pPager->jfd) ){
39183
          SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
36212
    if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
39184
          (pPager->tempFile ? 
36213
      sqlite3MemJournalOpen(pPager->jfd);
39185
            (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
36214
    }else{
39186
            (SQLITE_OPEN_MAIN_JOURNAL)
36215
      const int flags =                   /* VFS flags to open journal file */
39187
          );
36216
        SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
39188
  #ifdef SQLITE_ENABLE_ATOMIC_WRITE
36217
        (pPager->tempFile ? 
39189
        rc = sqlite3JournalOpen(
36218
          (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
39190
            pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
36219
          (SQLITE_OPEN_MAIN_JOURNAL)
36220
        );
39191
        );
36221
#ifdef SQLITE_ENABLE_ATOMIC_WRITE
39192
  #else
36222
      rc = sqlite3JournalOpen(
39193
        rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
36223
          pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
39194
  #endif
36224
      );
39195
      }
36225
#else
39196
      assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
36226
      rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
39197
    }
36227
#endif
39198
  
36228
    }
39199
  
36229
    assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
39200
    /* Write the first journal header to the journal file and open 
36230
  }
39201
    ** the sub-journal if necessary.
36231
39202
    */
36232
39203
    if( rc==SQLITE_OK ){
36233
  /* Write the first journal header to the journal file and open 
39204
      /* TODO: Check if all of these are really required. */
36234
  ** the sub-journal if necessary.
39205
      pPager->nRec = 0;
36235
  */
39206
      pPager->journalOff = 0;
36236
  if( rc==SQLITE_OK ){
39207
      pPager->setMaster = 0;
36237
    /* TODO: Check if all of these are really required. */
39208
      pPager->journalHdr = 0;
36238
    pPager->dbOrigSize = pPager->dbSize;
39209
      rc = writeJournalHdr(pPager);
36239
    pPager->journalStarted = 0;
39210
    }
36240
    pPager->needSync = 0;
36241
    pPager->nRec = 0;
36242
    pPager->journalOff = 0;
36243
    pPager->setMaster = 0;
36244
    pPager->journalHdr = 0;
36245
    rc = writeJournalHdr(pPager);
36246
  }
36247
  if( rc==SQLITE_OK && pPager->nSavepoint ){
36248
    rc = openSubJournal(pPager);
36249
  }
39211
  }
36250
39212
36251
  if( rc!=SQLITE_OK ){
39213
  if( rc!=SQLITE_OK ){
36252
    sqlite3BitvecDestroy(pPager->pInJournal);
39214
    sqlite3BitvecDestroy(pPager->pInJournal);
36253
    pPager->pInJournal = 0;
39215
    pPager->pInJournal = 0;
36254
  }
39216
  }else{
39217
    assert( pPager->eState==PAGER_WRITER_LOCKED );
39218
    pPager->eState = PAGER_WRITER_CACHEMOD;
39219
  }
39220
36255
  return rc;
39221
  return rc;
36256
}
39222
}
36257
39223
 Lines 36264-36277   static int pager_open_journal(Pager *pPa Link Here 
36264
** an EXCLUSIVE lock. If such a lock is already held, no locking 
39230
** an EXCLUSIVE lock. If such a lock is already held, no locking 
36265
** functions need be called.
39231
** functions need be called.
36266
**
39232
**
36267
** If this is not a temporary or in-memory file and, the journal file is 
36268
** opened if it has not been already. For a temporary file, the opening 
36269
** of the journal file is deferred until there is an actual need to 
36270
** write to the journal. TODO: Why handle temporary files differently?
36271
**
36272
** If the journal file is opened (or if it is already open), then a
36273
** journal-header is written to the start of it.
36274
**
36275
** If the subjInMemory argument is non-zero, then any sub-journal opened
39233
** If the subjInMemory argument is non-zero, then any sub-journal opened
36276
** within this transaction will be opened as an in-memory file. This
39234
** within this transaction will be opened as an in-memory file. This
36277
** has no effect if the sub-journal is already opened (as it may be when
39235
** has no effect if the sub-journal is already opened (as it may be when
 Lines 36282-36336   static int pager_open_journal(Pager *pPa Link Here 
36282
*/
39240
*/
36283
SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
39241
SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
36284
  int rc = SQLITE_OK;
39242
  int rc = SQLITE_OK;
36285
  assert( pPager->state!=PAGER_UNLOCK );
39243
39244
  if( pPager->errCode ) return pPager->errCode;
39245
  assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
36286
  pPager->subjInMemory = (u8)subjInMemory;
39246
  pPager->subjInMemory = (u8)subjInMemory;
36287
  if( pPager->state==PAGER_SHARED ){
39247
39248
  if( ALWAYS(pPager->eState==PAGER_READER) ){
36288
    assert( pPager->pInJournal==0 );
39249
    assert( pPager->pInJournal==0 );
36289
    assert( !MEMDB && !pPager->tempFile );
39250
36290
39251
    if( pagerUseWal(pPager) ){
36291
    /* Obtain a RESERVED lock on the database file. If the exFlag parameter
39252
      /* If the pager is configured to use locking_mode=exclusive, and an
36292
    ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
39253
      ** exclusive lock on the database is not already held, obtain it now.
36293
    ** busy-handler callback can be used when upgrading to the EXCLUSIVE
39254
      */
36294
    ** lock, but not when obtaining the RESERVED lock.
39255
      if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
36295
    */
39256
        rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
36296
    rc = sqlite3OsLock(pPager->fd, RESERVED_LOCK);
39257
        if( rc!=SQLITE_OK ){
39258
          return rc;
39259
        }
39260
        sqlite3WalExclusiveMode(pPager->pWal, 1);
39261
      }
39262
39263
      /* Grab the write lock on the log file. If successful, upgrade to
39264
      ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
39265
      ** The busy-handler is not invoked if another connection already
39266
      ** holds the write-lock. If possible, the upper layer will call it.
39267
      */
39268
      rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
39269
    }else{
39270
      /* Obtain a RESERVED lock on the database file. If the exFlag parameter
39271
      ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
39272
      ** busy-handler callback can be used when upgrading to the EXCLUSIVE
39273
      ** lock, but not when obtaining the RESERVED lock.
39274
      */
39275
      rc = pagerLockDb(pPager, RESERVED_LOCK);
39276
      if( rc==SQLITE_OK && exFlag ){
39277
        rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
39278
      }
39279
    }
39280
36297
    if( rc==SQLITE_OK ){
39281
    if( rc==SQLITE_OK ){
36298
      pPager->state = PAGER_RESERVED;
39282
      /* Change to WRITER_LOCKED state.
36299
      if( exFlag ){
39283
      **
36300
        rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
39284
      ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
36301
      }
39285
      ** when it has an open transaction, but never to DBMOD or FINISHED.
36302
    }
39286
      ** This is because in those states the code to roll back savepoint 
36303
39287
      ** transactions may copy data from the sub-journal into the database 
36304
    /* If the required locks were successfully obtained, open the journal
39288
      ** file as well as into the page cache. Which would be incorrect in 
36305
    ** file and write the first journal-header to it.
39289
      ** WAL mode.
36306
    */
39290
      */
36307
    if( rc==SQLITE_OK && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
39291
      pPager->eState = PAGER_WRITER_LOCKED;
36308
      rc = pager_open_journal(pPager);
39292
      pPager->dbHintSize = pPager->dbSize;
36309
    }
39293
      pPager->dbFileSize = pPager->dbSize;
36310
  }else if( isOpen(pPager->jfd) && pPager->journalOff==0 ){
39294
      pPager->dbOrigSize = pPager->dbSize;
36311
    /* This happens when the pager was in exclusive-access mode the last
39295
      pPager->journalOff = 0;
36312
    ** time a (read or write) transaction was successfully concluded
39296
    }
36313
    ** by this connection. Instead of deleting the journal file it was 
39297
36314
    ** kept open and either was truncated to 0 bytes or its header was
39298
    assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
36315
    ** overwritten with zeros.
39299
    assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
36316
    */
39300
    assert( assert_pager_state(pPager) );
36317
    assert( pPager->nRec==0 );
36318
    assert( pPager->dbOrigSize==0 );
36319
    assert( pPager->pInJournal==0 );
36320
    rc = pager_open_journal(pPager);
36321
  }
39301
  }
36322
39302
36323
  PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
39303
  PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
36324
  assert( !isOpen(pPager->jfd) || pPager->journalOff>0 || rc!=SQLITE_OK );
36325
  if( rc!=SQLITE_OK ){
36326
    assert( !pPager->dbModified );
36327
    /* Ignore any IO error that occurs within pager_end_transaction(). The
36328
    ** purpose of this call is to reset the internal state of the pager
36329
    ** sub-system. It doesn't matter if the journal-file is not properly
36330
    ** finalized at this point (since it is not a valid journal file anyway).
36331
    */
36332
    pager_end_transaction(pPager, 0);
36333
  }
36334
  return rc;
39304
  return rc;
36335
}
39305
}
36336
39306
 Lines 36346-36367   static int pager_write(PgHdr *pPg){ Link Here 
36346
  Pager *pPager = pPg->pPager;
39316
  Pager *pPager = pPg->pPager;
36347
  int rc = SQLITE_OK;
39317
  int rc = SQLITE_OK;
36348
39318
36349
  /* This routine is not called unless a transaction has already been
39319
  /* This routine is not called unless a write-transaction has already 
36350
  ** started.
39320
  ** been started. The journal file may or may not be open at this point.
36351
  */
39321
  ** It is never called in the ERROR state.
36352
  assert( pPager->state>=PAGER_RESERVED );
39322
  */
36353
39323
  assert( pPager->eState==PAGER_WRITER_LOCKED
36354
  /* If an error has been previously detected, we should not be
39324
       || pPager->eState==PAGER_WRITER_CACHEMOD
36355
  ** calling this routine.  Repeat the error for robustness.
39325
       || pPager->eState==PAGER_WRITER_DBMOD
36356
  */
39326
  );
39327
  assert( assert_pager_state(pPager) );
39328
39329
  /* If an error has been previously detected, report the same error
39330
  ** again. This should not happen, but the check provides robustness. */
36357
  if( NEVER(pPager->errCode) )  return pPager->errCode;
39331
  if( NEVER(pPager->errCode) )  return pPager->errCode;
36358
39332
36359
  /* Higher-level routines never call this function if database is not
39333
  /* Higher-level routines never call this function if database is not
36360
  ** writable.  But check anyway, just for robustness. */
39334
  ** writable.  But check anyway, just for robustness. */
36361
  if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
39335
  if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
36362
39336
36363
  assert( !pPager->setMaster );
36364
36365
  CHECK_PAGE(pPg);
39337
  CHECK_PAGE(pPg);
36366
39338
36367
  /* Mark the page as dirty.  If the page has already been written
39339
  /* Mark the page as dirty.  If the page has already been written
 Lines 36369-36421   static int pager_write(PgHdr *pPg){ Link Here 
36369
  */
39341
  */
36370
  sqlite3PcacheMakeDirty(pPg);
39342
  sqlite3PcacheMakeDirty(pPg);
36371
  if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
39343
  if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
36372
    pPager->dbModified = 1;
39344
    assert( !pagerUseWal(pPager) );
39345
    assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
36373
  }else{
39346
  }else{
36374
39347
36375
    /* If we get this far, it means that the page needs to be
39348
    /* If we get this far, it means that the page needs to be
36376
    ** written to the transaction journal or the ckeckpoint journal
39349
    ** written to the transaction journal or the checkpoint journal
36377
    ** or both.
39350
    ** or both.
36378
    **
39351
    **
36379
    ** Higher level routines should have already started a transaction,
39352
    ** Higher level routines have already obtained the necessary locks
36380
    ** which means they have acquired the necessary locks and opened
39353
    ** to begin the write-transaction, but the rollback journal might not 
36381
    ** a rollback journal.  Double-check to makes sure this is the case.
39354
    ** yet be open. Open it now if this is the case.
36382
    */
39355
    */
36383
    rc = sqlite3PagerBegin(pPager, 0, pPager->subjInMemory);
39356
    if( pPager->eState==PAGER_WRITER_LOCKED ){
36384
    if( NEVER(rc!=SQLITE_OK) ){
36385
      return rc;
36386
    }
36387
    if( !isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
36388
      assert( pPager->useJournal );
36389
      rc = pager_open_journal(pPager);
39357
      rc = pager_open_journal(pPager);
36390
      if( rc!=SQLITE_OK ) return rc;
39358
      if( rc!=SQLITE_OK ) return rc;
36391
    }
39359
    }
36392
    pPager->dbModified = 1;
39360
    assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
39361
    assert( assert_pager_state(pPager) );
36393
  
39362
  
36394
    /* The transaction journal now exists and we have a RESERVED or an
39363
    /* The transaction journal now exists and we have a RESERVED or an
36395
    ** EXCLUSIVE lock on the main database file.  Write the current page to
39364
    ** EXCLUSIVE lock on the main database file.  Write the current page to
36396
    ** the transaction journal if it is not there already.
39365
    ** the transaction journal if it is not there already.
36397
    */
39366
    */
36398
    if( !pageInJournal(pPg) && isOpen(pPager->jfd) ){
39367
    if( !pageInJournal(pPg) && !pagerUseWal(pPager) ){
36399
      if( pPg->pgno<=pPager->dbOrigSize ){
39368
      assert( pagerUseWal(pPager)==0 );
39369
      if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
36400
        u32 cksum;
39370
        u32 cksum;
36401
        char *pData2;
39371
        char *pData2;
39372
        i64 iOff = pPager->journalOff;
36402
39373
36403
        /* We should never write to the journal file the page that
39374
        /* We should never write to the journal file the page that
36404
        ** contains the database locks.  The following assert verifies
39375
        ** contains the database locks.  The following assert verifies
36405
        ** that we do not. */
39376
        ** that we do not. */
36406
        assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
39377
        assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
39378
39379
        assert( pPager->journalHdr<=pPager->journalOff );
36407
        CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
39380
        CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
36408
        cksum = pager_cksum(pPager, (u8*)pData2);
39381
        cksum = pager_cksum(pPager, (u8*)pData2);
36409
        rc = write32bits(pPager->jfd, pPager->journalOff, pPg->pgno);
39382
36410
        if( rc==SQLITE_OK ){
39383
        /* Even if an IO or diskfull error occurs while journalling the
36411
          rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize,
39384
        ** page in the block above, set the need-sync flag for the page.
36412
                              pPager->journalOff + 4);
39385
        ** Otherwise, when the transaction is rolled back, the logic in
36413
          pPager->journalOff += pPager->pageSize+4;
39386
        ** playback_one_page() will think that the page needs to be restored
36414
        }
39387
        ** in the database file. And if an IO error occurs while doing so,
36415
        if( rc==SQLITE_OK ){
39388
        ** then corruption may follow.
36416
          rc = write32bits(pPager->jfd, pPager->journalOff, cksum);
39389
        */
36417
          pPager->journalOff += 4;
39390
        pPg->flags |= PGHDR_NEED_SYNC;
36418
        }
39391
39392
        rc = write32bits(pPager->jfd, iOff, pPg->pgno);
39393
        if( rc!=SQLITE_OK ) return rc;
39394
        rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
39395
        if( rc!=SQLITE_OK ) return rc;
39396
        rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
39397
        if( rc!=SQLITE_OK ) return rc;
39398
36419
        IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno, 
39399
        IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno, 
36420
                 pPager->journalOff, pPager->pageSize));
39400
                 pPager->journalOff, pPager->pageSize));
36421
        PAGER_INCR(sqlite3_pager_writej_count);
39401
        PAGER_INCR(sqlite3_pager_writej_count);
 Lines 36423-36447   static int pager_write(PgHdr *pPg){ Link Here 
36423
             PAGERID(pPager), pPg->pgno, 
39403
             PAGERID(pPager), pPg->pgno, 
36424
             ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
39404
             ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
36425
39405
36426
        /* Even if an IO or diskfull error occurred while journalling the
39406
        pPager->journalOff += 8 + pPager->pageSize;
36427
        ** page in the block above, set the need-sync flag for the page.
36428
        ** Otherwise, when the transaction is rolled back, the logic in
36429
        ** playback_one_page() will think that the page needs to be restored
36430
        ** in the database file. And if an IO error occurs while doing so,
36431
        ** then corruption may follow.
36432
        */
36433
        if( !pPager->noSync ){
36434
          pPg->flags |= PGHDR_NEED_SYNC;
36435
          pPager->needSync = 1;
36436
        }
36437
36438
        /* An error has occurred writing to the journal file. The 
36439
        ** transaction will be rolled back by the layer above.
36440
        */
36441
        if( rc!=SQLITE_OK ){
36442
          return rc;
36443
        }
36444
36445
        pPager->nRec++;
39407
        pPager->nRec++;
36446
        assert( pPager->pInJournal!=0 );
39408
        assert( pPager->pInJournal!=0 );
36447
        rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
39409
        rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
 Lines 36453-36461   static int pager_write(PgHdr *pPg){ Link Here 
36453
          return rc;
39415
          return rc;
36454
        }
39416
        }
36455
      }else{
39417
      }else{
36456
        if( !pPager->journalStarted && !pPager->noSync ){
39418
        if( pPager->eState!=PAGER_WRITER_DBMOD ){
36457
          pPg->flags |= PGHDR_NEED_SYNC;
39419
          pPg->flags |= PGHDR_NEED_SYNC;
36458
          pPager->needSync = 1;
36459
        }
39420
        }
36460
        PAGERTRACE(("APPEND %d page %d needSync=%d\n",
39421
        PAGERTRACE(("APPEND %d page %d needSync=%d\n",
36461
                PAGERID(pPager), pPg->pgno,
39422
                PAGERID(pPager), pPg->pgno,
 Lines 36475-36481   static int pager_write(PgHdr *pPg){ Link Here 
36475
39436
36476
  /* Update the database size and return.
39437
  /* Update the database size and return.
36477
  */
39438
  */
36478
  assert( pPager->state>=PAGER_SHARED );
36479
  if( pPager->dbSize<pPg->pgno ){
39439
  if( pPager->dbSize<pPg->pgno ){
36480
    pPager->dbSize = pPg->pgno;
39440
    pPager->dbSize = pPg->pgno;
36481
  }
39441
  }
 Lines 36503-36521   SQLITE_PRIVATE int sqlite3PagerWrite(DbP Link Here 
36503
  Pager *pPager = pPg->pPager;
39463
  Pager *pPager = pPg->pPager;
36504
  Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
39464
  Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
36505
39465
39466
  assert( pPager->eState>=PAGER_WRITER_LOCKED );
39467
  assert( pPager->eState!=PAGER_ERROR );
39468
  assert( assert_pager_state(pPager) );
39469
36506
  if( nPagePerSector>1 ){
39470
  if( nPagePerSector>1 ){
36507
    Pgno nPageCount;          /* Total number of pages in database file */
39471
    Pgno nPageCount;          /* Total number of pages in database file */
36508
    Pgno pg1;                 /* First page of the sector pPg is located on. */
39472
    Pgno pg1;                 /* First page of the sector pPg is located on. */
36509
    int nPage;                /* Number of pages starting at pg1 to journal */
39473
    int nPage = 0;            /* Number of pages starting at pg1 to journal */
36510
    int ii;                   /* Loop counter */
39474
    int ii;                   /* Loop counter */
36511
    int needSync = 0;         /* True if any page has PGHDR_NEED_SYNC */
39475
    int needSync = 0;         /* True if any page has PGHDR_NEED_SYNC */
36512
39476
36513
    /* Set the doNotSync flag to 1. This is because we cannot allow a journal
39477
    /* Set the doNotSyncSpill flag to 1. This is because we cannot allow
36514
    ** header to be written between the pages journaled by this function.
39478
    ** a journal header to be written between the pages journaled by
39479
    ** this function.
36515
    */
39480
    */
36516
    assert( !MEMDB );
39481
    assert( !MEMDB );
36517
    assert( pPager->doNotSync==0 );
39482
    assert( pPager->doNotSyncSpill==0 );
36518
    pPager->doNotSync = 1;
39483
    pPager->doNotSyncSpill++;
36519
39484
36520
    /* This trick assumes that both the page-size and sector-size are
39485
    /* This trick assumes that both the page-size and sector-size are
36521
    ** an integer power of 2. It sets variable pg1 to the identifier
39486
    ** an integer power of 2. It sets variable pg1 to the identifier
 Lines 36523-36529   SQLITE_PRIVATE int sqlite3PagerWrite(DbP Link Here 
36523
    */
39488
    */
36524
    pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
39489
    pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
36525
39490
36526
    sqlite3PagerPagecount(pPager, (int *)&nPageCount);
39491
    nPageCount = pPager->dbSize;
36527
    if( pPg->pgno>nPageCount ){
39492
    if( pPg->pgno>nPageCount ){
36528
      nPage = (pPg->pgno - pg1)+1;
39493
      nPage = (pPg->pgno - pg1)+1;
36529
    }else if( (pg1+nPagePerSector-1)>nPageCount ){
39494
    }else if( (pg1+nPagePerSector-1)>nPageCount ){
 Lines 36545-36551   SQLITE_PRIVATE int sqlite3PagerWrite(DbP Link Here 
36545
            rc = pager_write(pPage);
39510
            rc = pager_write(pPage);
36546
            if( pPage->flags&PGHDR_NEED_SYNC ){
39511
            if( pPage->flags&PGHDR_NEED_SYNC ){
36547
              needSync = 1;
39512
              needSync = 1;
36548
              assert(pPager->needSync);
36549
            }
39513
            }
36550
            sqlite3PagerUnref(pPage);
39514
            sqlite3PagerUnref(pPage);
36551
          }
39515
          }
 Lines 36565-36571   SQLITE_PRIVATE int sqlite3PagerWrite(DbP Link Here 
36565
    ** before any of them can be written out to the database file.
39529
    ** before any of them can be written out to the database file.
36566
    */
39530
    */
36567
    if( rc==SQLITE_OK && needSync ){
39531
    if( rc==SQLITE_OK && needSync ){
36568
      assert( !MEMDB && pPager->noSync==0 );
39532
      assert( !MEMDB );
36569
      for(ii=0; ii<nPage; ii++){
39533
      for(ii=0; ii<nPage; ii++){
36570
        PgHdr *pPage = pager_lookup(pPager, pg1+ii);
39534
        PgHdr *pPage = pager_lookup(pPager, pg1+ii);
36571
        if( pPage ){
39535
        if( pPage ){
 Lines 36573-36583   SQLITE_PRIVATE int sqlite3PagerWrite(DbP Link Here 
36573
          sqlite3PagerUnref(pPage);
39537
          sqlite3PagerUnref(pPage);
36574
        }
39538
        }
36575
      }
39539
      }
36576
      assert(pPager->needSync);
39540
    }
36577
    }
39541
36578
39542
    assert( pPager->doNotSyncSpill==1 );
36579
    assert( pPager->doNotSync==1 );
39543
    pPager->doNotSyncSpill--;
36580
    pPager->doNotSync = 0;
36581
  }else{
39544
  }else{
36582
    rc = pager_write(pDbPage);
39545
    rc = pager_write(pDbPage);
36583
  }
39546
  }
 Lines 36640-36645   SQLITE_PRIVATE void sqlite3PagerDontWrit Link Here 
36640
static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
39603
static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
36641
  int rc = SQLITE_OK;
39604
  int rc = SQLITE_OK;
36642
39605
39606
  assert( pPager->eState==PAGER_WRITER_CACHEMOD
39607
       || pPager->eState==PAGER_WRITER_DBMOD
39608
  );
39609
  assert( assert_pager_state(pPager) );
39610
36643
  /* Declare and initialize constant integer 'isDirect'. If the
39611
  /* Declare and initialize constant integer 'isDirect'. If the
36644
  ** atomic-write optimization is enabled in this build, then isDirect
39612
  ** atomic-write optimization is enabled in this build, then isDirect
36645
  ** is initialized to the value passed as the isDirectMode parameter
39613
  ** is initialized to the value passed as the isDirectMode parameter
 Lines 36658-36664   static int pager_incr_changecounter(Page Link Here 
36658
# define DIRECT_MODE isDirectMode
39626
# define DIRECT_MODE isDirectMode
36659
#endif
39627
#endif
36660
39628
36661
  assert( pPager->state>=PAGER_RESERVED );
36662
  if( !pPager->changeCountDone && pPager->dbSize>0 ){
39629
  if( !pPager->changeCountDone && pPager->dbSize>0 ){
36663
    PgHdr *pPgHdr;                /* Reference to page 1 */
39630
    PgHdr *pPgHdr;                /* Reference to page 1 */
36664
    u32 change_counter;           /* Initial value of change-counter field */
39631
    u32 change_counter;           /* Initial value of change-counter field */
 Lines 36684-36694   static int pager_incr_changecounter(Page Link Here 
36684
      change_counter++;
39651
      change_counter++;
36685
      put32bits(((char*)pPgHdr->pData)+24, change_counter);
39652
      put32bits(((char*)pPgHdr->pData)+24, change_counter);
36686
39653
39654
      /* Also store the SQLite version number in bytes 96..99 and in
39655
      ** bytes 92..95 store the change counter for which the version number
39656
      ** is valid. */
39657
      put32bits(((char*)pPgHdr->pData)+92, change_counter);
39658
      put32bits(((char*)pPgHdr->pData)+96, SQLITE_VERSION_NUMBER);
39659
36687
      /* If running in direct mode, write the contents of page 1 to the file. */
39660
      /* If running in direct mode, write the contents of page 1 to the file. */
36688
      if( DIRECT_MODE ){
39661
      if( DIRECT_MODE ){
36689
        const void *zBuf = pPgHdr->pData;
39662
        const void *zBuf;
36690
        assert( pPager->dbFileSize>0 );
39663
        assert( pPager->dbFileSize>0 );
36691
        rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
39664
        CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
39665
        if( rc==SQLITE_OK ){
39666
          rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
39667
        }
36692
        if( rc==SQLITE_OK ){
39668
        if( rc==SQLITE_OK ){
36693
          pPager->changeCountDone = 1;
39669
          pPager->changeCountDone = 1;
36694
        }
39670
        }
 Lines 36722-36727   SQLITE_PRIVATE int sqlite3PagerSync(Page Link Here 
36722
}
39698
}
36723
39699
36724
/*
39700
/*
39701
** This function may only be called while a write-transaction is active in
39702
** rollback. If the connection is in WAL mode, this call is a no-op. 
39703
** Otherwise, if the connection does not already have an EXCLUSIVE lock on 
39704
** the database file, an attempt is made to obtain one.
39705
**
39706
** If the EXCLUSIVE lock is already held or the attempt to obtain it is
39707
** successful, or the connection is in WAL mode, SQLITE_OK is returned.
39708
** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is 
39709
** returned.
39710
*/
39711
SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
39712
  int rc = SQLITE_OK;
39713
  assert( pPager->eState==PAGER_WRITER_CACHEMOD 
39714
       || pPager->eState==PAGER_WRITER_DBMOD 
39715
       || pPager->eState==PAGER_WRITER_LOCKED 
39716
  );
39717
  assert( assert_pager_state(pPager) );
39718
  if( 0==pagerUseWal(pPager) ){
39719
    rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
39720
  }
39721
  return rc;
39722
}
39723
39724
/*
36725
** Sync the database file for the pager pPager. zMaster points to the name
39725
** Sync the database file for the pager pPager. zMaster points to the name
36726
** of a master journal file that should be written into the individual
39726
** of a master journal file that should be written into the individual
36727
** journal file. zMaster may be NULL, which is interpreted as no master
39727
** journal file. zMaster may be NULL, which is interpreted as no master
 Lines 36754-36904   SQLITE_PRIVATE int sqlite3PagerCommitPha Link Here 
36754
){
39754
){
36755
  int rc = SQLITE_OK;             /* Return code */
39755
  int rc = SQLITE_OK;             /* Return code */
36756
39756
36757
  /* The dbOrigSize is never set if journal_mode=OFF */
39757
  assert( pPager->eState==PAGER_WRITER_LOCKED
36758
  assert( pPager->journalMode!=PAGER_JOURNALMODE_OFF || pPager->dbOrigSize==0 );
39758
       || pPager->eState==PAGER_WRITER_CACHEMOD
36759
39759
       || pPager->eState==PAGER_WRITER_DBMOD
36760
  /* If a prior error occurred, this routine should not be called.  ROLLBACK
39760
       || pPager->eState==PAGER_ERROR
36761
  ** is the appropriate response to an error, not COMMIT.  Guard against
39761
  );
36762
  ** coding errors by repeating the prior error. */
39762
  assert( assert_pager_state(pPager) );
39763
39764
  /* If a prior error occurred, report that error again. */
36763
  if( NEVER(pPager->errCode) ) return pPager->errCode;
39765
  if( NEVER(pPager->errCode) ) return pPager->errCode;
36764
39766
36765
  PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n", 
39767
  PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n", 
36766
      pPager->zFilename, zMaster, pPager->dbSize));
39768
      pPager->zFilename, zMaster, pPager->dbSize));
36767
39769
36768
  if( MEMDB && pPager->dbModified ){
39770
  /* If no database changes have been made, return early. */
39771
  if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
39772
39773
  if( MEMDB ){
36769
    /* If this is an in-memory db, or no pages have been written to, or this
39774
    /* If this is an in-memory db, or no pages have been written to, or this
36770
    ** function has already been called, it is mostly a no-op.  However, any
39775
    ** function has already been called, it is mostly a no-op.  However, any
36771
    ** backup in progress needs to be restarted.
39776
    ** backup in progress needs to be restarted.
36772
    */
39777
    */
36773
    sqlite3BackupRestart(pPager->pBackup);
39778
    sqlite3BackupRestart(pPager->pBackup);
36774
  }else if( pPager->state!=PAGER_SYNCED && pPager->dbModified ){
39779
  }else{
36775
39780
    if( pagerUseWal(pPager) ){
36776
    /* The following block updates the change-counter. Exactly how it
39781
      PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
36777
    ** does this depends on whether or not the atomic-update optimization
39782
      if( pList ){
36778
    ** was enabled at compile time, and if this transaction meets the 
39783
        rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1, 
36779
    ** runtime criteria to use the operation: 
39784
            (pPager->fullSync ? pPager->sync_flags : 0)
36780
    **
39785
        );
36781
    **    * The file-system supports the atomic-write property for
39786
      }
36782
    **      blocks of size page-size, and 
36783
    **    * This commit is not part of a multi-file transaction, and
36784
    **    * Exactly one page has been modified and store in the journal file.
36785
    **
36786
    ** If the optimization was not enabled at compile time, then the
36787
    ** pager_incr_changecounter() function is called to update the change
36788
    ** counter in 'indirect-mode'. If the optimization is compiled in but
36789
    ** is not applicable to this transaction, call sqlite3JournalCreate()
36790
    ** to make sure the journal file has actually been created, then call
36791
    ** pager_incr_changecounter() to update the change-counter in indirect
36792
    ** mode. 
36793
    **
36794
    ** Otherwise, if the optimization is both enabled and applicable,
36795
    ** then call pager_incr_changecounter() to update the change-counter
36796
    ** in 'direct' mode. In this case the journal file will never be
36797
    ** created for this transaction.
36798
    */
36799
#ifdef SQLITE_ENABLE_ATOMIC_WRITE
36800
    PgHdr *pPg;
36801
    assert( isOpen(pPager->jfd) || pPager->journalMode==PAGER_JOURNALMODE_OFF );
36802
    if( !zMaster && isOpen(pPager->jfd) 
36803
     && pPager->journalOff==jrnlBufferSize(pPager) 
36804
     && pPager->dbSize>=pPager->dbFileSize
36805
     && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
36806
    ){
36807
      /* Update the db file change counter via the direct-write method. The 
36808
      ** following call will modify the in-memory representation of page 1 
36809
      ** to include the updated change counter and then write page 1 
36810
      ** directly to the database file. Because of the atomic-write 
36811
      ** property of the host file-system, this is safe.
36812
      */
36813
      rc = pager_incr_changecounter(pPager, 1);
36814
    }else{
36815
      rc = sqlite3JournalCreate(pPager->jfd);
36816
      if( rc==SQLITE_OK ){
39787
      if( rc==SQLITE_OK ){
36817
        rc = pager_incr_changecounter(pPager, 0);
39788
        sqlite3PcacheCleanAll(pPager->pPCache);
36818
      }
39789
      }
36819
    }
39790
    }else{
36820
#else
39791
      /* The following block updates the change-counter. Exactly how it
36821
    rc = pager_incr_changecounter(pPager, 0);
39792
      ** does this depends on whether or not the atomic-update optimization
36822
#endif
39793
      ** was enabled at compile time, and if this transaction meets the 
36823
    if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
39794
      ** runtime criteria to use the operation: 
36824
39795
      **
36825
    /* If this transaction has made the database smaller, then all pages
39796
      **    * The file-system supports the atomic-write property for
36826
    ** being discarded by the truncation must be written to the journal
39797
      **      blocks of size page-size, and 
36827
    ** file. This can only happen in auto-vacuum mode.
39798
      **    * This commit is not part of a multi-file transaction, and
36828
    **
39799
      **    * Exactly one page has been modified and store in the journal file.
36829
    ** Before reading the pages with page numbers larger than the 
39800
      **
36830
    ** current value of Pager.dbSize, set dbSize back to the value
39801
      ** If the optimization was not enabled at compile time, then the
36831
    ** that it took at the start of the transaction. Otherwise, the
39802
      ** pager_incr_changecounter() function is called to update the change
36832
    ** calls to sqlite3PagerGet() return zeroed pages instead of 
39803
      ** counter in 'indirect-mode'. If the optimization is compiled in but
36833
    ** reading data from the database file.
39804
      ** is not applicable to this transaction, call sqlite3JournalCreate()
36834
    **
39805
      ** to make sure the journal file has actually been created, then call
36835
    ** When journal_mode==OFF the dbOrigSize is always zero, so this
39806
      ** pager_incr_changecounter() to update the change-counter in indirect
36836
    ** block never runs if journal_mode=OFF.
39807
      ** mode. 
36837
    */
39808
      **
36838
#ifndef SQLITE_OMIT_AUTOVACUUM
39809
      ** Otherwise, if the optimization is both enabled and applicable,
36839
    if( pPager->dbSize<pPager->dbOrigSize 
39810
      ** then call pager_incr_changecounter() to update the change-counter
36840
     && ALWAYS(pPager->journalMode!=PAGER_JOURNALMODE_OFF)
39811
      ** in 'direct' mode. In this case the journal file will never be
36841
    ){
39812
      ** created for this transaction.
36842
      Pgno i;                                   /* Iterator variable */
39813
      */
36843
      const Pgno iSkip = PAGER_MJ_PGNO(pPager); /* Pending lock page */
39814
  #ifdef SQLITE_ENABLE_ATOMIC_WRITE
36844
      const Pgno dbSize = pPager->dbSize;       /* Database image size */ 
39815
      PgHdr *pPg;
36845
      pPager->dbSize = pPager->dbOrigSize;
39816
      assert( isOpen(pPager->jfd) 
36846
      for( i=dbSize+1; i<=pPager->dbOrigSize; i++ ){
39817
           || pPager->journalMode==PAGER_JOURNALMODE_OFF 
36847
        if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
39818
           || pPager->journalMode==PAGER_JOURNALMODE_WAL 
36848
          PgHdr *pPage;             /* Page to journal */
39819
      );
36849
          rc = sqlite3PagerGet(pPager, i, &pPage);
39820
      if( !zMaster && isOpen(pPager->jfd) 
36850
          if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
39821
       && pPager->journalOff==jrnlBufferSize(pPager) 
36851
          rc = sqlite3PagerWrite(pPage);
39822
       && pPager->dbSize>=pPager->dbOrigSize
36852
          sqlite3PagerUnref(pPage);
39823
       && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
36853
          if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
39824
      ){
36854
        }
39825
        /* Update the db file change counter via the direct-write method. The 
39826
        ** following call will modify the in-memory representation of page 1 
39827
        ** to include the updated change counter and then write page 1 
39828
        ** directly to the database file. Because of the atomic-write 
39829
        ** property of the host file-system, this is safe.
39830
        */
39831
        rc = pager_incr_changecounter(pPager, 1);
39832
      }else{
39833
        rc = sqlite3JournalCreate(pPager->jfd);
39834
        if( rc==SQLITE_OK ){
39835
          rc = pager_incr_changecounter(pPager, 0);
39836
        }
39837
      }
39838
  #else
39839
      rc = pager_incr_changecounter(pPager, 0);
39840
  #endif
39841
      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
39842
  
39843
      /* If this transaction has made the database smaller, then all pages
39844
      ** being discarded by the truncation must be written to the journal
39845
      ** file. This can only happen in auto-vacuum mode.
39846
      **
39847
      ** Before reading the pages with page numbers larger than the 
39848
      ** current value of Pager.dbSize, set dbSize back to the value
39849
      ** that it took at the start of the transaction. Otherwise, the
39850
      ** calls to sqlite3PagerGet() return zeroed pages instead of 
39851
      ** reading data from the database file.
39852
      */
39853
  #ifndef SQLITE_OMIT_AUTOVACUUM
39854
      if( pPager->dbSize<pPager->dbOrigSize 
39855
       && pPager->journalMode!=PAGER_JOURNALMODE_OFF
39856
      ){
39857
        Pgno i;                                   /* Iterator variable */
39858
        const Pgno iSkip = PAGER_MJ_PGNO(pPager); /* Pending lock page */
39859
        const Pgno dbSize = pPager->dbSize;       /* Database image size */ 
39860
        pPager->dbSize = pPager->dbOrigSize;
39861
        for( i=dbSize+1; i<=pPager->dbOrigSize; i++ ){
39862
          if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
39863
            PgHdr *pPage;             /* Page to journal */
39864
            rc = sqlite3PagerGet(pPager, i, &pPage);
39865
            if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
39866
            rc = sqlite3PagerWrite(pPage);
39867
            sqlite3PagerUnref(pPage);
39868
            if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
39869
          }
39870
        }
39871
        pPager->dbSize = dbSize;
36855
      } 
39872
      } 
36856
      pPager->dbSize = dbSize;
39873
  #endif
36857
    }
39874
  
36858
#endif
39875
      /* Write the master journal name into the journal file. If a master 
36859
39876
      ** journal file name has already been written to the journal file, 
36860
    /* Write the master journal name into the journal file. If a master 
39877
      ** or if zMaster is NULL (no master journal), then this call is a no-op.
36861
    ** journal file name has already been written to the journal file, 
39878
      */
36862
    ** or if zMaster is NULL (no master journal), then this call is a no-op.
39879
      rc = writeMasterJournal(pPager, zMaster);
36863
    */
36864
    rc = writeMasterJournal(pPager, zMaster);
36865
    if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
36866
36867
    /* Sync the journal file. If the atomic-update optimization is being
36868
    ** used, this call will not create the journal file or perform any
36869
    ** real IO.
36870
    */
36871
    rc = syncJournal(pPager);
36872
    if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
36873
36874
    /* Write all dirty pages to the database file. */
36875
    rc = pager_write_pagelist(sqlite3PcacheDirtyList(pPager->pPCache));
36876
    if( rc!=SQLITE_OK ){
36877
      assert( rc!=SQLITE_IOERR_BLOCKED );
36878
      goto commit_phase_one_exit;
36879
    }
36880
    sqlite3PcacheCleanAll(pPager->pPCache);
36881
36882
    /* If the file on disk is not the same size as the database image,
36883
    ** then use pager_truncate to grow or shrink the file here.
36884
    */
36885
    if( pPager->dbSize!=pPager->dbFileSize ){
36886
      Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
36887
      assert( pPager->state>=PAGER_EXCLUSIVE );
36888
      rc = pager_truncate(pPager, nNew);
36889
      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
39880
      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
36890
    }
39881
  
36891
39882
      /* Sync the journal file and write all dirty pages to the database.
36892
    /* Finally, sync the database file. */
39883
      ** If the atomic-update optimization is being used, this sync will not 
36893
    if( !pPager->noSync && !noSync ){
39884
      ** create the journal file or perform any real IO.
36894
      rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
39885
      **
36895
    }
39886
      ** Because the change-counter page was just modified, unless the
36896
    IOTRACE(("DBSYNC %p\n", pPager))
39887
      ** atomic-update optimization is used it is almost certain that the
36897
39888
      ** journal requires a sync here. However, in locking_mode=exclusive
36898
    pPager->state = PAGER_SYNCED;
39889
      ** on a system under memory pressure it is just possible that this is 
39890
      ** not the case. In this case it is likely enough that the redundant
39891
      ** xSync() call will be changed to a no-op by the OS anyhow. 
39892
      */
39893
      rc = syncJournal(pPager, 0);
39894
      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
39895
  
39896
      rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
39897
      if( rc!=SQLITE_OK ){
39898
        assert( rc!=SQLITE_IOERR_BLOCKED );
39899
        goto commit_phase_one_exit;
39900
      }
39901
      sqlite3PcacheCleanAll(pPager->pPCache);
39902
  
39903
      /* If the file on disk is not the same size as the database image,
39904
      ** then use pager_truncate to grow or shrink the file here.
39905
      */
39906
      if( pPager->dbSize!=pPager->dbFileSize ){
39907
        Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
39908
        assert( pPager->eState==PAGER_WRITER_DBMOD );
39909
        rc = pager_truncate(pPager, nNew);
39910
        if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
39911
      }
39912
  
39913
      /* Finally, sync the database file. */
39914
      if( !pPager->noSync && !noSync ){
39915
        rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
39916
      }
39917
      IOTRACE(("DBSYNC %p\n", pPager))
39918
    }
36899
  }
39919
  }
36900
39920
36901
commit_phase_one_exit:
39921
commit_phase_one_exit:
39922
  if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
39923
    pPager->eState = PAGER_WRITER_FINISHED;
39924
  }
36902
  return rc;
39925
  return rc;
36903
}
39926
}
36904
39927
 Lines 36926-36936   SQLITE_PRIVATE int sqlite3PagerCommitPha Link Here 
36926
  ** called, just return the same error code without doing anything. */
39949
  ** called, just return the same error code without doing anything. */
36927
  if( NEVER(pPager->errCode) ) return pPager->errCode;
39950
  if( NEVER(pPager->errCode) ) return pPager->errCode;
36928
39951
36929
  /* This function should not be called if the pager is not in at least
39952
  assert( pPager->eState==PAGER_WRITER_LOCKED
36930
  ** PAGER_RESERVED state. And indeed SQLite never does this. But it is
39953
       || pPager->eState==PAGER_WRITER_FINISHED
36931
  ** nice to have this defensive test here anyway.
39954
       || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
36932
  */
39955
  );
36933
  if( NEVER(pPager->state<PAGER_RESERVED) ) return SQLITE_ERROR;
39956
  assert( assert_pager_state(pPager) );
36934
39957
36935
  /* An optimization. If the database was not actually modified during
39958
  /* An optimization. If the database was not actually modified during
36936
  ** this transaction, the pager is running in exclusive-mode and is
39959
  ** this transaction, the pager is running in exclusive-mode and is
 Lines 36943-37037   SQLITE_PRIVATE int sqlite3PagerCommitPha Link Here 
36943
  ** header. Since the pager is in exclusive mode, there is no need
39966
  ** header. Since the pager is in exclusive mode, there is no need
36944
  ** to drop any locks either.
39967
  ** to drop any locks either.
36945
  */
39968
  */
36946
  if( pPager->dbModified==0 && pPager->exclusiveMode 
39969
  if( pPager->eState==PAGER_WRITER_LOCKED 
39970
   && pPager->exclusiveMode 
36947
   && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
39971
   && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
36948
  ){
39972
  ){
36949
    assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
39973
    assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
39974
    pPager->eState = PAGER_READER;
36950
    return SQLITE_OK;
39975
    return SQLITE_OK;
36951
  }
39976
  }
36952
39977
36953
  PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
39978
  PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
36954
  assert( pPager->state==PAGER_SYNCED || MEMDB || !pPager->dbModified );
36955
  rc = pager_end_transaction(pPager, pPager->setMaster);
39979
  rc = pager_end_transaction(pPager, pPager->setMaster);
36956
  return pager_error(pPager, rc);
39980
  return pager_error(pPager, rc);
36957
}
39981
}
36958
39982
36959
/*
39983
/*
36960
** Rollback all changes. The database falls back to PAGER_SHARED mode.
39984
** If a write transaction is open, then all changes made within the 
36961
**
39985
** transaction are reverted and the current write-transaction is closed.
36962
** This function performs two tasks:
39986
** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
39987
** state if an error occurs.
39988
**
39989
** If the pager is already in PAGER_ERROR state when this function is called,
39990
** it returns Pager.errCode immediately. No work is performed in this case.
39991
**
39992
** Otherwise, in rollback mode, this function performs two functions:
36963
**
39993
**
36964
**   1) It rolls back the journal file, restoring all database file and 
39994
**   1) It rolls back the journal file, restoring all database file and 
36965
**      in-memory cache pages to the state they were in when the transaction
39995
**      in-memory cache pages to the state they were in when the transaction
36966
**      was opened, and
39996
**      was opened, and
39997
**
36967
**   2) It finalizes the journal file, so that it is not used for hot
39998
**   2) It finalizes the journal file, so that it is not used for hot
36968
**      rollback at any point in the future.
39999
**      rollback at any point in the future.
36969
**
40000
**
36970
** subject to the following qualifications:
40001
** Finalization of the journal file (task 2) is only performed if the 
36971
**
40002
** rollback is successful.
36972
** * If the journal file is not yet open when this function is called,
40003
**
36973
**   then only (2) is performed. In this case there is no journal file
40004
** In WAL mode, all cache-entries containing data modified within the
36974
**   to roll back.
40005
** current transaction are either expelled from the cache or reverted to
36975
**
40006
** their pre-transaction state by re-reading data from the database or
36976
** * If in an error state other than SQLITE_FULL, then task (1) is 
40007
** WAL files. The WAL transaction is then closed.
36977
**   performed. If successful, task (2). Regardless of the outcome
36978
**   of either, the error state error code is returned to the caller
36979
**   (i.e. either SQLITE_IOERR or SQLITE_CORRUPT).
36980
**
36981
** * If the pager is in PAGER_RESERVED state, then attempt (1). Whether
36982
**   or not (1) is succussful, also attempt (2). If successful, return
36983
**   SQLITE_OK. Otherwise, enter the error state and return the first 
36984
**   error code encountered. 
36985
**
36986
**   In this case there is no chance that the database was written to. 
36987
**   So is safe to finalize the journal file even if the playback 
36988
**   (operation 1) failed. However the pager must enter the error state
36989
**   as the contents of the in-memory cache are now suspect.
36990
**
36991
** * Finally, if in PAGER_EXCLUSIVE state, then attempt (1). Only
36992
**   attempt (2) if (1) is successful. Return SQLITE_OK if successful,
36993
**   otherwise enter the error state and return the error code from the 
36994
**   failing operation.
36995
**
36996
**   In this case the database file may have been written to. So if the
36997
**   playback operation did not succeed it would not be safe to finalize
36998
**   the journal file. It needs to be left in the file-system so that
36999
**   some other process can use it to restore the database state (by
37000
**   hot-journal rollback).
37001
*/
40008
*/
37002
SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
40009
SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
37003
  int rc = SQLITE_OK;                  /* Return code */
40010
  int rc = SQLITE_OK;                  /* Return code */
37004
  PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
40011
  PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
37005
  if( !pPager->dbModified || !isOpen(pPager->jfd) ){
40012
37006
    rc = pager_end_transaction(pPager, pPager->setMaster);
40013
  /* PagerRollback() is a no-op if called in READER or OPEN state. If
37007
  }else if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
40014
  ** the pager is already in the ERROR state, the rollback is not 
37008
    if( pPager->state>=PAGER_EXCLUSIVE ){
40015
  ** attempted here. Instead, the error code is returned to the caller.
37009
      pager_playback(pPager, 0);
40016
  */
37010
    }
40017
  assert( assert_pager_state(pPager) );
37011
    rc = pPager->errCode;
40018
  if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
37012
  }else{
40019
  if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
37013
    if( pPager->state==PAGER_RESERVED ){
40020
37014
      int rc2;
40021
  if( pagerUseWal(pPager) ){
37015
      rc = pager_playback(pPager, 0);
40022
    int rc2;
37016
      rc2 = pager_end_transaction(pPager, pPager->setMaster);
40023
    rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
37017
      if( rc==SQLITE_OK ){
40024
    rc2 = pager_end_transaction(pPager, pPager->setMaster);
37018
        rc = rc2;
40025
    if( rc==SQLITE_OK ) rc = rc2;
37019
      }
40026
  }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
37020
    }else{
40027
    rc = pager_end_transaction(pPager, 0);
37021
      rc = pager_playback(pPager, 0);
40028
  }else{
37022
    }
40029
    rc = pager_playback(pPager, 0);
37023
40030
  }
37024
    if( !MEMDB ){
40031
37025
      pPager->dbSizeValid = 0;
40032
  assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
37026
    }
40033
  assert( rc==SQLITE_OK || rc==SQLITE_FULL || (rc&0xFF)==SQLITE_IOERR );
37027
40034
37028
    /* If an error occurs during a ROLLBACK, we can no longer trust the pager
40035
  /* If an error occurs during a ROLLBACK, we can no longer trust the pager
37029
    ** cache. So call pager_error() on the way out to make any error 
40036
  ** cache. So call pager_error() on the way out to make any error persistent.
37030
    ** persistent.
40037
  */
37031
    */
40038
  return pager_error(pPager, rc);
37032
    rc = pager_error(pPager, rc);
37033
  }
37034
  return rc;
37035
}
40039
}
37036
40040
37037
/*
40041
/*
 Lines 37050-37055   SQLITE_PRIVATE int sqlite3PagerRefcount( Link Here 
37050
}
40054
}
37051
40055
37052
/*
40056
/*
40057
** Return the approximate number of bytes of memory currently
40058
** used by the pager and its associated cache.
40059
*/
40060
SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
40061
  int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
40062
                                     + 5*sizeof(void*);
40063
  return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
40064
           + sqlite3MallocSize(pPager)
40065
           + pPager->pageSize;
40066
}
40067
40068
/*
37053
** Return the number of references to the specified page.
40069
** Return the number of references to the specified page.
37054
*/
40070
*/
37055
SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
40071
SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
 Lines 37065-37072   SQLITE_PRIVATE int *sqlite3PagerStats(Pa Link Here 
37065
  a[0] = sqlite3PcacheRefCount(pPager->pPCache);
40081
  a[0] = sqlite3PcacheRefCount(pPager->pPCache);
37066
  a[1] = sqlite3PcachePagecount(pPager->pPCache);
40082
  a[1] = sqlite3PcachePagecount(pPager->pPCache);
37067
  a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
40083
  a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
37068
  a[3] = pPager->dbSizeValid ? (int) pPager->dbSize : -1;
40084
  a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
37069
  a[4] = pPager->state;
40085
  a[4] = pPager->eState;
37070
  a[5] = pPager->errCode;
40086
  a[5] = pPager->errCode;
37071
  a[6] = pPager->nHit;
40087
  a[6] = pPager->nHit;
37072
  a[7] = pPager->nMiss;
40088
  a[7] = pPager->nMiss;
 Lines 37098-37112   SQLITE_PRIVATE int sqlite3PagerOpenSavep Link Here 
37098
  int rc = SQLITE_OK;                       /* Return code */
40114
  int rc = SQLITE_OK;                       /* Return code */
37099
  int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
40115
  int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
37100
40116
40117
  assert( pPager->eState>=PAGER_WRITER_LOCKED );
40118
  assert( assert_pager_state(pPager) );
40119
37101
  if( nSavepoint>nCurrent && pPager->useJournal ){
40120
  if( nSavepoint>nCurrent && pPager->useJournal ){
37102
    int ii;                                 /* Iterator variable */
40121
    int ii;                                 /* Iterator variable */
37103
    PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */
40122
    PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */
37104
40123
37105
    /* Either there is no active journal or the sub-journal is open or 
37106
    ** the journal is always stored in memory */
37107
    assert( pPager->nSavepoint==0 || isOpen(pPager->sjfd) ||
37108
            pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
37109
37110
    /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
40124
    /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
37111
    ** if the allocation fails. Otherwise, zero the new portion in case a 
40125
    ** if the allocation fails. Otherwise, zero the new portion in case a 
37112
    ** malloc failure occurs while populating it in the for(...) loop below.
40126
    ** malloc failure occurs while populating it in the for(...) loop below.
 Lines 37119-37131   SQLITE_PRIVATE int sqlite3PagerOpenSavep Link Here 
37119
    }
40133
    }
37120
    memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
40134
    memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
37121
    pPager->aSavepoint = aNew;
40135
    pPager->aSavepoint = aNew;
37122
    pPager->nSavepoint = nSavepoint;
37123
40136
37124
    /* Populate the PagerSavepoint structures just allocated. */
40137
    /* Populate the PagerSavepoint structures just allocated. */
37125
    for(ii=nCurrent; ii<nSavepoint; ii++){
40138
    for(ii=nCurrent; ii<nSavepoint; ii++){
37126
      assert( pPager->dbSizeValid );
37127
      aNew[ii].nOrig = pPager->dbSize;
40139
      aNew[ii].nOrig = pPager->dbSize;
37128
      if( isOpen(pPager->jfd) && ALWAYS(pPager->journalOff>0) ){
40140
      if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
37129
        aNew[ii].iOffset = pPager->journalOff;
40141
        aNew[ii].iOffset = pPager->journalOff;
37130
      }else{
40142
      }else{
37131
        aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
40143
        aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
 Lines 37135-37144   SQLITE_PRIVATE int sqlite3PagerOpenSavep Link Here 
37135
      if( !aNew[ii].pInSavepoint ){
40147
      if( !aNew[ii].pInSavepoint ){
37136
        return SQLITE_NOMEM;
40148
        return SQLITE_NOMEM;
37137
      }
40149
      }
37138
    }
40150
      if( pagerUseWal(pPager) ){
37139
40151
        sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
37140
    /* Open the sub-journal, if it is not already opened. */
40152
      }
37141
    rc = openSubJournal(pPager);
40153
      pPager->nSavepoint = ii+1;
40154
    }
40155
    assert( pPager->nSavepoint==nSavepoint );
37142
    assertTruncateConstraint(pPager);
40156
    assertTruncateConstraint(pPager);
37143
  }
40157
  }
37144
40158
 Lines 37176-37187   SQLITE_PRIVATE int sqlite3PagerOpenSavep Link Here 
37176
** savepoint. If no errors occur, SQLITE_OK is returned.
40190
** savepoint. If no errors occur, SQLITE_OK is returned.
37177
*/ 
40191
*/ 
37178
SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
40192
SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
37179
  int rc = SQLITE_OK;
40193
  int rc = pPager->errCode;       /* Return code */
37180
40194
37181
  assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
40195
  assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
37182
  assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
40196
  assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
37183
40197
37184
  if( iSavepoint<pPager->nSavepoint ){
40198
  if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
37185
    int ii;            /* Iterator variable */
40199
    int ii;            /* Iterator variable */
37186
    int nNew;          /* Number of remaining savepoints after this op. */
40200
    int nNew;          /* Number of remaining savepoints after this op. */
37187
40201
 Lines 37212-37224   SQLITE_PRIVATE int sqlite3PagerSavepoint Link Here 
37212
    ** not yet been opened. In this case there have been no changes to
40226
    ** not yet been opened. In this case there have been no changes to
37213
    ** the database file, so the playback operation can be skipped.
40227
    ** the database file, so the playback operation can be skipped.
37214
    */
40228
    */
37215
    else if( isOpen(pPager->jfd) ){
40229
    else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
37216
      PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
40230
      PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
37217
      rc = pagerPlaybackSavepoint(pPager, pSavepoint);
40231
      rc = pagerPlaybackSavepoint(pPager, pSavepoint);
37218
      assert(rc!=SQLITE_DONE);
40232
      assert(rc!=SQLITE_DONE);
37219
    }
40233
    }
37220
  
40234
  }
37221
  }
40235
37222
  return rc;
40236
  return rc;
37223
}
40237
}
37224
40238
 Lines 37264-37270   SQLITE_PRIVATE int sqlite3PagerNosync(Pa Link Here 
37264
/*
40278
/*
37265
** Set or retrieve the codec for this pager
40279
** Set or retrieve the codec for this pager
37266
*/
40280
*/
37267
static void sqlite3PagerSetCodec(
40281
SQLITE_PRIVATE void sqlite3PagerSetCodec(
37268
  Pager *pPager,
40282
  Pager *pPager,
37269
  void *(*xCodec)(void*,void*,Pgno,int),
40283
  void *(*xCodec)(void*,void*,Pgno,int),
37270
  void (*xCodecSizeChng)(void*,int,int),
40284
  void (*xCodecSizeChng)(void*,int,int),
 Lines 37278-37284   static void sqlite3PagerSetCodec( Link Here 
37278
  pPager->pCodec = pCodec;
40292
  pPager->pCodec = pCodec;
37279
  pagerReportSize(pPager);
40293
  pagerReportSize(pPager);
37280
}
40294
}
37281
static void *sqlite3PagerGetCodec(Pager *pPager){
40295
SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
37282
  return pPager->pCodec;
40296
  return pPager->pCodec;
37283
}
40297
}
37284
#endif
40298
#endif
 Lines 37316-37321   SQLITE_PRIVATE int sqlite3PagerMovepage( Link Here 
37316
  Pgno origPgno;               /* The original page number */
40330
  Pgno origPgno;               /* The original page number */
37317
40331
37318
  assert( pPg->nRef>0 );
40332
  assert( pPg->nRef>0 );
40333
  assert( pPager->eState==PAGER_WRITER_CACHEMOD
40334
       || pPager->eState==PAGER_WRITER_DBMOD
40335
  );
40336
  assert( assert_pager_state(pPager) );
37319
40337
37320
  /* In order to be able to rollback, an in-memory database must journal
40338
  /* In order to be able to rollback, an in-memory database must journal
37321
  ** the page we are moving from.
40339
  ** the page we are moving from.
 Lines 37365-37375   SQLITE_PRIVATE int sqlite3PagerMovepage( Link Here 
37365
    needSyncPgno = pPg->pgno;
40383
    needSyncPgno = pPg->pgno;
37366
    assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
40384
    assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
37367
    assert( pPg->flags&PGHDR_DIRTY );
40385
    assert( pPg->flags&PGHDR_DIRTY );
37368
    assert( pPager->needSync );
37369
  }
40386
  }
37370
40387
37371
  /* If the cache contains a page with page-number pgno, remove it
40388
  /* If the cache contains a page with page-number pgno, remove it
37372
  ** from its hash chain. Also, if the PgHdr.needSync was set for 
40389
  ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for 
37373
  ** page pgno before the 'move' operation, it needs to be retained 
40390
  ** page pgno before the 'move' operation, it needs to be retained 
37374
  ** for the page moved there.
40391
  ** for the page moved there.
37375
  */
40392
  */
 Lines 37381-37387   SQLITE_PRIVATE int sqlite3PagerMovepage( Link Here 
37381
    if( MEMDB ){
40398
    if( MEMDB ){
37382
      /* Do not discard pages from an in-memory database since we might
40399
      /* Do not discard pages from an in-memory database since we might
37383
      ** need to rollback later.  Just move the page out of the way. */
40400
      ** need to rollback later.  Just move the page out of the way. */
37384
      assert( pPager->dbSizeValid );
37385
      sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
40401
      sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
37386
    }else{
40402
    }else{
37387
      sqlite3PcacheDrop(pPgOld);
40403
      sqlite3PcacheDrop(pPgOld);
 Lines 37391-37404   SQLITE_PRIVATE int sqlite3PagerMovepage( Link Here 
37391
  origPgno = pPg->pgno;
40407
  origPgno = pPg->pgno;
37392
  sqlite3PcacheMove(pPg, pgno);
40408
  sqlite3PcacheMove(pPg, pgno);
37393
  sqlite3PcacheMakeDirty(pPg);
40409
  sqlite3PcacheMakeDirty(pPg);
37394
  pPager->dbModified = 1;
40410
40411
  /* For an in-memory database, make sure the original page continues
40412
  ** to exist, in case the transaction needs to roll back.  Use pPgOld
40413
  ** as the original page since it has already been allocated.
40414
  */
40415
  if( MEMDB ){
40416
    assert( pPgOld );
40417
    sqlite3PcacheMove(pPgOld, origPgno);
40418
    sqlite3PagerUnref(pPgOld);
40419
  }
37395
40420
37396
  if( needSyncPgno ){
40421
  if( needSyncPgno ){
37397
    /* If needSyncPgno is non-zero, then the journal file needs to be 
40422
    /* If needSyncPgno is non-zero, then the journal file needs to be 
37398
    ** sync()ed before any data is written to database file page needSyncPgno.
40423
    ** sync()ed before any data is written to database file page needSyncPgno.
37399
    ** Currently, no such page exists in the page-cache and the 
40424
    ** Currently, no such page exists in the page-cache and the 
37400
    ** "is journaled" bitvec flag has been set. This needs to be remedied by
40425
    ** "is journaled" bitvec flag has been set. This needs to be remedied by
37401
    ** loading the page into the pager-cache and setting the PgHdr.needSync 
40426
    ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
37402
    ** flag.
40427
    ** flag.
37403
    **
40428
    **
37404
    ** If the attempt to load the page into the page-cache fails, (due
40429
    ** If the attempt to load the page into the page-cache fails, (due
 Lines 37407-37418   SQLITE_PRIVATE int sqlite3PagerMovepage( Link Here 
37407
    ** this transaction, it may be written to the database file before
40432
    ** this transaction, it may be written to the database file before
37408
    ** it is synced into the journal file. This way, it may end up in
40433
    ** it is synced into the journal file. This way, it may end up in
37409
    ** the journal file twice, but that is not a problem.
40434
    ** the journal file twice, but that is not a problem.
37410
    **
37411
    ** The sqlite3PagerGet() call may cause the journal to sync. So make
37412
    ** sure the Pager.needSync flag is set too.
37413
    */
40435
    */
37414
    PgHdr *pPgHdr;
40436
    PgHdr *pPgHdr;
37415
    assert( pPager->needSync );
37416
    rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
40437
    rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
37417
    if( rc!=SQLITE_OK ){
40438
    if( rc!=SQLITE_OK ){
37418
      if( needSyncPgno<=pPager->dbOrigSize ){
40439
      if( needSyncPgno<=pPager->dbOrigSize ){
 Lines 37421-37443   SQLITE_PRIVATE int sqlite3PagerMovepage( Link Here 
37421
      }
40442
      }
37422
      return rc;
40443
      return rc;
37423
    }
40444
    }
37424
    pPager->needSync = 1;
37425
    assert( pPager->noSync==0 && !MEMDB );
37426
    pPgHdr->flags |= PGHDR_NEED_SYNC;
40445
    pPgHdr->flags |= PGHDR_NEED_SYNC;
37427
    sqlite3PcacheMakeDirty(pPgHdr);
40446
    sqlite3PcacheMakeDirty(pPgHdr);
37428
    sqlite3PagerUnref(pPgHdr);
40447
    sqlite3PagerUnref(pPgHdr);
37429
  }
40448
  }
37430
40449
37431
  /*
37432
  ** For an in-memory database, make sure the original page continues
37433
  ** to exist, in case the transaction needs to roll back.  Use pPgOld
37434
  ** as the original page since it has already been allocated.
37435
  */
37436
  if( MEMDB ){
37437
    sqlite3PcacheMove(pPgOld, origPgno);
37438
    sqlite3PagerUnref(pPgOld);
37439
  }
37440
37441
  return SQLITE_OK;
40450
  return SQLITE_OK;
37442
}
40451
}
37443
#endif
40452
#endif
 Lines 37481-37529   SQLITE_PRIVATE int sqlite3PagerLockingMo Link Here 
37481
}
40490
}
37482
40491
37483
/*
40492
/*
37484
** Get/set the journal-mode for this pager. Parameter eMode must be one of:
40493
** Set the journal-mode for this pager. Parameter eMode must be one of:
37485
**
40494
**
37486
**    PAGER_JOURNALMODE_QUERY
37487
**    PAGER_JOURNALMODE_DELETE
40495
**    PAGER_JOURNALMODE_DELETE
37488
**    PAGER_JOURNALMODE_TRUNCATE
40496
**    PAGER_JOURNALMODE_TRUNCATE
37489
**    PAGER_JOURNALMODE_PERSIST
40497
**    PAGER_JOURNALMODE_PERSIST
37490
**    PAGER_JOURNALMODE_OFF
40498
**    PAGER_JOURNALMODE_OFF
37491
**    PAGER_JOURNALMODE_MEMORY
40499
**    PAGER_JOURNALMODE_MEMORY
37492
**
40500
**    PAGER_JOURNALMODE_WAL
37493
** If the parameter is not _QUERY, then the journal_mode is set to the
40501
**
37494
** value specified if the change is allowed.  The change is disallowed
40502
** The journalmode is set to the value specified if the change is allowed.
37495
** for the following reasons:
40503
** The change may be disallowed for the following reasons:
37496
**
40504
**
37497
**   *  An in-memory database can only have its journal_mode set to _OFF
40505
**   *  An in-memory database can only have its journal_mode set to _OFF
37498
**      or _MEMORY.
40506
**      or _MEMORY.
37499
**
40507
**
37500
**   *  The journal mode may not be changed while a transaction is active.
40508
**   *  Temporary databases cannot have _WAL journalmode.
37501
**
40509
**
37502
** The returned indicate the current (possibly updated) journal-mode.
40510
** The returned indicate the current (possibly updated) journal-mode.
37503
*/
40511
*/
37504
SQLITE_PRIVATE int sqlite3PagerJournalMode(Pager *pPager, int eMode){
40512
SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
37505
  assert( eMode==PAGER_JOURNALMODE_QUERY
40513
  u8 eOld = pPager->journalMode;    /* Prior journalmode */
37506
            || eMode==PAGER_JOURNALMODE_DELETE
40514
40515
#ifdef SQLITE_DEBUG
40516
  /* The print_pager_state() routine is intended to be used by the debugger
40517
  ** only.  We invoke it once here to suppress a compiler warning. */
40518
  print_pager_state(pPager);
40519
#endif
40520
40521
40522
  /* The eMode parameter is always valid */
40523
  assert(      eMode==PAGER_JOURNALMODE_DELETE
37507
            || eMode==PAGER_JOURNALMODE_TRUNCATE
40524
            || eMode==PAGER_JOURNALMODE_TRUNCATE
37508
            || eMode==PAGER_JOURNALMODE_PERSIST
40525
            || eMode==PAGER_JOURNALMODE_PERSIST
37509
            || eMode==PAGER_JOURNALMODE_OFF 
40526
            || eMode==PAGER_JOURNALMODE_OFF 
40527
            || eMode==PAGER_JOURNALMODE_WAL 
37510
            || eMode==PAGER_JOURNALMODE_MEMORY );
40528
            || eMode==PAGER_JOURNALMODE_MEMORY );
37511
  assert( PAGER_JOURNALMODE_QUERY<0 );
40529
37512
  if( eMode>=0
40530
  /* This routine is only called from the OP_JournalMode opcode, and
37513
   && (!MEMDB || eMode==PAGER_JOURNALMODE_MEMORY 
40531
  ** the logic there will never allow a temporary file to be changed
37514
              || eMode==PAGER_JOURNALMODE_OFF)
40532
  ** to WAL mode.
37515
   && !pPager->dbModified
40533
  */
37516
   && (!isOpen(pPager->jfd) || 0==pPager->journalOff)
40534
  assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
37517
  ){
40535
37518
    if( isOpen(pPager->jfd) ){
40536
  /* Do allow the journalmode of an in-memory database to be set to
40537
  ** anything other than MEMORY or OFF
40538
  */
40539
  if( MEMDB ){
40540
    assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
40541
    if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
40542
      eMode = eOld;
40543
    }
40544
  }
40545
40546
  if( eMode!=eOld ){
40547
40548
    /* Change the journal mode. */
40549
    assert( pPager->eState!=PAGER_ERROR );
40550
    pPager->journalMode = (u8)eMode;
40551
40552
    /* When transistioning from TRUNCATE or PERSIST to any other journal
40553
    ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
40554
    ** delete the journal file.
40555
    */
40556
    assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
40557
    assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
40558
    assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
40559
    assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
40560
    assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
40561
    assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
40562
40563
    assert( isOpen(pPager->fd) || pPager->exclusiveMode );
40564
    if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
40565
40566
      /* In this case we would like to delete the journal file. If it is
40567
      ** not possible, then that is not a problem. Deleting the journal file
40568
      ** here is an optimization only.
40569
      **
40570
      ** Before deleting the journal file, obtain a RESERVED lock on the
40571
      ** database file. This ensures that the journal file is not deleted
40572
      ** while it is in use by some other client.
40573
      */
37519
      sqlite3OsClose(pPager->jfd);
40574
      sqlite3OsClose(pPager->jfd);
37520
    }
40575
      if( pPager->eLock>=RESERVED_LOCK ){
37521
    pPager->journalMode = (u8)eMode;
40576
        sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
37522
  }
40577
      }else{
40578
        int rc = SQLITE_OK;
40579
        int state = pPager->eState;
40580
        assert( state==PAGER_OPEN || state==PAGER_READER );
40581
        if( state==PAGER_OPEN ){
40582
          rc = sqlite3PagerSharedLock(pPager);
40583
        }
40584
        if( pPager->eState==PAGER_READER ){
40585
          assert( rc==SQLITE_OK );
40586
          rc = pagerLockDb(pPager, RESERVED_LOCK);
40587
        }
40588
        if( rc==SQLITE_OK ){
40589
          sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
40590
        }
40591
        if( rc==SQLITE_OK && state==PAGER_READER ){
40592
          pagerUnlockDb(pPager, SHARED_LOCK);
40593
        }else if( state==PAGER_OPEN ){
40594
          pager_unlock(pPager);
40595
        }
40596
        assert( state==pPager->eState );
40597
      }
40598
    }
40599
  }
40600
40601
  /* Return the new journal mode */
37523
  return (int)pPager->journalMode;
40602
  return (int)pPager->journalMode;
37524
}
40603
}
37525
40604
37526
/*
40605
/*
40606
** Return the current journal mode.
40607
*/
40608
SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
40609
  return (int)pPager->journalMode;
40610
}
40611
40612
/*
40613
** Return TRUE if the pager is in a state where it is OK to change the
40614
** journalmode.  Journalmode changes can only happen when the database
40615
** is unmodified.
40616
*/
40617
SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
40618
  assert( assert_pager_state(pPager) );
40619
  if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
40620
  if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
40621
  return 1;
40622
}
40623
40624
/*
37527
** Get/set the size-limit used for persistent journal files.
40625
** Get/set the size-limit used for persistent journal files.
37528
**
40626
**
37529
** Setting the size limit to -1 means no limit is enforced.
40627
** Setting the size limit to -1 means no limit is enforced.
 Lines 37546-37554   SQLITE_PRIVATE sqlite3_backup **sqlite3P Link Here 
37546
  return &pPager->pBackup;
40644
  return &pPager->pBackup;
37547
}
40645
}
37548
40646
40647
#ifndef SQLITE_OMIT_WAL
40648
/*
40649
** This function is called when the user invokes "PRAGMA checkpoint".
40650
*/
40651
SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager){
40652
  int rc = SQLITE_OK;
40653
  if( pPager->pWal ){
40654
    u8 *zBuf = (u8 *)pPager->pTmpSpace;
40655
    rc = sqlite3WalCheckpoint(pPager->pWal,
40656
        (pPager->noSync ? 0 : pPager->sync_flags),
40657
        pPager->pageSize, zBuf
40658
    );
40659
  }
40660
  return rc;
40661
}
40662
40663
SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
40664
  return sqlite3WalCallback(pPager->pWal);
40665
}
40666
40667
/*
40668
** Return true if the underlying VFS for the given pager supports the
40669
** primitives necessary for write-ahead logging.
40670
*/
40671
SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
40672
  const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
40673
  return pMethods->iVersion>=2 && pMethods->xShmMap!=0;
40674
}
40675
40676
/*
40677
** The caller must be holding a SHARED lock on the database file to call
40678
** this function.
40679
**
40680
** If the pager passed as the first argument is open on a real database
40681
** file (not a temp file or an in-memory database), and the WAL file
40682
** is not already open, make an attempt to open it now. If successful,
40683
** return SQLITE_OK. If an error occurs or the VFS used by the pager does 
40684
** not support the xShmXXX() methods, return an error code. *pbOpen is
40685
** not modified in either case.
40686
**
40687
** If the pager is open on a temp-file (or in-memory database), or if
40688
** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
40689
** without doing anything.
40690
*/
40691
SQLITE_PRIVATE int sqlite3PagerOpenWal(
40692
  Pager *pPager,                  /* Pager object */
40693
  int *pbOpen                     /* OUT: Set to true if call is a no-op */
40694
){
40695
  int rc = SQLITE_OK;             /* Return code */
40696
40697
  assert( assert_pager_state(pPager) );
40698
  assert( pPager->eState==PAGER_OPEN   || pbOpen );
40699
  assert( pPager->eState==PAGER_READER || !pbOpen );
40700
  assert( pbOpen==0 || *pbOpen==0 );
40701
  assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
40702
40703
  if( !pPager->tempFile && !pPager->pWal ){
40704
    if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
40705
40706
    /* Close any rollback journal previously open */
40707
    sqlite3OsClose(pPager->jfd);
40708
40709
    /* Open the connection to the log file. If this operation fails, 
40710
    ** (e.g. due to malloc() failure), unlock the database file and 
40711
    ** return an error code.
40712
    */
40713
    rc = sqlite3WalOpen(pPager->pVfs, pPager->fd, pPager->zWal, &pPager->pWal);
40714
    if( rc==SQLITE_OK ){
40715
      pPager->journalMode = PAGER_JOURNALMODE_WAL;
40716
      pPager->eState = PAGER_OPEN;
40717
    }
40718
  }else{
40719
    *pbOpen = 1;
40720
  }
40721
40722
  return rc;
40723
}
40724
40725
/*
40726
** This function is called to close the connection to the log file prior
40727
** to switching from WAL to rollback mode.
40728
**
40729
** Before closing the log file, this function attempts to take an 
40730
** EXCLUSIVE lock on the database file. If this cannot be obtained, an
40731
** error (SQLITE_BUSY) is returned and the log connection is not closed.
40732
** If successful, the EXCLUSIVE lock is not released before returning.
40733
*/
40734
SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
40735
  int rc = SQLITE_OK;
40736
40737
  assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
40738
40739
  /* If the log file is not already open, but does exist in the file-system,
40740
  ** it may need to be checkpointed before the connection can switch to
40741
  ** rollback mode. Open it now so this can happen.
40742
  */
40743
  if( !pPager->pWal ){
40744
    int logexists = 0;
40745
    rc = pagerLockDb(pPager, SHARED_LOCK);
40746
    if( rc==SQLITE_OK ){
40747
      rc = sqlite3OsAccess(
40748
          pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
40749
      );
40750
    }
40751
    if( rc==SQLITE_OK && logexists ){
40752
      rc = sqlite3WalOpen(pPager->pVfs, pPager->fd,
40753
                          pPager->zWal, &pPager->pWal);
40754
    }
40755
  }
40756
    
40757
  /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
40758
  ** the database file, the log and log-summary files will be deleted.
40759
  */
40760
  if( rc==SQLITE_OK && pPager->pWal ){
40761
    rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
40762
    if( rc==SQLITE_OK ){
40763
      rc = sqlite3WalClose(pPager->pWal,
40764
                           (pPager->noSync ? 0 : pPager->sync_flags), 
40765
        pPager->pageSize, (u8*)pPager->pTmpSpace
40766
      );
40767
      pPager->pWal = 0;
40768
    }else{
40769
      /* If we cannot get an EXCLUSIVE lock, downgrade the PENDING lock
40770
      ** that we did get back to SHARED. */
40771
      pagerUnlockDb(pPager, SQLITE_LOCK_SHARED);
40772
    }
40773
  }
40774
  return rc;
40775
}
40776
40777
#ifdef SQLITE_HAS_CODEC
40778
/*
40779
** This function is called by the wal module when writing page content
40780
** into the log file.
40781
**
40782
** This function returns a pointer to a buffer containing the encrypted
40783
** page content. If a malloc fails, this function may return NULL.
40784
*/
40785
SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
40786
  void *aData = 0;
40787
  CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
40788
  return aData;
40789
}
40790
#endif /* SQLITE_HAS_CODEC */
40791
40792
#endif /* !SQLITE_OMIT_WAL */
40793
37549
#endif /* SQLITE_OMIT_DISKIO */
40794
#endif /* SQLITE_OMIT_DISKIO */
37550
40795
37551
/************** End of pager.c ***********************************************/
40796
/************** End of pager.c ***********************************************/
40797
/************** Begin file wal.c *********************************************/
40798
/*
40799
** 2010 February 1
40800
**
40801
** The author disclaims copyright to this source code.  In place of
40802
** a legal notice, here is a blessing:
40803
**
40804
**    May you do good and not evil.
40805
**    May you find forgiveness for yourself and forgive others.
40806
**    May you share freely, never taking more than you give.
40807
**
40808
*************************************************************************
40809
**
40810
** This file contains the implementation of a write-ahead log (WAL) used in 
40811
** "journal_mode=WAL" mode.
40812
**
40813
** WRITE-AHEAD LOG (WAL) FILE FORMAT
40814
**
40815
** A WAL file consists of a header followed by zero or more "frames".
40816
** Each frame records the revised content of a single page from the
40817
** database file.  All changes to the database are recorded by writing
40818
** frames into the WAL.  Transactions commit when a frame is written that
40819
** contains a commit marker.  A single WAL can and usually does record 
40820
** multiple transactions.  Periodically, the content of the WAL is
40821
** transferred back into the database file in an operation called a
40822
** "checkpoint".
40823
**
40824
** A single WAL file can be used multiple times.  In other words, the
40825
** WAL can fill up with frames and then be checkpointed and then new
40826
** frames can overwrite the old ones.  A WAL always grows from beginning
40827
** toward the end.  Checksums and counters attached to each frame are
40828
** used to determine which frames within the WAL are valid and which
40829
** are leftovers from prior checkpoints.
40830
**
40831
** The WAL header is 32 bytes in size and consists of the following eight
40832
** big-endian 32-bit unsigned integer values:
40833
**
40834
**     0: Magic number.  0x377f0682 or 0x377f0683
40835
**     4: File format version.  Currently 3007000
40836
**     8: Database page size.  Example: 1024
40837
**    12: Checkpoint sequence number
40838
**    16: Salt-1, random integer incremented with each checkpoint
40839
**    20: Salt-2, a different random integer changing with each ckpt
40840
**    24: Checksum-1 (first part of checksum for first 24 bytes of header).
40841
**    28: Checksum-2 (second part of checksum for first 24 bytes of header).
40842
**
40843
** Immediately following the wal-header are zero or more frames. Each
40844
** frame consists of a 24-byte frame-header followed by a <page-size> bytes
40845
** of page data. The frame-header is six big-endian 32-bit unsigned 
40846
** integer values, as follows:
40847
**
40848
**     0: Page number.
40849
**     4: For commit records, the size of the database image in pages 
40850
**        after the commit. For all other records, zero.
40851
**     8: Salt-1 (copied from the header)
40852
**    12: Salt-2 (copied from the header)
40853
**    16: Checksum-1.
40854
**    20: Checksum-2.
40855
**
40856
** A frame is considered valid if and only if the following conditions are
40857
** true:
40858
**
40859
**    (1) The salt-1 and salt-2 values in the frame-header match
40860
**        salt values in the wal-header
40861
**
40862
**    (2) The checksum values in the final 8 bytes of the frame-header
40863
**        exactly match the checksum computed consecutively on the
40864
**        WAL header and the first 8 bytes and the content of all frames
40865
**        up to and including the current frame.
40866
**
40867
** The checksum is computed using 32-bit big-endian integers if the
40868
** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
40869
** is computed using little-endian if the magic number is 0x377f0682.
40870
** The checksum values are always stored in the frame header in a
40871
** big-endian format regardless of which byte order is used to compute
40872
** the checksum.  The checksum is computed by interpreting the input as
40873
** an even number of unsigned 32-bit integers: x[0] through x[N].  The
40874
** algorithm used for the checksum is as follows:
40875
** 
40876
**   for i from 0 to n-1 step 2:
40877
**     s0 += x[i] + s1;
40878
**     s1 += x[i+1] + s0;
40879
**   endfor
40880
**
40881
** Note that s0 and s1 are both weighted checksums using fibonacci weights
40882
** in reverse order (the largest fibonacci weight occurs on the first element
40883
** of the sequence being summed.)  The s1 value spans all 32-bit 
40884
** terms of the sequence whereas s0 omits the final term.
40885
**
40886
** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
40887
** WAL is transferred into the database, then the database is VFS.xSync-ed.
40888
** The VFS.xSync operations serve as write barriers - all writes launched
40889
** before the xSync must complete before any write that launches after the
40890
** xSync begins.
40891
**
40892
** After each checkpoint, the salt-1 value is incremented and the salt-2
40893
** value is randomized.  This prevents old and new frames in the WAL from
40894
** being considered valid at the same time and being checkpointing together
40895
** following a crash.
40896
**
40897
** READER ALGORITHM
40898
**
40899
** To read a page from the database (call it page number P), a reader
40900
** first checks the WAL to see if it contains page P.  If so, then the
40901
** last valid instance of page P that is a followed by a commit frame
40902
** or is a commit frame itself becomes the value read.  If the WAL
40903
** contains no copies of page P that are valid and which are a commit
40904
** frame or are followed by a commit frame, then page P is read from
40905
** the database file.
40906
**
40907
** To start a read transaction, the reader records the index of the last
40908
** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
40909
** for all subsequent read operations.  New transactions can be appended
40910
** to the WAL, but as long as the reader uses its original mxFrame value
40911
** and ignores the newly appended content, it will see a consistent snapshot
40912
** of the database from a single point in time.  This technique allows
40913
** multiple concurrent readers to view different versions of the database
40914
** content simultaneously.
40915
**
40916
** The reader algorithm in the previous paragraphs works correctly, but 
40917
** because frames for page P can appear anywhere within the WAL, the
40918
** reader has to scan the entire WAL looking for page P frames.  If the
40919
** WAL is large (multiple megabytes is typical) that scan can be slow,
40920
** and read performance suffers.  To overcome this problem, a separate
40921
** data structure called the wal-index is maintained to expedite the
40922
** search for frames of a particular page.
40923
** 
40924
** WAL-INDEX FORMAT
40925
**
40926
** Conceptually, the wal-index is shared memory, though VFS implementations
40927
** might choose to implement the wal-index using a mmapped file.  Because
40928
** the wal-index is shared memory, SQLite does not support journal_mode=WAL 
40929
** on a network filesystem.  All users of the database must be able to
40930
** share memory.
40931
**
40932
** The wal-index is transient.  After a crash, the wal-index can (and should
40933
** be) reconstructed from the original WAL file.  In fact, the VFS is required
40934
** to either truncate or zero the header of the wal-index when the last
40935
** connection to it closes.  Because the wal-index is transient, it can
40936
** use an architecture-specific format; it does not have to be cross-platform.
40937
** Hence, unlike the database and WAL file formats which store all values
40938
** as big endian, the wal-index can store multi-byte values in the native
40939
** byte order of the host computer.
40940
**
40941
** The purpose of the wal-index is to answer this question quickly:  Given
40942
** a page number P, return the index of the last frame for page P in the WAL,
40943
** or return NULL if there are no frames for page P in the WAL.
40944
**
40945
** The wal-index consists of a header region, followed by an one or
40946
** more index blocks.  
40947
**
40948
** The wal-index header contains the total number of frames within the WAL
40949
** in the the mxFrame field.  
40950
**
40951
** Each index block except for the first contains information on 
40952
** HASHTABLE_NPAGE frames. The first index block contains information on
40953
** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and 
40954
** HASHTABLE_NPAGE are selected so that together the wal-index header and
40955
** first index block are the same size as all other index blocks in the
40956
** wal-index.
40957
**
40958
** Each index block contains two sections, a page-mapping that contains the
40959
** database page number associated with each wal frame, and a hash-table 
40960
** that allows readers to query an index block for a specific page number.
40961
** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
40962
** for the first index block) 32-bit page numbers. The first entry in the 
40963
** first index-block contains the database page number corresponding to the
40964
** first frame in the WAL file. The first entry in the second index block
40965
** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
40966
** the log, and so on.
40967
**
40968
** The last index block in a wal-index usually contains less than the full
40969
** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
40970
** depending on the contents of the WAL file. This does not change the
40971
** allocated size of the page-mapping array - the page-mapping array merely
40972
** contains unused entries.
40973
**
40974
** Even without using the hash table, the last frame for page P
40975
** can be found by scanning the page-mapping sections of each index block
40976
** starting with the last index block and moving toward the first, and
40977
** within each index block, starting at the end and moving toward the
40978
** beginning.  The first entry that equals P corresponds to the frame
40979
** holding the content for that page.
40980
**
40981
** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
40982
** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
40983
** hash table for each page number in the mapping section, so the hash 
40984
** table is never more than half full.  The expected number of collisions 
40985
** prior to finding a match is 1.  Each entry of the hash table is an
40986
** 1-based index of an entry in the mapping section of the same
40987
** index block.   Let K be the 1-based index of the largest entry in
40988
** the mapping section.  (For index blocks other than the last, K will
40989
** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
40990
** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
40991
** contain a value of 0.
40992
**
40993
** To look for page P in the hash table, first compute a hash iKey on
40994
** P as follows:
40995
**
40996
**      iKey = (P * 383) % HASHTABLE_NSLOT
40997
**
40998
** Then start scanning entries of the hash table, starting with iKey
40999
** (wrapping around to the beginning when the end of the hash table is
41000
** reached) until an unused hash slot is found. Let the first unused slot
41001
** be at index iUnused.  (iUnused might be less than iKey if there was
41002
** wrap-around.) Because the hash table is never more than half full,
41003
** the search is guaranteed to eventually hit an unused entry.  Let 
41004
** iMax be the value between iKey and iUnused, closest to iUnused,
41005
** where aHash[iMax]==P.  If there is no iMax entry (if there exists
41006
** no hash slot such that aHash[i]==p) then page P is not in the
41007
** current index block.  Otherwise the iMax-th mapping entry of the
41008
** current index block corresponds to the last entry that references 
41009
** page P.
41010
**
41011
** A hash search begins with the last index block and moves toward the
41012
** first index block, looking for entries corresponding to page P.  On
41013
** average, only two or three slots in each index block need to be
41014
** examined in order to either find the last entry for page P, or to
41015
** establish that no such entry exists in the block.  Each index block
41016
** holds over 4000 entries.  So two or three index blocks are sufficient
41017
** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
41018
** comparisons (on average) suffice to either locate a frame in the
41019
** WAL or to establish that the frame does not exist in the WAL.  This
41020
** is much faster than scanning the entire 10MB WAL.
41021
**
41022
** Note that entries are added in order of increasing K.  Hence, one
41023
** reader might be using some value K0 and a second reader that started
41024
** at a later time (after additional transactions were added to the WAL
41025
** and to the wal-index) might be using a different value K1, where K1>K0.
41026
** Both readers can use the same hash table and mapping section to get
41027
** the correct result.  There may be entries in the hash table with
41028
** K>K0 but to the first reader, those entries will appear to be unused
41029
** slots in the hash table and so the first reader will get an answer as
41030
** if no values greater than K0 had ever been inserted into the hash table
41031
** in the first place - which is what reader one wants.  Meanwhile, the
41032
** second reader using K1 will see additional values that were inserted
41033
** later, which is exactly what reader two wants.  
41034
**
41035
** When a rollback occurs, the value of K is decreased. Hash table entries
41036
** that correspond to frames greater than the new K value are removed
41037
** from the hash table at this point.
41038
*/
41039
#ifndef SQLITE_OMIT_WAL
41040
41041
41042
/*
41043
** Trace output macros
41044
*/
41045
#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
41046
SQLITE_PRIVATE int sqlite3WalTrace = 0;
41047
# define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X
41048
#else
41049
# define WALTRACE(X)
41050
#endif
41051
41052
/*
41053
** The maximum (and only) versions of the wal and wal-index formats
41054
** that may be interpreted by this version of SQLite.
41055
**
41056
** If a client begins recovering a WAL file and finds that (a) the checksum
41057
** values in the wal-header are correct and (b) the version field is not
41058
** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
41059
**
41060
** Similarly, if a client successfully reads a wal-index header (i.e. the 
41061
** checksum test is successful) and finds that the version field is not
41062
** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
41063
** returns SQLITE_CANTOPEN.
41064
*/
41065
#define WAL_MAX_VERSION      3007000
41066
#define WALINDEX_MAX_VERSION 3007000
41067
41068
/*
41069
** Indices of various locking bytes.   WAL_NREADER is the number
41070
** of available reader locks and should be at least 3.
41071
*/
41072
#define WAL_WRITE_LOCK         0
41073
#define WAL_ALL_BUT_WRITE      1
41074
#define WAL_CKPT_LOCK          1
41075
#define WAL_RECOVER_LOCK       2
41076
#define WAL_READ_LOCK(I)       (3+(I))
41077
#define WAL_NREADER            (SQLITE_SHM_NLOCK-3)
41078
41079
41080
/* Object declarations */
41081
typedef struct WalIndexHdr WalIndexHdr;
41082
typedef struct WalIterator WalIterator;
41083
typedef struct WalCkptInfo WalCkptInfo;
41084
41085
41086
/*
41087
** The following object holds a copy of the wal-index header content.
41088
**
41089
** The actual header in the wal-index consists of two copies of this
41090
** object.
41091
**
41092
** The szPage value can be any power of 2 between 512 and 32768, inclusive.
41093
** Or it can be 1 to represent a 65536-byte page.  The latter case was
41094
** added in 3.7.1 when support for 64K pages was added.  
41095
*/
41096
struct WalIndexHdr {
41097
  u32 iVersion;                   /* Wal-index version */
41098
  u32 unused;                     /* Unused (padding) field */
41099
  u32 iChange;                    /* Counter incremented each transaction */
41100
  u8 isInit;                      /* 1 when initialized */
41101
  u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
41102
  u16 szPage;                     /* Database page size in bytes. 1==64K */
41103
  u32 mxFrame;                    /* Index of last valid frame in the WAL */
41104
  u32 nPage;                      /* Size of database in pages */
41105
  u32 aFrameCksum[2];             /* Checksum of last frame in log */
41106
  u32 aSalt[2];                   /* Two salt values copied from WAL header */
41107
  u32 aCksum[2];                  /* Checksum over all prior fields */
41108
};
41109
41110
/*
41111
** A copy of the following object occurs in the wal-index immediately
41112
** following the second copy of the WalIndexHdr.  This object stores
41113
** information used by checkpoint.
41114
**
41115
** nBackfill is the number of frames in the WAL that have been written
41116
** back into the database. (We call the act of moving content from WAL to
41117
** database "backfilling".)  The nBackfill number is never greater than
41118
** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
41119
** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
41120
** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
41121
** mxFrame back to zero when the WAL is reset.
41122
**
41123
** There is one entry in aReadMark[] for each reader lock.  If a reader
41124
** holds read-lock K, then the value in aReadMark[K] is no greater than
41125
** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
41126
** for any aReadMark[] means that entry is unused.  aReadMark[0] is 
41127
** a special case; its value is never used and it exists as a place-holder
41128
** to avoid having to offset aReadMark[] indexs by one.  Readers holding
41129
** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
41130
** directly from the database.
41131
**
41132
** The value of aReadMark[K] may only be changed by a thread that
41133
** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
41134
** aReadMark[K] cannot changed while there is a reader is using that mark
41135
** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
41136
**
41137
** The checkpointer may only transfer frames from WAL to database where
41138
** the frame numbers are less than or equal to every aReadMark[] that is
41139
** in use (that is, every aReadMark[j] for which there is a corresponding
41140
** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
41141
** largest value and will increase an unused aReadMark[] to mxFrame if there
41142
** is not already an aReadMark[] equal to mxFrame.  The exception to the
41143
** previous sentence is when nBackfill equals mxFrame (meaning that everything
41144
** in the WAL has been backfilled into the database) then new readers
41145
** will choose aReadMark[0] which has value 0 and hence such reader will
41146
** get all their all content directly from the database file and ignore 
41147
** the WAL.
41148
**
41149
** Writers normally append new frames to the end of the WAL.  However,
41150
** if nBackfill equals mxFrame (meaning that all WAL content has been
41151
** written back into the database) and if no readers are using the WAL
41152
** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
41153
** the writer will first "reset" the WAL back to the beginning and start
41154
** writing new content beginning at frame 1.
41155
**
41156
** We assume that 32-bit loads are atomic and so no locks are needed in
41157
** order to read from any aReadMark[] entries.
41158
*/
41159
struct WalCkptInfo {
41160
  u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
41161
  u32 aReadMark[WAL_NREADER];     /* Reader marks */
41162
};
41163
#define READMARK_NOT_USED  0xffffffff
41164
41165
41166
/* A block of WALINDEX_LOCK_RESERVED bytes beginning at
41167
** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
41168
** only support mandatory file-locks, we do not read or write data
41169
** from the region of the file on which locks are applied.
41170
*/
41171
#define WALINDEX_LOCK_OFFSET   (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
41172
#define WALINDEX_LOCK_RESERVED 16
41173
#define WALINDEX_HDR_SIZE      (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
41174
41175
/* Size of header before each frame in wal */
41176
#define WAL_FRAME_HDRSIZE 24
41177
41178
/* Size of write ahead log header, including checksum. */
41179
/* #define WAL_HDRSIZE 24 */
41180
#define WAL_HDRSIZE 32
41181
41182
/* WAL magic value. Either this value, or the same value with the least
41183
** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
41184
** big-endian format in the first 4 bytes of a WAL file.
41185
**
41186
** If the LSB is set, then the checksums for each frame within the WAL
41187
** file are calculated by treating all data as an array of 32-bit 
41188
** big-endian words. Otherwise, they are calculated by interpreting 
41189
** all data as 32-bit little-endian words.
41190
*/
41191
#define WAL_MAGIC 0x377f0682
41192
41193
/*
41194
** Return the offset of frame iFrame in the write-ahead log file, 
41195
** assuming a database page size of szPage bytes. The offset returned
41196
** is to the start of the write-ahead log frame-header.
41197
*/
41198
#define walFrameOffset(iFrame, szPage) (                               \
41199
  WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
41200
)
41201
41202
/*
41203
** An open write-ahead log file is represented by an instance of the
41204
** following object.
41205
*/
41206
struct Wal {
41207
  sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
41208
  sqlite3_file *pDbFd;       /* File handle for the database file */
41209
  sqlite3_file *pWalFd;      /* File handle for WAL file */
41210
  u32 iCallback;             /* Value to pass to log callback (or 0) */
41211
  int nWiData;               /* Size of array apWiData */
41212
  volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
41213
  u32 szPage;                /* Database page size */
41214
  i16 readLock;              /* Which read lock is being held.  -1 for none */
41215
  u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
41216
  u8 writeLock;              /* True if in a write transaction */
41217
  u8 ckptLock;               /* True if holding a checkpoint lock */
41218
  u8 readOnly;               /* True if the WAL file is open read-only */
41219
  WalIndexHdr hdr;           /* Wal-index header for current transaction */
41220
  const char *zWalName;      /* Name of WAL file */
41221
  u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
41222
#ifdef SQLITE_DEBUG
41223
  u8 lockError;              /* True if a locking error has occurred */
41224
#endif
41225
};
41226
41227
/*
41228
** Each page of the wal-index mapping contains a hash-table made up of
41229
** an array of HASHTABLE_NSLOT elements of the following type.
41230
*/
41231
typedef u16 ht_slot;
41232
41233
/*
41234
** This structure is used to implement an iterator that loops through
41235
** all frames in the WAL in database page order. Where two or more frames
41236
** correspond to the same database page, the iterator visits only the 
41237
** frame most recently written to the WAL (in other words, the frame with
41238
** the largest index).
41239
**
41240
** The internals of this structure are only accessed by:
41241
**
41242
**   walIteratorInit() - Create a new iterator,
41243
**   walIteratorNext() - Step an iterator,
41244
**   walIteratorFree() - Free an iterator.
41245
**
41246
** This functionality is used by the checkpoint code (see walCheckpoint()).
41247
*/
41248
struct WalIterator {
41249
  int iPrior;                     /* Last result returned from the iterator */
41250
  int nSegment;                   /* Size of the aSegment[] array */
41251
  struct WalSegment {
41252
    int iNext;                    /* Next slot in aIndex[] not yet returned */
41253
    ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
41254
    u32 *aPgno;                   /* Array of page numbers. */
41255
    int nEntry;                   /* Max size of aPgno[] and aIndex[] arrays */
41256
    int iZero;                    /* Frame number associated with aPgno[0] */
41257
  } aSegment[1];                  /* One for every 32KB page in the WAL */
41258
};
41259
41260
/*
41261
** Define the parameters of the hash tables in the wal-index file. There
41262
** is a hash-table following every HASHTABLE_NPAGE page numbers in the
41263
** wal-index.
41264
**
41265
** Changing any of these constants will alter the wal-index format and
41266
** create incompatibilities.
41267
*/
41268
#define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
41269
#define HASHTABLE_HASH_1     383                  /* Should be prime */
41270
#define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
41271
41272
/* 
41273
** The block of page numbers associated with the first hash-table in a
41274
** wal-index is smaller than usual. This is so that there is a complete
41275
** hash-table on each aligned 32KB page of the wal-index.
41276
*/
41277
#define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
41278
41279
/* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
41280
#define WALINDEX_PGSZ   (                                         \
41281
    sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
41282
)
41283
41284
/*
41285
** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
41286
** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
41287
** numbered from zero.
41288
**
41289
** If this call is successful, *ppPage is set to point to the wal-index
41290
** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
41291
** then an SQLite error code is returned and *ppPage is set to 0.
41292
*/
41293
static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
41294
  int rc = SQLITE_OK;
41295
41296
  /* Enlarge the pWal->apWiData[] array if required */
41297
  if( pWal->nWiData<=iPage ){
41298
    int nByte = sizeof(u32*)*(iPage+1);
41299
    volatile u32 **apNew;
41300
    apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
41301
    if( !apNew ){
41302
      *ppPage = 0;
41303
      return SQLITE_NOMEM;
41304
    }
41305
    memset((void*)&apNew[pWal->nWiData], 0,
41306
           sizeof(u32*)*(iPage+1-pWal->nWiData));
41307
    pWal->apWiData = apNew;
41308
    pWal->nWiData = iPage+1;
41309
  }
41310
41311
  /* Request a pointer to the required page from the VFS */
41312
  if( pWal->apWiData[iPage]==0 ){
41313
    rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ, 
41314
        pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
41315
    );
41316
  }
41317
41318
  *ppPage = pWal->apWiData[iPage];
41319
  assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
41320
  return rc;
41321
}
41322
41323
/*
41324
** Return a pointer to the WalCkptInfo structure in the wal-index.
41325
*/
41326
static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
41327
  assert( pWal->nWiData>0 && pWal->apWiData[0] );
41328
  return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
41329
}
41330
41331
/*
41332
** Return a pointer to the WalIndexHdr structure in the wal-index.
41333
*/
41334
static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
41335
  assert( pWal->nWiData>0 && pWal->apWiData[0] );
41336
  return (volatile WalIndexHdr*)pWal->apWiData[0];
41337
}
41338
41339
/*
41340
** The argument to this macro must be of type u32. On a little-endian
41341
** architecture, it returns the u32 value that results from interpreting
41342
** the 4 bytes as a big-endian value. On a big-endian architecture, it
41343
** returns the value that would be produced by intepreting the 4 bytes
41344
** of the input value as a little-endian integer.
41345
*/
41346
#define BYTESWAP32(x) ( \
41347
    (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
41348
  + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
41349
)
41350
41351
/*
41352
** Generate or extend an 8 byte checksum based on the data in 
41353
** array aByte[] and the initial values of aIn[0] and aIn[1] (or
41354
** initial values of 0 and 0 if aIn==NULL).
41355
**
41356
** The checksum is written back into aOut[] before returning.
41357
**
41358
** nByte must be a positive multiple of 8.
41359
*/
41360
static void walChecksumBytes(
41361
  int nativeCksum, /* True for native byte-order, false for non-native */
41362
  u8 *a,           /* Content to be checksummed */
41363
  int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
41364
  const u32 *aIn,  /* Initial checksum value input */
41365
  u32 *aOut        /* OUT: Final checksum value output */
41366
){
41367
  u32 s1, s2;
41368
  u32 *aData = (u32 *)a;
41369
  u32 *aEnd = (u32 *)&a[nByte];
41370
41371
  if( aIn ){
41372
    s1 = aIn[0];
41373
    s2 = aIn[1];
41374
  }else{
41375
    s1 = s2 = 0;
41376
  }
41377
41378
  assert( nByte>=8 );
41379
  assert( (nByte&0x00000007)==0 );
41380
41381
  if( nativeCksum ){
41382
    do {
41383
      s1 += *aData++ + s2;
41384
      s2 += *aData++ + s1;
41385
    }while( aData<aEnd );
41386
  }else{
41387
    do {
41388
      s1 += BYTESWAP32(aData[0]) + s2;
41389
      s2 += BYTESWAP32(aData[1]) + s1;
41390
      aData += 2;
41391
    }while( aData<aEnd );
41392
  }
41393
41394
  aOut[0] = s1;
41395
  aOut[1] = s2;
41396
}
41397
41398
/*
41399
** Write the header information in pWal->hdr into the wal-index.
41400
**
41401
** The checksum on pWal->hdr is updated before it is written.
41402
*/
41403
static void walIndexWriteHdr(Wal *pWal){
41404
  volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
41405
  const int nCksum = offsetof(WalIndexHdr, aCksum);
41406
41407
  assert( pWal->writeLock );
41408
  pWal->hdr.isInit = 1;
41409
  pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
41410
  walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
41411
  memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
41412
  sqlite3OsShmBarrier(pWal->pDbFd);
41413
  memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
41414
}
41415
41416
/*
41417
** This function encodes a single frame header and writes it to a buffer
41418
** supplied by the caller. A frame-header is made up of a series of 
41419
** 4-byte big-endian integers, as follows:
41420
**
41421
**     0: Page number.
41422
**     4: For commit records, the size of the database image in pages 
41423
**        after the commit. For all other records, zero.
41424
**     8: Salt-1 (copied from the wal-header)
41425
**    12: Salt-2 (copied from the wal-header)
41426
**    16: Checksum-1.
41427
**    20: Checksum-2.
41428
*/
41429
static void walEncodeFrame(
41430
  Wal *pWal,                      /* The write-ahead log */
41431
  u32 iPage,                      /* Database page number for frame */
41432
  u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
41433
  u8 *aData,                      /* Pointer to page data */
41434
  u8 *aFrame                      /* OUT: Write encoded frame here */
41435
){
41436
  int nativeCksum;                /* True for native byte-order checksums */
41437
  u32 *aCksum = pWal->hdr.aFrameCksum;
41438
  assert( WAL_FRAME_HDRSIZE==24 );
41439
  sqlite3Put4byte(&aFrame[0], iPage);
41440
  sqlite3Put4byte(&aFrame[4], nTruncate);
41441
  memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
41442
41443
  nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
41444
  walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
41445
  walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
41446
41447
  sqlite3Put4byte(&aFrame[16], aCksum[0]);
41448
  sqlite3Put4byte(&aFrame[20], aCksum[1]);
41449
}
41450
41451
/*
41452
** Check to see if the frame with header in aFrame[] and content
41453
** in aData[] is valid.  If it is a valid frame, fill *piPage and
41454
** *pnTruncate and return true.  Return if the frame is not valid.
41455
*/
41456
static int walDecodeFrame(
41457
  Wal *pWal,                      /* The write-ahead log */
41458
  u32 *piPage,                    /* OUT: Database page number for frame */
41459
  u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
41460
  u8 *aData,                      /* Pointer to page data (for checksum) */
41461
  u8 *aFrame                      /* Frame data */
41462
){
41463
  int nativeCksum;                /* True for native byte-order checksums */
41464
  u32 *aCksum = pWal->hdr.aFrameCksum;
41465
  u32 pgno;                       /* Page number of the frame */
41466
  assert( WAL_FRAME_HDRSIZE==24 );
41467
41468
  /* A frame is only valid if the salt values in the frame-header
41469
  ** match the salt values in the wal-header. 
41470
  */
41471
  if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
41472
    return 0;
41473
  }
41474
41475
  /* A frame is only valid if the page number is creater than zero.
41476
  */
41477
  pgno = sqlite3Get4byte(&aFrame[0]);
41478
  if( pgno==0 ){
41479
    return 0;
41480
  }
41481
41482
  /* A frame is only valid if a checksum of the WAL header,
41483
  ** all prior frams, the first 16 bytes of this frame-header, 
41484
  ** and the frame-data matches the checksum in the last 8 
41485
  ** bytes of this frame-header.
41486
  */
41487
  nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
41488
  walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
41489
  walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
41490
  if( aCksum[0]!=sqlite3Get4byte(&aFrame[16]) 
41491
   || aCksum[1]!=sqlite3Get4byte(&aFrame[20]) 
41492
  ){
41493
    /* Checksum failed. */
41494
    return 0;
41495
  }
41496
41497
  /* If we reach this point, the frame is valid.  Return the page number
41498
  ** and the new database size.
41499
  */
41500
  *piPage = pgno;
41501
  *pnTruncate = sqlite3Get4byte(&aFrame[4]);
41502
  return 1;
41503
}
41504
41505
41506
#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
41507
/*
41508
** Names of locks.  This routine is used to provide debugging output and is not
41509
** a part of an ordinary build.
41510
*/
41511
static const char *walLockName(int lockIdx){
41512
  if( lockIdx==WAL_WRITE_LOCK ){
41513
    return "WRITE-LOCK";
41514
  }else if( lockIdx==WAL_CKPT_LOCK ){
41515
    return "CKPT-LOCK";
41516
  }else if( lockIdx==WAL_RECOVER_LOCK ){
41517
    return "RECOVER-LOCK";
41518
  }else{
41519
    static char zName[15];
41520
    sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
41521
                     lockIdx-WAL_READ_LOCK(0));
41522
    return zName;
41523
  }
41524
}
41525
#endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
41526
    
41527
41528
/*
41529
** Set or release locks on the WAL.  Locks are either shared or exclusive.
41530
** A lock cannot be moved directly between shared and exclusive - it must go
41531
** through the unlocked state first.
41532
**
41533
** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
41534
*/
41535
static int walLockShared(Wal *pWal, int lockIdx){
41536
  int rc;
41537
  if( pWal->exclusiveMode ) return SQLITE_OK;
41538
  rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
41539
                        SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
41540
  WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
41541
            walLockName(lockIdx), rc ? "failed" : "ok"));
41542
  VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
41543
  return rc;
41544
}
41545
static void walUnlockShared(Wal *pWal, int lockIdx){
41546
  if( pWal->exclusiveMode ) return;
41547
  (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
41548
                         SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
41549
  WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
41550
}
41551
static int walLockExclusive(Wal *pWal, int lockIdx, int n){
41552
  int rc;
41553
  if( pWal->exclusiveMode ) return SQLITE_OK;
41554
  rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
41555
                        SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
41556
  WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
41557
            walLockName(lockIdx), n, rc ? "failed" : "ok"));
41558
  VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
41559
  return rc;
41560
}
41561
static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
41562
  if( pWal->exclusiveMode ) return;
41563
  (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
41564
                         SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
41565
  WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
41566
             walLockName(lockIdx), n));
41567
}
41568
41569
/*
41570
** Compute a hash on a page number.  The resulting hash value must land
41571
** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
41572
** the hash to the next value in the event of a collision.
41573
*/
41574
static int walHash(u32 iPage){
41575
  assert( iPage>0 );
41576
  assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
41577
  return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
41578
}
41579
static int walNextHash(int iPriorHash){
41580
  return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
41581
}
41582
41583
/* 
41584
** Return pointers to the hash table and page number array stored on
41585
** page iHash of the wal-index. The wal-index is broken into 32KB pages
41586
** numbered starting from 0.
41587
**
41588
** Set output variable *paHash to point to the start of the hash table
41589
** in the wal-index file. Set *piZero to one less than the frame 
41590
** number of the first frame indexed by this hash table. If a
41591
** slot in the hash table is set to N, it refers to frame number 
41592
** (*piZero+N) in the log.
41593
**
41594
** Finally, set *paPgno so that *paPgno[1] is the page number of the
41595
** first frame indexed by the hash table, frame (*piZero+1).
41596
*/
41597
static int walHashGet(
41598
  Wal *pWal,                      /* WAL handle */
41599
  int iHash,                      /* Find the iHash'th table */
41600
  volatile ht_slot **paHash,      /* OUT: Pointer to hash index */
41601
  volatile u32 **paPgno,          /* OUT: Pointer to page number array */
41602
  u32 *piZero                     /* OUT: Frame associated with *paPgno[0] */
41603
){
41604
  int rc;                         /* Return code */
41605
  volatile u32 *aPgno;
41606
41607
  rc = walIndexPage(pWal, iHash, &aPgno);
41608
  assert( rc==SQLITE_OK || iHash>0 );
41609
41610
  if( rc==SQLITE_OK ){
41611
    u32 iZero;
41612
    volatile ht_slot *aHash;
41613
41614
    aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
41615
    if( iHash==0 ){
41616
      aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
41617
      iZero = 0;
41618
    }else{
41619
      iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
41620
    }
41621
  
41622
    *paPgno = &aPgno[-1];
41623
    *paHash = aHash;
41624
    *piZero = iZero;
41625
  }
41626
  return rc;
41627
}
41628
41629
/*
41630
** Return the number of the wal-index page that contains the hash-table
41631
** and page-number array that contain entries corresponding to WAL frame
41632
** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages 
41633
** are numbered starting from 0.
41634
*/
41635
static int walFramePage(u32 iFrame){
41636
  int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
41637
  assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
41638
       && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
41639
       && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
41640
       && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
41641
       && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
41642
  );
41643
  return iHash;
41644
}
41645
41646
/*
41647
** Return the page number associated with frame iFrame in this WAL.
41648
*/
41649
static u32 walFramePgno(Wal *pWal, u32 iFrame){
41650
  int iHash = walFramePage(iFrame);
41651
  if( iHash==0 ){
41652
    return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
41653
  }
41654
  return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
41655
}
41656
41657
/*
41658
** Remove entries from the hash table that point to WAL slots greater
41659
** than pWal->hdr.mxFrame.
41660
**
41661
** This function is called whenever pWal->hdr.mxFrame is decreased due
41662
** to a rollback or savepoint.
41663
**
41664
** At most only the hash table containing pWal->hdr.mxFrame needs to be
41665
** updated.  Any later hash tables will be automatically cleared when
41666
** pWal->hdr.mxFrame advances to the point where those hash tables are
41667
** actually needed.
41668
*/
41669
static void walCleanupHash(Wal *pWal){
41670
  volatile ht_slot *aHash = 0;    /* Pointer to hash table to clear */
41671
  volatile u32 *aPgno = 0;        /* Page number array for hash table */
41672
  u32 iZero = 0;                  /* frame == (aHash[x]+iZero) */
41673
  int iLimit = 0;                 /* Zero values greater than this */
41674
  int nByte;                      /* Number of bytes to zero in aPgno[] */
41675
  int i;                          /* Used to iterate through aHash[] */
41676
41677
  assert( pWal->writeLock );
41678
  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
41679
  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
41680
  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
41681
41682
  if( pWal->hdr.mxFrame==0 ) return;
41683
41684
  /* Obtain pointers to the hash-table and page-number array containing 
41685
  ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
41686
  ** that the page said hash-table and array reside on is already mapped.
41687
  */
41688
  assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
41689
  assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
41690
  walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
41691
41692
  /* Zero all hash-table entries that correspond to frame numbers greater
41693
  ** than pWal->hdr.mxFrame.
41694
  */
41695
  iLimit = pWal->hdr.mxFrame - iZero;
41696
  assert( iLimit>0 );
41697
  for(i=0; i<HASHTABLE_NSLOT; i++){
41698
    if( aHash[i]>iLimit ){
41699
      aHash[i] = 0;
41700
    }
41701
  }
41702
  
41703
  /* Zero the entries in the aPgno array that correspond to frames with
41704
  ** frame numbers greater than pWal->hdr.mxFrame. 
41705
  */
41706
  nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
41707
  memset((void *)&aPgno[iLimit+1], 0, nByte);
41708
41709
#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
41710
  /* Verify that the every entry in the mapping region is still reachable
41711
  ** via the hash table even after the cleanup.
41712
  */
41713
  if( iLimit ){
41714
    int i;           /* Loop counter */
41715
    int iKey;        /* Hash key */
41716
    for(i=1; i<=iLimit; i++){
41717
      for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
41718
        if( aHash[iKey]==i ) break;
41719
      }
41720
      assert( aHash[iKey]==i );
41721
    }
41722
  }
41723
#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
41724
}
41725
41726
41727
/*
41728
** Set an entry in the wal-index that will map database page number
41729
** pPage into WAL frame iFrame.
41730
*/
41731
static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
41732
  int rc;                         /* Return code */
41733
  u32 iZero = 0;                  /* One less than frame number of aPgno[1] */
41734
  volatile u32 *aPgno = 0;        /* Page number array */
41735
  volatile ht_slot *aHash = 0;    /* Hash table */
41736
41737
  rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
41738
41739
  /* Assuming the wal-index file was successfully mapped, populate the
41740
  ** page number array and hash table entry.
41741
  */
41742
  if( rc==SQLITE_OK ){
41743
    int iKey;                     /* Hash table key */
41744
    int idx;                      /* Value to write to hash-table slot */
41745
    int nCollide;                 /* Number of hash collisions */
41746
41747
    idx = iFrame - iZero;
41748
    assert( idx <= HASHTABLE_NSLOT/2 + 1 );
41749
    
41750
    /* If this is the first entry to be added to this hash-table, zero the
41751
    ** entire hash table and aPgno[] array before proceding. 
41752
    */
41753
    if( idx==1 ){
41754
      int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
41755
      memset((void*)&aPgno[1], 0, nByte);
41756
    }
41757
41758
    /* If the entry in aPgno[] is already set, then the previous writer
41759
    ** must have exited unexpectedly in the middle of a transaction (after
41760
    ** writing one or more dirty pages to the WAL to free up memory). 
41761
    ** Remove the remnants of that writers uncommitted transaction from 
41762
    ** the hash-table before writing any new entries.
41763
    */
41764
    if( aPgno[idx] ){
41765
      walCleanupHash(pWal);
41766
      assert( !aPgno[idx] );
41767
    }
41768
41769
    /* Write the aPgno[] array entry and the hash-table slot. */
41770
    nCollide = idx;
41771
    for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
41772
      if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
41773
    }
41774
    aPgno[idx] = iPage;
41775
    aHash[iKey] = (ht_slot)idx;
41776
41777
#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
41778
    /* Verify that the number of entries in the hash table exactly equals
41779
    ** the number of entries in the mapping region.
41780
    */
41781
    {
41782
      int i;           /* Loop counter */
41783
      int nEntry = 0;  /* Number of entries in the hash table */
41784
      for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
41785
      assert( nEntry==idx );
41786
    }
41787
41788
    /* Verify that the every entry in the mapping region is reachable
41789
    ** via the hash table.  This turns out to be a really, really expensive
41790
    ** thing to check, so only do this occasionally - not on every
41791
    ** iteration.
41792
    */
41793
    if( (idx&0x3ff)==0 ){
41794
      int i;           /* Loop counter */
41795
      for(i=1; i<=idx; i++){
41796
        for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
41797
          if( aHash[iKey]==i ) break;
41798
        }
41799
        assert( aHash[iKey]==i );
41800
      }
41801
    }
41802
#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
41803
  }
41804
41805
41806
  return rc;
41807
}
41808
41809
41810
/*
41811
** Recover the wal-index by reading the write-ahead log file. 
41812
**
41813
** This routine first tries to establish an exclusive lock on the
41814
** wal-index to prevent other threads/processes from doing anything
41815
** with the WAL or wal-index while recovery is running.  The
41816
** WAL_RECOVER_LOCK is also held so that other threads will know
41817
** that this thread is running recovery.  If unable to establish
41818
** the necessary locks, this routine returns SQLITE_BUSY.
41819
*/
41820
static int walIndexRecover(Wal *pWal){
41821
  int rc;                         /* Return Code */
41822
  i64 nSize;                      /* Size of log file */
41823
  u32 aFrameCksum[2] = {0, 0};
41824
  int iLock;                      /* Lock offset to lock for checkpoint */
41825
  int nLock;                      /* Number of locks to hold */
41826
41827
  /* Obtain an exclusive lock on all byte in the locking range not already
41828
  ** locked by the caller. The caller is guaranteed to have locked the
41829
  ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
41830
  ** If successful, the same bytes that are locked here are unlocked before
41831
  ** this function returns.
41832
  */
41833
  assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
41834
  assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
41835
  assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
41836
  assert( pWal->writeLock );
41837
  iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
41838
  nLock = SQLITE_SHM_NLOCK - iLock;
41839
  rc = walLockExclusive(pWal, iLock, nLock);
41840
  if( rc ){
41841
    return rc;
41842
  }
41843
  WALTRACE(("WAL%p: recovery begin...\n", pWal));
41844
41845
  memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
41846
41847
  rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
41848
  if( rc!=SQLITE_OK ){
41849
    goto recovery_error;
41850
  }
41851
41852
  if( nSize>WAL_HDRSIZE ){
41853
    u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
41854
    u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
41855
    int szFrame;                  /* Number of bytes in buffer aFrame[] */
41856
    u8 *aData;                    /* Pointer to data part of aFrame buffer */
41857
    int iFrame;                   /* Index of last frame read */
41858
    i64 iOffset;                  /* Next offset to read from log file */
41859
    int szPage;                   /* Page size according to the log */
41860
    u32 magic;                    /* Magic value read from WAL header */
41861
    u32 version;                  /* Magic value read from WAL header */
41862
41863
    /* Read in the WAL header. */
41864
    rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
41865
    if( rc!=SQLITE_OK ){
41866
      goto recovery_error;
41867
    }
41868
41869
    /* If the database page size is not a power of two, or is greater than
41870
    ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid 
41871
    ** data. Similarly, if the 'magic' value is invalid, ignore the whole
41872
    ** WAL file.
41873
    */
41874
    magic = sqlite3Get4byte(&aBuf[0]);
41875
    szPage = sqlite3Get4byte(&aBuf[8]);
41876
    if( (magic&0xFFFFFFFE)!=WAL_MAGIC 
41877
     || szPage&(szPage-1) 
41878
     || szPage>SQLITE_MAX_PAGE_SIZE 
41879
     || szPage<512 
41880
    ){
41881
      goto finished;
41882
    }
41883
    pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
41884
    pWal->szPage = szPage;
41885
    pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
41886
    memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
41887
41888
    /* Verify that the WAL header checksum is correct */
41889
    walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN, 
41890
        aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
41891
    );
41892
    if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
41893
     || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
41894
    ){
41895
      goto finished;
41896
    }
41897
41898
    /* Verify that the version number on the WAL format is one that
41899
    ** are able to understand */
41900
    version = sqlite3Get4byte(&aBuf[4]);
41901
    if( version!=WAL_MAX_VERSION ){
41902
      rc = SQLITE_CANTOPEN_BKPT;
41903
      goto finished;
41904
    }
41905
41906
    /* Malloc a buffer to read frames into. */
41907
    szFrame = szPage + WAL_FRAME_HDRSIZE;
41908
    aFrame = (u8 *)sqlite3_malloc(szFrame);
41909
    if( !aFrame ){
41910
      rc = SQLITE_NOMEM;
41911
      goto recovery_error;
41912
    }
41913
    aData = &aFrame[WAL_FRAME_HDRSIZE];
41914
41915
    /* Read all frames from the log file. */
41916
    iFrame = 0;
41917
    for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
41918
      u32 pgno;                   /* Database page number for frame */
41919
      u32 nTruncate;              /* dbsize field from frame header */
41920
      int isValid;                /* True if this frame is valid */
41921
41922
      /* Read and decode the next log frame. */
41923
      rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
41924
      if( rc!=SQLITE_OK ) break;
41925
      isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
41926
      if( !isValid ) break;
41927
      rc = walIndexAppend(pWal, ++iFrame, pgno);
41928
      if( rc!=SQLITE_OK ) break;
41929
41930
      /* If nTruncate is non-zero, this is a commit record. */
41931
      if( nTruncate ){
41932
        pWal->hdr.mxFrame = iFrame;
41933
        pWal->hdr.nPage = nTruncate;
41934
        pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
41935
        testcase( szPage<=32768 );
41936
        testcase( szPage>=65536 );
41937
        aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
41938
        aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
41939
      }
41940
    }
41941
41942
    sqlite3_free(aFrame);
41943
  }
41944
41945
finished:
41946
  if( rc==SQLITE_OK ){
41947
    volatile WalCkptInfo *pInfo;
41948
    int i;
41949
    pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
41950
    pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
41951
    walIndexWriteHdr(pWal);
41952
41953
    /* Reset the checkpoint-header. This is safe because this thread is 
41954
    ** currently holding locks that exclude all other readers, writers and
41955
    ** checkpointers.
41956
    */
41957
    pInfo = walCkptInfo(pWal);
41958
    pInfo->nBackfill = 0;
41959
    pInfo->aReadMark[0] = 0;
41960
    for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
41961
41962
    /* If more than one frame was recovered from the log file, report an
41963
    ** event via sqlite3_log(). This is to help with identifying performance
41964
    ** problems caused by applications routinely shutting down without
41965
    ** checkpointing the log file.
41966
    */
41967
    if( pWal->hdr.nPage ){
41968
      sqlite3_log(SQLITE_OK, "Recovered %d frames from WAL file %s",
41969
          pWal->hdr.nPage, pWal->zWalName
41970
      );
41971
    }
41972
  }
41973
41974
recovery_error:
41975
  WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
41976
  walUnlockExclusive(pWal, iLock, nLock);
41977
  return rc;
41978
}
41979
41980
/*
41981
** Close an open wal-index.
41982
*/
41983
static void walIndexClose(Wal *pWal, int isDelete){
41984
  sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
41985
}
41986
41987
/* 
41988
** Open a connection to the WAL file zWalName. The database file must 
41989
** already be opened on connection pDbFd. The buffer that zWalName points
41990
** to must remain valid for the lifetime of the returned Wal* handle.
41991
**
41992
** A SHARED lock should be held on the database file when this function
41993
** is called. The purpose of this SHARED lock is to prevent any other
41994
** client from unlinking the WAL or wal-index file. If another process
41995
** were to do this just after this client opened one of these files, the
41996
** system would be badly broken.
41997
**
41998
** If the log file is successfully opened, SQLITE_OK is returned and 
41999
** *ppWal is set to point to a new WAL handle. If an error occurs,
42000
** an SQLite error code is returned and *ppWal is left unmodified.
42001
*/
42002
SQLITE_PRIVATE int sqlite3WalOpen(
42003
  sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
42004
  sqlite3_file *pDbFd,            /* The open database file */
42005
  const char *zWalName,           /* Name of the WAL file */
42006
  Wal **ppWal                     /* OUT: Allocated Wal handle */
42007
){
42008
  int rc;                         /* Return Code */
42009
  Wal *pRet;                      /* Object to allocate and return */
42010
  int flags;                      /* Flags passed to OsOpen() */
42011
42012
  assert( zWalName && zWalName[0] );
42013
  assert( pDbFd );
42014
42015
  /* In the amalgamation, the os_unix.c and os_win.c source files come before
42016
  ** this source file.  Verify that the #defines of the locking byte offsets
42017
  ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
42018
  */
42019
#ifdef WIN_SHM_BASE
42020
  assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
42021
#endif
42022
#ifdef UNIX_SHM_BASE
42023
  assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
42024
#endif
42025
42026
42027
  /* Allocate an instance of struct Wal to return. */
42028
  *ppWal = 0;
42029
  pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
42030
  if( !pRet ){
42031
    return SQLITE_NOMEM;
42032
  }
42033
42034
  pRet->pVfs = pVfs;
42035
  pRet->pWalFd = (sqlite3_file *)&pRet[1];
42036
  pRet->pDbFd = pDbFd;
42037
  pRet->readLock = -1;
42038
  pRet->zWalName = zWalName;
42039
42040
  /* Open file handle on the write-ahead log file. */
42041
  flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
42042
  rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
42043
  if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
42044
    pRet->readOnly = 1;
42045
  }
42046
42047
  if( rc!=SQLITE_OK ){
42048
    walIndexClose(pRet, 0);
42049
    sqlite3OsClose(pRet->pWalFd);
42050
    sqlite3_free(pRet);
42051
  }else{
42052
    *ppWal = pRet;
42053
    WALTRACE(("WAL%d: opened\n", pRet));
42054
  }
42055
  return rc;
42056
}
42057
42058
/*
42059
** Find the smallest page number out of all pages held in the WAL that
42060
** has not been returned by any prior invocation of this method on the
42061
** same WalIterator object.   Write into *piFrame the frame index where
42062
** that page was last written into the WAL.  Write into *piPage the page
42063
** number.
42064
**
42065
** Return 0 on success.  If there are no pages in the WAL with a page
42066
** number larger than *piPage, then return 1.
42067
*/
42068
static int walIteratorNext(
42069
  WalIterator *p,               /* Iterator */
42070
  u32 *piPage,                  /* OUT: The page number of the next page */
42071
  u32 *piFrame                  /* OUT: Wal frame index of next page */
42072
){
42073
  u32 iMin;                     /* Result pgno must be greater than iMin */
42074
  u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
42075
  int i;                        /* For looping through segments */
42076
42077
  iMin = p->iPrior;
42078
  assert( iMin<0xffffffff );
42079
  for(i=p->nSegment-1; i>=0; i--){
42080
    struct WalSegment *pSegment = &p->aSegment[i];
42081
    while( pSegment->iNext<pSegment->nEntry ){
42082
      u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
42083
      if( iPg>iMin ){
42084
        if( iPg<iRet ){
42085
          iRet = iPg;
42086
          *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
42087
        }
42088
        break;
42089
      }
42090
      pSegment->iNext++;
42091
    }
42092
  }
42093
42094
  *piPage = p->iPrior = iRet;
42095
  return (iRet==0xFFFFFFFF);
42096
}
42097
42098
/*
42099
** This function merges two sorted lists into a single sorted list.
42100
*/
42101
static void walMerge(
42102
  u32 *aContent,                  /* Pages in wal */
42103
  ht_slot *aLeft,                 /* IN: Left hand input list */
42104
  int nLeft,                      /* IN: Elements in array *paLeft */
42105
  ht_slot **paRight,              /* IN/OUT: Right hand input list */
42106
  int *pnRight,                   /* IN/OUT: Elements in *paRight */
42107
  ht_slot *aTmp                   /* Temporary buffer */
42108
){
42109
  int iLeft = 0;                  /* Current index in aLeft */
42110
  int iRight = 0;                 /* Current index in aRight */
42111
  int iOut = 0;                   /* Current index in output buffer */
42112
  int nRight = *pnRight;
42113
  ht_slot *aRight = *paRight;
42114
42115
  assert( nLeft>0 && nRight>0 );
42116
  while( iRight<nRight || iLeft<nLeft ){
42117
    ht_slot logpage;
42118
    Pgno dbpage;
42119
42120
    if( (iLeft<nLeft) 
42121
     && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
42122
    ){
42123
      logpage = aLeft[iLeft++];
42124
    }else{
42125
      logpage = aRight[iRight++];
42126
    }
42127
    dbpage = aContent[logpage];
42128
42129
    aTmp[iOut++] = logpage;
42130
    if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
42131
42132
    assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
42133
    assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
42134
  }
42135
42136
  *paRight = aLeft;
42137
  *pnRight = iOut;
42138
  memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
42139
}
42140
42141
/*
42142
** Sort the elements in list aList, removing any duplicates.
42143
*/
42144
static void walMergesort(
42145
  u32 *aContent,                  /* Pages in wal */
42146
  ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
42147
  ht_slot *aList,                 /* IN/OUT: List to sort */
42148
  int *pnList                     /* IN/OUT: Number of elements in aList[] */
42149
){
42150
  struct Sublist {
42151
    int nList;                    /* Number of elements in aList */
42152
    ht_slot *aList;               /* Pointer to sub-list content */
42153
  };
42154
42155
  const int nList = *pnList;      /* Size of input list */
42156
  int nMerge = 0;                 /* Number of elements in list aMerge */
42157
  ht_slot *aMerge = 0;            /* List to be merged */
42158
  int iList;                      /* Index into input list */
42159
  int iSub = 0;                   /* Index into aSub array */
42160
  struct Sublist aSub[13];        /* Array of sub-lists */
42161
42162
  memset(aSub, 0, sizeof(aSub));
42163
  assert( nList<=HASHTABLE_NPAGE && nList>0 );
42164
  assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
42165
42166
  for(iList=0; iList<nList; iList++){
42167
    nMerge = 1;
42168
    aMerge = &aList[iList];
42169
    for(iSub=0; iList & (1<<iSub); iSub++){
42170
      struct Sublist *p = &aSub[iSub];
42171
      assert( p->aList && p->nList<=(1<<iSub) );
42172
      assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
42173
      walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
42174
    }
42175
    aSub[iSub].aList = aMerge;
42176
    aSub[iSub].nList = nMerge;
42177
  }
42178
42179
  for(iSub++; iSub<ArraySize(aSub); iSub++){
42180
    if( nList & (1<<iSub) ){
42181
      struct Sublist *p = &aSub[iSub];
42182
      assert( p->nList<=(1<<iSub) );
42183
      assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
42184
      walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
42185
    }
42186
  }
42187
  assert( aMerge==aList );
42188
  *pnList = nMerge;
42189
42190
#ifdef SQLITE_DEBUG
42191
  {
42192
    int i;
42193
    for(i=1; i<*pnList; i++){
42194
      assert( aContent[aList[i]] > aContent[aList[i-1]] );
42195
    }
42196
  }
42197
#endif
42198
}
42199
42200
/* 
42201
** Free an iterator allocated by walIteratorInit().
42202
*/
42203
static void walIteratorFree(WalIterator *p){
42204
  sqlite3ScratchFree(p);
42205
}
42206
42207
/*
42208
** Construct a WalInterator object that can be used to loop over all 
42209
** pages in the WAL in ascending order. The caller must hold the checkpoint
42210
**
42211
** On success, make *pp point to the newly allocated WalInterator object
42212
** return SQLITE_OK. Otherwise, return an error code. If this routine
42213
** returns an error, the value of *pp is undefined.
42214
**
42215
** The calling routine should invoke walIteratorFree() to destroy the
42216
** WalIterator object when it has finished with it.
42217
*/
42218
static int walIteratorInit(Wal *pWal, WalIterator **pp){
42219
  WalIterator *p;                 /* Return value */
42220
  int nSegment;                   /* Number of segments to merge */
42221
  u32 iLast;                      /* Last frame in log */
42222
  int nByte;                      /* Number of bytes to allocate */
42223
  int i;                          /* Iterator variable */
42224
  ht_slot *aTmp;                  /* Temp space used by merge-sort */
42225
  int rc = SQLITE_OK;             /* Return Code */
42226
42227
  /* This routine only runs while holding the checkpoint lock. And
42228
  ** it only runs if there is actually content in the log (mxFrame>0).
42229
  */
42230
  assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
42231
  iLast = pWal->hdr.mxFrame;
42232
42233
  /* Allocate space for the WalIterator object. */
42234
  nSegment = walFramePage(iLast) + 1;
42235
  nByte = sizeof(WalIterator) 
42236
        + (nSegment-1)*sizeof(struct WalSegment)
42237
        + iLast*sizeof(ht_slot);
42238
  p = (WalIterator *)sqlite3ScratchMalloc(nByte);
42239
  if( !p ){
42240
    return SQLITE_NOMEM;
42241
  }
42242
  memset(p, 0, nByte);
42243
  p->nSegment = nSegment;
42244
42245
  /* Allocate temporary space used by the merge-sort routine. This block
42246
  ** of memory will be freed before this function returns.
42247
  */
42248
  aTmp = (ht_slot *)sqlite3ScratchMalloc(
42249
      sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
42250
  );
42251
  if( !aTmp ){
42252
    rc = SQLITE_NOMEM;
42253
  }
42254
42255
  for(i=0; rc==SQLITE_OK && i<nSegment; i++){
42256
    volatile ht_slot *aHash;
42257
    u32 iZero;
42258
    volatile u32 *aPgno;
42259
42260
    rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
42261
    if( rc==SQLITE_OK ){
42262
      int j;                      /* Counter variable */
42263
      int nEntry;                 /* Number of entries in this segment */
42264
      ht_slot *aIndex;            /* Sorted index for this segment */
42265
42266
      aPgno++;
42267
      if( (i+1)==nSegment ){
42268
        nEntry = (int)(iLast - iZero);
42269
      }else{
42270
        nEntry = (int)((u32*)aHash - (u32*)aPgno);
42271
      }
42272
      aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
42273
      iZero++;
42274
  
42275
      for(j=0; j<nEntry; j++){
42276
        aIndex[j] = (ht_slot)j;
42277
      }
42278
      walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
42279
      p->aSegment[i].iZero = iZero;
42280
      p->aSegment[i].nEntry = nEntry;
42281
      p->aSegment[i].aIndex = aIndex;
42282
      p->aSegment[i].aPgno = (u32 *)aPgno;
42283
    }
42284
  }
42285
  sqlite3ScratchFree(aTmp);
42286
42287
  if( rc!=SQLITE_OK ){
42288
    walIteratorFree(p);
42289
  }
42290
  *pp = p;
42291
  return rc;
42292
}
42293
42294
/*
42295
** Copy as much content as we can from the WAL back into the database file
42296
** in response to an sqlite3_wal_checkpoint() request or the equivalent.
42297
**
42298
** The amount of information copies from WAL to database might be limited
42299
** by active readers.  This routine will never overwrite a database page
42300
** that a concurrent reader might be using.
42301
**
42302
** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
42303
** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if 
42304
** checkpoints are always run by a background thread or background 
42305
** process, foreground threads will never block on a lengthy fsync call.
42306
**
42307
** Fsync is called on the WAL before writing content out of the WAL and
42308
** into the database.  This ensures that if the new content is persistent
42309
** in the WAL and can be recovered following a power-loss or hard reset.
42310
**
42311
** Fsync is also called on the database file if (and only if) the entire
42312
** WAL content is copied into the database file.  This second fsync makes
42313
** it safe to delete the WAL since the new content will persist in the
42314
** database file.
42315
**
42316
** This routine uses and updates the nBackfill field of the wal-index header.
42317
** This is the only routine tha will increase the value of nBackfill.  
42318
** (A WAL reset or recovery will revert nBackfill to zero, but not increase
42319
** its value.)
42320
**
42321
** The caller must be holding sufficient locks to ensure that no other
42322
** checkpoint is running (in any other thread or process) at the same
42323
** time.
42324
*/
42325
static int walCheckpoint(
42326
  Wal *pWal,                      /* Wal connection */
42327
  int sync_flags,                 /* Flags for OsSync() (or 0) */
42328
  int nBuf,                       /* Size of zBuf in bytes */
42329
  u8 *zBuf                        /* Temporary buffer to use */
42330
){
42331
  int rc;                         /* Return code */
42332
  int szPage;                     /* Database page-size */
42333
  WalIterator *pIter = 0;         /* Wal iterator context */
42334
  u32 iDbpage = 0;                /* Next database page to write */
42335
  u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
42336
  u32 mxSafeFrame;                /* Max frame that can be backfilled */
42337
  u32 mxPage;                     /* Max database page to write */
42338
  int i;                          /* Loop counter */
42339
  volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
42340
42341
  szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
42342
  testcase( szPage<=32768 );
42343
  testcase( szPage>=65536 );
42344
  if( pWal->hdr.mxFrame==0 ) return SQLITE_OK;
42345
42346
  /* Allocate the iterator */
42347
  rc = walIteratorInit(pWal, &pIter);
42348
  if( rc!=SQLITE_OK ){
42349
    return rc;
42350
  }
42351
  assert( pIter );
42352
42353
  /*** TODO:  Move this test out to the caller.  Make it an assert() here ***/
42354
  if( szPage!=nBuf ){
42355
    rc = SQLITE_CORRUPT_BKPT;
42356
    goto walcheckpoint_out;
42357
  }
42358
42359
  /* Compute in mxSafeFrame the index of the last frame of the WAL that is
42360
  ** safe to write into the database.  Frames beyond mxSafeFrame might
42361
  ** overwrite database pages that are in use by active readers and thus
42362
  ** cannot be backfilled from the WAL.
42363
  */
42364
  mxSafeFrame = pWal->hdr.mxFrame;
42365
  mxPage = pWal->hdr.nPage;
42366
  pInfo = walCkptInfo(pWal);
42367
  for(i=1; i<WAL_NREADER; i++){
42368
    u32 y = pInfo->aReadMark[i];
42369
    if( mxSafeFrame>=y ){
42370
      assert( y<=pWal->hdr.mxFrame );
42371
      rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
42372
      if( rc==SQLITE_OK ){
42373
        pInfo->aReadMark[i] = READMARK_NOT_USED;
42374
        walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
42375
      }else if( rc==SQLITE_BUSY ){
42376
        mxSafeFrame = y;
42377
      }else{
42378
        goto walcheckpoint_out;
42379
      }
42380
    }
42381
  }
42382
42383
  if( pInfo->nBackfill<mxSafeFrame
42384
   && (rc = walLockExclusive(pWal, WAL_READ_LOCK(0), 1))==SQLITE_OK
42385
  ){
42386
    i64 nSize;                    /* Current size of database file */
42387
    u32 nBackfill = pInfo->nBackfill;
42388
42389
    /* Sync the WAL to disk */
42390
    if( sync_flags ){
42391
      rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
42392
    }
42393
42394
    /* If the database file may grow as a result of this checkpoint, hint
42395
    ** about the eventual size of the db file to the VFS layer. 
42396
    */
42397
    if( rc==SQLITE_OK ){
42398
      i64 nReq = ((i64)mxPage * szPage);
42399
      rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
42400
      if( rc==SQLITE_OK && nSize<nReq ){
42401
        sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
42402
      }
42403
    }
42404
42405
    /* Iterate through the contents of the WAL, copying data to the db file. */
42406
    while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
42407
      i64 iOffset;
42408
      assert( walFramePgno(pWal, iFrame)==iDbpage );
42409
      if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
42410
      iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
42411
      /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
42412
      rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
42413
      if( rc!=SQLITE_OK ) break;
42414
      iOffset = (iDbpage-1)*(i64)szPage;
42415
      testcase( IS_BIG_INT(iOffset) );
42416
      rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
42417
      if( rc!=SQLITE_OK ) break;
42418
    }
42419
42420
    /* If work was actually accomplished... */
42421
    if( rc==SQLITE_OK ){
42422
      if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
42423
        i64 szDb = pWal->hdr.nPage*(i64)szPage;
42424
        testcase( IS_BIG_INT(szDb) );
42425
        rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
42426
        if( rc==SQLITE_OK && sync_flags ){
42427
          rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
42428
        }
42429
      }
42430
      if( rc==SQLITE_OK ){
42431
        pInfo->nBackfill = mxSafeFrame;
42432
      }
42433
    }
42434
42435
    /* Release the reader lock held while backfilling */
42436
    walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
42437
  }else if( rc==SQLITE_BUSY ){
42438
    /* Reset the return code so as not to report a checkpoint failure
42439
    ** just because active readers prevent any backfill.
42440
    */
42441
    rc = SQLITE_OK;
42442
  }
42443
42444
 walcheckpoint_out:
42445
  walIteratorFree(pIter);
42446
  return rc;
42447
}
42448
42449
/*
42450
** Close a connection to a log file.
42451
*/
42452
SQLITE_PRIVATE int sqlite3WalClose(
42453
  Wal *pWal,                      /* Wal to close */
42454
  int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
42455
  int nBuf,
42456
  u8 *zBuf                        /* Buffer of at least nBuf bytes */
42457
){
42458
  int rc = SQLITE_OK;
42459
  if( pWal ){
42460
    int isDelete = 0;             /* True to unlink wal and wal-index files */
42461
42462
    /* If an EXCLUSIVE lock can be obtained on the database file (using the
42463
    ** ordinary, rollback-mode locking methods, this guarantees that the
42464
    ** connection associated with this log file is the only connection to
42465
    ** the database. In this case checkpoint the database and unlink both
42466
    ** the wal and wal-index files.
42467
    **
42468
    ** The EXCLUSIVE lock is not released before returning.
42469
    */
42470
    rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
42471
    if( rc==SQLITE_OK ){
42472
      pWal->exclusiveMode = 1;
42473
      rc = sqlite3WalCheckpoint(pWal, sync_flags, nBuf, zBuf);
42474
      if( rc==SQLITE_OK ){
42475
        isDelete = 1;
42476
      }
42477
    }
42478
42479
    walIndexClose(pWal, isDelete);
42480
    sqlite3OsClose(pWal->pWalFd);
42481
    if( isDelete ){
42482
      sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
42483
    }
42484
    WALTRACE(("WAL%p: closed\n", pWal));
42485
    sqlite3_free((void *)pWal->apWiData);
42486
    sqlite3_free(pWal);
42487
  }
42488
  return rc;
42489
}
42490
42491
/*
42492
** Try to read the wal-index header.  Return 0 on success and 1 if
42493
** there is a problem.
42494
**
42495
** The wal-index is in shared memory.  Another thread or process might
42496
** be writing the header at the same time this procedure is trying to
42497
** read it, which might result in inconsistency.  A dirty read is detected
42498
** by verifying that both copies of the header are the same and also by
42499
** a checksum on the header.
42500
**
42501
** If and only if the read is consistent and the header is different from
42502
** pWal->hdr, then pWal->hdr is updated to the content of the new header
42503
** and *pChanged is set to 1.
42504
**
42505
** If the checksum cannot be verified return non-zero. If the header
42506
** is read successfully and the checksum verified, return zero.
42507
*/
42508
static int walIndexTryHdr(Wal *pWal, int *pChanged){
42509
  u32 aCksum[2];                  /* Checksum on the header content */
42510
  WalIndexHdr h1, h2;             /* Two copies of the header content */
42511
  WalIndexHdr volatile *aHdr;     /* Header in shared memory */
42512
42513
  /* The first page of the wal-index must be mapped at this point. */
42514
  assert( pWal->nWiData>0 && pWal->apWiData[0] );
42515
42516
  /* Read the header. This might happen concurrently with a write to the
42517
  ** same area of shared memory on a different CPU in a SMP,
42518
  ** meaning it is possible that an inconsistent snapshot is read
42519
  ** from the file. If this happens, return non-zero.
42520
  **
42521
  ** There are two copies of the header at the beginning of the wal-index.
42522
  ** When reading, read [0] first then [1].  Writes are in the reverse order.
42523
  ** Memory barriers are used to prevent the compiler or the hardware from
42524
  ** reordering the reads and writes.
42525
  */
42526
  aHdr = walIndexHdr(pWal);
42527
  memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
42528
  sqlite3OsShmBarrier(pWal->pDbFd);
42529
  memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
42530
42531
  if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
42532
    return 1;   /* Dirty read */
42533
  }  
42534
  if( h1.isInit==0 ){
42535
    return 1;   /* Malformed header - probably all zeros */
42536
  }
42537
  walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
42538
  if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
42539
    return 1;   /* Checksum does not match */
42540
  }
42541
42542
  if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
42543
    *pChanged = 1;
42544
    memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
42545
    pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
42546
    testcase( pWal->szPage<=32768 );
42547
    testcase( pWal->szPage>=65536 );
42548
  }
42549
42550
  /* The header was successfully read. Return zero. */
42551
  return 0;
42552
}
42553
42554
/*
42555
** Read the wal-index header from the wal-index and into pWal->hdr.
42556
** If the wal-header appears to be corrupt, try to reconstruct the
42557
** wal-index from the WAL before returning.
42558
**
42559
** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
42560
** changed by this opertion.  If pWal->hdr is unchanged, set *pChanged
42561
** to 0.
42562
**
42563
** If the wal-index header is successfully read, return SQLITE_OK. 
42564
** Otherwise an SQLite error code.
42565
*/
42566
static int walIndexReadHdr(Wal *pWal, int *pChanged){
42567
  int rc;                         /* Return code */
42568
  int badHdr;                     /* True if a header read failed */
42569
  volatile u32 *page0;            /* Chunk of wal-index containing header */
42570
42571
  /* Ensure that page 0 of the wal-index (the page that contains the 
42572
  ** wal-index header) is mapped. Return early if an error occurs here.
42573
  */
42574
  assert( pChanged );
42575
  rc = walIndexPage(pWal, 0, &page0);
42576
  if( rc!=SQLITE_OK ){
42577
    return rc;
42578
  };
42579
  assert( page0 || pWal->writeLock==0 );
42580
42581
  /* If the first page of the wal-index has been mapped, try to read the
42582
  ** wal-index header immediately, without holding any lock. This usually
42583
  ** works, but may fail if the wal-index header is corrupt or currently 
42584
  ** being modified by another thread or process.
42585
  */
42586
  badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
42587
42588
  /* If the first attempt failed, it might have been due to a race
42589
  ** with a writer.  So get a WRITE lock and try again.
42590
  */
42591
  assert( badHdr==0 || pWal->writeLock==0 );
42592
  if( badHdr && SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
42593
    pWal->writeLock = 1;
42594
    if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
42595
      badHdr = walIndexTryHdr(pWal, pChanged);
42596
      if( badHdr ){
42597
        /* If the wal-index header is still malformed even while holding
42598
        ** a WRITE lock, it can only mean that the header is corrupted and
42599
        ** needs to be reconstructed.  So run recovery to do exactly that.
42600
        */
42601
        rc = walIndexRecover(pWal);
42602
        *pChanged = 1;
42603
      }
42604
    }
42605
    pWal->writeLock = 0;
42606
    walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
42607
  }
42608
42609
  /* If the header is read successfully, check the version number to make
42610
  ** sure the wal-index was not constructed with some future format that
42611
  ** this version of SQLite cannot understand.
42612
  */
42613
  if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
42614
    rc = SQLITE_CANTOPEN_BKPT;
42615
  }
42616
42617
  return rc;
42618
}
42619
42620
/*
42621
** This is the value that walTryBeginRead returns when it needs to
42622
** be retried.
42623
*/
42624
#define WAL_RETRY  (-1)
42625
42626
/*
42627
** Attempt to start a read transaction.  This might fail due to a race or
42628
** other transient condition.  When that happens, it returns WAL_RETRY to
42629
** indicate to the caller that it is safe to retry immediately.
42630
**
42631
** On success return SQLITE_OK.  On a permanent failure (such an
42632
** I/O error or an SQLITE_BUSY because another process is running
42633
** recovery) return a positive error code.
42634
**
42635
** The useWal parameter is true to force the use of the WAL and disable
42636
** the case where the WAL is bypassed because it has been completely
42637
** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr() 
42638
** to make a copy of the wal-index header into pWal->hdr.  If the 
42639
** wal-index header has changed, *pChanged is set to 1 (as an indication 
42640
** to the caller that the local paget cache is obsolete and needs to be 
42641
** flushed.)  When useWal==1, the wal-index header is assumed to already
42642
** be loaded and the pChanged parameter is unused.
42643
**
42644
** The caller must set the cnt parameter to the number of prior calls to
42645
** this routine during the current read attempt that returned WAL_RETRY.
42646
** This routine will start taking more aggressive measures to clear the
42647
** race conditions after multiple WAL_RETRY returns, and after an excessive
42648
** number of errors will ultimately return SQLITE_PROTOCOL.  The
42649
** SQLITE_PROTOCOL return indicates that some other process has gone rogue
42650
** and is not honoring the locking protocol.  There is a vanishingly small
42651
** chance that SQLITE_PROTOCOL could be returned because of a run of really
42652
** bad luck when there is lots of contention for the wal-index, but that
42653
** possibility is so small that it can be safely neglected, we believe.
42654
**
42655
** On success, this routine obtains a read lock on 
42656
** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
42657
** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
42658
** that means the Wal does not hold any read lock.  The reader must not
42659
** access any database page that is modified by a WAL frame up to and
42660
** including frame number aReadMark[pWal->readLock].  The reader will
42661
** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
42662
** Or if pWal->readLock==0, then the reader will ignore the WAL
42663
** completely and get all content directly from the database file.
42664
** If the useWal parameter is 1 then the WAL will never be ignored and
42665
** this routine will always set pWal->readLock>0 on success.
42666
** When the read transaction is completed, the caller must release the
42667
** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
42668
**
42669
** This routine uses the nBackfill and aReadMark[] fields of the header
42670
** to select a particular WAL_READ_LOCK() that strives to let the
42671
** checkpoint process do as much work as possible.  This routine might
42672
** update values of the aReadMark[] array in the header, but if it does
42673
** so it takes care to hold an exclusive lock on the corresponding
42674
** WAL_READ_LOCK() while changing values.
42675
*/
42676
static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
42677
  volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
42678
  u32 mxReadMark;                 /* Largest aReadMark[] value */
42679
  int mxI;                        /* Index of largest aReadMark[] value */
42680
  int i;                          /* Loop counter */
42681
  int rc = SQLITE_OK;             /* Return code  */
42682
42683
  assert( pWal->readLock<0 );     /* Not currently locked */
42684
42685
  /* Take steps to avoid spinning forever if there is a protocol error. */
42686
  if( cnt>5 ){
42687
    if( cnt>100 ) return SQLITE_PROTOCOL;
42688
    sqlite3OsSleep(pWal->pVfs, 1);
42689
  }
42690
42691
  if( !useWal ){
42692
    rc = walIndexReadHdr(pWal, pChanged);
42693
    if( rc==SQLITE_BUSY ){
42694
      /* If there is not a recovery running in another thread or process
42695
      ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
42696
      ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
42697
      ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
42698
      ** would be technically correct.  But the race is benign since with
42699
      ** WAL_RETRY this routine will be called again and will probably be
42700
      ** right on the second iteration.
42701
      */
42702
      if( pWal->apWiData[0]==0 ){
42703
        /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
42704
        ** We assume this is a transient condition, so return WAL_RETRY. The
42705
        ** xShmMap() implementation used by the default unix and win32 VFS 
42706
        ** modules may return SQLITE_BUSY due to a race condition in the 
42707
        ** code that determines whether or not the shared-memory region 
42708
        ** must be zeroed before the requested page is returned.
42709
        */
42710
        rc = WAL_RETRY;
42711
      }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
42712
        walUnlockShared(pWal, WAL_RECOVER_LOCK);
42713
        rc = WAL_RETRY;
42714
      }else if( rc==SQLITE_BUSY ){
42715
        rc = SQLITE_BUSY_RECOVERY;
42716
      }
42717
    }
42718
    if( rc!=SQLITE_OK ){
42719
      return rc;
42720
    }
42721
  }
42722
42723
  pInfo = walCkptInfo(pWal);
42724
  if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
42725
    /* The WAL has been completely backfilled (or it is empty).
42726
    ** and can be safely ignored.
42727
    */
42728
    rc = walLockShared(pWal, WAL_READ_LOCK(0));
42729
    sqlite3OsShmBarrier(pWal->pDbFd);
42730
    if( rc==SQLITE_OK ){
42731
      if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
42732
        /* It is not safe to allow the reader to continue here if frames
42733
        ** may have been appended to the log before READ_LOCK(0) was obtained.
42734
        ** When holding READ_LOCK(0), the reader ignores the entire log file,
42735
        ** which implies that the database file contains a trustworthy
42736
        ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from
42737
        ** happening, this is usually correct.
42738
        **
42739
        ** However, if frames have been appended to the log (or if the log 
42740
        ** is wrapped and written for that matter) before the READ_LOCK(0)
42741
        ** is obtained, that is not necessarily true. A checkpointer may
42742
        ** have started to backfill the appended frames but crashed before
42743
        ** it finished. Leaving a corrupt image in the database file.
42744
        */
42745
        walUnlockShared(pWal, WAL_READ_LOCK(0));
42746
        return WAL_RETRY;
42747
      }
42748
      pWal->readLock = 0;
42749
      return SQLITE_OK;
42750
    }else if( rc!=SQLITE_BUSY ){
42751
      return rc;
42752
    }
42753
  }
42754
42755
  /* If we get this far, it means that the reader will want to use
42756
  ** the WAL to get at content from recent commits.  The job now is
42757
  ** to select one of the aReadMark[] entries that is closest to
42758
  ** but not exceeding pWal->hdr.mxFrame and lock that entry.
42759
  */
42760
  mxReadMark = 0;
42761
  mxI = 0;
42762
  for(i=1; i<WAL_NREADER; i++){
42763
    u32 thisMark = pInfo->aReadMark[i];
42764
    if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
42765
      assert( thisMark!=READMARK_NOT_USED );
42766
      mxReadMark = thisMark;
42767
      mxI = i;
42768
    }
42769
  }
42770
  if( mxI==0 ){
42771
    /* If we get here, it means that all of the aReadMark[] entries between
42772
    ** 1 and WAL_NREADER-1 are zero.  Try to initialize aReadMark[1] to
42773
    ** be mxFrame, then retry.
42774
    */
42775
    rc = walLockExclusive(pWal, WAL_READ_LOCK(1), 1);
42776
    if( rc==SQLITE_OK ){
42777
      pInfo->aReadMark[1] = pWal->hdr.mxFrame;
42778
      walUnlockExclusive(pWal, WAL_READ_LOCK(1), 1);
42779
      rc = WAL_RETRY;
42780
    }else if( rc==SQLITE_BUSY ){
42781
      rc = WAL_RETRY;
42782
    }
42783
    return rc;
42784
  }else{
42785
    if( mxReadMark < pWal->hdr.mxFrame ){
42786
      for(i=1; i<WAL_NREADER; i++){
42787
        rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
42788
        if( rc==SQLITE_OK ){
42789
          mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
42790
          mxI = i;
42791
          walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
42792
          break;
42793
        }else if( rc!=SQLITE_BUSY ){
42794
          return rc;
42795
        }
42796
      }
42797
    }
42798
42799
    rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
42800
    if( rc ){
42801
      return rc==SQLITE_BUSY ? WAL_RETRY : rc;
42802
    }
42803
    /* Now that the read-lock has been obtained, check that neither the
42804
    ** value in the aReadMark[] array or the contents of the wal-index
42805
    ** header have changed.
42806
    **
42807
    ** It is necessary to check that the wal-index header did not change
42808
    ** between the time it was read and when the shared-lock was obtained
42809
    ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
42810
    ** that the log file may have been wrapped by a writer, or that frames
42811
    ** that occur later in the log than pWal->hdr.mxFrame may have been
42812
    ** copied into the database by a checkpointer. If either of these things
42813
    ** happened, then reading the database with the current value of
42814
    ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
42815
    ** instead.
42816
    **
42817
    ** This does not guarantee that the copy of the wal-index header is up to
42818
    ** date before proceeding. That would not be possible without somehow
42819
    ** blocking writers. It only guarantees that a dangerous checkpoint or 
42820
    ** log-wrap (either of which would require an exclusive lock on
42821
    ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
42822
    */
42823
    sqlite3OsShmBarrier(pWal->pDbFd);
42824
    if( pInfo->aReadMark[mxI]!=mxReadMark
42825
     || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
42826
    ){
42827
      walUnlockShared(pWal, WAL_READ_LOCK(mxI));
42828
      return WAL_RETRY;
42829
    }else{
42830
      assert( mxReadMark<=pWal->hdr.mxFrame );
42831
      pWal->readLock = (i16)mxI;
42832
    }
42833
  }
42834
  return rc;
42835
}
42836
42837
/*
42838
** Begin a read transaction on the database.
42839
**
42840
** This routine used to be called sqlite3OpenSnapshot() and with good reason:
42841
** it takes a snapshot of the state of the WAL and wal-index for the current
42842
** instant in time.  The current thread will continue to use this snapshot.
42843
** Other threads might append new content to the WAL and wal-index but
42844
** that extra content is ignored by the current thread.
42845
**
42846
** If the database contents have changes since the previous read
42847
** transaction, then *pChanged is set to 1 before returning.  The
42848
** Pager layer will use this to know that is cache is stale and
42849
** needs to be flushed.
42850
*/
42851
SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
42852
  int rc;                         /* Return code */
42853
  int cnt = 0;                    /* Number of TryBeginRead attempts */
42854
42855
  do{
42856
    rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
42857
  }while( rc==WAL_RETRY );
42858
  return rc;
42859
}
42860
42861
/*
42862
** Finish with a read transaction.  All this does is release the
42863
** read-lock.
42864
*/
42865
SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
42866
  sqlite3WalEndWriteTransaction(pWal);
42867
  if( pWal->readLock>=0 ){
42868
    walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
42869
    pWal->readLock = -1;
42870
  }
42871
}
42872
42873
/*
42874
** Read a page from the WAL, if it is present in the WAL and if the 
42875
** current read transaction is configured to use the WAL.  
42876
**
42877
** The *pInWal is set to 1 if the requested page is in the WAL and
42878
** has been loaded.  Or *pInWal is set to 0 if the page was not in 
42879
** the WAL and needs to be read out of the database.
42880
*/
42881
SQLITE_PRIVATE int sqlite3WalRead(
42882
  Wal *pWal,                      /* WAL handle */
42883
  Pgno pgno,                      /* Database page number to read data for */
42884
  int *pInWal,                    /* OUT: True if data is read from WAL */
42885
  int nOut,                       /* Size of buffer pOut in bytes */
42886
  u8 *pOut                        /* Buffer to write page data to */
42887
){
42888
  u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
42889
  u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
42890
  int iHash;                      /* Used to loop through N hash tables */
42891
42892
  /* This routine is only be called from within a read transaction. */
42893
  assert( pWal->readLock>=0 || pWal->lockError );
42894
42895
  /* If the "last page" field of the wal-index header snapshot is 0, then
42896
  ** no data will be read from the wal under any circumstances. Return early
42897
  ** in this case as an optimization.  Likewise, if pWal->readLock==0, 
42898
  ** then the WAL is ignored by the reader so return early, as if the 
42899
  ** WAL were empty.
42900
  */
42901
  if( iLast==0 || pWal->readLock==0 ){
42902
    *pInWal = 0;
42903
    return SQLITE_OK;
42904
  }
42905
42906
  /* Search the hash table or tables for an entry matching page number
42907
  ** pgno. Each iteration of the following for() loop searches one
42908
  ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
42909
  **
42910
  ** This code might run concurrently to the code in walIndexAppend()
42911
  ** that adds entries to the wal-index (and possibly to this hash 
42912
  ** table). This means the value just read from the hash 
42913
  ** slot (aHash[iKey]) may have been added before or after the 
42914
  ** current read transaction was opened. Values added after the
42915
  ** read transaction was opened may have been written incorrectly -
42916
  ** i.e. these slots may contain garbage data. However, we assume
42917
  ** that any slots written before the current read transaction was
42918
  ** opened remain unmodified.
42919
  **
42920
  ** For the reasons above, the if(...) condition featured in the inner
42921
  ** loop of the following block is more stringent that would be required 
42922
  ** if we had exclusive access to the hash-table:
42923
  **
42924
  **   (aPgno[iFrame]==pgno): 
42925
  **     This condition filters out normal hash-table collisions.
42926
  **
42927
  **   (iFrame<=iLast): 
42928
  **     This condition filters out entries that were added to the hash
42929
  **     table after the current read-transaction had started.
42930
  */
42931
  for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
42932
    volatile ht_slot *aHash;      /* Pointer to hash table */
42933
    volatile u32 *aPgno;          /* Pointer to array of page numbers */
42934
    u32 iZero;                    /* Frame number corresponding to aPgno[0] */
42935
    int iKey;                     /* Hash slot index */
42936
    int nCollide;                 /* Number of hash collisions remaining */
42937
    int rc;                       /* Error code */
42938
42939
    rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
42940
    if( rc!=SQLITE_OK ){
42941
      return rc;
42942
    }
42943
    nCollide = HASHTABLE_NSLOT;
42944
    for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
42945
      u32 iFrame = aHash[iKey] + iZero;
42946
      if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
42947
        assert( iFrame>iRead );
42948
        iRead = iFrame;
42949
      }
42950
      if( (nCollide--)==0 ){
42951
        return SQLITE_CORRUPT_BKPT;
42952
      }
42953
    }
42954
  }
42955
42956
#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
42957
  /* If expensive assert() statements are available, do a linear search
42958
  ** of the wal-index file content. Make sure the results agree with the
42959
  ** result obtained using the hash indexes above.  */
42960
  {
42961
    u32 iRead2 = 0;
42962
    u32 iTest;
42963
    for(iTest=iLast; iTest>0; iTest--){
42964
      if( walFramePgno(pWal, iTest)==pgno ){
42965
        iRead2 = iTest;
42966
        break;
42967
      }
42968
    }
42969
    assert( iRead==iRead2 );
42970
  }
42971
#endif
42972
42973
  /* If iRead is non-zero, then it is the log frame number that contains the
42974
  ** required page. Read and return data from the log file.
42975
  */
42976
  if( iRead ){
42977
    int sz;
42978
    i64 iOffset;
42979
    sz = pWal->hdr.szPage;
42980
    sz = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
42981
    testcase( sz<=32768 );
42982
    testcase( sz>=65536 );
42983
    iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
42984
    *pInWal = 1;
42985
    /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
42986
    return sqlite3OsRead(pWal->pWalFd, pOut, nOut, iOffset);
42987
  }
42988
42989
  *pInWal = 0;
42990
  return SQLITE_OK;
42991
}
42992
42993
42994
/* 
42995
** Return the size of the database in pages (or zero, if unknown).
42996
*/
42997
SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
42998
  if( pWal && ALWAYS(pWal->readLock>=0) ){
42999
    return pWal->hdr.nPage;
43000
  }
43001
  return 0;
43002
}
43003
43004
43005
/* 
43006
** This function starts a write transaction on the WAL.
43007
**
43008
** A read transaction must have already been started by a prior call
43009
** to sqlite3WalBeginReadTransaction().
43010
**
43011
** If another thread or process has written into the database since
43012
** the read transaction was started, then it is not possible for this
43013
** thread to write as doing so would cause a fork.  So this routine
43014
** returns SQLITE_BUSY in that case and no write transaction is started.
43015
**
43016
** There can only be a single writer active at a time.
43017
*/
43018
SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
43019
  int rc;
43020
43021
  /* Cannot start a write transaction without first holding a read
43022
  ** transaction. */
43023
  assert( pWal->readLock>=0 );
43024
43025
  if( pWal->readOnly ){
43026
    return SQLITE_READONLY;
43027
  }
43028
43029
  /* Only one writer allowed at a time.  Get the write lock.  Return
43030
  ** SQLITE_BUSY if unable.
43031
  */
43032
  rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
43033
  if( rc ){
43034
    return rc;
43035
  }
43036
  pWal->writeLock = 1;
43037
43038
  /* If another connection has written to the database file since the
43039
  ** time the read transaction on this connection was started, then
43040
  ** the write is disallowed.
43041
  */
43042
  if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
43043
    walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
43044
    pWal->writeLock = 0;
43045
    rc = SQLITE_BUSY;
43046
  }
43047
43048
  return rc;
43049
}
43050
43051
/*
43052
** End a write transaction.  The commit has already been done.  This
43053
** routine merely releases the lock.
43054
*/
43055
SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
43056
  if( pWal->writeLock ){
43057
    walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
43058
    pWal->writeLock = 0;
43059
  }
43060
  return SQLITE_OK;
43061
}
43062
43063
/*
43064
** If any data has been written (but not committed) to the log file, this
43065
** function moves the write-pointer back to the start of the transaction.
43066
**
43067
** Additionally, the callback function is invoked for each frame written
43068
** to the WAL since the start of the transaction. If the callback returns
43069
** other than SQLITE_OK, it is not invoked again and the error code is
43070
** returned to the caller.
43071
**
43072
** Otherwise, if the callback function does not return an error, this
43073
** function returns SQLITE_OK.
43074
*/
43075
SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
43076
  int rc = SQLITE_OK;
43077
  if( ALWAYS(pWal->writeLock) ){
43078
    Pgno iMax = pWal->hdr.mxFrame;
43079
    Pgno iFrame;
43080
  
43081
    /* Restore the clients cache of the wal-index header to the state it
43082
    ** was in before the client began writing to the database. 
43083
    */
43084
    memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
43085
43086
    for(iFrame=pWal->hdr.mxFrame+1; 
43087
        ALWAYS(rc==SQLITE_OK) && iFrame<=iMax; 
43088
        iFrame++
43089
    ){
43090
      /* This call cannot fail. Unless the page for which the page number
43091
      ** is passed as the second argument is (a) in the cache and 
43092
      ** (b) has an outstanding reference, then xUndo is either a no-op
43093
      ** (if (a) is false) or simply expels the page from the cache (if (b)
43094
      ** is false).
43095
      **
43096
      ** If the upper layer is doing a rollback, it is guaranteed that there
43097
      ** are no outstanding references to any page other than page 1. And
43098
      ** page 1 is never written to the log until the transaction is
43099
      ** committed. As a result, the call to xUndo may not fail.
43100
      */
43101
      assert( walFramePgno(pWal, iFrame)!=1 );
43102
      rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
43103
    }
43104
    walCleanupHash(pWal);
43105
  }
43106
  assert( rc==SQLITE_OK );
43107
  return rc;
43108
}
43109
43110
/* 
43111
** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32 
43112
** values. This function populates the array with values required to 
43113
** "rollback" the write position of the WAL handle back to the current 
43114
** point in the event of a savepoint rollback (via WalSavepointUndo()).
43115
*/
43116
SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
43117
  assert( pWal->writeLock );
43118
  aWalData[0] = pWal->hdr.mxFrame;
43119
  aWalData[1] = pWal->hdr.aFrameCksum[0];
43120
  aWalData[2] = pWal->hdr.aFrameCksum[1];
43121
  aWalData[3] = pWal->nCkpt;
43122
}
43123
43124
/* 
43125
** Move the write position of the WAL back to the point identified by
43126
** the values in the aWalData[] array. aWalData must point to an array
43127
** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
43128
** by a call to WalSavepoint().
43129
*/
43130
SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
43131
  int rc = SQLITE_OK;
43132
43133
  assert( pWal->writeLock );
43134
  assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
43135
43136
  if( aWalData[3]!=pWal->nCkpt ){
43137
    /* This savepoint was opened immediately after the write-transaction
43138
    ** was started. Right after that, the writer decided to wrap around
43139
    ** to the start of the log. Update the savepoint values to match.
43140
    */
43141
    aWalData[0] = 0;
43142
    aWalData[3] = pWal->nCkpt;
43143
  }
43144
43145
  if( aWalData[0]<pWal->hdr.mxFrame ){
43146
    pWal->hdr.mxFrame = aWalData[0];
43147
    pWal->hdr.aFrameCksum[0] = aWalData[1];
43148
    pWal->hdr.aFrameCksum[1] = aWalData[2];
43149
    walCleanupHash(pWal);
43150
  }
43151
43152
  return rc;
43153
}
43154
43155
/*
43156
** This function is called just before writing a set of frames to the log
43157
** file (see sqlite3WalFrames()). It checks to see if, instead of appending
43158
** to the current log file, it is possible to overwrite the start of the
43159
** existing log file with the new frames (i.e. "reset" the log). If so,
43160
** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
43161
** unchanged.
43162
**
43163
** SQLITE_OK is returned if no error is encountered (regardless of whether
43164
** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
43165
** if some error 
43166
*/
43167
static int walRestartLog(Wal *pWal){
43168
  int rc = SQLITE_OK;
43169
  int cnt;
43170
43171
  if( pWal->readLock==0 ){
43172
    volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
43173
    assert( pInfo->nBackfill==pWal->hdr.mxFrame );
43174
    if( pInfo->nBackfill>0 ){
43175
      rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
43176
      if( rc==SQLITE_OK ){
43177
        /* If all readers are using WAL_READ_LOCK(0) (in other words if no
43178
        ** readers are currently using the WAL), then the transactions
43179
        ** frames will overwrite the start of the existing log. Update the
43180
        ** wal-index header to reflect this.
43181
        **
43182
        ** In theory it would be Ok to update the cache of the header only
43183
        ** at this point. But updating the actual wal-index header is also
43184
        ** safe and means there is no special case for sqlite3WalUndo()
43185
        ** to handle if this transaction is rolled back.
43186
        */
43187
        int i;                    /* Loop counter */
43188
        u32 *aSalt = pWal->hdr.aSalt;       /* Big-endian salt values */
43189
        pWal->nCkpt++;
43190
        pWal->hdr.mxFrame = 0;
43191
        sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
43192
        sqlite3_randomness(4, &aSalt[1]);
43193
        walIndexWriteHdr(pWal);
43194
        pInfo->nBackfill = 0;
43195
        for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
43196
        assert( pInfo->aReadMark[0]==0 );
43197
        walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
43198
      }
43199
    }
43200
    walUnlockShared(pWal, WAL_READ_LOCK(0));
43201
    pWal->readLock = -1;
43202
    cnt = 0;
43203
    do{
43204
      int notUsed;
43205
      rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
43206
    }while( rc==WAL_RETRY );
43207
  }
43208
  return rc;
43209
}
43210
43211
/* 
43212
** Write a set of frames to the log. The caller must hold the write-lock
43213
** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
43214
*/
43215
SQLITE_PRIVATE int sqlite3WalFrames(
43216
  Wal *pWal,                      /* Wal handle to write to */
43217
  int szPage,                     /* Database page-size in bytes */
43218
  PgHdr *pList,                   /* List of dirty pages to write */
43219
  Pgno nTruncate,                 /* Database size after this commit */
43220
  int isCommit,                   /* True if this is a commit */
43221
  int sync_flags                  /* Flags to pass to OsSync() (or 0) */
43222
){
43223
  int rc;                         /* Used to catch return codes */
43224
  u32 iFrame;                     /* Next frame address */
43225
  u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
43226
  PgHdr *p;                       /* Iterator to run through pList with. */
43227
  PgHdr *pLast = 0;               /* Last frame in list */
43228
  int nLast = 0;                  /* Number of extra copies of last page */
43229
43230
  assert( pList );
43231
  assert( pWal->writeLock );
43232
43233
#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
43234
  { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
43235
    WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
43236
              pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
43237
  }
43238
#endif
43239
43240
  /* See if it is possible to write these frames into the start of the
43241
  ** log file, instead of appending to it at pWal->hdr.mxFrame.
43242
  */
43243
  if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
43244
    return rc;
43245
  }
43246
43247
  /* If this is the first frame written into the log, write the WAL
43248
  ** header to the start of the WAL file. See comments at the top of
43249
  ** this source file for a description of the WAL header format.
43250
  */
43251
  iFrame = pWal->hdr.mxFrame;
43252
  if( iFrame==0 ){
43253
    u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
43254
    u32 aCksum[2];                /* Checksum for wal-header */
43255
43256
    sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
43257
    sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
43258
    sqlite3Put4byte(&aWalHdr[8], szPage);
43259
    sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
43260
    sqlite3_randomness(8, pWal->hdr.aSalt);
43261
    memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
43262
    walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
43263
    sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
43264
    sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
43265
    
43266
    pWal->szPage = szPage;
43267
    pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
43268
    pWal->hdr.aFrameCksum[0] = aCksum[0];
43269
    pWal->hdr.aFrameCksum[1] = aCksum[1];
43270
43271
    rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
43272
    WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
43273
    if( rc!=SQLITE_OK ){
43274
      return rc;
43275
    }
43276
  }
43277
  assert( pWal->szPage==szPage );
43278
43279
  /* Write the log file. */
43280
  for(p=pList; p; p=p->pDirty){
43281
    u32 nDbsize;                  /* Db-size field for frame header */
43282
    i64 iOffset;                  /* Write offset in log file */
43283
    void *pData;
43284
   
43285
    iOffset = walFrameOffset(++iFrame, szPage);
43286
    /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
43287
    
43288
    /* Populate and write the frame header */
43289
    nDbsize = (isCommit && p->pDirty==0) ? nTruncate : 0;
43290
#if defined(SQLITE_HAS_CODEC)
43291
    if( (pData = sqlite3PagerCodec(p))==0 ) return SQLITE_NOMEM;
43292
#else
43293
    pData = p->pData;
43294
#endif
43295
    walEncodeFrame(pWal, p->pgno, nDbsize, pData, aFrame);
43296
    rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOffset);
43297
    if( rc!=SQLITE_OK ){
43298
      return rc;
43299
    }
43300
43301
    /* Write the page data */
43302
    rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOffset+sizeof(aFrame));
43303
    if( rc!=SQLITE_OK ){
43304
      return rc;
43305
    }
43306
    pLast = p;
43307
  }
43308
43309
  /* Sync the log file if the 'isSync' flag was specified. */
43310
  if( sync_flags ){
43311
    i64 iSegment = sqlite3OsSectorSize(pWal->pWalFd);
43312
    i64 iOffset = walFrameOffset(iFrame+1, szPage);
43313
43314
    assert( isCommit );
43315
    assert( iSegment>0 );
43316
43317
    iSegment = (((iOffset+iSegment-1)/iSegment) * iSegment);
43318
    while( iOffset<iSegment ){
43319
      void *pData;
43320
#if defined(SQLITE_HAS_CODEC)
43321
      if( (pData = sqlite3PagerCodec(pLast))==0 ) return SQLITE_NOMEM;
43322
#else
43323
      pData = pLast->pData;
43324
#endif
43325
      walEncodeFrame(pWal, pLast->pgno, nTruncate, pData, aFrame);
43326
      /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
43327
      rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOffset);
43328
      if( rc!=SQLITE_OK ){
43329
        return rc;
43330
      }
43331
      iOffset += WAL_FRAME_HDRSIZE;
43332
      rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOffset); 
43333
      if( rc!=SQLITE_OK ){
43334
        return rc;
43335
      }
43336
      nLast++;
43337
      iOffset += szPage;
43338
    }
43339
43340
    rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
43341
  }
43342
43343
  /* Append data to the wal-index. It is not necessary to lock the 
43344
  ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
43345
  ** guarantees that there are no other writers, and no data that may
43346
  ** be in use by existing readers is being overwritten.
43347
  */
43348
  iFrame = pWal->hdr.mxFrame;
43349
  for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
43350
    iFrame++;
43351
    rc = walIndexAppend(pWal, iFrame, p->pgno);
43352
  }
43353
  while( nLast>0 && rc==SQLITE_OK ){
43354
    iFrame++;
43355
    nLast--;
43356
    rc = walIndexAppend(pWal, iFrame, pLast->pgno);
43357
  }
43358
43359
  if( rc==SQLITE_OK ){
43360
    /* Update the private copy of the header. */
43361
    pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
43362
    testcase( szPage<=32768 );
43363
    testcase( szPage>=65536 );
43364
    pWal->hdr.mxFrame = iFrame;
43365
    if( isCommit ){
43366
      pWal->hdr.iChange++;
43367
      pWal->hdr.nPage = nTruncate;
43368
    }
43369
    /* If this is a commit, update the wal-index header too. */
43370
    if( isCommit ){
43371
      walIndexWriteHdr(pWal);
43372
      pWal->iCallback = iFrame;
43373
    }
43374
  }
43375
43376
  WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
43377
  return rc;
43378
}
43379
43380
/* 
43381
** This routine is called to implement sqlite3_wal_checkpoint() and
43382
** related interfaces.
43383
**
43384
** Obtain a CHECKPOINT lock and then backfill as much information as
43385
** we can from WAL into the database.
43386
*/
43387
SQLITE_PRIVATE int sqlite3WalCheckpoint(
43388
  Wal *pWal,                      /* Wal connection */
43389
  int sync_flags,                 /* Flags to sync db file with (or 0) */
43390
  int nBuf,                       /* Size of temporary buffer */
43391
  u8 *zBuf                        /* Temporary buffer to use */
43392
){
43393
  int rc;                         /* Return code */
43394
  int isChanged = 0;              /* True if a new wal-index header is loaded */
43395
43396
  assert( pWal->ckptLock==0 );
43397
43398
  WALTRACE(("WAL%p: checkpoint begins\n", pWal));
43399
  rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
43400
  if( rc ){
43401
    /* Usually this is SQLITE_BUSY meaning that another thread or process
43402
    ** is already running a checkpoint, or maybe a recovery.  But it might
43403
    ** also be SQLITE_IOERR. */
43404
    return rc;
43405
  }
43406
  pWal->ckptLock = 1;
43407
43408
  /* Copy data from the log to the database file. */
43409
  rc = walIndexReadHdr(pWal, &isChanged);
43410
  if( rc==SQLITE_OK ){
43411
    rc = walCheckpoint(pWal, sync_flags, nBuf, zBuf);
43412
  }
43413
  if( isChanged ){
43414
    /* If a new wal-index header was loaded before the checkpoint was 
43415
    ** performed, then the pager-cache associated with pWal is now
43416
    ** out of date. So zero the cached wal-index header to ensure that
43417
    ** next time the pager opens a snapshot on this database it knows that
43418
    ** the cache needs to be reset.
43419
    */
43420
    memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
43421
  }
43422
43423
  /* Release the locks. */
43424
  walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
43425
  pWal->ckptLock = 0;
43426
  WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
43427
  return rc;
43428
}
43429
43430
/* Return the value to pass to a sqlite3_wal_hook callback, the
43431
** number of frames in the WAL at the point of the last commit since
43432
** sqlite3WalCallback() was called.  If no commits have occurred since
43433
** the last call, then return 0.
43434
*/
43435
SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
43436
  u32 ret = 0;
43437
  if( pWal ){
43438
    ret = pWal->iCallback;
43439
    pWal->iCallback = 0;
43440
  }
43441
  return (int)ret;
43442
}
43443
43444
/*
43445
** This function is called to change the WAL subsystem into or out
43446
** of locking_mode=EXCLUSIVE.
43447
**
43448
** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
43449
** into locking_mode=NORMAL.  This means that we must acquire a lock
43450
** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
43451
** or if the acquisition of the lock fails, then return 0.  If the
43452
** transition out of exclusive-mode is successful, return 1.  This
43453
** operation must occur while the pager is still holding the exclusive
43454
** lock on the main database file.
43455
**
43456
** If op is one, then change from locking_mode=NORMAL into 
43457
** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
43458
** be released.  Return 1 if the transition is made and 0 if the
43459
** WAL is already in exclusive-locking mode - meaning that this
43460
** routine is a no-op.  The pager must already hold the exclusive lock
43461
** on the main database file before invoking this operation.
43462
**
43463
** If op is negative, then do a dry-run of the op==1 case but do
43464
** not actually change anything.  The pager uses this to see if it
43465
** should acquire the database exclusive lock prior to invoking
43466
** the op==1 case.
43467
*/
43468
SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
43469
  int rc;
43470
  assert( pWal->writeLock==0 );
43471
43472
  /* pWal->readLock is usually set, but might be -1 if there was a 
43473
  ** prior error while attempting to acquire are read-lock. This cannot 
43474
  ** happen if the connection is actually in exclusive mode (as no xShmLock
43475
  ** locks are taken in this case). Nor should the pager attempt to
43476
  ** upgrade to exclusive-mode following such an error.
43477
  */
43478
  assert( pWal->readLock>=0 || pWal->lockError );
43479
  assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
43480
43481
  if( op==0 ){
43482
    if( pWal->exclusiveMode ){
43483
      pWal->exclusiveMode = 0;
43484
      if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
43485
        pWal->exclusiveMode = 1;
43486
      }
43487
      rc = pWal->exclusiveMode==0;
43488
    }else{
43489
      /* Already in locking_mode=NORMAL */
43490
      rc = 0;
43491
    }
43492
  }else if( op>0 ){
43493
    assert( pWal->exclusiveMode==0 );
43494
    assert( pWal->readLock>=0 );
43495
    walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
43496
    pWal->exclusiveMode = 1;
43497
    rc = 1;
43498
  }else{
43499
    rc = pWal->exclusiveMode==0;
43500
  }
43501
  return rc;
43502
}
43503
43504
#endif /* #ifndef SQLITE_OMIT_WAL */
43505
43506
/************** End of wal.c *************************************************/
37552
/************** Begin file btmutex.c *****************************************/
43507
/************** Begin file btmutex.c *****************************************/
37553
/*
43508
/*
37554
** 2007 August 27
43509
** 2007 August 27
 Lines 37617-37623   SQLITE_PRIVATE sqlite3_backup **sqlite3P Link Here 
37617
**
43572
**
37618
** The file is divided into pages.  The first page is called page 1,
43573
** The file is divided into pages.  The first page is called page 1,
37619
** the second is page 2, and so forth.  A page number of zero indicates
43574
** the second is page 2, and so forth.  A page number of zero indicates
37620
** "no such page".  The page size can be any power of 2 between 512 and 32768.
43575
** "no such page".  The page size can be any power of 2 between 512 and 65536.
37621
** Each page can be either a btree page, a freelist page, an overflow
43576
** Each page can be either a btree page, a freelist page, an overflow
37622
** page, or a pointer-map page.
43577
** page, or a pointer-map page.
37623
**
43578
**
 Lines 37978-37995   struct BtShared { Link Here 
37978
  u8 readOnly;          /* True if the underlying file is readonly */
43933
  u8 readOnly;          /* True if the underlying file is readonly */
37979
  u8 pageSizeFixed;     /* True if the page size can no longer be changed */
43934
  u8 pageSizeFixed;     /* True if the page size can no longer be changed */
37980
  u8 secureDelete;      /* True if secure_delete is enabled */
43935
  u8 secureDelete;      /* True if secure_delete is enabled */
43936
  u8 initiallyEmpty;    /* Database is empty at start of transaction */
37981
#ifndef SQLITE_OMIT_AUTOVACUUM
43937
#ifndef SQLITE_OMIT_AUTOVACUUM
37982
  u8 autoVacuum;        /* True if auto-vacuum is enabled */
43938
  u8 autoVacuum;        /* True if auto-vacuum is enabled */
37983
  u8 incrVacuum;        /* True if incr-vacuum is enabled */
43939
  u8 incrVacuum;        /* True if incr-vacuum is enabled */
37984
#endif
43940
#endif
37985
  u16 pageSize;         /* Total number of bytes on a page */
37986
  u16 usableSize;       /* Number of usable bytes on each page */
37987
  u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
43941
  u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
37988
  u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
43942
  u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
37989
  u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
43943
  u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
37990
  u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
43944
  u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
37991
  u8 inTransaction;     /* Transaction state */
43945
  u8 inTransaction;     /* Transaction state */
43946
  u8 doNotUseWAL;       /* If true, do not open write-ahead-log file */
43947
  u32 pageSize;         /* Total number of bytes on a page */
43948
  u32 usableSize;       /* Number of usable bytes on each page */
37992
  int nTransaction;     /* Number of open transactions (read + write) */
43949
  int nTransaction;     /* Number of open transactions (read + write) */
43950
  u32 nPage;            /* Number of pages in the database */
37993
  void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
43951
  void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
37994
  void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
43952
  void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
37995
  sqlite3_mutex *mutex; /* Non-recursive mutex required to access this struct */
43953
  sqlite3_mutex *mutex; /* Non-recursive mutex required to access this struct */
 Lines 38586-38592   int sqlite3BtreeTrace=1; /* True to ena Link Here 
38586
# define TRACE(X)
44544
# define TRACE(X)
38587
#endif
44545
#endif
38588
44546
38589
44547
/*
44548
** Extract a 2-byte big-endian integer from an array of unsigned bytes.
44549
** But if the value is zero, make it 65536.
44550
**
44551
** This routine is used to extract the "offset to cell content area" value
44552
** from the header of a btree page.  If the page size is 65536 and the page
44553
** is empty, the offset should be 65536, but the 2-byte value stores zero.
44554
** This routine makes the necessary adjustment to 65536.
44555
*/
44556
#define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
38590
44557
38591
#ifndef SQLITE_OMIT_SHARED_CACHE
44558
#ifndef SQLITE_OMIT_SHARED_CACHE
38592
/*
44559
/*
 Lines 39070-39080   static void invalidateIncrblobCursors( Link Here 
39070
static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
45037
static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
39071
  int rc = SQLITE_OK;
45038
  int rc = SQLITE_OK;
39072
  if( !pBt->pHasContent ){
45039
  if( !pBt->pHasContent ){
39073
    int nPage = 100;
45040
    assert( pgno<=pBt->nPage );
39074
    sqlite3PagerPagecount(pBt->pPager, &nPage);
45041
    pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
39075
    /* If sqlite3PagerPagecount() fails there is no harm because the
39076
    ** nPage variable is unchanged from its default value of 100 */
39077
    pBt->pHasContent = sqlite3BitvecCreate((u32)nPage);
39078
    if( !pBt->pHasContent ){
45042
    if( !pBt->pHasContent ){
39079
      rc = SQLITE_NOMEM;
45043
      rc = SQLITE_NOMEM;
39080
    }
45044
    }
 Lines 39711-39717   static int allocateSpace(MemPage *pPage, Link Here 
39711
  nFrag = data[hdr+7];
45675
  nFrag = data[hdr+7];
39712
  assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
45676
  assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
39713
  gap = pPage->cellOffset + 2*pPage->nCell;
45677
  gap = pPage->cellOffset + 2*pPage->nCell;
39714
  top = get2byte(&data[hdr+5]);
45678
  top = get2byteNotZero(&data[hdr+5]);
39715
  if( gap>top ) return SQLITE_CORRUPT_BKPT;
45679
  if( gap>top ) return SQLITE_CORRUPT_BKPT;
39716
  testcase( gap+2==top );
45680
  testcase( gap+2==top );
39717
  testcase( gap+1==top );
45681
  testcase( gap+1==top );
 Lines 39721-39727   static int allocateSpace(MemPage *pPage, Link Here 
39721
    /* Always defragment highly fragmented pages */
45685
    /* Always defragment highly fragmented pages */
39722
    rc = defragmentPage(pPage);
45686
    rc = defragmentPage(pPage);
39723
    if( rc ) return rc;
45687
    if( rc ) return rc;
39724
    top = get2byte(&data[hdr+5]);
45688
    top = get2byteNotZero(&data[hdr+5]);
39725
  }else if( gap+2<=top ){
45689
  }else if( gap+2<=top ){
39726
    /* Search the freelist looking for a free slot big enough to satisfy 
45690
    /* Search the freelist looking for a free slot big enough to satisfy 
39727
    ** the request. The allocation is made from the first free slot in 
45691
    ** the request. The allocation is made from the first free slot in 
 Lines 39763-39769   static int allocateSpace(MemPage *pPage, Link Here 
39763
  if( gap+2+nByte>top ){
45727
  if( gap+2+nByte>top ){
39764
    rc = defragmentPage(pPage);
45728
    rc = defragmentPage(pPage);
39765
    if( rc ) return rc;
45729
    if( rc ) return rc;
39766
    top = get2byte(&data[hdr+5]);
45730
    top = get2byteNotZero(&data[hdr+5]);
39767
    assert( gap+nByte<=top );
45731
    assert( gap+nByte<=top );
39768
  }
45732
  }
39769
45733
 Lines 39929-39938   static int btreeInitPage(MemPage *pPage) Link Here 
39929
    u8 hdr;            /* Offset to beginning of page header */
45893
    u8 hdr;            /* Offset to beginning of page header */
39930
    u8 *data;          /* Equal to pPage->aData */
45894
    u8 *data;          /* Equal to pPage->aData */
39931
    BtShared *pBt;        /* The main btree structure */
45895
    BtShared *pBt;        /* The main btree structure */
39932
    u16 usableSize;    /* Amount of usable space on each page */
45896
    int usableSize;    /* Amount of usable space on each page */
39933
    u16 cellOffset;    /* Offset from start of page to first cell pointer */
45897
    u16 cellOffset;    /* Offset from start of page to first cell pointer */
39934
    u16 nFree;         /* Number of unused bytes on the page */
45898
    int nFree;         /* Number of unused bytes on the page */
39935
    u16 top;           /* First byte of the cell content area */
45899
    int top;           /* First byte of the cell content area */
39936
    int iCellFirst;    /* First allowable cell or freeblock offset */
45900
    int iCellFirst;    /* First allowable cell or freeblock offset */
39937
    int iCellLast;     /* Last possible cell or freeblock offset */
45901
    int iCellLast;     /* Last possible cell or freeblock offset */
39938
45902
 Lines 39941-39952   static int btreeInitPage(MemPage *pPage) Link Here 
39941
    hdr = pPage->hdrOffset;
45905
    hdr = pPage->hdrOffset;
39942
    data = pPage->aData;
45906
    data = pPage->aData;
39943
    if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
45907
    if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
39944
    assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
45908
    assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
39945
    pPage->maskPage = pBt->pageSize - 1;
45909
    pPage->maskPage = (u16)(pBt->pageSize - 1);
39946
    pPage->nOverflow = 0;
45910
    pPage->nOverflow = 0;
39947
    usableSize = pBt->usableSize;
45911
    usableSize = pBt->usableSize;
39948
    pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
45912
    pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
39949
    top = get2byte(&data[hdr+5]);
45913
    top = get2byteNotZero(&data[hdr+5]);
39950
    pPage->nCell = get2byte(&data[hdr+3]);
45914
    pPage->nCell = get2byte(&data[hdr+3]);
39951
    if( pPage->nCell>MX_CELL(pBt) ){
45915
    if( pPage->nCell>MX_CELL(pBt) ){
39952
      /* To many cells for a single page.  The page must be corrupt */
45916
      /* To many cells for a single page.  The page must be corrupt */
 Lines 40045-40057   static void zeroPage(MemPage *pPage, int Link Here 
40045
  memset(&data[hdr+1], 0, 4);
46009
  memset(&data[hdr+1], 0, 4);
40046
  data[hdr+7] = 0;
46010
  data[hdr+7] = 0;
40047
  put2byte(&data[hdr+5], pBt->usableSize);
46011
  put2byte(&data[hdr+5], pBt->usableSize);
40048
  pPage->nFree = pBt->usableSize - first;
46012
  pPage->nFree = (u16)(pBt->usableSize - first);
40049
  decodeFlags(pPage, flags);
46013
  decodeFlags(pPage, flags);
40050
  pPage->hdrOffset = hdr;
46014
  pPage->hdrOffset = hdr;
40051
  pPage->cellOffset = first;
46015
  pPage->cellOffset = first;
40052
  pPage->nOverflow = 0;
46016
  pPage->nOverflow = 0;
40053
  assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
46017
  assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
40054
  pPage->maskPage = pBt->pageSize - 1;
46018
  pPage->maskPage = (u16)(pBt->pageSize - 1);
40055
  pPage->nCell = 0;
46019
  pPage->nCell = 0;
40056
  pPage->isInit = 1;
46020
  pPage->isInit = 1;
40057
}
46021
}
 Lines 40117-40129   static MemPage *btreePageLookup(BtShared Link Here 
40117
** Return the size of the database file in pages. If there is any kind of
46081
** Return the size of the database file in pages. If there is any kind of
40118
** error, return ((unsigned int)-1).
46082
** error, return ((unsigned int)-1).
40119
*/
46083
*/
40120
static Pgno pagerPagecount(BtShared *pBt){
46084
static Pgno btreePagecount(BtShared *pBt){
40121
  int nPage = -1;
46085
  return pBt->nPage;
40122
  int rc;
46086
}
40123
  assert( pBt->pPage1 );
46087
SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
40124
  rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
46088
  assert( sqlite3BtreeHoldsMutex(p) );
40125
  assert( rc==SQLITE_OK || nPage==-1 );
46089
  assert( ((p->pBt->nPage)&0x8000000)==0 );
40126
  return (Pgno)nPage;
46090
  return (int)btreePagecount(p->pBt);
40127
}
46091
}
40128
46092
40129
/*
46093
/*
 Lines 40140-40164   static int getAndInitPage( Link Here 
40140
  MemPage **ppPage     /* Write the page pointer here */
46104
  MemPage **ppPage     /* Write the page pointer here */
40141
){
46105
){
40142
  int rc;
46106
  int rc;
40143
  TESTONLY( Pgno iLastPg = pagerPagecount(pBt); )
40144
  assert( sqlite3_mutex_held(pBt->mutex) );
46107
  assert( sqlite3_mutex_held(pBt->mutex) );
40145
46108
40146
  rc = btreeGetPage(pBt, pgno, ppPage, 0);
46109
  if( pgno>btreePagecount(pBt) ){
40147
  if( rc==SQLITE_OK ){
46110
    rc = SQLITE_CORRUPT_BKPT;
40148
    rc = btreeInitPage(*ppPage);
46111
  }else{
40149
    if( rc!=SQLITE_OK ){
46112
    rc = btreeGetPage(pBt, pgno, ppPage, 0);
40150
      releasePage(*ppPage);
46113
    if( rc==SQLITE_OK ){
40151
    }
46114
      rc = btreeInitPage(*ppPage);
40152
  }
46115
      if( rc!=SQLITE_OK ){
40153
46116
        releasePage(*ppPage);
40154
  /* If the requested page number was either 0 or greater than the page
46117
      }
40155
  ** number of the last page in the database, this function should return
46118
    }
40156
  ** SQLITE_CORRUPT or some other error (i.e. SQLITE_FULL). Check that this
46119
  }
40157
  ** is the case.  */
46120
40158
  assert( (pgno>0 && pgno<=iLastPg) || rc!=SQLITE_OK );
40159
  testcase( pgno==0 );
46121
  testcase( pgno==0 );
40160
  testcase( pgno==iLastPg );
46122
  assert( pgno!=0 || rc==SQLITE_CORRUPT );
40161
40162
  return rc;
46123
  return rc;
40163
}
46124
}
40164
46125
 Lines 40362-40368   SQLITE_PRIVATE int sqlite3BtreeOpen( Link Here 
40362
#ifdef SQLITE_SECURE_DELETE
46323
#ifdef SQLITE_SECURE_DELETE
40363
    pBt->secureDelete = 1;
46324
    pBt->secureDelete = 1;
40364
#endif
46325
#endif
40365
    pBt->pageSize = get2byte(&zDbHeader[16]);
46326
    pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
40366
    if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
46327
    if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
40367
         || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
46328
         || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
40368
      pBt->pageSize = 0;
46329
      pBt->pageSize = 0;
 Lines 40564-40570   SQLITE_PRIVATE int sqlite3BtreeClose(Btr Link Here 
40564
    if( pBt->xFreeSchema && pBt->pSchema ){
46525
    if( pBt->xFreeSchema && pBt->pSchema ){
40565
      pBt->xFreeSchema(pBt->pSchema);
46526
      pBt->xFreeSchema(pBt->pSchema);
40566
    }
46527
    }
40567
    sqlite3_free(pBt->pSchema);
46528
    sqlite3DbFree(0, pBt->pSchema);
40568
    freeTempSpace(pBt);
46529
    freeTempSpace(pBt);
40569
    sqlite3_free(pBt);
46530
    sqlite3_free(pBt);
40570
  }
46531
  }
 Lines 40676-40682   SQLITE_PRIVATE int sqlite3BtreeSetPageSi Link Here 
40676
        ((pageSize-1)&pageSize)==0 ){
46637
        ((pageSize-1)&pageSize)==0 ){
40677
    assert( (pageSize & 7)==0 );
46638
    assert( (pageSize & 7)==0 );
40678
    assert( !pBt->pPage1 && !pBt->pCursor );
46639
    assert( !pBt->pPage1 && !pBt->pCursor );
40679
    pBt->pageSize = (u16)pageSize;
46640
    pBt->pageSize = (u32)pageSize;
40680
    freeTempSpace(pBt);
46641
    freeTempSpace(pBt);
40681
  }
46642
  }
40682
  rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
46643
  rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
 Lines 40794-40802   SQLITE_PRIVATE int sqlite3BtreeGetAutoVa Link Here 
40794
** is returned if we run out of memory. 
46755
** is returned if we run out of memory. 
40795
*/
46756
*/
40796
static int lockBtree(BtShared *pBt){
46757
static int lockBtree(BtShared *pBt){
40797
  int rc;
46758
  int rc;              /* Result code from subfunctions */
40798
  MemPage *pPage1;
46759
  MemPage *pPage1;     /* Page 1 of the database file */
40799
  int nPage;
46760
  int nPage;           /* Number of pages in the database */
46761
  int nPageFile = 0;   /* Number of pages in the database file */
46762
  int nPageHeader;     /* Number of pages in the database according to hdr */
40800
46763
40801
  assert( sqlite3_mutex_held(pBt->mutex) );
46764
  assert( sqlite3_mutex_held(pBt->mutex) );
40802
  assert( pBt->pPage1==0 );
46765
  assert( pBt->pPage1==0 );
 Lines 40808-40830   static int lockBtree(BtShared *pBt){ Link Here 
40808
  /* Do some checking to help insure the file we opened really is
46771
  /* Do some checking to help insure the file we opened really is
40809
  ** a valid database file. 
46772
  ** a valid database file. 
40810
  */
46773
  */
40811
  rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
46774
  nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
40812
  if( rc!=SQLITE_OK ){
46775
  sqlite3PagerPagecount(pBt->pPager, &nPageFile);
40813
    goto page1_init_failed;
46776
  if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
40814
  }else if( nPage>0 ){
46777
    nPage = nPageFile;
40815
    int pageSize;
46778
  }
40816
    int usableSize;
46779
  if( nPage>0 ){
46780
    u32 pageSize;
46781
    u32 usableSize;
40817
    u8 *page1 = pPage1->aData;
46782
    u8 *page1 = pPage1->aData;
40818
    rc = SQLITE_NOTADB;
46783
    rc = SQLITE_NOTADB;
40819
    if( memcmp(page1, zMagicHeader, 16)!=0 ){
46784
    if( memcmp(page1, zMagicHeader, 16)!=0 ){
40820
      goto page1_init_failed;
46785
      goto page1_init_failed;
40821
    }
46786
    }
46787
46788
#ifdef SQLITE_OMIT_WAL
40822
    if( page1[18]>1 ){
46789
    if( page1[18]>1 ){
40823
      pBt->readOnly = 1;
46790
      pBt->readOnly = 1;
40824
    }
46791
    }
40825
    if( page1[19]>1 ){
46792
    if( page1[19]>1 ){
40826
      goto page1_init_failed;
46793
      goto page1_init_failed;
40827
    }
46794
    }
46795
#else
46796
    if( page1[18]>2 ){
46797
      pBt->readOnly = 1;
46798
    }
46799
    if( page1[19]>2 ){
46800
      goto page1_init_failed;
46801
    }
46802
46803
    /* If the write version is set to 2, this database should be accessed
46804
    ** in WAL mode. If the log is not already open, open it now. Then 
46805
    ** return SQLITE_OK and return without populating BtShared.pPage1.
46806
    ** The caller detects this and calls this function again. This is
46807
    ** required as the version of page 1 currently in the page1 buffer
46808
    ** may not be the latest version - there may be a newer one in the log
46809
    ** file.
46810
    */
46811
    if( page1[19]==2 && pBt->doNotUseWAL==0 ){
46812
      int isOpen = 0;
46813
      rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
46814
      if( rc!=SQLITE_OK ){
46815
        goto page1_init_failed;
46816
      }else if( isOpen==0 ){
46817
        releasePage(pPage1);
46818
        return SQLITE_OK;
46819
      }
46820
      rc = SQLITE_NOTADB;
46821
    }
46822
#endif
40828
46823
40829
    /* The maximum embedded fraction must be exactly 25%.  And the minimum
46824
    /* The maximum embedded fraction must be exactly 25%.  And the minimum
40830
    ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
46825
    ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
 Lines 40834-40848   static int lockBtree(BtShared *pBt){ Link Here 
40834
    if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
46829
    if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
40835
      goto page1_init_failed;
46830
      goto page1_init_failed;
40836
    }
46831
    }
40837
    pageSize = get2byte(&page1[16]);
46832
    pageSize = (page1[16]<<8) | (page1[17]<<16);
40838
    if( ((pageSize-1)&pageSize)!=0 || pageSize<512 ||
46833
    if( ((pageSize-1)&pageSize)!=0
40839
        (SQLITE_MAX_PAGE_SIZE<32768 && pageSize>SQLITE_MAX_PAGE_SIZE)
46834
     || pageSize>SQLITE_MAX_PAGE_SIZE 
46835
     || pageSize<=256 
40840
    ){
46836
    ){
40841
      goto page1_init_failed;
46837
      goto page1_init_failed;
40842
    }
46838
    }
40843
    assert( (pageSize & 7)==0 );
46839
    assert( (pageSize & 7)==0 );
40844
    usableSize = pageSize - page1[20];
46840
    usableSize = pageSize - page1[20];
40845
    if( pageSize!=pBt->pageSize ){
46841
    if( (u32)pageSize!=pBt->pageSize ){
40846
      /* After reading the first page of the database assuming a page size
46842
      /* After reading the first page of the database assuming a page size
40847
      ** of BtShared.pageSize, we have discovered that the page-size is
46843
      ** of BtShared.pageSize, we have discovered that the page-size is
40848
      ** actually pageSize. Unlock the database, leave pBt->pPage1 at
46844
      ** actually pageSize. Unlock the database, leave pBt->pPage1 at
 Lines 40850-40867   static int lockBtree(BtShared *pBt){ Link Here 
40850
      ** again with the correct page-size.
46846
      ** again with the correct page-size.
40851
      */
46847
      */
40852
      releasePage(pPage1);
46848
      releasePage(pPage1);
40853
      pBt->usableSize = (u16)usableSize;
46849
      pBt->usableSize = usableSize;
40854
      pBt->pageSize = (u16)pageSize;
46850
      pBt->pageSize = pageSize;
40855
      freeTempSpace(pBt);
46851
      freeTempSpace(pBt);
40856
      rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
46852
      rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
40857
                                   pageSize-usableSize);
46853
                                   pageSize-usableSize);
40858
      return rc;
46854
      return rc;
40859
    }
46855
    }
46856
    if( nPageHeader>nPageFile ){
46857
      rc = SQLITE_CORRUPT_BKPT;
46858
      goto page1_init_failed;
46859
    }
40860
    if( usableSize<480 ){
46860
    if( usableSize<480 ){
40861
      goto page1_init_failed;
46861
      goto page1_init_failed;
40862
    }
46862
    }
40863
    pBt->pageSize = (u16)pageSize;
46863
    pBt->pageSize = pageSize;
40864
    pBt->usableSize = (u16)usableSize;
46864
    pBt->usableSize = usableSize;
40865
#ifndef SQLITE_OMIT_AUTOVACUUM
46865
#ifndef SQLITE_OMIT_AUTOVACUUM
40866
    pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
46866
    pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
40867
    pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
46867
    pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
 Lines 40877-40892   static int lockBtree(BtShared *pBt){ Link Here 
40877
  **     9-byte nKey value
46877
  **     9-byte nKey value
40878
  **     4-byte nData value
46878
  **     4-byte nData value
40879
  **     4-byte overflow page pointer
46879
  **     4-byte overflow page pointer
40880
  ** So a cell consists of a 2-byte poiner, a header which is as much as
46880
  ** So a cell consists of a 2-byte pointer, a header which is as much as
40881
  ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
46881
  ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
40882
  ** page pointer.
46882
  ** page pointer.
40883
  */
46883
  */
40884
  pBt->maxLocal = (pBt->usableSize-12)*64/255 - 23;
46884
  pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
40885
  pBt->minLocal = (pBt->usableSize-12)*32/255 - 23;
46885
  pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
40886
  pBt->maxLeaf = pBt->usableSize - 35;
46886
  pBt->maxLeaf = (u16)(pBt->usableSize - 35);
40887
  pBt->minLeaf = (pBt->usableSize-12)*32/255 - 23;
46887
  pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
40888
  assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
46888
  assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
40889
  pBt->pPage1 = pPage1;
46889
  pBt->pPage1 = pPage1;
46890
  pBt->nPage = nPage;
40890
  return SQLITE_OK;
46891
  return SQLITE_OK;
40891
46892
40892
page1_init_failed:
46893
page1_init_failed:
 Lines 40924-40935   static int newDatabase(BtShared *pBt){ Link Here 
40924
  MemPage *pP1;
46925
  MemPage *pP1;
40925
  unsigned char *data;
46926
  unsigned char *data;
40926
  int rc;
46927
  int rc;
40927
  int nPage;
40928
46928
40929
  assert( sqlite3_mutex_held(pBt->mutex) );
46929
  assert( sqlite3_mutex_held(pBt->mutex) );
40930
  rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
46930
  if( pBt->nPage>0 ){
40931
  if( rc!=SQLITE_OK || nPage>0 ){
46931
    return SQLITE_OK;
40932
    return rc;
40933
  }
46932
  }
40934
  pP1 = pBt->pPage1;
46933
  pP1 = pBt->pPage1;
40935
  assert( pP1!=0 );
46934
  assert( pP1!=0 );
 Lines 40938-40944   static int newDatabase(BtShared *pBt){ Link Here 
40938
  if( rc ) return rc;
46937
  if( rc ) return rc;
40939
  memcpy(data, zMagicHeader, sizeof(zMagicHeader));
46938
  memcpy(data, zMagicHeader, sizeof(zMagicHeader));
40940
  assert( sizeof(zMagicHeader)==16 );
46939
  assert( sizeof(zMagicHeader)==16 );
40941
  put2byte(&data[16], pBt->pageSize);
46940
  data[16] = (u8)((pBt->pageSize>>8)&0xff);
46941
  data[17] = (u8)((pBt->pageSize>>16)&0xff);
40942
  data[18] = 1;
46942
  data[18] = 1;
40943
  data[19] = 1;
46943
  data[19] = 1;
40944
  assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
46944
  assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
 Lines 40955-40960   static int newDatabase(BtShared *pBt){ Link Here 
40955
  put4byte(&data[36 + 4*4], pBt->autoVacuum);
46955
  put4byte(&data[36 + 4*4], pBt->autoVacuum);
40956
  put4byte(&data[36 + 7*4], pBt->incrVacuum);
46956
  put4byte(&data[36 + 7*4], pBt->incrVacuum);
40957
#endif
46957
#endif
46958
  pBt->nPage = 1;
46959
  data[31] = 1;
40958
  return SQLITE_OK;
46960
  return SQLITE_OK;
40959
}
46961
}
40960
46962
 Lines 41044-41049   SQLITE_PRIVATE int sqlite3BtreeBeginTran Link Here 
41044
  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
47046
  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
41045
  if( SQLITE_OK!=rc ) goto trans_begun;
47047
  if( SQLITE_OK!=rc ) goto trans_begun;
41046
47048
47049
  pBt->initiallyEmpty = (u8)(pBt->nPage==0);
41047
  do {
47050
  do {
41048
    /* Call lockBtree() until either pBt->pPage1 is populated or
47051
    /* Call lockBtree() until either pBt->pPage1 is populated or
41049
    ** lockBtree() returns something other than SQLITE_OK. lockBtree()
47052
    ** lockBtree() returns something other than SQLITE_OK. lockBtree()
 Lines 41068-41074   SQLITE_PRIVATE int sqlite3BtreeBeginTran Link Here 
41068
    if( rc!=SQLITE_OK ){
47071
    if( rc!=SQLITE_OK ){
41069
      unlockBtreeIfUnused(pBt);
47072
      unlockBtreeIfUnused(pBt);
41070
    }
47073
    }
41071
  }while( rc==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
47074
  }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
41072
          btreeInvokeBusyHandler(pBt) );
47075
          btreeInvokeBusyHandler(pBt) );
41073
47076
41074
  if( rc==SQLITE_OK ){
47077
  if( rc==SQLITE_OK ){
 Lines 41087-41099   SQLITE_PRIVATE int sqlite3BtreeBeginTran Link Here 
41087
    if( p->inTrans>pBt->inTransaction ){
47090
    if( p->inTrans>pBt->inTransaction ){
41088
      pBt->inTransaction = p->inTrans;
47091
      pBt->inTransaction = p->inTrans;
41089
    }
47092
    }
47093
    if( wrflag ){
47094
      MemPage *pPage1 = pBt->pPage1;
41090
#ifndef SQLITE_OMIT_SHARED_CACHE
47095
#ifndef SQLITE_OMIT_SHARED_CACHE
41091
    if( wrflag ){
41092
      assert( !pBt->pWriter );
47096
      assert( !pBt->pWriter );
41093
      pBt->pWriter = p;
47097
      pBt->pWriter = p;
41094
      pBt->isExclusive = (u8)(wrflag>1);
47098
      pBt->isExclusive = (u8)(wrflag>1);
41095
    }
47099
#endif
41096
#endif
47100
47101
      /* If the db-size header field is incorrect (as it may be if an old
47102
      ** client has been writing the database file), update it now. Doing
47103
      ** this sooner rather than later means the database size can safely 
47104
      ** re-read the database size from page 1 if a savepoint or transaction
47105
      ** rollback occurs within the transaction.
47106
      */
47107
      if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
47108
        rc = sqlite3PagerWrite(pPage1->pDbPage);
47109
        if( rc==SQLITE_OK ){
47110
          put4byte(&pPage1->aData[28], pBt->nPage);
47111
        }
47112
      }
47113
    }
41097
  }
47114
  }
41098
47115
41099
47116
 Lines 41323-41334   static int allocateBtreePage(BtShared *, Link Here 
41323
*/
47340
*/
41324
static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
47341
static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
41325
  Pgno nFreeList;           /* Number of pages still on the free-list */
47342
  Pgno nFreeList;           /* Number of pages still on the free-list */
47343
  int rc;
41326
47344
41327
  assert( sqlite3_mutex_held(pBt->mutex) );
47345
  assert( sqlite3_mutex_held(pBt->mutex) );
41328
  assert( iLastPg>nFin );
47346
  assert( iLastPg>nFin );
41329
47347
41330
  if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
47348
  if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
41331
    int rc;
41332
    u8 eType;
47349
    u8 eType;
41333
    Pgno iPtrPage;
47350
    Pgno iPtrPage;
41334
47351
 Lines 41404-41410   static int incrVacuumStep(BtShared *pBt, Link Here 
41404
    while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
47421
    while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
41405
      if( PTRMAP_ISPAGE(pBt, iLastPg) ){
47422
      if( PTRMAP_ISPAGE(pBt, iLastPg) ){
41406
        MemPage *pPg;
47423
        MemPage *pPg;
41407
        int rc = btreeGetPage(pBt, iLastPg, &pPg, 0);
47424
        rc = btreeGetPage(pBt, iLastPg, &pPg, 0);
41408
        if( rc!=SQLITE_OK ){
47425
        if( rc!=SQLITE_OK ){
41409
          return rc;
47426
          return rc;
41410
        }
47427
        }
 Lines 41417-41422   static int incrVacuumStep(BtShared *pBt, Link Here 
41417
      iLastPg--;
47434
      iLastPg--;
41418
    }
47435
    }
41419
    sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
47436
    sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
47437
    pBt->nPage = iLastPg;
41420
  }
47438
  }
41421
  return SQLITE_OK;
47439
  return SQLITE_OK;
41422
}
47440
}
 Lines 41439-41445   SQLITE_PRIVATE int sqlite3BtreeIncrVacuu Link Here 
41439
    rc = SQLITE_DONE;
47457
    rc = SQLITE_DONE;
41440
  }else{
47458
  }else{
41441
    invalidateAllOverflowCache(pBt);
47459
    invalidateAllOverflowCache(pBt);
41442
    rc = incrVacuumStep(pBt, 0, pagerPagecount(pBt));
47460
    rc = incrVacuumStep(pBt, 0, btreePagecount(pBt));
47461
    if( rc==SQLITE_OK ){
47462
      rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
47463
      put4byte(&pBt->pPage1->aData[28], pBt->nPage);
47464
    }
41443
  }
47465
  }
41444
  sqlite3BtreeLeave(p);
47466
  sqlite3BtreeLeave(p);
41445
  return rc;
47467
  return rc;
 Lines 41470-41476   static int autoVacuumCommit(BtShared *pB Link Here 
41470
    int nEntry;        /* Number of entries on one ptrmap page */
47492
    int nEntry;        /* Number of entries on one ptrmap page */
41471
    Pgno nOrig;        /* Database size before freeing */
47493
    Pgno nOrig;        /* Database size before freeing */
41472
47494
41473
    nOrig = pagerPagecount(pBt);
47495
    nOrig = btreePagecount(pBt);
41474
    if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
47496
    if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
41475
      /* It is not possible to create a database for which the final page
47497
      /* It is not possible to create a database for which the final page
41476
      ** is either a pointer-map page or the pending-byte page. If one
47498
      ** is either a pointer-map page or the pending-byte page. If one
 Lines 41495-41505   static int autoVacuumCommit(BtShared *pB Link Here 
41495
      rc = incrVacuumStep(pBt, nFin, iFree);
47517
      rc = incrVacuumStep(pBt, nFin, iFree);
41496
    }
47518
    }
41497
    if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
47519
    if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
41498
      rc = SQLITE_OK;
41499
      rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
47520
      rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
41500
      put4byte(&pBt->pPage1->aData[32], 0);
47521
      put4byte(&pBt->pPage1->aData[32], 0);
41501
      put4byte(&pBt->pPage1->aData[36], 0);
47522
      put4byte(&pBt->pPage1->aData[36], 0);
47523
      put4byte(&pBt->pPage1->aData[28], nFin);
41502
      sqlite3PagerTruncateImage(pBt->pPager, nFin);
47524
      sqlite3PagerTruncateImage(pBt->pPager, nFin);
47525
      pBt->nPage = nFin;
41503
    }
47526
    }
41504
    if( rc!=SQLITE_OK ){
47527
    if( rc!=SQLITE_OK ){
41505
      sqlite3PagerRollback(pPager);
47528
      sqlite3PagerRollback(pPager);
 Lines 41749-41754   SQLITE_PRIVATE int sqlite3BtreeRollback( Link Here 
41749
    ** call btreeGetPage() on page 1 again to make
47772
    ** call btreeGetPage() on page 1 again to make
41750
    ** sure pPage1->aData is set correctly. */
47773
    ** sure pPage1->aData is set correctly. */
41751
    if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
47774
    if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
47775
      int nPage = get4byte(28+(u8*)pPage1->aData);
47776
      testcase( nPage==0 );
47777
      if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
47778
      testcase( pBt->nPage!=nPage );
47779
      pBt->nPage = nPage;
41752
      releasePage(pPage1);
47780
      releasePage(pPage1);
41753
    }
47781
    }
41754
    assert( countWriteCursors(pBt)==0 );
47782
    assert( countWriteCursors(pBt)==0 );
 Lines 41786-41802   SQLITE_PRIVATE int sqlite3BtreeBeginStmt Link Here 
41786
  assert( pBt->readOnly==0 );
47814
  assert( pBt->readOnly==0 );
41787
  assert( iStatement>0 );
47815
  assert( iStatement>0 );
41788
  assert( iStatement>p->db->nSavepoint );
47816
  assert( iStatement>p->db->nSavepoint );
41789
  if( NEVER(p->inTrans!=TRANS_WRITE || pBt->readOnly) ){
47817
  assert( pBt->inTransaction==TRANS_WRITE );
41790
    rc = SQLITE_INTERNAL;
47818
  /* At the pager level, a statement transaction is a savepoint with
41791
  }else{
47819
  ** an index greater than all savepoints created explicitly using
41792
    assert( pBt->inTransaction==TRANS_WRITE );
47820
  ** SQL statements. It is illegal to open, release or rollback any
41793
    /* At the pager level, a statement transaction is a savepoint with
47821
  ** such savepoints while the statement transaction savepoint is active.
41794
    ** an index greater than all savepoints created explicitly using
47822
  */
41795
    ** SQL statements. It is illegal to open, release or rollback any
47823
  rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
41796
    ** such savepoints while the statement transaction savepoint is active.
41797
    */
41798
    rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
41799
  }
41800
  sqlite3BtreeLeave(p);
47824
  sqlite3BtreeLeave(p);
41801
  return rc;
47825
  return rc;
41802
}
47826
}
 Lines 41822-41828   SQLITE_PRIVATE int sqlite3BtreeSavepoint Link Here 
41822
    sqlite3BtreeEnter(p);
47846
    sqlite3BtreeEnter(p);
41823
    rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
47847
    rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
41824
    if( rc==SQLITE_OK ){
47848
    if( rc==SQLITE_OK ){
47849
      if( iSavepoint<0 && pBt->initiallyEmpty ) pBt->nPage = 0;
41825
      rc = newDatabase(pBt);
47850
      rc = newDatabase(pBt);
47851
      pBt->nPage = get4byte(28 + pBt->pPage1->aData);
47852
47853
      /* The database size was written into the offset 28 of the header
47854
      ** when the transaction started, so we know that the value at offset
47855
      ** 28 is nonzero. */
47856
      assert( pBt->nPage>0 );
41826
    }
47857
    }
41827
    sqlite3BtreeLeave(p);
47858
    sqlite3BtreeLeave(p);
41828
  }
47859
  }
 Lines 41888-41894   static int btreeCursor( Link Here 
41888
  if( NEVER(wrFlag && pBt->readOnly) ){
47919
  if( NEVER(wrFlag && pBt->readOnly) ){
41889
    return SQLITE_READONLY;
47920
    return SQLITE_READONLY;
41890
  }
47921
  }
41891
  if( iTable==1 && pagerPagecount(pBt)==0 ){
47922
  if( iTable==1 && btreePagecount(pBt)==0 ){
41892
    return SQLITE_EMPTY;
47923
    return SQLITE_EMPTY;
41893
  }
47924
  }
41894
47925
 Lines 42159-42165   static int getOverflowPage( Link Here 
42159
      iGuess++;
48190
      iGuess++;
42160
    }
48191
    }
42161
48192
42162
    if( iGuess<=pagerPagecount(pBt) ){
48193
    if( iGuess<=btreePagecount(pBt) ){
42163
      rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
48194
      rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
42164
      if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
48195
      if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
42165
        next = iGuess;
48196
        next = iGuess;
 Lines 42754-42760   SQLITE_PRIVATE int sqlite3BtreeFirst(BtC Link Here 
42754
    if( pCur->eState==CURSOR_INVALID ){
48785
    if( pCur->eState==CURSOR_INVALID ){
42755
      assert( pCur->apPage[pCur->iPage]->nCell==0 );
48786
      assert( pCur->apPage[pCur->iPage]->nCell==0 );
42756
      *pRes = 1;
48787
      *pRes = 1;
42757
      rc = SQLITE_OK;
42758
    }else{
48788
    }else{
42759
      assert( pCur->apPage[pCur->iPage]->nCell>0 );
48789
      assert( pCur->apPage[pCur->iPage]->nCell>0 );
42760
      *pRes = 0;
48790
      *pRes = 0;
 Lines 42919-42927   SQLITE_PRIVATE int sqlite3BtreeMovetoUnp Link Here 
42919
        pCur->validNKey = 1;
48949
        pCur->validNKey = 1;
42920
        pCur->info.nKey = nCellKey;
48950
        pCur->info.nKey = nCellKey;
42921
      }else{
48951
      }else{
42922
        /* The maximum supported page-size is 32768 bytes. This means that
48952
        /* The maximum supported page-size is 65536 bytes. This means that
42923
        ** the maximum number of record bytes stored on an index B-Tree
48953
        ** the maximum number of record bytes stored on an index B-Tree
42924
        ** page is at most 8198 bytes, which may be stored as a 2-byte
48954
        ** page is less than 16384 bytes and may be stored as a 2-byte
42925
        ** varint. This information is used to attempt to avoid parsing 
48955
        ** varint. This information is used to attempt to avoid parsing 
42926
        ** the entire cell by checking for the cases where the record is 
48956
        ** the entire cell by checking for the cases where the record is 
42927
        ** stored entirely within the b-tree page by inspecting the first 
48957
        ** stored entirely within the b-tree page by inspecting the first 
 Lines 43191-43197   static int allocateBtreePage( Link Here 
43191
49221
43192
  assert( sqlite3_mutex_held(pBt->mutex) );
49222
  assert( sqlite3_mutex_held(pBt->mutex) );
43193
  pPage1 = pBt->pPage1;
49223
  pPage1 = pBt->pPage1;
43194
  mxPage = pagerPagecount(pBt);
49224
  mxPage = btreePagecount(pBt);
43195
  n = get4byte(&pPage1->aData[36]);
49225
  n = get4byte(&pPage1->aData[36]);
43196
  testcase( n==mxPage-1 );
49226
  testcase( n==mxPage-1 );
43197
  if( n>=mxPage ){
49227
  if( n>=mxPage ){
 Lines 43387-43421   static int allocateBtreePage( Link Here 
43387
  }else{
49417
  }else{
43388
    /* There are no pages on the freelist, so create a new page at the
49418
    /* There are no pages on the freelist, so create a new page at the
43389
    ** end of the file */
49419
    ** end of the file */
43390
    int nPage = pagerPagecount(pBt);
49420
    rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
43391
    *pPgno = nPage + 1;
49421
    if( rc ) return rc;
43392
49422
    pBt->nPage++;
43393
    if( *pPgno==PENDING_BYTE_PAGE(pBt) ){
49423
    if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
43394
      (*pPgno)++;
43395
    }
43396
49424
43397
#ifndef SQLITE_OMIT_AUTOVACUUM
49425
#ifndef SQLITE_OMIT_AUTOVACUUM
43398
    if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, *pPgno) ){
49426
    if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
43399
      /* If *pPgno refers to a pointer-map page, allocate two new pages
49427
      /* If *pPgno refers to a pointer-map page, allocate two new pages
43400
      ** at the end of the file instead of one. The first allocated page
49428
      ** at the end of the file instead of one. The first allocated page
43401
      ** becomes a new pointer-map page, the second is used by the caller.
49429
      ** becomes a new pointer-map page, the second is used by the caller.
43402
      */
49430
      */
43403
      MemPage *pPg = 0;
49431
      MemPage *pPg = 0;
43404
      TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", *pPgno));
49432
      TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
43405
      assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
49433
      assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
43406
      rc = btreeGetPage(pBt, *pPgno, &pPg, 0);
49434
      rc = btreeGetPage(pBt, pBt->nPage, &pPg, 1);
43407
      if( rc==SQLITE_OK ){
49435
      if( rc==SQLITE_OK ){
43408
        rc = sqlite3PagerWrite(pPg->pDbPage);
49436
        rc = sqlite3PagerWrite(pPg->pDbPage);
43409
        releasePage(pPg);
49437
        releasePage(pPg);
43410
      }
49438
      }
43411
      if( rc ) return rc;
49439
      if( rc ) return rc;
43412
      (*pPgno)++;
49440
      pBt->nPage++;
43413
      if( *pPgno==PENDING_BYTE_PAGE(pBt) ){ (*pPgno)++; }
49441
      if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
43414
    }
49442
    }
43415
#endif
49443
#endif
49444
    put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
49445
    *pPgno = pBt->nPage;
43416
49446
43417
    assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
49447
    assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
43418
    rc = btreeGetPage(pBt, *pPgno, ppPage, 0);
49448
    rc = btreeGetPage(pBt, *pPgno, ppPage, 1);
43419
    if( rc ) return rc;
49449
    if( rc ) return rc;
43420
    rc = sqlite3PagerWrite((*ppPage)->pDbPage);
49450
    rc = sqlite3PagerWrite((*ppPage)->pDbPage);
43421
    if( rc!=SQLITE_OK ){
49451
    if( rc!=SQLITE_OK ){
 Lines 43590-43596   static int clearCell(MemPage *pPage, uns Link Here 
43590
  Pgno ovflPgno;
49620
  Pgno ovflPgno;
43591
  int rc;
49621
  int rc;
43592
  int nOvfl;
49622
  int nOvfl;
43593
  u16 ovflPageSize;
49623
  u32 ovflPageSize;
43594
49624
43595
  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49625
  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
43596
  btreeParseCellPtr(pPage, pCell, &info);
49626
  btreeParseCellPtr(pPage, pCell, &info);
 Lines 43605-43611   static int clearCell(MemPage *pPage, uns Link Here 
43605
  while( nOvfl-- ){
49635
  while( nOvfl-- ){
43606
    Pgno iNext = 0;
49636
    Pgno iNext = 0;
43607
    MemPage *pOvfl = 0;
49637
    MemPage *pOvfl = 0;
43608
    if( ovflPgno<2 || ovflPgno>pagerPagecount(pBt) ){
49638
    if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
43609
      /* 0 is not a legal page number and page 1 cannot be an 
49639
      /* 0 is not a legal page number and page 1 cannot be an 
43610
      ** overflow page. Therefore if ovflPgno<2 or past the end of the 
49640
      ** overflow page. Therefore if ovflPgno<2 or past the end of the 
43611
      ** file the database must be corrupt. */
49641
      ** file the database must be corrupt. */
 Lines 43815-43821   static int fillInCell( Link Here 
43815
*/
49845
*/
43816
static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
49846
static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
43817
  int i;          /* Loop counter */
49847
  int i;          /* Loop counter */
43818
  int pc;         /* Offset to cell content of cell being deleted */
49848
  u32 pc;         /* Offset to cell content of cell being deleted */
43819
  u8 *data;       /* pPage->aData */
49849
  u8 *data;       /* pPage->aData */
43820
  u8 *ptr;        /* Used to move bytes around within data[] */
49850
  u8 *ptr;        /* Used to move bytes around within data[] */
43821
  int rc;         /* The return code */
49851
  int rc;         /* The return code */
 Lines 43833-43839   static void dropCell(MemPage *pPage, int Link Here 
43833
  hdr = pPage->hdrOffset;
49863
  hdr = pPage->hdrOffset;
43834
  testcase( pc==get2byte(&data[hdr+5]) );
49864
  testcase( pc==get2byte(&data[hdr+5]) );
43835
  testcase( pc+sz==pPage->pBt->usableSize );
49865
  testcase( pc+sz==pPage->pBt->usableSize );
43836
  if( pc < get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
49866
  if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
43837
    *pRC = SQLITE_CORRUPT_BKPT;
49867
    *pRC = SQLITE_CORRUPT_BKPT;
43838
    return;
49868
    return;
43839
  }
49869
  }
 Lines 43890-43896   static void insertCell( Link Here 
43890
  if( *pRC ) return;
49920
  if( *pRC ) return;
43891
49921
43892
  assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
49922
  assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
43893
  assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
49923
  assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 );
43894
  assert( pPage->nOverflow<=ArraySize(pPage->aOvfl) );
49924
  assert( pPage->nOverflow<=ArraySize(pPage->aOvfl) );
43895
  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49925
  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
43896
  /* The cell should normally be sized correctly.  However, when moving a
49926
  /* The cell should normally be sized correctly.  However, when moving a
 Lines 43970-43981   static void assemblePage( Link Here 
43970
50000
43971
  assert( pPage->nOverflow==0 );
50001
  assert( pPage->nOverflow==0 );
43972
  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50002
  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
43973
  assert( nCell>=0 && nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
50003
  assert( nCell>=0 && nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921);
43974
  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
50004
  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
43975
50005
43976
  /* Check that the page has just been zeroed by zeroPage() */
50006
  /* Check that the page has just been zeroed by zeroPage() */
43977
  assert( pPage->nCell==0 );
50007
  assert( pPage->nCell==0 );
43978
  assert( get2byte(&data[hdr+5])==nUsable );
50008
  assert( get2byteNotZero(&data[hdr+5])==nUsable );
43979
50009
43980
  pCellptr = &data[pPage->cellOffset + nCell*2];
50010
  pCellptr = &data[pPage->cellOffset + nCell*2];
43981
  cellbody = nUsable;
50011
  cellbody = nUsable;
 Lines 44041-44046   static int balance_quick(MemPage *pParen Link Here 
44041
  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
50071
  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
44042
  assert( pPage->nOverflow==1 );
50072
  assert( pPage->nOverflow==1 );
44043
50073
50074
  /* This error condition is now caught prior to reaching this function */
44044
  if( pPage->nCell<=0 ) return SQLITE_CORRUPT_BKPT;
50075
  if( pPage->nCell<=0 ) return SQLITE_CORRUPT_BKPT;
44045
50076
44046
  /* Allocate a new page. This page will become the right-sibling of 
50077
  /* Allocate a new page. This page will become the right-sibling of 
 Lines 44370-44376   static int balance_nonroot( Link Here 
44370
      ** is allocated.  */
50401
      ** is allocated.  */
44371
      if( pBt->secureDelete ){
50402
      if( pBt->secureDelete ){
44372
        int iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
50403
        int iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
44373
        if( (iOff+szNew[i])>pBt->usableSize ){
50404
        if( (iOff+szNew[i])>(int)pBt->usableSize ){
44374
          rc = SQLITE_CORRUPT_BKPT;
50405
          rc = SQLITE_CORRUPT_BKPT;
44375
          memset(apOld, 0, (i+1)*sizeof(MemPage*));
50406
          memset(apOld, 0, (i+1)*sizeof(MemPage*));
44376
          goto balance_cleanup;
50407
          goto balance_cleanup;
 Lines 44449-44455   static int balance_nonroot( Link Here 
44449
      szCell[nCell] = sz;
50480
      szCell[nCell] = sz;
44450
      pTemp = &aSpace1[iSpace1];
50481
      pTemp = &aSpace1[iSpace1];
44451
      iSpace1 += sz;
50482
      iSpace1 += sz;
44452
      assert( sz<=pBt->pageSize/4 );
50483
      assert( sz<=pBt->maxLocal+23 );
44453
      assert( iSpace1<=pBt->pageSize );
50484
      assert( iSpace1<=pBt->pageSize );
44454
      memcpy(pTemp, apDiv[i], sz);
50485
      memcpy(pTemp, apDiv[i], sz);
44455
      apCell[nCell] = pTemp+leafCorrection;
50486
      apCell[nCell] = pTemp+leafCorrection;
 Lines 44695-44701   static int balance_nonroot( Link Here 
44695
        }
50726
        }
44696
      }
50727
      }
44697
      iOvflSpace += sz;
50728
      iOvflSpace += sz;
44698
      assert( sz<=pBt->pageSize/4 );
50729
      assert( sz<=pBt->maxLocal+23 );
44699
      assert( iOvflSpace<=pBt->pageSize );
50730
      assert( iOvflSpace<=pBt->pageSize );
44700
      insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
50731
      insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
44701
      if( rc!=SQLITE_OK ) goto balance_cleanup;
50732
      if( rc!=SQLITE_OK ) goto balance_cleanup;
 Lines 45437-45444   static int btreeCreateTable(Btree *p, in Link Here 
45437
      releasePage(pRoot);
51468
      releasePage(pRoot);
45438
      return rc;
51469
      return rc;
45439
    }
51470
    }
51471
51472
    /* When the new root page was allocated, page 1 was made writable in
51473
    ** order either to increase the database filesize, or to decrement the
51474
    ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
51475
    */
51476
    assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
45440
    rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
51477
    rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
45441
    if( rc ){
51478
    if( NEVER(rc) ){
45442
      releasePage(pRoot);
51479
      releasePage(pRoot);
45443
      return rc;
51480
      return rc;
45444
    }
51481
    }
 Lines 45478-45484   static int clearDatabasePage( Link Here 
45478
  int i;
51515
  int i;
45479
51516
45480
  assert( sqlite3_mutex_held(pBt->mutex) );
51517
  assert( sqlite3_mutex_held(pBt->mutex) );
45481
  if( pgno>pagerPagecount(pBt) ){
51518
  if( pgno>btreePagecount(pBt) ){
45482
    return SQLITE_CORRUPT_BKPT;
51519
    return SQLITE_CORRUPT_BKPT;
45483
  }
51520
  }
45484
51521
 Lines 45933-45939   static void checkList( Link Here 
45933
        checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
51970
        checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
45934
      }
51971
      }
45935
#endif
51972
#endif
45936
      if( n>pCheck->pBt->usableSize/4-2 ){
51973
      if( n>(int)pCheck->pBt->usableSize/4-2 ){
45937
        checkAppendMsg(pCheck, zContext,
51974
        checkAppendMsg(pCheck, zContext,
45938
           "freelist leaf count too big on page %d", iPage);
51975
           "freelist leaf count too big on page %d", iPage);
45939
        N--;
51976
        N--;
 Lines 46144-46150   static int checkTreePage( Link Here 
46144
  if( hit==0 ){
52181
  if( hit==0 ){
46145
    pCheck->mallocFailed = 1;
52182
    pCheck->mallocFailed = 1;
46146
  }else{
52183
  }else{
46147
    u16 contentOffset = get2byte(&data[hdr+5]);
52184
    int contentOffset = get2byteNotZero(&data[hdr+5]);
46148
    assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
52185
    assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
46149
    memset(hit+contentOffset, 0, usableSize-contentOffset);
52186
    memset(hit+contentOffset, 0, usableSize-contentOffset);
46150
    memset(hit, 1, contentOffset);
52187
    memset(hit, 1, contentOffset);
 Lines 46152-46163   static int checkTreePage( Link Here 
46152
    cellStart = hdr + 12 - 4*pPage->leaf;
52189
    cellStart = hdr + 12 - 4*pPage->leaf;
46153
    for(i=0; i<nCell; i++){
52190
    for(i=0; i<nCell; i++){
46154
      int pc = get2byte(&data[cellStart+i*2]);
52191
      int pc = get2byte(&data[cellStart+i*2]);
46155
      u16 size = 1024;
52192
      u32 size = 65536;
46156
      int j;
52193
      int j;
46157
      if( pc<=usableSize-4 ){
52194
      if( pc<=usableSize-4 ){
46158
        size = cellSizePtr(pPage, &data[pc]);
52195
        size = cellSizePtr(pPage, &data[pc]);
46159
      }
52196
      }
46160
      if( (pc+size-1)>=usableSize ){
52197
      if( (int)(pc+size-1)>=usableSize ){
46161
        checkAppendMsg(pCheck, 0, 
52198
        checkAppendMsg(pCheck, 0, 
46162
            "Corruption detected in cell %d on page %d",i,iPage);
52199
            "Corruption detected in cell %d on page %d",i,iPage);
46163
      }else{
52200
      }else{
 Lines 46229-46235   SQLITE_PRIVATE char *sqlite3BtreeIntegri Link Here 
46229
  nRef = sqlite3PagerRefcount(pBt->pPager);
52266
  nRef = sqlite3PagerRefcount(pBt->pPager);
46230
  sCheck.pBt = pBt;
52267
  sCheck.pBt = pBt;
46231
  sCheck.pPager = pBt->pPager;
52268
  sCheck.pPager = pBt->pPager;
46232
  sCheck.nPage = pagerPagecount(sCheck.pBt);
52269
  sCheck.nPage = btreePagecount(sCheck.pBt);
46233
  sCheck.mxErr = mxErr;
52270
  sCheck.mxErr = mxErr;
46234
  sCheck.nErr = 0;
52271
  sCheck.nErr = 0;
46235
  sCheck.mallocFailed = 0;
52272
  sCheck.mallocFailed = 0;
 Lines 46250-46255   SQLITE_PRIVATE char *sqlite3BtreeIntegri Link Here 
46250
    sCheck.anRef[i] = 1;
52287
    sCheck.anRef[i] = 1;
46251
  }
52288
  }
46252
  sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
52289
  sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
52290
  sCheck.errMsg.useMalloc = 2;
46253
52291
46254
  /* Check the integrity of the freelist
52292
  /* Check the integrity of the freelist
46255
  */
52293
  */
 Lines 46348-46353   SQLITE_PRIVATE int sqlite3BtreeIsInTrans Link Here 
46348
  return (p && (p->inTrans==TRANS_WRITE));
52386
  return (p && (p->inTrans==TRANS_WRITE));
46349
}
52387
}
46350
52388
52389
#ifndef SQLITE_OMIT_WAL
52390
/*
52391
** Run a checkpoint on the Btree passed as the first argument.
52392
**
52393
** Return SQLITE_LOCKED if this or any other connection has an open 
52394
** transaction on the shared-cache the argument Btree is connected to.
52395
*/
52396
SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p){
52397
  int rc = SQLITE_OK;
52398
  if( p ){
52399
    BtShared *pBt = p->pBt;
52400
    sqlite3BtreeEnter(p);
52401
    if( pBt->inTransaction!=TRANS_NONE ){
52402
      rc = SQLITE_LOCKED;
52403
    }else{
52404
      rc = sqlite3PagerCheckpoint(pBt->pPager);
52405
    }
52406
    sqlite3BtreeLeave(p);
52407
  }
52408
  return rc;
52409
}
52410
#endif
52411
46351
/*
52412
/*
46352
** Return non-zero if a read (or write) transaction is active.
52413
** Return non-zero if a read (or write) transaction is active.
46353
*/
52414
*/
 Lines 46387-46393   SQLITE_PRIVATE void *sqlite3BtreeSchema( Link Here 
46387
  BtShared *pBt = p->pBt;
52448
  BtShared *pBt = p->pBt;
46388
  sqlite3BtreeEnter(p);
52449
  sqlite3BtreeEnter(p);
46389
  if( !pBt->pSchema && nBytes ){
52450
  if( !pBt->pSchema && nBytes ){
46390
    pBt->pSchema = sqlite3MallocZero(nBytes);
52451
    pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
46391
    pBt->xFreeSchema = xFree;
52452
    pBt->xFreeSchema = xFree;
46392
  }
52453
  }
46393
  sqlite3BtreeLeave(p);
52454
  sqlite3BtreeLeave(p);
 Lines 46498-46503   SQLITE_PRIVATE void sqlite3BtreeCacheOve Link Here 
46498
}
52559
}
46499
#endif
52560
#endif
46500
52561
52562
/*
52563
** Set both the "read version" (single byte at byte offset 18) and 
52564
** "write version" (single byte at byte offset 19) fields in the database
52565
** header to iVersion.
52566
*/
52567
SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
52568
  BtShared *pBt = pBtree->pBt;
52569
  int rc;                         /* Return code */
52570
 
52571
  assert( pBtree->inTrans==TRANS_NONE );
52572
  assert( iVersion==1 || iVersion==2 );
52573
52574
  /* If setting the version fields to 1, do not automatically open the
52575
  ** WAL connection, even if the version fields are currently set to 2.
52576
  */
52577
  pBt->doNotUseWAL = (u8)(iVersion==1);
52578
52579
  rc = sqlite3BtreeBeginTrans(pBtree, 0);
52580
  if( rc==SQLITE_OK ){
52581
    u8 *aData = pBt->pPage1->aData;
52582
    if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
52583
      rc = sqlite3BtreeBeginTrans(pBtree, 2);
52584
      if( rc==SQLITE_OK ){
52585
        rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
52586
        if( rc==SQLITE_OK ){
52587
          aData[18] = (u8)iVersion;
52588
          aData[19] = (u8)iVersion;
52589
        }
52590
      }
52591
    }
52592
  }
52593
52594
  pBt->doNotUseWAL = 0;
52595
  return rc;
52596
}
52597
46501
/************** End of btree.c ***********************************************/
52598
/************** End of btree.c ***********************************************/
46502
/************** Begin file backup.c ******************************************/
52599
/************** Begin file backup.c ******************************************/
46503
/*
52600
/*
 Lines 46717-46723   static int backupOnePage(sqlite3_backup Link Here 
46717
  /* Catch the case where the destination is an in-memory database and the
52814
  /* Catch the case where the destination is an in-memory database and the
46718
  ** page sizes of the source and destination differ. 
52815
  ** page sizes of the source and destination differ. 
46719
  */
52816
  */
46720
  if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(sqlite3BtreePager(p->pDest)) ){
52817
  if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
46721
    rc = SQLITE_READONLY;
52818
    rc = SQLITE_READONLY;
46722
  }
52819
  }
46723
52820
 Lines 46787-46792   static void attachBackupObject(sqlite3_b Link Here 
46787
*/
52884
*/
46788
SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
52885
SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
46789
  int rc;
52886
  int rc;
52887
  int destMode;       /* Destination journal mode */
52888
  int pgszSrc = 0;    /* Source page size */
52889
  int pgszDest = 0;   /* Destination page size */
46790
52890
46791
  sqlite3_mutex_enter(p->pSrcDb->mutex);
52891
  sqlite3_mutex_enter(p->pSrcDb->mutex);
46792
  sqlite3BtreeEnter(p->pSrc);
52892
  sqlite3BtreeEnter(p->pSrc);
 Lines 46827-46839   SQLITE_API int sqlite3_backup_step(sqlit Link Here 
46827
      rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
52927
      rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
46828
      bCloseTrans = 1;
52928
      bCloseTrans = 1;
46829
    }
52929
    }
52930
52931
    /* Do not allow backup if the destination database is in WAL mode
52932
    ** and the page sizes are different between source and destination */
52933
    pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
52934
    pgszDest = sqlite3BtreeGetPageSize(p->pDest);
52935
    destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
52936
    if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
52937
      rc = SQLITE_READONLY;
52938
    }
46830
  
52939
  
46831
    /* Now that there is a read-lock on the source database, query the
52940
    /* Now that there is a read-lock on the source database, query the
46832
    ** source pager for the number of pages in the database.
52941
    ** source pager for the number of pages in the database.
46833
    */
52942
    */
46834
    if( rc==SQLITE_OK ){
52943
    nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
46835
      rc = sqlite3PagerPagecount(pSrcPager, &nSrcPage);
52944
    assert( nSrcPage>=0 );
46836
    }
46837
    for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
52945
    for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
46838
      const Pgno iSrcPg = p->iNext;                 /* Source page number */
52946
      const Pgno iSrcPg = p->iNext;                 /* Source page number */
46839
      if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
52947
      if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
 Lines 46864-46871   SQLITE_API int sqlite3_backup_step(sqlit Link Here 
46864
    if( rc==SQLITE_DONE 
52972
    if( rc==SQLITE_DONE 
46865
     && (rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1))==SQLITE_OK
52973
     && (rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1))==SQLITE_OK
46866
    ){
52974
    ){
46867
      const int nSrcPagesize = sqlite3BtreeGetPageSize(p->pSrc);
46868
      const int nDestPagesize = sqlite3BtreeGetPageSize(p->pDest);
46869
      int nDestTruncate;
52975
      int nDestTruncate;
46870
  
52976
  
46871
      if( p->pDestDb ){
52977
      if( p->pDestDb ){
 Lines 46884-46901   SQLITE_API int sqlite3_backup_step(sqlit Link Here 
46884
      ** journalled by PagerCommitPhaseOne() before they are destroyed
52990
      ** journalled by PagerCommitPhaseOne() before they are destroyed
46885
      ** by the file truncation.
52991
      ** by the file truncation.
46886
      */
52992
      */
46887
      if( nSrcPagesize<nDestPagesize ){
52993
      assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
46888
        int ratio = nDestPagesize/nSrcPagesize;
52994
      assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
52995
      if( pgszSrc<pgszDest ){
52996
        int ratio = pgszDest/pgszSrc;
46889
        nDestTruncate = (nSrcPage+ratio-1)/ratio;
52997
        nDestTruncate = (nSrcPage+ratio-1)/ratio;
46890
        if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
52998
        if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
46891
          nDestTruncate--;
52999
          nDestTruncate--;
46892
        }
53000
        }
46893
      }else{
53001
      }else{
46894
        nDestTruncate = nSrcPage * (nSrcPagesize/nDestPagesize);
53002
        nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
46895
      }
53003
      }
46896
      sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
53004
      sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
46897
53005
46898
      if( nSrcPagesize<nDestPagesize ){
53006
      if( pgszSrc<pgszDest ){
46899
        /* If the source page-size is smaller than the destination page-size,
53007
        /* If the source page-size is smaller than the destination page-size,
46900
        ** two extra things may need to happen:
53008
        ** two extra things may need to happen:
46901
        **
53009
        **
 Lines 46905-46935   SQLITE_API int sqlite3_backup_step(sqlit Link Here 
46905
        **     pending-byte page in the source database may need to be
53013
        **     pending-byte page in the source database may need to be
46906
        **     copied into the destination database.
53014
        **     copied into the destination database.
46907
        */
53015
        */
46908
        const i64 iSize = (i64)nSrcPagesize * (i64)nSrcPage;
53016
        const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
46909
        sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
53017
        sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
46910
53018
46911
        assert( pFile );
53019
        assert( pFile );
46912
        assert( (i64)nDestTruncate*(i64)nDestPagesize >= iSize || (
53020
        assert( (i64)nDestTruncate*(i64)pgszDest >= iSize || (
46913
              nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
53021
              nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
46914
           && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+nDestPagesize
53022
           && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
46915
        ));
53023
        ));
46916
        if( SQLITE_OK==(rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1))
53024
        if( SQLITE_OK==(rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1))
46917
         && SQLITE_OK==(rc = backupTruncateFile(pFile, iSize))
53025
         && SQLITE_OK==(rc = backupTruncateFile(pFile, iSize))
46918
         && SQLITE_OK==(rc = sqlite3PagerSync(pDestPager))
53026
         && SQLITE_OK==(rc = sqlite3PagerSync(pDestPager))
46919
        ){
53027
        ){
46920
          i64 iOff;
53028
          i64 iOff;
46921
          i64 iEnd = MIN(PENDING_BYTE + nDestPagesize, iSize);
53029
          i64 iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
46922
          for(
53030
          for(
46923
            iOff=PENDING_BYTE+nSrcPagesize; 
53031
            iOff=PENDING_BYTE+pgszSrc; 
46924
            rc==SQLITE_OK && iOff<iEnd; 
53032
            rc==SQLITE_OK && iOff<iEnd; 
46925
            iOff+=nSrcPagesize
53033
            iOff+=pgszSrc
46926
          ){
53034
          ){
46927
            PgHdr *pSrcPg = 0;
53035
            PgHdr *pSrcPg = 0;
46928
            const Pgno iSrcPg = (Pgno)((iOff/nSrcPagesize)+1);
53036
            const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
46929
            rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
53037
            rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
46930
            if( rc==SQLITE_OK ){
53038
            if( rc==SQLITE_OK ){
46931
              u8 *zData = sqlite3PagerGetData(pSrcPg);
53039
              u8 *zData = sqlite3PagerGetData(pSrcPg);
46932
              rc = sqlite3OsWrite(pFile, zData, nSrcPagesize, iOff);
53040
              rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
46933
            }
53041
            }
46934
            sqlite3PagerUnref(pSrcPg);
53042
            sqlite3PagerUnref(pSrcPg);
46935
          }
53043
          }
 Lines 46958-46963   SQLITE_API int sqlite3_backup_step(sqlit Link Here 
46958
      assert( rc2==SQLITE_OK );
53066
      assert( rc2==SQLITE_OK );
46959
    }
53067
    }
46960
  
53068
  
53069
    if( rc==SQLITE_IOERR_NOMEM ){
53070
      rc = SQLITE_NOMEM;
53071
    }
46961
    p->rc = rc;
53072
    p->rc = rc;
46962
  }
53073
  }
46963
  if( p->pDestDb ){
53074
  if( p->pDestDb ){
 Lines 48144-48152   SQLITE_PRIVATE int sqlite3ValueFromExpr( Link Here 
48144
    return SQLITE_OK;
54255
    return SQLITE_OK;
48145
  }
54256
  }
48146
  op = pExpr->op;
54257
  op = pExpr->op;
48147
  if( op==TK_REGISTER ){
54258
48148
    op = pExpr->op2;  /* This only happens with SQLITE_ENABLE_STAT2 */
54259
  /* op can only be TK_REGISTER if we have compiled with SQLITE_ENABLE_STAT2.
48149
  }
54260
  ** The ifdef here is to enable us to achieve 100% branch test coverage even
54261
  ** when SQLITE_ENABLE_STAT2 is omitted.
54262
  */
54263
#ifdef SQLITE_ENABLE_STAT2
54264
  if( op==TK_REGISTER ) op = pExpr->op2;
54265
#else
54266
  if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
54267
#endif
48150
54268
48151
  if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
54269
  if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
48152
    pVal = sqlite3ValueNew(db);
54270
    pVal = sqlite3ValueNew(db);
 Lines 48816-48830   static void freeEphemeralFunction(sqlite Link Here 
48816
  }
54934
  }
48817
}
54935
}
48818
54936
54937
static void vdbeFreeOpArray(sqlite3 *, Op *, int);
54938
48819
/*
54939
/*
48820
** Delete a P4 value if necessary.
54940
** Delete a P4 value if necessary.
48821
*/
54941
*/
48822
static void freeP4(sqlite3 *db, int p4type, void *p4){
54942
static void freeP4(sqlite3 *db, int p4type, void *p4){
48823
  if( p4 ){
54943
  if( p4 ){
54944
    assert( db );
48824
    switch( p4type ){
54945
    switch( p4type ){
48825
      case P4_REAL:
54946
      case P4_REAL:
48826
      case P4_INT64:
54947
      case P4_INT64:
48827
      case P4_MPRINTF:
48828
      case P4_DYNAMIC:
54948
      case P4_DYNAMIC:
48829
      case P4_KEYINFO:
54949
      case P4_KEYINFO:
48830
      case P4_INTARRAY:
54950
      case P4_INTARRAY:
 Lines 48832-48841   static void freeP4(sqlite3 *db, int p4ty Link Here 
48832
        sqlite3DbFree(db, p4);
54952
        sqlite3DbFree(db, p4);
48833
        break;
54953
        break;
48834
      }
54954
      }
54955
      case P4_MPRINTF: {
54956
        if( db->pnBytesFreed==0 ) sqlite3_free(p4);
54957
        break;
54958
      }
48835
      case P4_VDBEFUNC: {
54959
      case P4_VDBEFUNC: {
48836
        VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
54960
        VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
48837
        freeEphemeralFunction(db, pVdbeFunc->pFunc);
54961
        freeEphemeralFunction(db, pVdbeFunc->pFunc);
48838
        sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
54962
        if( db->pnBytesFreed==0 ) sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
48839
        sqlite3DbFree(db, pVdbeFunc);
54963
        sqlite3DbFree(db, pVdbeFunc);
48840
        break;
54964
        break;
48841
      }
54965
      }
 Lines 48844-48858   static void freeP4(sqlite3 *db, int p4ty Link Here 
48844
        break;
54968
        break;
48845
      }
54969
      }
48846
      case P4_MEM: {
54970
      case P4_MEM: {
48847
        sqlite3ValueFree((sqlite3_value*)p4);
54971
        if( db->pnBytesFreed==0 ){
54972
          sqlite3ValueFree((sqlite3_value*)p4);
54973
        }else{
54974
          Mem *p = (Mem*)p4;
54975
          sqlite3DbFree(db, p->zMalloc);
54976
          sqlite3DbFree(db, p);
54977
        }
48848
        break;
54978
        break;
48849
      }
54979
      }
48850
      case P4_VTAB : {
54980
      case P4_VTAB : {
48851
        sqlite3VtabUnlock((VTable *)p4);
54981
        if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
48852
        break;
48853
      }
48854
      case P4_SUBPROGRAM : {
48855
        sqlite3VdbeProgramDelete(db, (SubProgram *)p4, 1);
48856
        break;
54982
        break;
48857
      }
54983
      }
48858
    }
54984
    }
 Lines 48878-48911   static void vdbeFreeOpArray(sqlite3 *db, Link Here 
48878
}
55004
}
48879
55005
48880
/*
55006
/*
48881
** Decrement the ref-count on the SubProgram structure passed as the
55007
** Link the SubProgram object passed as the second argument into the linked
48882
** second argument. If the ref-count reaches zero, free the structure.
55008
** list at Vdbe.pSubProgram. This list is used to delete all sub-program
48883
**
55009
** objects when the VM is no longer required.
48884
** The array of VDBE opcodes stored as SubProgram.aOp is freed if
55010
*/
48885
** either the ref-count reaches zero or parameter freeop is non-zero.
55011
SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
48886
**
55012
  p->pNext = pVdbe->pProgram;
48887
** Since the array of opcodes pointed to by SubProgram.aOp may directly
55013
  pVdbe->pProgram = p;
48888
** or indirectly contain a reference to the SubProgram structure itself.
55014
}
48889
** By passing a non-zero freeop parameter, the caller may ensure that all
48890
** SubProgram structures and their aOp arrays are freed, even when there
48891
** are such circular references.
48892
*/
48893
SQLITE_PRIVATE void sqlite3VdbeProgramDelete(sqlite3 *db, SubProgram *p, int freeop){
48894
  if( p ){
48895
    assert( p->nRef>0 );
48896
    if( freeop || p->nRef==1 ){
48897
      Op *aOp = p->aOp;
48898
      p->aOp = 0;
48899
      vdbeFreeOpArray(db, aOp, p->nOp);
48900
      p->nOp = 0;
48901
    }
48902
    p->nRef--;
48903
    if( p->nRef==0 ){
48904
      sqlite3DbFree(db, p);
48905
    }
48906
  }
48907
}
48908
48909
55015
48910
/*
55016
/*
48911
** Change N opcodes starting at addr to No-ops.
55017
** Change N opcodes starting at addr to No-ops.
 Lines 48982-48992   SQLITE_PRIVATE void sqlite3VdbeChangeP4( Link Here 
48982
55088
48983
    nField = ((KeyInfo*)zP4)->nField;
55089
    nField = ((KeyInfo*)zP4)->nField;
48984
    nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
55090
    nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
48985
    pKeyInfo = sqlite3Malloc( nByte );
55091
    pKeyInfo = sqlite3DbMallocRaw(0, nByte);
48986
    pOp->p4.pKeyInfo = pKeyInfo;
55092
    pOp->p4.pKeyInfo = pKeyInfo;
48987
    if( pKeyInfo ){
55093
    if( pKeyInfo ){
48988
      u8 *aSortOrder;
55094
      u8 *aSortOrder;
48989
      memcpy(pKeyInfo, zP4, nByte);
55095
      memcpy((char*)pKeyInfo, zP4, nByte - nField);
48990
      aSortOrder = pKeyInfo->aSortOrder;
55096
      aSortOrder = pKeyInfo->aSortOrder;
48991
      if( aSortOrder ){
55097
      if( aSortOrder ){
48992
        pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
55098
        pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
 Lines 49057-49065   SQLITE_PRIVATE void sqlite3VdbeNoopComme Link Here 
49057
**
55163
**
49058
** If a memory allocation error has occurred prior to the calling of this
55164
** If a memory allocation error has occurred prior to the calling of this
49059
** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
55165
** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
49060
** is readable and writable, but it has no effect.  The return of a dummy
55166
** is readable but not writable, though it is cast to a writable value.
49061
** opcode allows the call to continue functioning after a OOM fault without
55167
** The return of a dummy opcode allows the call to continue functioning
49062
** having to check to see if the return from this routine is a valid pointer.
55168
** after a OOM fault without having to check to see if the return from 
55169
** this routine is a valid pointer.  But because the dummy.opcode is 0,
55170
** dummy will never be written to.  This is verified by code inspection and
55171
** by running with Valgrind.
49063
**
55172
**
49064
** About the #ifdef SQLITE_OMIT_TRACE:  Normally, this routine is never called
55173
** About the #ifdef SQLITE_OMIT_TRACE:  Normally, this routine is never called
49065
** unless p->nOp>0.  This is because in the absense of SQLITE_OMIT_TRACE,
55174
** unless p->nOp>0.  This is because in the absense of SQLITE_OMIT_TRACE,
 Lines 49070-49086   SQLITE_PRIVATE void sqlite3VdbeNoopComme Link Here 
49070
** check the value of p->nOp-1 before continuing.
55179
** check the value of p->nOp-1 before continuing.
49071
*/
55180
*/
49072
SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
55181
SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
49073
  static VdbeOp dummy;
55182
  /* C89 specifies that the constant "dummy" will be initialized to all
55183
  ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
55184
  static const VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
49074
  assert( p->magic==VDBE_MAGIC_INIT );
55185
  assert( p->magic==VDBE_MAGIC_INIT );
49075
  if( addr<0 ){
55186
  if( addr<0 ){
49076
#ifdef SQLITE_OMIT_TRACE
55187
#ifdef SQLITE_OMIT_TRACE
49077
    if( p->nOp==0 ) return &dummy;
55188
    if( p->nOp==0 ) return (VdbeOp*)&dummy;
49078
#endif
55189
#endif
49079
    addr = p->nOp - 1;
55190
    addr = p->nOp - 1;
49080
  }
55191
  }
49081
  assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
55192
  assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
49082
  if( p->db->mallocFailed ){
55193
  if( p->db->mallocFailed ){
49083
    return &dummy;
55194
    return (VdbeOp*)&dummy;
49084
  }else{
55195
  }else{
49085
    return &p->aOp[addr];
55196
    return &p->aOp[addr];
49086
  }
55197
  }
 Lines 49193-49198   static char *displayP4(Op *pOp, char *zT Link Here 
49193
55304
49194
/*
55305
/*
49195
** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
55306
** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
55307
**
55308
** The prepared statement has to know in advance which Btree objects
55309
** will be used so that it can acquire mutexes on them all in sorted
55310
** order (via sqlite3VdbeMutexArrayEnter().  Mutexes are acquired
55311
** in order (and released in reverse order) to avoid deadlocks.
49196
*/
55312
*/
49197
SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
55313
SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
49198
  int mask;
55314
  int mask;
 Lines 49236-49241   static void releaseMemArray(Mem *p, int Link Here 
49236
    Mem *pEnd;
55352
    Mem *pEnd;
49237
    sqlite3 *db = p->db;
55353
    sqlite3 *db = p->db;
49238
    u8 malloc_failed = db->mallocFailed;
55354
    u8 malloc_failed = db->mallocFailed;
55355
    if( db->pnBytesFreed ){
55356
      for(pEnd=&p[N]; p<pEnd; p++){
55357
        sqlite3DbFree(db, p->zMalloc);
55358
      }
55359
      return;
55360
    }
49239
    for(pEnd=&p[N]; p<pEnd; p++){
55361
    for(pEnd=&p[N]; p<pEnd; p++){
49240
      assert( (&p[1])==pEnd || p[0].db==p[1].db );
55362
      assert( (&p[1])==pEnd || p[0].db==p[1].db );
49241
55363
 Lines 49692-49697   SQLITE_PRIVATE void sqlite3VdbeMakeReady Link Here 
49692
  p->cacheCtr = 1;
55814
  p->cacheCtr = 1;
49693
  p->minWriteFileFormat = 255;
55815
  p->minWriteFileFormat = 255;
49694
  p->iStatement = 0;
55816
  p->iStatement = 0;
55817
  p->nFkConstraint = 0;
49695
#ifdef VDBE_PROFILE
55818
#ifdef VDBE_PROFILE
49696
  {
55819
  {
49697
    int i;
55820
    int i;
 Lines 49884-49892   static int vdbeCommit(sqlite3 *db, Vdbe Link Here 
49884
  ** to the transaction.
56007
  ** to the transaction.
49885
  */
56008
  */
49886
  rc = sqlite3VtabSync(db, &p->zErrMsg);
56009
  rc = sqlite3VtabSync(db, &p->zErrMsg);
49887
  if( rc!=SQLITE_OK ){
49888
    return rc;
49889
  }
49890
56010
49891
  /* This loop determines (a) if the commit hook should be invoked and
56011
  /* This loop determines (a) if the commit hook should be invoked and
49892
  ** (b) how many database files have open write transactions, not 
56012
  ** (b) how many database files have open write transactions, not 
 Lines 49894-49905   static int vdbeCommit(sqlite3 *db, Vdbe Link Here 
49894
  ** one database file has an open write transaction, a master journal
56014
  ** one database file has an open write transaction, a master journal
49895
  ** file is required for an atomic commit.
56015
  ** file is required for an atomic commit.
49896
  */ 
56016
  */ 
49897
  for(i=0; i<db->nDb; i++){ 
56017
  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
49898
    Btree *pBt = db->aDb[i].pBt;
56018
    Btree *pBt = db->aDb[i].pBt;
49899
    if( sqlite3BtreeIsInTrans(pBt) ){
56019
    if( sqlite3BtreeIsInTrans(pBt) ){
49900
      needXcommit = 1;
56020
      needXcommit = 1;
49901
      if( i!=1 ) nTrans++;
56021
      if( i!=1 ) nTrans++;
49902
    }
56022
      rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
56023
    }
56024
  }
56025
  if( rc!=SQLITE_OK ){
56026
    return rc;
49903
  }
56027
  }
49904
56028
49905
  /* If there are any write-transactions at all, invoke the commit hook */
56029
  /* If there are any write-transactions at all, invoke the commit hook */
 Lines 50039-50044   static int vdbeCommit(sqlite3 *db, Vdbe Link Here 
50039
      }
56163
      }
50040
    }
56164
    }
50041
    sqlite3OsCloseFree(pMaster);
56165
    sqlite3OsCloseFree(pMaster);
56166
    assert( rc!=SQLITE_BUSY );
50042
    if( rc!=SQLITE_OK ){
56167
    if( rc!=SQLITE_OK ){
50043
      sqlite3DbFree(db, zMaster);
56168
      sqlite3DbFree(db, zMaster);
50044
      return rc;
56169
      return rc;
 Lines 50297-50304   SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe Link Here 
50297
    isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
56422
    isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
50298
                     || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
56423
                     || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
50299
    if( isSpecialError ){
56424
    if( isSpecialError ){
50300
      /* If the query was read-only, we need do no rollback at all. Otherwise,
56425
      /* If the query was read-only and the error code is SQLITE_INTERRUPT, 
50301
      ** proceed with the special handling.
56426
      ** no rollback is necessary. Otherwise, at least a savepoint 
56427
      ** transaction must be rolled back to restore the database to a 
56428
      ** consistent state.
56429
      **
56430
      ** Even if the statement is read-only, it is important to perform
56431
      ** a statement or transaction rollback operation. If the error 
56432
      ** occured while writing to the journal, sub-journal or database
56433
      ** file as part of an effort to free up cache space (see function
56434
      ** pagerStress() in pager.c), the rollback is required to restore 
56435
      ** the pager to a consistent state.
50302
      */
56436
      */
50303
      if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
56437
      if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
50304
        if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
56438
        if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
 Lines 50380-50389   SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe Link Here 
50380
    */
56514
    */
50381
    if( eStatementOp ){
56515
    if( eStatementOp ){
50382
      rc = sqlite3VdbeCloseStatement(p, eStatementOp);
56516
      rc = sqlite3VdbeCloseStatement(p, eStatementOp);
50383
      if( rc && (NEVER(p->rc==SQLITE_OK) || p->rc==SQLITE_CONSTRAINT) ){
56517
      if( rc ){
50384
        p->rc = rc;
56518
        assert( eStatementOp==SAVEPOINT_ROLLBACK );
50385
        sqlite3DbFree(db, p->zErrMsg);
56519
        if( NEVER(p->rc==SQLITE_OK) || p->rc==SQLITE_CONSTRAINT ){
50386
        p->zErrMsg = 0;
56520
          p->rc = rc;
56521
          sqlite3DbFree(db, p->zErrMsg);
56522
          p->zErrMsg = 0;
56523
        }
56524
        invalidateCursorsOnModifiedBtrees(db);
56525
        sqlite3RollbackAll(db);
56526
        sqlite3CloseSavepoints(db);
56527
        db->autoCommit = 1;
50387
      }
56528
      }
50388
    }
56529
    }
50389
  
56530
  
 Lines 50561-50566   SQLITE_PRIVATE void sqlite3VdbeDeleteAux Link Here 
50561
}
56702
}
50562
56703
50563
/*
56704
/*
56705
** Free all memory associated with the Vdbe passed as the second argument.
56706
** The difference between this function and sqlite3VdbeDelete() is that
56707
** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
56708
** the database connection.
56709
*/
56710
SQLITE_PRIVATE void sqlite3VdbeDeleteObject(sqlite3 *db, Vdbe *p){
56711
  SubProgram *pSub, *pNext;
56712
  assert( p->db==0 || p->db==db );
56713
  releaseMemArray(p->aVar, p->nVar);
56714
  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
56715
  for(pSub=p->pProgram; pSub; pSub=pNext){
56716
    pNext = pSub->pNext;
56717
    vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
56718
    sqlite3DbFree(db, pSub);
56719
  }
56720
  vdbeFreeOpArray(db, p->aOp, p->nOp);
56721
  sqlite3DbFree(db, p->aLabel);
56722
  sqlite3DbFree(db, p->aColName);
56723
  sqlite3DbFree(db, p->zSql);
56724
  sqlite3DbFree(db, p->pFree);
56725
  sqlite3DbFree(db, p);
56726
}
56727
56728
/*
50564
** Delete an entire VDBE.
56729
** Delete an entire VDBE.
50565
*/
56730
*/
50566
SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
56731
SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
 Lines 50577-50592   SQLITE_PRIVATE void sqlite3VdbeDelete(Vd Link Here 
50577
  if( p->pNext ){
56742
  if( p->pNext ){
50578
    p->pNext->pPrev = p->pPrev;
56743
    p->pNext->pPrev = p->pPrev;
50579
  }
56744
  }
50580
  releaseMemArray(p->aVar, p->nVar);
50581
  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
50582
  vdbeFreeOpArray(db, p->aOp, p->nOp);
50583
  sqlite3DbFree(db, p->aLabel);
50584
  sqlite3DbFree(db, p->aColName);
50585
  sqlite3DbFree(db, p->zSql);
50586
  p->magic = VDBE_MAGIC_DEAD;
56745
  p->magic = VDBE_MAGIC_DEAD;
50587
  sqlite3DbFree(db, p->pFree);
50588
  p->db = 0;
56746
  p->db = 0;
50589
  sqlite3DbFree(db, p);
56747
  sqlite3VdbeDeleteObject(db, p);
50590
}
56748
}
50591
56749
50592
/*
56750
/*
 Lines 50612-50622   SQLITE_PRIVATE int sqlite3VdbeCursorMove Link Here 
50612
    rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
56770
    rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
50613
    if( rc ) return rc;
56771
    if( rc ) return rc;
50614
    p->lastRowid = p->movetoTarget;
56772
    p->lastRowid = p->movetoTarget;
50615
    p->rowidIsValid = ALWAYS(res==0) ?1:0;
56773
    if( res!=0 ) return SQLITE_CORRUPT_BKPT;
50616
    if( NEVER(res<0) ){
56774
    p->rowidIsValid = 1;
50617
      rc = sqlite3BtreeNext(p->pCursor, &res);
50618
      if( rc ) return rc;
50619
    }
50620
#ifdef SQLITE_TEST
56775
#ifdef SQLITE_TEST
50621
    sqlite3_search_count++;
56776
    sqlite3_search_count++;
50622
#endif
56777
#endif
 Lines 51669-51674   SQLITE_API void sqlite3_result_error_nom Link Here 
51669
}
57824
}
51670
57825
51671
/*
57826
/*
57827
** This function is called after a transaction has been committed. It 
57828
** invokes callbacks registered with sqlite3_wal_hook() as required.
57829
*/
57830
static int doWalCallbacks(sqlite3 *db){
57831
  int rc = SQLITE_OK;
57832
#ifndef SQLITE_OMIT_WAL
57833
  int i;
57834
  for(i=0; i<db->nDb; i++){
57835
    Btree *pBt = db->aDb[i].pBt;
57836
    if( pBt ){
57837
      int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
57838
      if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
57839
        rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
57840
      }
57841
    }
57842
  }
57843
#endif
57844
  return rc;
57845
}
57846
57847
/*
51672
** Execute the statement pStmt, either until a row of data is ready, the
57848
** Execute the statement pStmt, either until a row of data is ready, the
51673
** statement is completely executed or an error occurs.
57849
** statement is completely executed or an error occurs.
51674
**
57850
**
 Lines 51683-51691   static int sqlite3Step(Vdbe *p){ Link Here 
51683
57859
51684
  assert(p);
57860
  assert(p);
51685
  if( p->magic!=VDBE_MAGIC_RUN ){
57861
  if( p->magic!=VDBE_MAGIC_RUN ){
51686
    sqlite3_log(SQLITE_MISUSE, 
57862
    /* We used to require that sqlite3_reset() be called before retrying
51687
          "attempt to step a halted statement: [%s]", p->zSql);
57863
    ** sqlite3_step() after any error.  But after 3.6.23, we changed this
51688
    return SQLITE_MISUSE_BKPT;
57864
    ** so that sqlite3_reset() would be called automatically instead of
57865
    ** throwing the error.
57866
    */
57867
    sqlite3_reset((sqlite3_stmt*)p);
51689
  }
57868
  }
51690
57869
51691
  /* Check that malloc() has not failed. If it has, return early. */
57870
  /* Check that malloc() has not failed. If it has, return early. */
 Lines 51713-51721   static int sqlite3Step(Vdbe *p){ Link Here 
51713
57892
51714
#ifndef SQLITE_OMIT_TRACE
57893
#ifndef SQLITE_OMIT_TRACE
51715
    if( db->xProfile && !db->init.busy ){
57894
    if( db->xProfile && !db->init.busy ){
51716
      double rNow;
57895
      sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
51717
      sqlite3OsCurrentTime(db->pVfs, &rNow);
51718
      p->startTime = (u64)((rNow - (int)rNow)*3600.0*24.0*1000000000.0);
51719
    }
57896
    }
51720
#endif
57897
#endif
51721
57898
 Lines 51736-51750   static int sqlite3Step(Vdbe *p){ Link Here 
51736
  /* Invoke the profile callback if there is one
57913
  /* Invoke the profile callback if there is one
51737
  */
57914
  */
51738
  if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
57915
  if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
51739
    double rNow;
57916
    sqlite3_int64 iNow;
51740
    u64 elapseTime;
57917
    sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
51741
57918
    db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
51742
    sqlite3OsCurrentTime(db->pVfs, &rNow);
57919
  }
51743
    elapseTime = (u64)((rNow - (int)rNow)*3600.0*24.0*1000000000.0);
57920
#endif
51744
    elapseTime -= p->startTime;
57921
51745
    db->xProfile(db->pProfileArg, p->zSql, elapseTime);
57922
  if( rc==SQLITE_DONE ){
51746
  }
57923
    assert( p->rc==SQLITE_OK );
51747
#endif
57924
    p->rc = doWalCallbacks(db);
57925
    if( p->rc!=SQLITE_OK ){
57926
      rc = SQLITE_ERROR;
57927
    }
57928
  }
51748
57929
51749
  db->errCode = rc;
57930
  db->errCode = rc;
51750
  if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
57931
  if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
 Lines 53329-53350   SQLITE_PRIVATE sqlite_uint64 sqlite3Hw Link Here 
53329
#define CHECK_FOR_INTERRUPT \
59510
#define CHECK_FOR_INTERRUPT \
53330
   if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
59511
   if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
53331
59512
53332
#ifdef SQLITE_DEBUG
53333
static int fileExists(sqlite3 *db, const char *zFile){
53334
  int res = 0;
53335
  int rc = SQLITE_OK;
53336
#ifdef SQLITE_TEST
53337
  /* If we are currently testing IO errors, then do not call OsAccess() to
53338
  ** test for the presence of zFile. This is because any IO error that
53339
  ** occurs here will not be reported, causing the test to fail.
53340
  */
53341
  extern int sqlite3_io_error_pending;
53342
  if( sqlite3_io_error_pending<=0 )
53343
#endif
53344
    rc = sqlite3OsAccess(db->pVfs, zFile, SQLITE_ACCESS_EXISTS, &res);
53345
  return (res && rc==SQLITE_OK);
53346
}
53347
#endif
53348
59513
53349
#ifndef NDEBUG
59514
#ifndef NDEBUG
53350
/*
59515
/*
 Lines 53367-53372   static int checkSavepointCount(sqlite3 * Link Here 
53367
#endif
59532
#endif
53368
59533
53369
/*
59534
/*
59535
** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
59536
** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
59537
** in memory obtained from sqlite3DbMalloc).
59538
*/
59539
static void importVtabErrMsg(Vdbe *p, sqlite3_vtab *pVtab){
59540
  sqlite3 *db = p->db;
59541
  sqlite3DbFree(db, p->zErrMsg);
59542
  p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
59543
  sqlite3_free(pVtab->zErrMsg);
59544
  pVtab->zErrMsg = 0;
59545
}
59546
59547
59548
/*
53370
** Execute as much of a VDBE program as we can then return.
59549
** Execute as much of a VDBE program as we can then return.
53371
**
59550
**
53372
** sqlite3VdbeMakeReady() must be called before this routine in order to
59551
** sqlite3VdbeMakeReady() must be called before this routine in order to
 Lines 53435-53443   SQLITE_PRIVATE int sqlite3VdbeExec( Link Here 
53435
      int pcDest;
59614
      int pcDest;
53436
    } aa;
59615
    } aa;
53437
    struct OP_Variable_stack_vars {
59616
    struct OP_Variable_stack_vars {
53438
      int p1;          /* Variable to copy from */
53439
      int p2;          /* Register to copy to */
53440
      int n;           /* Number of values left to copy */
53441
      Mem *pVar;       /* Value being transferred */
59617
      Mem *pVar;       /* Value being transferred */
53442
    } ab;
59618
    } ab;
53443
    struct OP_Move_stack_vars {
59619
    struct OP_Move_stack_vars {
 Lines 53762-53779   SQLITE_PRIVATE int sqlite3VdbeExec( Link Here 
53762
    struct OP_AggFinal_stack_vars {
59938
    struct OP_AggFinal_stack_vars {
53763
      Mem *pMem;
59939
      Mem *pMem;
53764
    } cc;
59940
    } cc;
59941
    struct OP_JournalMode_stack_vars {
59942
      Btree *pBt;                     /* Btree to change journal mode of */
59943
      Pager *pPager;                  /* Pager associated with pBt */
59944
      int eNew;                       /* New journal mode */
59945
      int eOld;                       /* The old journal mode */
59946
      const char *zFilename;          /* Name of database file for pPager */
59947
    } cd;
53765
    struct OP_IncrVacuum_stack_vars {
59948
    struct OP_IncrVacuum_stack_vars {
53766
      Btree *pBt;
59949
      Btree *pBt;
53767
    } cd;
59950
    } ce;
53768
    struct OP_VBegin_stack_vars {
59951
    struct OP_VBegin_stack_vars {
53769
      VTable *pVTab;
59952
      VTable *pVTab;
53770
    } ce;
59953
    } cf;
53771
    struct OP_VOpen_stack_vars {
59954
    struct OP_VOpen_stack_vars {
53772
      VdbeCursor *pCur;
59955
      VdbeCursor *pCur;
53773
      sqlite3_vtab_cursor *pVtabCursor;
59956
      sqlite3_vtab_cursor *pVtabCursor;
53774
      sqlite3_vtab *pVtab;
59957
      sqlite3_vtab *pVtab;
53775
      sqlite3_module *pModule;
59958
      sqlite3_module *pModule;
53776
    } cf;
59959
    } cg;
53777
    struct OP_VFilter_stack_vars {
59960
    struct OP_VFilter_stack_vars {
53778
      int nArg;
59961
      int nArg;
53779
      int iQuery;
59962
      int iQuery;
 Lines 53786-53808   SQLITE_PRIVATE int sqlite3VdbeExec( Link Here 
53786
      int res;
59969
      int res;
53787
      int i;
59970
      int i;
53788
      Mem **apArg;
59971
      Mem **apArg;
53789
    } cg;
59972
    } ch;
53790
    struct OP_VColumn_stack_vars {
59973
    struct OP_VColumn_stack_vars {
53791
      sqlite3_vtab *pVtab;
59974
      sqlite3_vtab *pVtab;
53792
      const sqlite3_module *pModule;
59975
      const sqlite3_module *pModule;
53793
      Mem *pDest;
59976
      Mem *pDest;
53794
      sqlite3_context sContext;
59977
      sqlite3_context sContext;
53795
    } ch;
59978
    } ci;
53796
    struct OP_VNext_stack_vars {
59979
    struct OP_VNext_stack_vars {
53797
      sqlite3_vtab *pVtab;
59980
      sqlite3_vtab *pVtab;
53798
      const sqlite3_module *pModule;
59981
      const sqlite3_module *pModule;
53799
      int res;
59982
      int res;
53800
      VdbeCursor *pCur;
59983
      VdbeCursor *pCur;
53801
    } ci;
59984
    } cj;
53802
    struct OP_VRename_stack_vars {
59985
    struct OP_VRename_stack_vars {
53803
      sqlite3_vtab *pVtab;
59986
      sqlite3_vtab *pVtab;
53804
      Mem *pName;
59987
      Mem *pName;
53805
    } cj;
59988
    } ck;
53806
    struct OP_VUpdate_stack_vars {
59989
    struct OP_VUpdate_stack_vars {
53807
      sqlite3_vtab *pVtab;
59990
      sqlite3_vtab *pVtab;
53808
      sqlite3_module *pModule;
59991
      sqlite3_module *pModule;
 Lines 53811-53821   SQLITE_PRIVATE int sqlite3VdbeExec( Link Here 
53811
      sqlite_int64 rowid;
59994
      sqlite_int64 rowid;
53812
      Mem **apArg;
59995
      Mem **apArg;
53813
      Mem *pX;
59996
      Mem *pX;
53814
    } ck;
53815
    struct OP_Pagecount_stack_vars {
53816
      int p1;
53817
      int nPage;
53818
      Pager *pPager;
53819
    } cl;
59997
    } cl;
53820
    struct OP_Trace_stack_vars {
59998
    struct OP_Trace_stack_vars {
53821
      char *zTrace;
59999
      char *zTrace;
 Lines 53843-53851   SQLITE_PRIVATE int sqlite3VdbeExec( Link Here 
53843
#endif
60021
#endif
53844
#ifdef SQLITE_DEBUG
60022
#ifdef SQLITE_DEBUG
53845
  sqlite3BeginBenignMalloc();
60023
  sqlite3BeginBenignMalloc();
53846
  if( p->pc==0 
60024
  if( p->pc==0  && (p->db->flags & SQLITE_VdbeListing)!=0 ){
53847
   && ((p->db->flags & SQLITE_VdbeListing) || fileExists(db, "vdbe_explain"))
53848
  ){
53849
    int i;
60025
    int i;
53850
    printf("VDBE Program Listing:\n");
60026
    printf("VDBE Program Listing:\n");
53851
    sqlite3VdbePrintSql(p);
60027
    sqlite3VdbePrintSql(p);
 Lines 53853-53861   SQLITE_PRIVATE int sqlite3VdbeExec( Link Here 
53853
      sqlite3VdbePrintOp(stdout, i, &aOp[i]);
60029
      sqlite3VdbePrintOp(stdout, i, &aOp[i]);
53854
    }
60030
    }
53855
  }
60031
  }
53856
  if( fileExists(db, "vdbe_trace") ){
53857
    p->trace = stdout;
53858
  }
53859
  sqlite3EndBenignMalloc();
60032
  sqlite3EndBenignMalloc();
53860
#endif
60033
#endif
53861
  for(pc=p->pc; rc==SQLITE_OK; pc++){
60034
  for(pc=p->pc; rc==SQLITE_OK; pc++){
 Lines 53877-53889   SQLITE_PRIVATE int sqlite3VdbeExec( Link Here 
53877
      }
60050
      }
53878
      sqlite3VdbePrintOp(p->trace, pc, pOp);
60051
      sqlite3VdbePrintOp(p->trace, pc, pOp);
53879
    }
60052
    }
53880
    if( p->trace==0 && pc==0 ){
53881
      sqlite3BeginBenignMalloc();
53882
      if( fileExists(db, "vdbe_sqltrace") ){
53883
        sqlite3VdbePrintSql(p);
53884
      }
53885
      sqlite3EndBenignMalloc();
53886
    }
53887
#endif
60053
#endif
53888
      
60054
      
53889
60055
 Lines 54240-54279   case OP_Blob: { /* out2-p Link Here 
54240
  break;
60406
  break;
54241
}
60407
}
54242
60408
54243
/* Opcode: Variable P1 P2 P3 P4 *
60409
/* Opcode: Variable P1 P2 * P4 *
54244
**
60410
**
54245
** Transfer the values of bound parameters P1..P1+P3-1 into registers
60411
** Transfer the values of bound parameter P1 into register P2
54246
** P2..P2+P3-1.
54247
**
60412
**
54248
** If the parameter is named, then its name appears in P4 and P3==1.
60413
** If the parameter is named, then its name appears in P4 and P3==1.
54249
** The P4 value is used by sqlite3_bind_parameter_name().
60414
** The P4 value is used by sqlite3_bind_parameter_name().
54250
*/
60415
*/
54251
case OP_Variable: {
60416
case OP_Variable: {            /* out2-prerelease */
54252
#if 0  /* local variables moved into u.ab */
60417
#if 0  /* local variables moved into u.ab */
54253
  int p1;          /* Variable to copy from */
54254
  int p2;          /* Register to copy to */
54255
  int n;           /* Number of values left to copy */
54256
  Mem *pVar;       /* Value being transferred */
60418
  Mem *pVar;       /* Value being transferred */
54257
#endif /* local variables moved into u.ab */
60419
#endif /* local variables moved into u.ab */
54258
60420
54259
  u.ab.p1 = pOp->p1 - 1;
60421
  assert( pOp->p1>0 && pOp->p1<=p->nVar );
54260
  u.ab.p2 = pOp->p2;
60422
  u.ab.pVar = &p->aVar[pOp->p1 - 1];
54261
  u.ab.n = pOp->p3;
60423
  if( sqlite3VdbeMemTooBig(u.ab.pVar) ){
54262
  assert( u.ab.p1>=0 && u.ab.p1+u.ab.n<=p->nVar );
60424
    goto too_big;
54263
  assert( u.ab.p2>=1 && u.ab.p2+u.ab.n-1<=p->nMem );
60425
  }
54264
  assert( pOp->p4.z==0 || pOp->p3==1 || pOp->p3==0 );
60426
  sqlite3VdbeMemShallowCopy(pOut, u.ab.pVar, MEM_Static);
54265
60427
  UPDATE_MAX_BLOBSIZE(pOut);
54266
  while( u.ab.n-- > 0 ){
54267
    u.ab.pVar = &p->aVar[u.ab.p1++];
54268
    if( sqlite3VdbeMemTooBig(u.ab.pVar) ){
54269
      goto too_big;
54270
    }
54271
    pOut = &aMem[u.ab.p2++];
54272
    sqlite3VdbeMemReleaseExternal(pOut);
54273
    pOut->flags = MEM_Null;
54274
    sqlite3VdbeMemShallowCopy(pOut, u.ab.pVar, MEM_Static);
54275
    UPDATE_MAX_BLOBSIZE(pOut);
54276
  }
54277
  break;
60428
  break;
54278
}
60429
}
54279
60430
 Lines 54646-54652   case OP_Function: { Link Here 
54646
  for(u.ag.i=0; u.ag.i<u.ag.n; u.ag.i++, u.ag.pArg++){
60797
  for(u.ag.i=0; u.ag.i<u.ag.n; u.ag.i++, u.ag.pArg++){
54647
    u.ag.apVal[u.ag.i] = u.ag.pArg;
60798
    u.ag.apVal[u.ag.i] = u.ag.pArg;
54648
    sqlite3VdbeMemStoreType(u.ag.pArg);
60799
    sqlite3VdbeMemStoreType(u.ag.pArg);
54649
    REGISTER_TRACE(pOp->p2, u.ag.pArg);
60800
    REGISTER_TRACE(pOp->p2+u.ag.i, u.ag.pArg);
54650
  }
60801
  }
54651
60802
54652
  assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
60803
  assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
 Lines 56363-56372   case OP_OpenWrite: { Link Here 
56363
**
62514
**
56364
** Open a new cursor P1 to a transient table.
62515
** Open a new cursor P1 to a transient table.
56365
** The cursor is always opened read/write even if 
62516
** The cursor is always opened read/write even if 
56366
** the main database is read-only.  The transient or virtual
62517
** the main database is read-only.  The ephemeral
56367
** table is deleted automatically when the cursor is closed.
62518
** table is deleted automatically when the cursor is closed.
56368
**
62519
**
56369
** P2 is the number of columns in the virtual table.
62520
** P2 is the number of columns in the ephemeral table.
56370
** The cursor points to a BTree table if P4==0 and to a BTree index
62521
** The cursor points to a BTree table if P4==0 and to a BTree index
56371
** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
62522
** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
56372
** that defines the format of keys in the index.
62523
** that defines the format of keys in the index.
 Lines 56377-56382   case OP_OpenWrite: { Link Here 
56377
** this opcode.  Then this opcode was call OpenVirtual.  But
62528
** this opcode.  Then this opcode was call OpenVirtual.  But
56378
** that created confusion with the whole virtual-table idea.
62529
** that created confusion with the whole virtual-table idea.
56379
*/
62530
*/
62531
/* Opcode: OpenAutoindex P1 P2 * P4 *
62532
**
62533
** This opcode works the same as OP_OpenEphemeral.  It has a
62534
** different name to distinguish its use.  Tables created using
62535
** by this opcode will be used for automatically created transient
62536
** indices in joins.
62537
*/
62538
case OP_OpenAutoindex: 
56380
case OP_OpenEphemeral: {
62539
case OP_OpenEphemeral: {
56381
#if 0  /* local variables moved into u.ax */
62540
#if 0  /* local variables moved into u.ax */
56382
  VdbeCursor *pCx;
62541
  VdbeCursor *pCx;
 Lines 57384-57392   case OP_Rowid: { /* out2 Link Here 
57384
    u.bi.pModule = u.bi.pVtab->pModule;
63543
    u.bi.pModule = u.bi.pVtab->pModule;
57385
    assert( u.bi.pModule->xRowid );
63544
    assert( u.bi.pModule->xRowid );
57386
    rc = u.bi.pModule->xRowid(u.bi.pC->pVtabCursor, &u.bi.v);
63545
    rc = u.bi.pModule->xRowid(u.bi.pC->pVtabCursor, &u.bi.v);
57387
    sqlite3DbFree(db, p->zErrMsg);
63546
    importVtabErrMsg(p, u.bi.pVtab);
57388
    p->zErrMsg = u.bi.pVtab->zErrMsg;
57389
    u.bi.pVtab->zErrMsg = 0;
57390
#endif /* SQLITE_OMIT_VIRTUALTABLE */
63547
#endif /* SQLITE_OMIT_VIRTUALTABLE */
57391
  }else{
63548
  }else{
57392
    assert( u.bi.pC->pCursor!=0 );
63549
    assert( u.bi.pC->pCursor!=0 );
 Lines 57498-57511   case OP_Rewind: { /* jump */ Link Here 
57498
  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
63655
  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
57499
  u.bl.pC = p->apCsr[pOp->p1];
63656
  u.bl.pC = p->apCsr[pOp->p1];
57500
  assert( u.bl.pC!=0 );
63657
  assert( u.bl.pC!=0 );
63658
  u.bl.res = 1;
57501
  if( (u.bl.pCrsr = u.bl.pC->pCursor)!=0 ){
63659
  if( (u.bl.pCrsr = u.bl.pC->pCursor)!=0 ){
57502
    rc = sqlite3BtreeFirst(u.bl.pCrsr, &u.bl.res);
63660
    rc = sqlite3BtreeFirst(u.bl.pCrsr, &u.bl.res);
57503
    u.bl.pC->atFirst = u.bl.res==0 ?1:0;
63661
    u.bl.pC->atFirst = u.bl.res==0 ?1:0;
57504
    u.bl.pC->deferredMoveto = 0;
63662
    u.bl.pC->deferredMoveto = 0;
57505
    u.bl.pC->cacheStatus = CACHE_STALE;
63663
    u.bl.pC->cacheStatus = CACHE_STALE;
57506
    u.bl.pC->rowidIsValid = 0;
63664
    u.bl.pC->rowidIsValid = 0;
57507
  }else{
57508
    u.bl.res = 1;
57509
  }
63665
  }
57510
  u.bl.pC->nullRow = (u8)u.bl.res;
63666
  u.bl.pC->nullRow = (u8)u.bl.res;
57511
  assert( pOp->p2>0 && pOp->p2<p->nOp );
63667
  assert( pOp->p2>0 && pOp->p2<p->nOp );
 Lines 57515-57521   case OP_Rewind: { /* jump */ Link Here 
57515
  break;
63671
  break;
57516
}
63672
}
57517
63673
57518
/* Opcode: Next P1 P2 * * *
63674
/* Opcode: Next P1 P2 * * P5
57519
**
63675
**
57520
** Advance cursor P1 so that it points to the next key/data pair in its
63676
** Advance cursor P1 so that it points to the next key/data pair in its
57521
** table or index.  If there are no more key/value pairs then fall through
63677
** table or index.  If there are no more key/value pairs then fall through
 Lines 57524-57532   case OP_Rewind: { /* jump */ Link Here 
57524
**
63680
**
57525
** The P1 cursor must be for a real table, not a pseudo-table.
63681
** The P1 cursor must be for a real table, not a pseudo-table.
57526
**
63682
**
63683
** If P5 is positive and the jump is taken, then event counter
63684
** number P5-1 in the prepared statement is incremented.
63685
**
57527
** See also: Prev
63686
** See also: Prev
57528
*/
63687
*/
57529
/* Opcode: Prev P1 P2 * * *
63688
/* Opcode: Prev P1 P2 * * P5
57530
**
63689
**
57531
** Back up cursor P1 so that it points to the previous key/data pair in its
63690
** Back up cursor P1 so that it points to the previous key/data pair in its
57532
** table or index.  If there is no previous key/value pairs then fall through
63691
** table or index.  If there is no previous key/value pairs then fall through
 Lines 57534-57539   case OP_Rewind: { /* jump */ Link Here 
57534
** jump immediately to P2.
63693
** jump immediately to P2.
57535
**
63694
**
57536
** The P1 cursor must be for a real table, not a pseudo-table.
63695
** The P1 cursor must be for a real table, not a pseudo-table.
63696
**
63697
** If P5 is positive and the jump is taken, then event counter
63698
** number P5-1 in the prepared statement is incremented.
57537
*/
63699
*/
57538
case OP_Prev:          /* jump */
63700
case OP_Prev:          /* jump */
57539
case OP_Next: {        /* jump */
63701
case OP_Next: {        /* jump */
 Lines 57545-57550   case OP_Next: { /* jump */ Link Here 
57545
63707
57546
  CHECK_FOR_INTERRUPT;
63708
  CHECK_FOR_INTERRUPT;
57547
  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
63709
  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
63710
  assert( pOp->p5<=ArraySize(p->aCounter) );
57548
  u.bm.pC = p->apCsr[pOp->p1];
63711
  u.bm.pC = p->apCsr[pOp->p1];
57549
  if( u.bm.pC==0 ){
63712
  if( u.bm.pC==0 ){
57550
    break;  /* See ticket #2273 */
63713
    break;  /* See ticket #2273 */
 Lines 57699-57705   case OP_IdxRowid: { /* out2 Link Here 
57699
** that if the key from register P3 is a prefix of the key in the cursor,
63862
** that if the key from register P3 is a prefix of the key in the cursor,
57700
** the result is false whereas it would be true with IdxGT.
63863
** the result is false whereas it would be true with IdxGT.
57701
*/
63864
*/
57702
/* Opcode: IdxLT P1 P2 P3 * P5
63865
/* Opcode: IdxLT P1 P2 P3 P4 P5
57703
**
63866
**
57704
** The P4 register values beginning with P3 form an unpacked index 
63867
** The P4 register values beginning with P3 form an unpacked index 
57705
** key that omits the ROWID.  Compare this key value against the index 
63868
** key that omits the ROWID.  Compare this key value against the index 
 Lines 58530-58535   case OP_AggFinal: { Link Here 
58530
  break;
64693
  break;
58531
}
64694
}
58532
64695
64696
#ifndef SQLITE_OMIT_WAL
64697
/* Opcode: Checkpoint P1 * * * *
64698
**
64699
** Checkpoint database P1. This is a no-op if P1 is not currently in
64700
** WAL mode.
64701
*/
64702
case OP_Checkpoint: {
64703
  rc = sqlite3Checkpoint(db, pOp->p1);
64704
  break;
64705
};  
64706
#endif
64707
64708
#ifndef SQLITE_OMIT_PRAGMA
64709
/* Opcode: JournalMode P1 P2 P3 * P5
64710
**
64711
** Change the journal mode of database P1 to P3. P3 must be one of the
64712
** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
64713
** modes (delete, truncate, persist, off and memory), this is a simple
64714
** operation. No IO is required.
64715
**
64716
** If changing into or out of WAL mode the procedure is more complicated.
64717
**
64718
** Write a string containing the final journal-mode to register P2.
64719
*/
64720
case OP_JournalMode: {    /* out2-prerelease */
64721
#if 0  /* local variables moved into u.cd */
64722
  Btree *pBt;                     /* Btree to change journal mode of */
64723
  Pager *pPager;                  /* Pager associated with pBt */
64724
  int eNew;                       /* New journal mode */
64725
  int eOld;                       /* The old journal mode */
64726
  const char *zFilename;          /* Name of database file for pPager */
64727
#endif /* local variables moved into u.cd */
64728
64729
  u.cd.eNew = pOp->p3;
64730
  assert( u.cd.eNew==PAGER_JOURNALMODE_DELETE
64731
       || u.cd.eNew==PAGER_JOURNALMODE_TRUNCATE
64732
       || u.cd.eNew==PAGER_JOURNALMODE_PERSIST
64733
       || u.cd.eNew==PAGER_JOURNALMODE_OFF
64734
       || u.cd.eNew==PAGER_JOURNALMODE_MEMORY
64735
       || u.cd.eNew==PAGER_JOURNALMODE_WAL
64736
       || u.cd.eNew==PAGER_JOURNALMODE_QUERY
64737
  );
64738
  assert( pOp->p1>=0 && pOp->p1<db->nDb );
64739
64740
  /* This opcode is used in two places: PRAGMA journal_mode and ATTACH.
64741
  ** In PRAGMA journal_mode, the sqlite3VdbeUsesBtree() routine is called
64742
  ** when the statment is prepared and so p->aMutex.nMutex>0.  All mutexes
64743
  ** are already acquired.  But when used in ATTACH, sqlite3VdbeUsesBtree()
64744
  ** is not called when the statement is prepared because it requires the
64745
  ** iDb index of the database as a parameter, and the database has not
64746
  ** yet been attached so that index is unavailable.  We have to wait
64747
  ** until runtime (now) to get the mutex on the newly attached database.
64748
  ** No other mutexes are required by the ATTACH command so this is safe
64749
  ** to do.
64750
  */
64751
  assert( (p->btreeMask & (1<<pOp->p1))!=0 || p->aMutex.nMutex==0 );
64752
  if( p->aMutex.nMutex==0 ){
64753
    /* This occurs right after ATTACH.  Get a mutex on the newly ATTACHed
64754
    ** database. */
64755
    sqlite3VdbeUsesBtree(p, pOp->p1);
64756
    sqlite3VdbeMutexArrayEnter(p);
64757
  }
64758
64759
  u.cd.pBt = db->aDb[pOp->p1].pBt;
64760
  u.cd.pPager = sqlite3BtreePager(u.cd.pBt);
64761
  u.cd.eOld = sqlite3PagerGetJournalMode(u.cd.pPager);
64762
  if( u.cd.eNew==PAGER_JOURNALMODE_QUERY ) u.cd.eNew = u.cd.eOld;
64763
  if( !sqlite3PagerOkToChangeJournalMode(u.cd.pPager) ) u.cd.eNew = u.cd.eOld;
64764
64765
#ifndef SQLITE_OMIT_WAL
64766
  u.cd.zFilename = sqlite3PagerFilename(u.cd.pPager);
64767
64768
  /* Do not allow a transition to journal_mode=WAL for a database
64769
  ** in temporary storage or if the VFS does not support shared memory
64770
  */
64771
  if( u.cd.eNew==PAGER_JOURNALMODE_WAL
64772
   && (u.cd.zFilename[0]==0                         /* Temp file */
64773
       || !sqlite3PagerWalSupported(u.cd.pPager))   /* No shared-memory support */
64774
  ){
64775
    u.cd.eNew = u.cd.eOld;
64776
  }
64777
64778
  if( (u.cd.eNew!=u.cd.eOld)
64779
   && (u.cd.eOld==PAGER_JOURNALMODE_WAL || u.cd.eNew==PAGER_JOURNALMODE_WAL)
64780
  ){
64781
    if( !db->autoCommit || db->activeVdbeCnt>1 ){
64782
      rc = SQLITE_ERROR;
64783
      sqlite3SetString(&p->zErrMsg, db,
64784
          "cannot change %s wal mode from within a transaction",
64785
          (u.cd.eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
64786
      );
64787
      break;
64788
    }else{
64789
64790
      if( u.cd.eOld==PAGER_JOURNALMODE_WAL ){
64791
        /* If leaving WAL mode, close the log file. If successful, the call
64792
        ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
64793
        ** file. An EXCLUSIVE lock may still be held on the database file
64794
        ** after a successful return.
64795
        */
64796
        rc = sqlite3PagerCloseWal(u.cd.pPager);
64797
        if( rc==SQLITE_OK ){
64798
          sqlite3PagerSetJournalMode(u.cd.pPager, u.cd.eNew);
64799
        }
64800
      }else if( u.cd.eOld==PAGER_JOURNALMODE_MEMORY ){
64801
        /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
64802
        ** as an intermediate */
64803
        sqlite3PagerSetJournalMode(u.cd.pPager, PAGER_JOURNALMODE_OFF);
64804
      }
64805
64806
      /* Open a transaction on the database file. Regardless of the journal
64807
      ** mode, this transaction always uses a rollback journal.
64808
      */
64809
      assert( sqlite3BtreeIsInTrans(u.cd.pBt)==0 );
64810
      if( rc==SQLITE_OK ){
64811
        rc = sqlite3BtreeSetVersion(u.cd.pBt, (u.cd.eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
64812
      }
64813
    }
64814
  }
64815
#endif /* ifndef SQLITE_OMIT_WAL */
64816
64817
  if( rc ){
64818
    u.cd.eNew = u.cd.eOld;
64819
  }
64820
  u.cd.eNew = sqlite3PagerSetJournalMode(u.cd.pPager, u.cd.eNew);
64821
64822
  pOut = &aMem[pOp->p2];
64823
  pOut->flags = MEM_Str|MEM_Static|MEM_Term;
64824
  pOut->z = (char *)sqlite3JournalModename(u.cd.eNew);
64825
  pOut->n = sqlite3Strlen30(pOut->z);
64826
  pOut->enc = SQLITE_UTF8;
64827
  sqlite3VdbeChangeEncoding(pOut, encoding);
64828
  break;
64829
};
64830
#endif /* SQLITE_OMIT_PRAGMA */
58533
64831
58534
#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
64832
#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
58535
/* Opcode: Vacuum * * * * *
64833
/* Opcode: Vacuum * * * * *
 Lines 58552-58565   case OP_Vacuum: { Link Here 
58552
** P2. Otherwise, fall through to the next instruction.
64850
** P2. Otherwise, fall through to the next instruction.
58553
*/
64851
*/
58554
case OP_IncrVacuum: {        /* jump */
64852
case OP_IncrVacuum: {        /* jump */
58555
#if 0  /* local variables moved into u.cd */
64853
#if 0  /* local variables moved into u.ce */
58556
  Btree *pBt;
64854
  Btree *pBt;
58557
#endif /* local variables moved into u.cd */
64855
#endif /* local variables moved into u.ce */
58558
64856
58559
  assert( pOp->p1>=0 && pOp->p1<db->nDb );
64857
  assert( pOp->p1>=0 && pOp->p1<db->nDb );
58560
  assert( (p->btreeMask & (1<<pOp->p1))!=0 );
64858
  assert( (p->btreeMask & (1<<pOp->p1))!=0 );
58561
  u.cd.pBt = db->aDb[pOp->p1].pBt;
64859
  u.ce.pBt = db->aDb[pOp->p1].pBt;
58562
  rc = sqlite3BtreeIncrVacuum(u.cd.pBt);
64860
  rc = sqlite3BtreeIncrVacuum(u.ce.pBt);
58563
  if( rc==SQLITE_DONE ){
64861
  if( rc==SQLITE_DONE ){
58564
    pc = pOp->p2 - 1;
64862
    pc = pOp->p2 - 1;
58565
    rc = SQLITE_OK;
64863
    rc = SQLITE_OK;
 Lines 58629-58644   case OP_TableLock: { Link Here 
58629
** code will be set to SQLITE_LOCKED.
64927
** code will be set to SQLITE_LOCKED.
58630
*/
64928
*/
58631
case OP_VBegin: {
64929
case OP_VBegin: {
58632
#if 0  /* local variables moved into u.ce */
64930
#if 0  /* local variables moved into u.cf */
58633
  VTable *pVTab;
64931
  VTable *pVTab;
58634
#endif /* local variables moved into u.ce */
64932
#endif /* local variables moved into u.cf */
58635
  u.ce.pVTab = pOp->p4.pVtab;
64933
  u.cf.pVTab = pOp->p4.pVtab;
58636
  rc = sqlite3VtabBegin(db, u.ce.pVTab);
64934
  rc = sqlite3VtabBegin(db, u.cf.pVTab);
58637
  if( u.ce.pVTab ){
64935
  if( u.cf.pVTab ) importVtabErrMsg(p, u.cf.pVTab->pVtab);
58638
    sqlite3DbFree(db, p->zErrMsg);
58639
    p->zErrMsg = u.ce.pVTab->pVtab->zErrMsg;
58640
    u.ce.pVTab->pVtab->zErrMsg = 0;
58641
  }
58642
  break;
64936
  break;
58643
}
64937
}
58644
#endif /* SQLITE_OMIT_VIRTUALTABLE */
64938
#endif /* SQLITE_OMIT_VIRTUALTABLE */
 Lines 58677-58710   case OP_VDestroy: { Link Here 
58677
** table and stores that cursor in P1.
64971
** table and stores that cursor in P1.
58678
*/
64972
*/
58679
case OP_VOpen: {
64973
case OP_VOpen: {
58680
#if 0  /* local variables moved into u.cf */
64974
#if 0  /* local variables moved into u.cg */
58681
  VdbeCursor *pCur;
64975
  VdbeCursor *pCur;
58682
  sqlite3_vtab_cursor *pVtabCursor;
64976
  sqlite3_vtab_cursor *pVtabCursor;
58683
  sqlite3_vtab *pVtab;
64977
  sqlite3_vtab *pVtab;
58684
  sqlite3_module *pModule;
64978
  sqlite3_module *pModule;
58685
#endif /* local variables moved into u.cf */
64979
#endif /* local variables moved into u.cg */
58686
64980
58687
  u.cf.pCur = 0;
64981
  u.cg.pCur = 0;
58688
  u.cf.pVtabCursor = 0;
64982
  u.cg.pVtabCursor = 0;
58689
  u.cf.pVtab = pOp->p4.pVtab->pVtab;
64983
  u.cg.pVtab = pOp->p4.pVtab->pVtab;
58690
  u.cf.pModule = (sqlite3_module *)u.cf.pVtab->pModule;
64984
  u.cg.pModule = (sqlite3_module *)u.cg.pVtab->pModule;
58691
  assert(u.cf.pVtab && u.cf.pModule);
64985
  assert(u.cg.pVtab && u.cg.pModule);
58692
  rc = u.cf.pModule->xOpen(u.cf.pVtab, &u.cf.pVtabCursor);
64986
  rc = u.cg.pModule->xOpen(u.cg.pVtab, &u.cg.pVtabCursor);
58693
  sqlite3DbFree(db, p->zErrMsg);
64987
  importVtabErrMsg(p, u.cg.pVtab);
58694
  p->zErrMsg = u.cf.pVtab->zErrMsg;
58695
  u.cf.pVtab->zErrMsg = 0;
58696
  if( SQLITE_OK==rc ){
64988
  if( SQLITE_OK==rc ){
58697
    /* Initialize sqlite3_vtab_cursor base class */
64989
    /* Initialize sqlite3_vtab_cursor base class */
58698
    u.cf.pVtabCursor->pVtab = u.cf.pVtab;
64990
    u.cg.pVtabCursor->pVtab = u.cg.pVtab;
58699
64991
58700
    /* Initialise vdbe cursor object */
64992
    /* Initialise vdbe cursor object */
58701
    u.cf.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
64993
    u.cg.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
58702
    if( u.cf.pCur ){
64994
    if( u.cg.pCur ){
58703
      u.cf.pCur->pVtabCursor = u.cf.pVtabCursor;
64995
      u.cg.pCur->pVtabCursor = u.cg.pVtabCursor;
58704
      u.cf.pCur->pModule = u.cf.pVtabCursor->pVtab->pModule;
64996
      u.cg.pCur->pModule = u.cg.pVtabCursor->pVtab->pModule;
58705
    }else{
64997
    }else{
58706
      db->mallocFailed = 1;
64998
      db->mallocFailed = 1;
58707
      u.cf.pModule->xClose(u.cf.pVtabCursor);
64999
      u.cg.pModule->xClose(u.cg.pVtabCursor);
58708
    }
65000
    }
58709
  }
65001
  }
58710
  break;
65002
  break;
 Lines 58731-58737   case OP_VOpen: { Link Here 
58731
** A jump is made to P2 if the result set after filtering would be empty.
65023
** A jump is made to P2 if the result set after filtering would be empty.
58732
*/
65024
*/
58733
case OP_VFilter: {   /* jump */
65025
case OP_VFilter: {   /* jump */
58734
#if 0  /* local variables moved into u.cg */
65026
#if 0  /* local variables moved into u.ch */
58735
  int nArg;
65027
  int nArg;
58736
  int iQuery;
65028
  int iQuery;
58737
  const sqlite3_module *pModule;
65029
  const sqlite3_module *pModule;
 Lines 58743-58788   case OP_VFilter: { /* jump */ Link Here 
58743
  int res;
65035
  int res;
58744
  int i;
65036
  int i;
58745
  Mem **apArg;
65037
  Mem **apArg;
58746
#endif /* local variables moved into u.cg */
65038
#endif /* local variables moved into u.ch */
58747
65039
58748
  u.cg.pQuery = &aMem[pOp->p3];
65040
  u.ch.pQuery = &aMem[pOp->p3];
58749
  u.cg.pArgc = &u.cg.pQuery[1];
65041
  u.ch.pArgc = &u.ch.pQuery[1];
58750
  u.cg.pCur = p->apCsr[pOp->p1];
65042
  u.ch.pCur = p->apCsr[pOp->p1];
58751
  REGISTER_TRACE(pOp->p3, u.cg.pQuery);
65043
  REGISTER_TRACE(pOp->p3, u.ch.pQuery);
58752
  assert( u.cg.pCur->pVtabCursor );
65044
  assert( u.ch.pCur->pVtabCursor );
58753
  u.cg.pVtabCursor = u.cg.pCur->pVtabCursor;
65045
  u.ch.pVtabCursor = u.ch.pCur->pVtabCursor;
58754
  u.cg.pVtab = u.cg.pVtabCursor->pVtab;
65046
  u.ch.pVtab = u.ch.pVtabCursor->pVtab;
58755
  u.cg.pModule = u.cg.pVtab->pModule;
65047
  u.ch.pModule = u.ch.pVtab->pModule;
58756
65048
58757
  /* Grab the index number and argc parameters */
65049
  /* Grab the index number and argc parameters */
58758
  assert( (u.cg.pQuery->flags&MEM_Int)!=0 && u.cg.pArgc->flags==MEM_Int );
65050
  assert( (u.ch.pQuery->flags&MEM_Int)!=0 && u.ch.pArgc->flags==MEM_Int );
58759
  u.cg.nArg = (int)u.cg.pArgc->u.i;
65051
  u.ch.nArg = (int)u.ch.pArgc->u.i;
58760
  u.cg.iQuery = (int)u.cg.pQuery->u.i;
65052
  u.ch.iQuery = (int)u.ch.pQuery->u.i;
58761
65053
58762
  /* Invoke the xFilter method */
65054
  /* Invoke the xFilter method */
58763
  {
65055
  {
58764
    u.cg.res = 0;
65056
    u.ch.res = 0;
58765
    u.cg.apArg = p->apArg;
65057
    u.ch.apArg = p->apArg;
58766
    for(u.cg.i = 0; u.cg.i<u.cg.nArg; u.cg.i++){
65058
    for(u.ch.i = 0; u.ch.i<u.ch.nArg; u.ch.i++){
58767
      u.cg.apArg[u.cg.i] = &u.cg.pArgc[u.cg.i+1];
65059
      u.ch.apArg[u.ch.i] = &u.ch.pArgc[u.ch.i+1];
58768
      sqlite3VdbeMemStoreType(u.cg.apArg[u.cg.i]);
65060
      sqlite3VdbeMemStoreType(u.ch.apArg[u.ch.i]);
58769
    }
65061
    }
58770
65062
58771
    p->inVtabMethod = 1;
65063
    p->inVtabMethod = 1;
58772
    rc = u.cg.pModule->xFilter(u.cg.pVtabCursor, u.cg.iQuery, pOp->p4.z, u.cg.nArg, u.cg.apArg);
65064
    rc = u.ch.pModule->xFilter(u.ch.pVtabCursor, u.ch.iQuery, pOp->p4.z, u.ch.nArg, u.ch.apArg);
58773
    p->inVtabMethod = 0;
65065
    p->inVtabMethod = 0;
58774
    sqlite3DbFree(db, p->zErrMsg);
65066
    importVtabErrMsg(p, u.ch.pVtab);
58775
    p->zErrMsg = u.cg.pVtab->zErrMsg;
58776
    u.cg.pVtab->zErrMsg = 0;
58777
    if( rc==SQLITE_OK ){
65067
    if( rc==SQLITE_OK ){
58778
      u.cg.res = u.cg.pModule->xEof(u.cg.pVtabCursor);
65068
      u.ch.res = u.ch.pModule->xEof(u.ch.pVtabCursor);
58779
    }
65069
    }
58780
65070
58781
    if( u.cg.res ){
65071
    if( u.ch.res ){
58782
      pc = pOp->p2 - 1;
65072
      pc = pOp->p2 - 1;
58783
    }
65073
    }
58784
  }
65074
  }
58785
  u.cg.pCur->nullRow = 0;
65075
  u.ch.pCur->nullRow = 0;
58786
65076
58787
  break;
65077
  break;
58788
}
65078
}
 Lines 58796-58847   case OP_VFilter: { /* jump */ Link Here 
58796
** P1 cursor is pointing to into register P3.
65086
** P1 cursor is pointing to into register P3.
58797
*/
65087
*/
58798
case OP_VColumn: {
65088
case OP_VColumn: {
58799
#if 0  /* local variables moved into u.ch */
65089
#if 0  /* local variables moved into u.ci */
58800
  sqlite3_vtab *pVtab;
65090
  sqlite3_vtab *pVtab;
58801
  const sqlite3_module *pModule;
65091
  const sqlite3_module *pModule;
58802
  Mem *pDest;
65092
  Mem *pDest;
58803
  sqlite3_context sContext;
65093
  sqlite3_context sContext;
58804
#endif /* local variables moved into u.ch */
65094
#endif /* local variables moved into u.ci */
58805
65095
58806
  VdbeCursor *pCur = p->apCsr[pOp->p1];
65096
  VdbeCursor *pCur = p->apCsr[pOp->p1];
58807
  assert( pCur->pVtabCursor );
65097
  assert( pCur->pVtabCursor );
58808
  assert( pOp->p3>0 && pOp->p3<=p->nMem );
65098
  assert( pOp->p3>0 && pOp->p3<=p->nMem );
58809
  u.ch.pDest = &aMem[pOp->p3];
65099
  u.ci.pDest = &aMem[pOp->p3];
58810
  if( pCur->nullRow ){
65100
  if( pCur->nullRow ){
58811
    sqlite3VdbeMemSetNull(u.ch.pDest);
65101
    sqlite3VdbeMemSetNull(u.ci.pDest);
58812
    break;
65102
    break;
58813
  }
65103
  }
58814
  u.ch.pVtab = pCur->pVtabCursor->pVtab;
65104
  u.ci.pVtab = pCur->pVtabCursor->pVtab;
58815
  u.ch.pModule = u.ch.pVtab->pModule;
65105
  u.ci.pModule = u.ci.pVtab->pModule;
58816
  assert( u.ch.pModule->xColumn );
65106
  assert( u.ci.pModule->xColumn );
58817
  memset(&u.ch.sContext, 0, sizeof(u.ch.sContext));
65107
  memset(&u.ci.sContext, 0, sizeof(u.ci.sContext));
58818
65108
58819
  /* The output cell may already have a buffer allocated. Move
65109
  /* The output cell may already have a buffer allocated. Move
58820
  ** the current contents to u.ch.sContext.s so in case the user-function
65110
  ** the current contents to u.ci.sContext.s so in case the user-function
58821
  ** can use the already allocated buffer instead of allocating a
65111
  ** can use the already allocated buffer instead of allocating a
58822
  ** new one.
65112
  ** new one.
58823
  */
65113
  */
58824
  sqlite3VdbeMemMove(&u.ch.sContext.s, u.ch.pDest);
65114
  sqlite3VdbeMemMove(&u.ci.sContext.s, u.ci.pDest);
58825
  MemSetTypeFlag(&u.ch.sContext.s, MEM_Null);
65115
  MemSetTypeFlag(&u.ci.sContext.s, MEM_Null);
58826
65116
58827
  rc = u.ch.pModule->xColumn(pCur->pVtabCursor, &u.ch.sContext, pOp->p2);
65117
  rc = u.ci.pModule->xColumn(pCur->pVtabCursor, &u.ci.sContext, pOp->p2);
58828
  sqlite3DbFree(db, p->zErrMsg);
65118
  importVtabErrMsg(p, u.ci.pVtab);
58829
  p->zErrMsg = u.ch.pVtab->zErrMsg;
65119
  if( u.ci.sContext.isError ){
58830
  u.ch.pVtab->zErrMsg = 0;
65120
    rc = u.ci.sContext.isError;
58831
  if( u.ch.sContext.isError ){
58832
    rc = u.ch.sContext.isError;
58833
  }
65121
  }
58834
65122
58835
  /* Copy the result of the function to the P3 register. We
65123
  /* Copy the result of the function to the P3 register. We
58836
  ** do this regardless of whether or not an error occurred to ensure any
65124
  ** do this regardless of whether or not an error occurred to ensure any
58837
  ** dynamic allocation in u.ch.sContext.s (a Mem struct) is  released.
65125
  ** dynamic allocation in u.ci.sContext.s (a Mem struct) is  released.
58838
  */
65126
  */
58839
  sqlite3VdbeChangeEncoding(&u.ch.sContext.s, encoding);
65127
  sqlite3VdbeChangeEncoding(&u.ci.sContext.s, encoding);
58840
  sqlite3VdbeMemMove(u.ch.pDest, &u.ch.sContext.s);
65128
  sqlite3VdbeMemMove(u.ci.pDest, &u.ci.sContext.s);
58841
  REGISTER_TRACE(pOp->p3, u.ch.pDest);
65129
  REGISTER_TRACE(pOp->p3, u.ci.pDest);
58842
  UPDATE_MAX_BLOBSIZE(u.ch.pDest);
65130
  UPDATE_MAX_BLOBSIZE(u.ci.pDest);
58843
65131
58844
  if( sqlite3VdbeMemTooBig(u.ch.pDest) ){
65132
  if( sqlite3VdbeMemTooBig(u.ci.pDest) ){
58845
    goto too_big;
65133
    goto too_big;
58846
  }
65134
  }
58847
  break;
65135
  break;
 Lines 58856-58877   case OP_VColumn: { Link Here 
58856
** the end of its result set, then fall through to the next instruction.
65144
** the end of its result set, then fall through to the next instruction.
58857
*/
65145
*/
58858
case OP_VNext: {   /* jump */
65146
case OP_VNext: {   /* jump */
58859
#if 0  /* local variables moved into u.ci */
65147
#if 0  /* local variables moved into u.cj */
58860
  sqlite3_vtab *pVtab;
65148
  sqlite3_vtab *pVtab;
58861
  const sqlite3_module *pModule;
65149
  const sqlite3_module *pModule;
58862
  int res;
65150
  int res;
58863
  VdbeCursor *pCur;
65151
  VdbeCursor *pCur;
58864
#endif /* local variables moved into u.ci */
65152
#endif /* local variables moved into u.cj */
58865
65153
58866
  u.ci.res = 0;
65154
  u.cj.res = 0;
58867
  u.ci.pCur = p->apCsr[pOp->p1];
65155
  u.cj.pCur = p->apCsr[pOp->p1];
58868
  assert( u.ci.pCur->pVtabCursor );
65156
  assert( u.cj.pCur->pVtabCursor );
58869
  if( u.ci.pCur->nullRow ){
65157
  if( u.cj.pCur->nullRow ){
58870
    break;
65158
    break;
58871
  }
65159
  }
58872
  u.ci.pVtab = u.ci.pCur->pVtabCursor->pVtab;
65160
  u.cj.pVtab = u.cj.pCur->pVtabCursor->pVtab;
58873
  u.ci.pModule = u.ci.pVtab->pModule;
65161
  u.cj.pModule = u.cj.pVtab->pModule;
58874
  assert( u.ci.pModule->xNext );
65162
  assert( u.cj.pModule->xNext );
58875
65163
58876
  /* Invoke the xNext() method of the module. There is no way for the
65164
  /* Invoke the xNext() method of the module. There is no way for the
58877
  ** underlying implementation to return an error if one occurs during
65165
  ** underlying implementation to return an error if one occurs during
 Lines 58880-58895   case OP_VNext: { /* jump */ Link Here 
58880
  ** some other method is next invoked on the save virtual table cursor.
65168
  ** some other method is next invoked on the save virtual table cursor.
58881
  */
65169
  */
58882
  p->inVtabMethod = 1;
65170
  p->inVtabMethod = 1;
58883
  rc = u.ci.pModule->xNext(u.ci.pCur->pVtabCursor);
65171
  rc = u.cj.pModule->xNext(u.cj.pCur->pVtabCursor);
58884
  p->inVtabMethod = 0;
65172
  p->inVtabMethod = 0;
58885
  sqlite3DbFree(db, p->zErrMsg);
65173
  importVtabErrMsg(p, u.cj.pVtab);
58886
  p->zErrMsg = u.ci.pVtab->zErrMsg;
58887
  u.ci.pVtab->zErrMsg = 0;
58888
  if( rc==SQLITE_OK ){
65174
  if( rc==SQLITE_OK ){
58889
    u.ci.res = u.ci.pModule->xEof(u.ci.pCur->pVtabCursor);
65175
    u.cj.res = u.cj.pModule->xEof(u.cj.pCur->pVtabCursor);
58890
  }
65176
  }
58891
65177
58892
  if( !u.ci.res ){
65178
  if( !u.cj.res ){
58893
    /* If there is data, jump to P2 */
65179
    /* If there is data, jump to P2 */
58894
    pc = pOp->p2 - 1;
65180
    pc = pOp->p2 - 1;
58895
  }
65181
  }
 Lines 58905-58924   case OP_VNext: { /* jump */ Link Here 
58905
** in register P1 is passed as the zName argument to the xRename method.
65191
** in register P1 is passed as the zName argument to the xRename method.
58906
*/
65192
*/
58907
case OP_VRename: {
65193
case OP_VRename: {
58908
#if 0  /* local variables moved into u.cj */
65194
#if 0  /* local variables moved into u.ck */
58909
  sqlite3_vtab *pVtab;
65195
  sqlite3_vtab *pVtab;
58910
  Mem *pName;
65196
  Mem *pName;
58911
#endif /* local variables moved into u.cj */
65197
#endif /* local variables moved into u.ck */
58912
65198
58913
  u.cj.pVtab = pOp->p4.pVtab->pVtab;
65199
  u.ck.pVtab = pOp->p4.pVtab->pVtab;
58914
  u.cj.pName = &aMem[pOp->p1];
65200
  u.ck.pName = &aMem[pOp->p1];
58915
  assert( u.cj.pVtab->pModule->xRename );
65201
  assert( u.ck.pVtab->pModule->xRename );
58916
  REGISTER_TRACE(pOp->p1, u.cj.pName);
65202
  REGISTER_TRACE(pOp->p1, u.ck.pName);
58917
  assert( u.cj.pName->flags & MEM_Str );
65203
  assert( u.ck.pName->flags & MEM_Str );
58918
  rc = u.cj.pVtab->pModule->xRename(u.cj.pVtab, u.cj.pName->z);
65204
  rc = u.ck.pVtab->pModule->xRename(u.ck.pVtab, u.ck.pName->z);
58919
  sqlite3DbFree(db, p->zErrMsg);
65205
  importVtabErrMsg(p, u.ck.pVtab);
58920
  p->zErrMsg = u.cj.pVtab->zErrMsg;
58921
  u.cj.pVtab->zErrMsg = 0;
58922
65206
58923
  break;
65207
  break;
58924
}
65208
}
 Lines 58949-58955   case OP_VRename: { Link Here 
58949
** is set to the value of the rowid for the row just inserted.
65233
** is set to the value of the rowid for the row just inserted.
58950
*/
65234
*/
58951
case OP_VUpdate: {
65235
case OP_VUpdate: {
58952
#if 0  /* local variables moved into u.ck */
65236
#if 0  /* local variables moved into u.cl */
58953
  sqlite3_vtab *pVtab;
65237
  sqlite3_vtab *pVtab;
58954
  sqlite3_module *pModule;
65238
  sqlite3_module *pModule;
58955
  int nArg;
65239
  int nArg;
 Lines 58957-58983   case OP_VUpdate: { Link Here 
58957
  sqlite_int64 rowid;
65241
  sqlite_int64 rowid;
58958
  Mem **apArg;
65242
  Mem **apArg;
58959
  Mem *pX;
65243
  Mem *pX;
58960
#endif /* local variables moved into u.ck */
65244
#endif /* local variables moved into u.cl */
58961
65245
58962
  u.ck.pVtab = pOp->p4.pVtab->pVtab;
65246
  u.cl.pVtab = pOp->p4.pVtab->pVtab;
58963
  u.ck.pModule = (sqlite3_module *)u.ck.pVtab->pModule;
65247
  u.cl.pModule = (sqlite3_module *)u.cl.pVtab->pModule;
58964
  u.ck.nArg = pOp->p2;
65248
  u.cl.nArg = pOp->p2;
58965
  assert( pOp->p4type==P4_VTAB );
65249
  assert( pOp->p4type==P4_VTAB );
58966
  if( ALWAYS(u.ck.pModule->xUpdate) ){
65250
  if( ALWAYS(u.cl.pModule->xUpdate) ){
58967
    u.ck.apArg = p->apArg;
65251
    u.cl.apArg = p->apArg;
58968
    u.ck.pX = &aMem[pOp->p3];
65252
    u.cl.pX = &aMem[pOp->p3];
58969
    for(u.ck.i=0; u.ck.i<u.ck.nArg; u.ck.i++){
65253
    for(u.cl.i=0; u.cl.i<u.cl.nArg; u.cl.i++){
58970
      sqlite3VdbeMemStoreType(u.ck.pX);
65254
      sqlite3VdbeMemStoreType(u.cl.pX);
58971
      u.ck.apArg[u.ck.i] = u.ck.pX;
65255
      u.cl.apArg[u.cl.i] = u.cl.pX;
58972
      u.ck.pX++;
65256
      u.cl.pX++;
58973
    }
65257
    }
58974
    rc = u.ck.pModule->xUpdate(u.ck.pVtab, u.ck.nArg, u.ck.apArg, &u.ck.rowid);
65258
    rc = u.cl.pModule->xUpdate(u.cl.pVtab, u.cl.nArg, u.cl.apArg, &u.cl.rowid);
58975
    sqlite3DbFree(db, p->zErrMsg);
65259
    importVtabErrMsg(p, u.cl.pVtab);
58976
    p->zErrMsg = u.ck.pVtab->zErrMsg;
58977
    u.ck.pVtab->zErrMsg = 0;
58978
    if( rc==SQLITE_OK && pOp->p1 ){
65260
    if( rc==SQLITE_OK && pOp->p1 ){
58979
      assert( u.ck.nArg>1 && u.ck.apArg[0] && (u.ck.apArg[0]->flags&MEM_Null) );
65261
      assert( u.cl.nArg>1 && u.cl.apArg[0] && (u.cl.apArg[0]->flags&MEM_Null) );
58980
      db->lastRowid = u.ck.rowid;
65262
      db->lastRowid = u.cl.rowid;
58981
    }
65263
    }
58982
    p->nChange++;
65264
    p->nChange++;
58983
  }
65265
  }
 Lines 58991-59011   case OP_VUpdate: { Link Here 
58991
** Write the current number of pages in database P1 to memory cell P2.
65273
** Write the current number of pages in database P1 to memory cell P2.
58992
*/
65274
*/
58993
case OP_Pagecount: {            /* out2-prerelease */
65275
case OP_Pagecount: {            /* out2-prerelease */
58994
#if 0  /* local variables moved into u.cl */
65276
  pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
58995
  int p1;
58996
  int nPage;
58997
  Pager *pPager;
58998
#endif /* local variables moved into u.cl */
58999
59000
  u.cl.p1 = pOp->p1;
59001
  u.cl.pPager = sqlite3BtreePager(db->aDb[u.cl.p1].pBt);
59002
  rc = sqlite3PagerPagecount(u.cl.pPager, &u.cl.nPage);
59003
  /* OP_Pagecount is always called from within a read transaction.  The
59004
  ** page count has already been successfully read and cached.  So the
59005
  ** sqlite3PagerPagecount() call above cannot fail. */
59006
  if( ALWAYS(rc==SQLITE_OK) ){
59007
    pOut->u.i = u.cl.nPage;
59008
  }
59009
  break;
65277
  break;
59010
}
65278
}
59011
#endif
65279
#endif
 Lines 59349-59358   SQLITE_API int sqlite3_blob_open( Link Here 
59349
      sqlite3VdbeUsesBtree(v, iDb); 
65617
      sqlite3VdbeUsesBtree(v, iDb); 
59350
65618
59351
      /* Configure the OP_TableLock instruction */
65619
      /* Configure the OP_TableLock instruction */
65620
#ifdef SQLITE_OMIT_SHARED_CACHE
65621
      sqlite3VdbeChangeToNoop(v, 2, 1);
65622
#else
59352
      sqlite3VdbeChangeP1(v, 2, iDb);
65623
      sqlite3VdbeChangeP1(v, 2, iDb);
59353
      sqlite3VdbeChangeP2(v, 2, pTab->tnum);
65624
      sqlite3VdbeChangeP2(v, 2, pTab->tnum);
59354
      sqlite3VdbeChangeP3(v, 2, flags);
65625
      sqlite3VdbeChangeP3(v, 2, flags);
59355
      sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
65626
      sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
65627
#endif
59356
65628
59357
      /* Remove either the OP_OpenWrite or OpenRead. Set the P2 
65629
      /* Remove either the OP_OpenWrite or OpenRead. Set the P2 
59358
      ** parameter of the other to pTab->tnum.  */
65630
      ** parameter of the other to pTab->tnum.  */
 Lines 59723-59729   static struct sqlite3_io_methods Journal Link Here 
59723
  0,             /* xCheckReservedLock */
65995
  0,             /* xCheckReservedLock */
59724
  0,             /* xFileControl */
65996
  0,             /* xFileControl */
59725
  0,             /* xSectorSize */
65997
  0,             /* xSectorSize */
59726
  0              /* xDeviceCharacteristics */
65998
  0,             /* xDeviceCharacteristics */
65999
  0,             /* xShmMap */
66000
  0,             /* xShmLock */
66001
  0,             /* xShmBarrier */
66002
  0              /* xShmUnmap */
59727
};
66003
};
59728
66004
59729
/* 
66005
/* 
 Lines 59973-59983   static int memjrnlClose(sqlite3_file *pJ Link Here 
59973
** exists purely as a contingency, in case some malfunction in some other
66249
** exists purely as a contingency, in case some malfunction in some other
59974
** part of SQLite causes Sync to be called by mistake.
66250
** part of SQLite causes Sync to be called by mistake.
59975
*/
66251
*/
59976
static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){   /*NO_TEST*/
66252
static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
59977
  UNUSED_PARAMETER2(NotUsed, NotUsed2);                        /*NO_TEST*/
66253
  UNUSED_PARAMETER2(NotUsed, NotUsed2);
59978
  assert( 0 );                                                 /*NO_TEST*/
66254
  return SQLITE_OK;
59979
  return SQLITE_OK;                                            /*NO_TEST*/
66255
}
59980
}                                                              /*NO_TEST*/
59981
66256
59982
/*
66257
/*
59983
** Query the size of the file in bytes.
66258
** Query the size of the file in bytes.
 Lines 59991-59997   static int memjrnlFileSize(sqlite3_file Link Here 
59991
/*
66266
/*
59992
** Table of methods for MemJournal sqlite3_file object.
66267
** Table of methods for MemJournal sqlite3_file object.
59993
*/
66268
*/
59994
static struct sqlite3_io_methods MemJournalMethods = {
66269
static const struct sqlite3_io_methods MemJournalMethods = {
59995
  1,                /* iVersion */
66270
  1,                /* iVersion */
59996
  memjrnlClose,     /* xClose */
66271
  memjrnlClose,     /* xClose */
59997
  memjrnlRead,      /* xRead */
66272
  memjrnlRead,      /* xRead */
 Lines 60004-60010   static struct sqlite3_io_methods MemJour Link Here 
60004
  0,                /* xCheckReservedLock */
66279
  0,                /* xCheckReservedLock */
60005
  0,                /* xFileControl */
66280
  0,                /* xFileControl */
60006
  0,                /* xSectorSize */
66281
  0,                /* xSectorSize */
60007
  0                 /* xDeviceCharacteristics */
66282
  0,                /* xDeviceCharacteristics */
66283
  0,                /* xShmMap */
66284
  0,                /* xShmLock */
66285
  0,                /* xShmBarrier */
66286
  0                 /* xShmUnlock */
60008
};
66287
};
60009
66288
60010
/* 
66289
/* 
 Lines 60014-60020   SQLITE_PRIVATE void sqlite3MemJournalOpe Link Here 
60014
  MemJournal *p = (MemJournal *)pJfd;
66293
  MemJournal *p = (MemJournal *)pJfd;
60015
  assert( EIGHT_BYTE_ALIGNMENT(p) );
66294
  assert( EIGHT_BYTE_ALIGNMENT(p) );
60016
  memset(p, 0, sqlite3MemJournalSize());
66295
  memset(p, 0, sqlite3MemJournalSize());
60017
  p->pMethod = &MemJournalMethods;
66296
  p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
60018
}
66297
}
60019
66298
60020
/*
66299
/*
 Lines 60527-60532   static int lookupName( Link Here 
60527
    }else{
66806
    }else{
60528
      sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
66807
      sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
60529
    }
66808
    }
66809
    pParse->checkSchema = 1;
60530
    pTopNC->nErr++;
66810
    pTopNC->nErr++;
60531
  }
66811
  }
60532
66812
 Lines 60573-60579   lookupname_end: Link Here 
60573
66853
60574
/*
66854
/*
60575
** Allocate and return a pointer to an expression to load the column iCol
66855
** Allocate and return a pointer to an expression to load the column iCol
60576
** from datasource iSrc datasource in SrcList pSrc.
66856
** from datasource iSrc in SrcList pSrc.
60577
*/
66857
*/
60578
SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
66858
SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
60579
  Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
66859
  Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
 Lines 60585-60590   SQLITE_PRIVATE Expr *sqlite3CreateColumn Link Here 
60585
      p->iColumn = -1;
66865
      p->iColumn = -1;
60586
    }else{
66866
    }else{
60587
      p->iColumn = (ynVar)iCol;
66867
      p->iColumn = (ynVar)iCol;
66868
      testcase( iCol==BMS );
66869
      testcase( iCol==BMS-1 );
60588
      pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
66870
      pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
60589
    }
66871
    }
60590
    ExprSetProperty(p, EP_Resolved);
66872
    ExprSetProperty(p, EP_Resolved);
 Lines 61429-61452   SQLITE_PRIVATE char sqlite3ExprAffinity( Link Here 
61429
}
67711
}
61430
67712
61431
/*
67713
/*
67714
** Set the explicit collating sequence for an expression to the
67715
** collating sequence supplied in the second argument.
67716
*/
67717
SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Expr *pExpr, CollSeq *pColl){
67718
  if( pExpr && pColl ){
67719
    pExpr->pColl = pColl;
67720
    pExpr->flags |= EP_ExpCollate;
67721
  }
67722
  return pExpr;
67723
}
67724
67725
/*
61432
** Set the collating sequence for expression pExpr to be the collating
67726
** Set the collating sequence for expression pExpr to be the collating
61433
** sequence named by pToken.   Return a pointer to the revised expression.
67727
** sequence named by pToken.   Return a pointer to the revised expression.
61434
** The collating sequence is marked as "explicit" using the EP_ExpCollate
67728
** The collating sequence is marked as "explicit" using the EP_ExpCollate
61435
** flag.  An explicit collating sequence will override implicit
67729
** flag.  An explicit collating sequence will override implicit
61436
** collating sequences.
67730
** collating sequences.
61437
*/
67731
*/
61438
SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Parse *pParse, Expr *pExpr, Token *pCollName){
67732
SQLITE_PRIVATE Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr *pExpr, Token *pCollName){
61439
  char *zColl = 0;            /* Dequoted name of collation sequence */
67733
  char *zColl = 0;            /* Dequoted name of collation sequence */
61440
  CollSeq *pColl;
67734
  CollSeq *pColl;
61441
  sqlite3 *db = pParse->db;
67735
  sqlite3 *db = pParse->db;
61442
  zColl = sqlite3NameFromToken(db, pCollName);
67736
  zColl = sqlite3NameFromToken(db, pCollName);
61443
  if( pExpr && zColl ){
67737
  pColl = sqlite3LocateCollSeq(pParse, zColl);
61444
    pColl = sqlite3LocateCollSeq(pParse, zColl);
67738
  sqlite3ExprSetColl(pExpr, pColl);
61445
    if( pColl ){
61446
      pExpr->pColl = pColl;
61447
      pExpr->flags |= EP_ExpCollate;
61448
    }
61449
  }
61450
  sqlite3DbFree(db, zColl);
67739
  sqlite3DbFree(db, zColl);
61451
  return pExpr;
67740
  return pExpr;
61452
}
67741
}
 Lines 61920-61937   SQLITE_PRIVATE void sqlite3ExprAssignVar Link Here 
61920
  }else if( z[0]=='?' ){
68209
  }else if( z[0]=='?' ){
61921
    /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
68210
    /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
61922
    ** use it as the variable number */
68211
    ** use it as the variable number */
61923
    int i = atoi((char*)&z[1]);
68212
    i64 i;
68213
    int bOk = sqlite3Atoi64(&z[1], &i);
61924
    pExpr->iColumn = (ynVar)i;
68214
    pExpr->iColumn = (ynVar)i;
61925
    testcase( i==0 );
68215
    testcase( i==0 );
61926
    testcase( i==1 );
68216
    testcase( i==1 );
61927
    testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
68217
    testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
61928
    testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
68218
    testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
61929
    if( i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
68219
    if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
61930
      sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
68220
      sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
61931
          db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
68221
          db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
61932
    }
68222
    }
61933
    if( i>pParse->nVar ){
68223
    if( i>pParse->nVar ){
61934
      pParse->nVar = i;
68224
      pParse->nVar = (int)i;
61935
    }
68225
    }
61936
  }else{
68226
  }else{
61937
    /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
68227
    /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
 Lines 62878-62891   SQLITE_PRIVATE int sqlite3FindInIndex(Pa Link Here 
62878
    /* Could not found an existing table or index to use as the RHS b-tree.
69168
    /* Could not found an existing table or index to use as the RHS b-tree.
62879
    ** We will have to generate an ephemeral table to do the job.
69169
    ** We will have to generate an ephemeral table to do the job.
62880
    */
69170
    */
69171
    double savedNQueryLoop = pParse->nQueryLoop;
62881
    int rMayHaveNull = 0;
69172
    int rMayHaveNull = 0;
62882
    eType = IN_INDEX_EPH;
69173
    eType = IN_INDEX_EPH;
62883
    if( prNotFound ){
69174
    if( prNotFound ){
62884
      *prNotFound = rMayHaveNull = ++pParse->nMem;
69175
      *prNotFound = rMayHaveNull = ++pParse->nMem;
62885
    }else if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
69176
    }else{
62886
      eType = IN_INDEX_ROWID;
69177
      testcase( pParse->nQueryLoop>(double)1 );
69178
      pParse->nQueryLoop = (double)1;
69179
      if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
69180
        eType = IN_INDEX_ROWID;
69181
      }
62887
    }
69182
    }
62888
    sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
69183
    sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
69184
    pParse->nQueryLoop = savedNQueryLoop;
62889
  }else{
69185
  }else{
62890
    pX->iTable = iTab;
69186
    pX->iTable = iTab;
62891
  }
69187
  }
 Lines 63008-63014   SQLITE_PRIVATE int sqlite3CodeSubselect( Link Here 
63008
          keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
69304
          keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
63009
              pEList->a[0].pExpr);
69305
              pEList->a[0].pExpr);
63010
        }
69306
        }
63011
      }else if( pExpr->x.pList!=0 ){
69307
      }else if( ALWAYS(pExpr->x.pList!=0) ){
63012
        /* Case 2:     expr IN (exprlist)
69308
        /* Case 2:     expr IN (exprlist)
63013
        **
69309
        **
63014
        ** For each expression, build an index key from the evaluation and
69310
        ** For each expression, build an index key from the evaluation and
 Lines 63078-63084   SQLITE_PRIVATE int sqlite3CodeSubselect( Link Here 
63078
      ** an integer 0 (not exists) or 1 (exists) into a memory cell
69374
      ** an integer 0 (not exists) or 1 (exists) into a memory cell
63079
      ** and record that memory cell in iColumn.
69375
      ** and record that memory cell in iColumn.
63080
      */
69376
      */
63081
      static const Token one = { "1", 1 };  /* Token for literal value 1 */
63082
      Select *pSel;                         /* SELECT statement to encode */
69377
      Select *pSel;                         /* SELECT statement to encode */
63083
      SelectDest dest;                      /* How to deal with SELECt result */
69378
      SelectDest dest;                      /* How to deal with SELECt result */
63084
69379
 Lines 63099-63105   SQLITE_PRIVATE int sqlite3CodeSubselect( Link Here 
63099
        VdbeComment((v, "Init EXISTS result"));
69394
        VdbeComment((v, "Init EXISTS result"));
63100
      }
69395
      }
63101
      sqlite3ExprDelete(pParse->db, pSel->pLimit);
69396
      sqlite3ExprDelete(pParse->db, pSel->pLimit);
63102
      pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &one);
69397
      pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
69398
                                  &sqlite3IntTokens[1]);
63103
      if( sqlite3Select(pParse, pSel, &dest) ){
69399
      if( sqlite3Select(pParse, pSel, &dest) ){
63104
        return 0;
69400
        return 0;
63105
      }
69401
      }
 Lines 63167-63174   static void sqlite3ExprCodeIN( Link Here 
63167
  sqlite3ExprCachePush(pParse);
69463
  sqlite3ExprCachePush(pParse);
63168
  r1 = sqlite3GetTempReg(pParse);
69464
  r1 = sqlite3GetTempReg(pParse);
63169
  sqlite3ExprCode(pParse, pExpr->pLeft, r1);
69465
  sqlite3ExprCode(pParse, pExpr->pLeft, r1);
63170
  sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
69466
63171
69467
  /* If the LHS is NULL, then the result is either false or NULL depending
69468
  ** on whether the RHS is empty or not, respectively.
69469
  */
69470
  if( destIfNull==destIfFalse ){
69471
    /* Shortcut for the common case where the false and NULL outcomes are
69472
    ** the same. */
69473
    sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
69474
  }else{
69475
    int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
69476
    sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
69477
    sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
69478
    sqlite3VdbeJumpHere(v, addr1);
69479
  }
63172
69480
63173
  if( eType==IN_INDEX_ROWID ){
69481
  if( eType==IN_INDEX_ROWID ){
63174
    /* In this case, the RHS is the ROWID of table b-tree
69482
    /* In this case, the RHS is the ROWID of table b-tree
 Lines 63456-63461   static void sqlite3ExprCachePinRegister( Link Here 
63456
}
69764
}
63457
69765
63458
/*
69766
/*
69767
** Generate code to extract the value of the iCol-th column of a table.
69768
*/
69769
SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
69770
  Vdbe *v,        /* The VDBE under construction */
69771
  Table *pTab,    /* The table containing the value */
69772
  int iTabCur,    /* The cursor for this table */
69773
  int iCol,       /* Index of the column to extract */
69774
  int regOut      /* Extract the valud into this register */
69775
){
69776
  if( iCol<0 || iCol==pTab->iPKey ){
69777
    sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
69778
  }else{
69779
    int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
69780
    sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut);
69781
  }
69782
  if( iCol>=0 ){
69783
    sqlite3ColumnDefault(v, pTab, iCol, regOut);
69784
  }
69785
}
69786
69787
/*
63459
** Generate code that will extract the iColumn-th column from
69788
** Generate code that will extract the iColumn-th column from
63460
** table pTab and store the column value in a register.  An effort
69789
** table pTab and store the column value in a register.  An effort
63461
** is made to store the column value in register iReg, but this is
69790
** is made to store the column value in register iReg, but this is
 Lines 63483-63495   SQLITE_PRIVATE int sqlite3ExprCodeGetCol Link Here 
63483
    }
69812
    }
63484
  }  
69813
  }  
63485
  assert( v!=0 );
69814
  assert( v!=0 );
63486
  if( iColumn<0 ){
69815
  sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
63487
    sqlite3VdbeAddOp2(v, OP_Rowid, iTable, iReg);
63488
  }else if( ALWAYS(pTab!=0) ){
63489
    int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
63490
    sqlite3VdbeAddOp3(v, op, iTable, iColumn, iReg);
63491
    sqlite3ColumnDefault(v, pTab, iColumn, iReg);
63492
  }
63493
  sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
69816
  sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
63494
  return iReg;
69817
  return iReg;
63495
}
69818
}
 Lines 63726-63752   SQLITE_PRIVATE int sqlite3ExprCodeTarget Link Here 
63726
    }
70049
    }
63727
#endif
70050
#endif
63728
    case TK_VARIABLE: {
70051
    case TK_VARIABLE: {
63729
      VdbeOp *pOp;
63730
      assert( !ExprHasProperty(pExpr, EP_IntValue) );
70052
      assert( !ExprHasProperty(pExpr, EP_IntValue) );
63731
      assert( pExpr->u.zToken!=0 );
70053
      assert( pExpr->u.zToken!=0 );
63732
      assert( pExpr->u.zToken[0]!=0 );
70054
      assert( pExpr->u.zToken[0]!=0 );
63733
      if( pExpr->u.zToken[1]==0
70055
      sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
63734
         && (pOp = sqlite3VdbeGetOp(v, -1))->opcode==OP_Variable
70056
      if( pExpr->u.zToken[1]!=0 ){
63735
         && pOp->p1+pOp->p3==pExpr->iColumn
70057
        sqlite3VdbeChangeP4(v, -1, pExpr->u.zToken, 0);
63736
         && pOp->p2+pOp->p3==target
63737
         && pOp->p4.z==0
63738
      ){
63739
        /* If the previous instruction was a copy of the previous unnamed
63740
        ** parameter into the previous register, then simply increment the
63741
        ** repeat count on the prior instruction rather than making a new
63742
        ** instruction.
63743
        */
63744
        pOp->p3++;
63745
      }else{
63746
        sqlite3VdbeAddOp3(v, OP_Variable, pExpr->iColumn, target, 1);
63747
        if( pExpr->u.zToken[1]!=0 ){
63748
          sqlite3VdbeChangeP4(v, -1, pExpr->u.zToken, 0);
63749
        }
63750
      }
70058
      }
63751
      break;
70059
      break;
63752
    }
70060
    }
 Lines 64813-64819   SQLITE_PRIVATE void sqlite3ExprIfFalse(P Link Here 
64813
** an incorrect 0 or 1 could lead to a malfunction.
71121
** an incorrect 0 or 1 could lead to a malfunction.
64814
*/
71122
*/
64815
SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
71123
SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
64816
  int i;
64817
  if( pA==0||pB==0 ){
71124
  if( pA==0||pB==0 ){
64818
    return pB==pA ? 0 : 2;
71125
    return pB==pA ? 0 : 2;
64819
  }
71126
  }
 Lines 64826-64843   SQLITE_PRIVATE int sqlite3ExprCompare(Ex Link Here 
64826
  if( pA->op!=pB->op ) return 2;
71133
  if( pA->op!=pB->op ) return 2;
64827
  if( sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 2;
71134
  if( sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 2;
64828
  if( sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 2;
71135
  if( sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 2;
64829
71136
  if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList) ) return 2;
64830
  if( pA->x.pList && pB->x.pList ){
64831
    if( pA->x.pList->nExpr!=pB->x.pList->nExpr ) return 2;
64832
    for(i=0; i<pA->x.pList->nExpr; i++){
64833
      Expr *pExprA = pA->x.pList->a[i].pExpr;
64834
      Expr *pExprB = pB->x.pList->a[i].pExpr;
64835
      if( sqlite3ExprCompare(pExprA, pExprB) ) return 2;
64836
    }
64837
  }else if( pA->x.pList || pB->x.pList ){
64838
    return 2;
64839
  }
64840
64841
  if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 2;
71137
  if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 2;
64842
  if( ExprHasProperty(pA, EP_IntValue) ){
71138
  if( ExprHasProperty(pA, EP_IntValue) ){
64843
    if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
71139
    if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
 Lines 64854-64859   SQLITE_PRIVATE int sqlite3ExprCompare(Ex Link Here 
64854
  return 0;
71150
  return 0;
64855
}
71151
}
64856
71152
71153
/*
71154
** Compare two ExprList objects.  Return 0 if they are identical and 
71155
** non-zero if they differ in any way.
71156
**
71157
** This routine might return non-zero for equivalent ExprLists.  The
71158
** only consequence will be disabled optimizations.  But this routine
71159
** must never return 0 if the two ExprList objects are different, or
71160
** a malfunction will result.
71161
**
71162
** Two NULL pointers are considered to be the same.  But a NULL pointer
71163
** always differs from a non-NULL pointer.
71164
*/
71165
SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB){
71166
  int i;
71167
  if( pA==0 && pB==0 ) return 0;
71168
  if( pA==0 || pB==0 ) return 1;
71169
  if( pA->nExpr!=pB->nExpr ) return 1;
71170
  for(i=0; i<pA->nExpr; i++){
71171
    Expr *pExprA = pA->a[i].pExpr;
71172
    Expr *pExprB = pB->a[i].pExpr;
71173
    if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
71174
    if( sqlite3ExprCompare(pExprA, pExprB) ) return 1;
71175
  }
71176
  return 0;
71177
}
64857
71178
64858
/*
71179
/*
64859
** Add a new element to the pAggInfo->aCol[] array.  Return the index of
71180
** Add a new element to the pAggInfo->aCol[] array.  Return the index of
 Lines 65350-65366   static void renameTriggerFunc( Link Here 
65350
/*
71671
/*
65351
** Register built-in functions used to help implement ALTER TABLE
71672
** Register built-in functions used to help implement ALTER TABLE
65352
*/
71673
*/
65353
SQLITE_PRIVATE void sqlite3AlterFunctions(sqlite3 *db){
71674
SQLITE_PRIVATE void sqlite3AlterFunctions(void){
65354
  sqlite3CreateFunc(db, "sqlite_rename_table", 2, SQLITE_UTF8, 0,
71675
  static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
65355
                         renameTableFunc, 0, 0);
71676
    FUNCTION(sqlite_rename_table,   2, 0, 0, renameTableFunc),
65356
#ifndef SQLITE_OMIT_TRIGGER
71677
#ifndef SQLITE_OMIT_TRIGGER
65357
  sqlite3CreateFunc(db, "sqlite_rename_trigger", 2, SQLITE_UTF8, 0,
71678
    FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
65358
                         renameTriggerFunc, 0, 0);
65359
#endif
71679
#endif
65360
#ifndef SQLITE_OMIT_FOREIGN_KEY
71680
#ifndef SQLITE_OMIT_FOREIGN_KEY
65361
  sqlite3CreateFunc(db, "sqlite_rename_parent", 3, SQLITE_UTF8, 0,
71681
    FUNCTION(sqlite_rename_parent,  3, 0, 0, renameParentFunc),
65362
                         renameParentFunc, 0, 0);
71682
#endif
65363
#endif
71683
  };
71684
  int i;
71685
  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
71686
  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
71687
71688
  for(i=0; i<ArraySize(aAlterTableFuncs); i++){
71689
    sqlite3FuncDefInsert(pHash, &aFunc[i]);
71690
  }
65364
}
71691
}
65365
71692
65366
/*
71693
/*
 Lines 65504-65510   SQLITE_PRIVATE void sqlite3AlterRenameTa Link Here 
65504
  char *zWhere = 0;         /* Where clause to locate temp triggers */
71831
  char *zWhere = 0;         /* Where clause to locate temp triggers */
65505
#endif
71832
#endif
65506
  VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
71833
  VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
65507
  
71834
  int savedDbFlags;         /* Saved value of db->flags */
71835
71836
  savedDbFlags = db->flags;  
65508
  if( NEVER(db->mallocFailed) ) goto exit_rename_table;
71837
  if( NEVER(db->mallocFailed) ) goto exit_rename_table;
65509
  assert( pSrc->nSrc==1 );
71838
  assert( pSrc->nSrc==1 );
65510
  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
71839
  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
 Lines 65513-65518   SQLITE_PRIVATE void sqlite3AlterRenameTa Link Here 
65513
  if( !pTab ) goto exit_rename_table;
71842
  if( !pTab ) goto exit_rename_table;
65514
  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
71843
  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
65515
  zDb = db->aDb[iDb].zName;
71844
  zDb = db->aDb[iDb].zName;
71845
  db->flags |= SQLITE_PreferBuiltin;
65516
71846
65517
  /* Get a NULL terminated version of the new table name. */
71847
  /* Get a NULL terminated version of the new table name. */
65518
  zName = sqlite3NameFromToken(db, pName);
71848
  zName = sqlite3NameFromToken(db, pName);
 Lines 65680-65685   SQLITE_PRIVATE void sqlite3AlterRenameTa Link Here 
65680
exit_rename_table:
72010
exit_rename_table:
65681
  sqlite3SrcListDelete(db, pSrc);
72011
  sqlite3SrcListDelete(db, pSrc);
65682
  sqlite3DbFree(db, zName);
72012
  sqlite3DbFree(db, zName);
72013
  db->flags = savedDbFlags;
65683
}
72014
}
65684
72015
65685
72016
 Lines 65799-65807   SQLITE_PRIVATE void sqlite3AlterFinishAd Link Here 
65799
  zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
72130
  zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
65800
  if( zCol ){
72131
  if( zCol ){
65801
    char *zEnd = &zCol[pColDef->n-1];
72132
    char *zEnd = &zCol[pColDef->n-1];
72133
    int savedDbFlags = db->flags;
65802
    while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
72134
    while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
65803
      *zEnd-- = '\0';
72135
      *zEnd-- = '\0';
65804
    }
72136
    }
72137
    db->flags |= SQLITE_PreferBuiltin;
65805
    sqlite3NestedParse(pParse, 
72138
    sqlite3NestedParse(pParse, 
65806
        "UPDATE \"%w\".%s SET "
72139
        "UPDATE \"%w\".%s SET "
65807
          "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
72140
          "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
 Lines 65810-65815   SQLITE_PRIVATE void sqlite3AlterFinishAd Link Here 
65810
      zTab
72143
      zTab
65811
    );
72144
    );
65812
    sqlite3DbFree(db, zCol);
72145
    sqlite3DbFree(db, zCol);
72146
    db->flags = savedDbFlags;
65813
  }
72147
  }
65814
72148
65815
  /* If the default value of the new column is NULL, then set the file
72149
  /* If the default value of the new column is NULL, then set the file
 Lines 65880-65886   SQLITE_PRIVATE void sqlite3AlterBeginAdd Link Here 
65880
  if( !pNew ) goto exit_begin_add_column;
72214
  if( !pNew ) goto exit_begin_add_column;
65881
  pParse->pNewTable = pNew;
72215
  pParse->pNewTable = pNew;
65882
  pNew->nRef = 1;
72216
  pNew->nRef = 1;
65883
  pNew->dbMem = pTab->dbMem;
65884
  pNew->nCol = pTab->nCol;
72217
  pNew->nCol = pTab->nCol;
65885
  assert( pNew->nCol>0 );
72218
  assert( pNew->nCol>0 );
65886
  nAlloc = (((pNew->nCol-1)/8)*8)+8;
72219
  nAlloc = (((pNew->nCol-1)/8)*8)+8;
 Lines 65955-65961   static void openStatTable( Link Here 
65955
  int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
72288
  int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
65956
  const char *zWhere      /* Delete entries associated with this table */
72289
  const char *zWhere      /* Delete entries associated with this table */
65957
){
72290
){
65958
  static struct {
72291
  static const struct {
65959
    const char *zName;
72292
    const char *zName;
65960
    const char *zCols;
72293
    const char *zCols;
65961
  } aTable[] = {
72294
  } aTable[] = {
 Lines 66409-66429   static int analysisLoader(void *pData, i Link Here 
66409
** If the Index.aSample variable is not NULL, delete the aSample[] array
72742
** If the Index.aSample variable is not NULL, delete the aSample[] array
66410
** and its contents.
72743
** and its contents.
66411
*/
72744
*/
66412
SQLITE_PRIVATE void sqlite3DeleteIndexSamples(Index *pIdx){
72745
SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
66413
#ifdef SQLITE_ENABLE_STAT2
72746
#ifdef SQLITE_ENABLE_STAT2
66414
  if( pIdx->aSample ){
72747
  if( pIdx->aSample ){
66415
    int j;
72748
    int j;
66416
    sqlite3 *dbMem = pIdx->pTable->dbMem;
66417
    for(j=0; j<SQLITE_INDEX_SAMPLES; j++){
72749
    for(j=0; j<SQLITE_INDEX_SAMPLES; j++){
66418
      IndexSample *p = &pIdx->aSample[j];
72750
      IndexSample *p = &pIdx->aSample[j];
66419
      if( p->eType==SQLITE_TEXT || p->eType==SQLITE_BLOB ){
72751
      if( p->eType==SQLITE_TEXT || p->eType==SQLITE_BLOB ){
66420
        sqlite3DbFree(pIdx->pTable->dbMem, p->u.z);
72752
        sqlite3DbFree(db, p->u.z);
66421
      }
72753
      }
66422
    }
72754
    }
66423
    sqlite3DbFree(dbMem, pIdx->aSample);
72755
    sqlite3DbFree(db, pIdx->aSample);
66424
    pIdx->aSample = 0;
72756
  }
66425
  }
72757
#else
66426
#else
72758
  UNUSED_PARAMETER(db);
66427
  UNUSED_PARAMETER(pIdx);
72759
  UNUSED_PARAMETER(pIdx);
66428
#endif
72760
#endif
66429
}
72761
}
 Lines 66462-66468   SQLITE_PRIVATE int sqlite3AnalysisLoad(s Link Here 
66462
  for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
72794
  for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
66463
    Index *pIdx = sqliteHashData(i);
72795
    Index *pIdx = sqliteHashData(i);
66464
    sqlite3DefaultRowEst(pIdx);
72796
    sqlite3DefaultRowEst(pIdx);
66465
    sqlite3DeleteIndexSamples(pIdx);
72797
    sqlite3DeleteIndexSamples(db, pIdx);
72798
    pIdx->aSample = 0;
66466
  }
72799
  }
66467
72800
66468
  /* Check to make sure the sqlite_stat1 table exists */
72801
  /* Check to make sure the sqlite_stat1 table exists */
 Lines 66506-66523   SQLITE_PRIVATE int sqlite3AnalysisLoad(s Link Here 
66506
        Index *pIdx = sqlite3FindIndex(db, zIndex, sInfo.zDatabase);
72839
        Index *pIdx = sqlite3FindIndex(db, zIndex, sInfo.zDatabase);
66507
        if( pIdx ){
72840
        if( pIdx ){
66508
          int iSample = sqlite3_column_int(pStmt, 1);
72841
          int iSample = sqlite3_column_int(pStmt, 1);
66509
          sqlite3 *dbMem = pIdx->pTable->dbMem;
66510
          assert( dbMem==db || dbMem==0 );
66511
          if( iSample<SQLITE_INDEX_SAMPLES && iSample>=0 ){
72842
          if( iSample<SQLITE_INDEX_SAMPLES && iSample>=0 ){
66512
            int eType = sqlite3_column_type(pStmt, 2);
72843
            int eType = sqlite3_column_type(pStmt, 2);
66513
72844
66514
            if( pIdx->aSample==0 ){
72845
            if( pIdx->aSample==0 ){
66515
              static const int sz = sizeof(IndexSample)*SQLITE_INDEX_SAMPLES;
72846
              static const int sz = sizeof(IndexSample)*SQLITE_INDEX_SAMPLES;
66516
              pIdx->aSample = (IndexSample *)sqlite3DbMallocZero(dbMem, sz);
72847
              pIdx->aSample = (IndexSample *)sqlite3DbMallocRaw(0, sz);
66517
              if( pIdx->aSample==0 ){
72848
              if( pIdx->aSample==0 ){
66518
                db->mallocFailed = 1;
72849
                db->mallocFailed = 1;
66519
                break;
72850
                break;
66520
              }
72851
              }
72852
	      memset(pIdx->aSample, 0, sz);
66521
            }
72853
            }
66522
72854
66523
            assert( pIdx->aSample );
72855
            assert( pIdx->aSample );
 Lines 66537-66548   SQLITE_PRIVATE int sqlite3AnalysisLoad(s Link Here 
66537
                  n = 24;
72869
                  n = 24;
66538
                }
72870
                }
66539
                pSample->nByte = (u8)n;
72871
                pSample->nByte = (u8)n;
66540
                pSample->u.z = sqlite3DbMallocRaw(dbMem, n);
72872
                if( n < 1){
66541
                if( pSample->u.z ){
72873
                  pSample->u.z = 0;
66542
                  memcpy(pSample->u.z, z, n);
66543
                }else{
72874
                }else{
66544
                  db->mallocFailed = 1;
72875
                  pSample->u.z = sqlite3DbStrNDup(0, z, n);
66545
                  break;
72876
                  if( pSample->u.z==0 ){
72877
                    db->mallocFailed = 1;
72878
                    break;
72879
                  }
66546
                }
72880
                }
66547
              }
72881
              }
66548
            }
72882
            }
 Lines 66709-66715   static void attachFunc( Link Here 
66709
    }
73043
    }
66710
    pPager = sqlite3BtreePager(aNew->pBt);
73044
    pPager = sqlite3BtreePager(aNew->pBt);
66711
    sqlite3PagerLockingMode(pPager, db->dfltLockMode);
73045
    sqlite3PagerLockingMode(pPager, db->dfltLockMode);
66712
    sqlite3PagerJournalMode(pPager, db->dfltJournalMode);
66713
    sqlite3BtreeSecureDelete(aNew->pBt,
73046
    sqlite3BtreeSecureDelete(aNew->pBt,
66714
                             sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
73047
                             sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
66715
  }
73048
  }
 Lines 66854-66860   detach_error: Link Here 
66854
static void codeAttach(
73187
static void codeAttach(
66855
  Parse *pParse,       /* The parser context */
73188
  Parse *pParse,       /* The parser context */
66856
  int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
73189
  int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
66857
  FuncDef *pFunc,      /* FuncDef wrapper for detachFunc() or attachFunc() */
73190
  FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
66858
  Expr *pAuthArg,      /* Expression to pass to authorization callback */
73191
  Expr *pAuthArg,      /* Expression to pass to authorization callback */
66859
  Expr *pFilename,     /* Name of database file */
73192
  Expr *pFilename,     /* Name of database file */
66860
  Expr *pDbname,       /* Name of the database to use internally */
73193
  Expr *pDbname,       /* Name of the database to use internally */
 Lines 66924-66930   attach_end: Link Here 
66924
**     DETACH pDbname
73257
**     DETACH pDbname
66925
*/
73258
*/
66926
SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
73259
SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
66927
  static FuncDef detach_func = {
73260
  static const FuncDef detach_func = {
66928
    1,                /* nArg */
73261
    1,                /* nArg */
66929
    SQLITE_UTF8,      /* iPrefEnc */
73262
    SQLITE_UTF8,      /* iPrefEnc */
66930
    0,                /* flags */
73263
    0,                /* flags */
 Lines 66945-66951   SQLITE_PRIVATE void sqlite3Detach(Parse Link Here 
66945
**     ATTACH p AS pDbname KEY pKey
73278
**     ATTACH p AS pDbname KEY pKey
66946
*/
73279
*/
66947
SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
73280
SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
66948
  static FuncDef attach_func = {
73281
  static const FuncDef attach_func = {
66949
    3,                /* nArg */
73282
    3,                /* nArg */
66950
    SQLITE_UTF8,      /* iPrefEnc */
73283
    SQLITE_UTF8,      /* iPrefEnc */
66951
    0,                /* flags */
73284
    0,                /* flags */
 Lines 67703-67736   SQLITE_PRIVATE Index *sqlite3FindIndex(s Link Here 
67703
/*
74036
/*
67704
** Reclaim the memory used by an index
74037
** Reclaim the memory used by an index
67705
*/
74038
*/
67706
static void freeIndex(Index *p){
74039
static void freeIndex(sqlite3 *db, Index *p){
67707
  sqlite3 *db = p->pTable->dbMem;
67708
#ifndef SQLITE_OMIT_ANALYZE
74040
#ifndef SQLITE_OMIT_ANALYZE
67709
  sqlite3DeleteIndexSamples(p);
74041
  sqlite3DeleteIndexSamples(db, p);
67710
#endif
74042
#endif
67711
  sqlite3DbFree(db, p->zColAff);
74043
  sqlite3DbFree(db, p->zColAff);
67712
  sqlite3DbFree(db, p);
74044
  sqlite3DbFree(db, p);
67713
}
74045
}
67714
74046
67715
/*
74047
/*
67716
** Remove the given index from the index hash table, and free
67717
** its memory structures.
67718
**
67719
** The index is removed from the database hash tables but
67720
** it is not unlinked from the Table that it indexes.
67721
** Unlinking from the Table must be done by the calling function.
67722
*/
67723
static void sqlite3DeleteIndex(Index *p){
67724
  Index *pOld;
67725
  const char *zName = p->zName;
67726
67727
  pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName,
67728
                           sqlite3Strlen30(zName), 0);
67729
  assert( pOld==0 || pOld==p );
67730
  freeIndex(p);
67731
}
67732
67733
/*
67734
** For the index called zIdxName which is found in the database iDb,
74048
** For the index called zIdxName which is found in the database iDb,
67735
** unlike that index from its Table then remove the index from
74049
** unlike that index from its Table then remove the index from
67736
** the index hash table and free all memory structures associated
74050
** the index hash table and free all memory structures associated
 Lines 67756-67762   SQLITE_PRIVATE void sqlite3UnlinkAndDele Link Here 
67756
        p->pNext = pIndex->pNext;
74070
        p->pNext = pIndex->pNext;
67757
      }
74071
      }
67758
    }
74072
    }
67759
    freeIndex(pIndex);
74073
    freeIndex(db, pIndex);
67760
  }
74074
  }
67761
  db->flags |= SQLITE_InternChanges;
74075
  db->flags |= SQLITE_InternChanges;
67762
}
74076
}
 Lines 67827-67839   SQLITE_PRIVATE void sqlite3CommitInterna Link Here 
67827
}
74141
}
67828
74142
67829
/*
74143
/*
67830
** Clear the column names from a table or view.
74144
** Delete memory allocated for the column names of a table or view (the
67831
*/
74145
** Table.aCol[] array).
67832
static void sqliteResetColumnNames(Table *pTable){
74146
*/
74147
static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
67833
  int i;
74148
  int i;
67834
  Column *pCol;
74149
  Column *pCol;
67835
  sqlite3 *db = pTable->dbMem;
67836
  testcase( db==0 );
67837
  assert( pTable!=0 );
74150
  assert( pTable!=0 );
67838
  if( (pCol = pTable->aCol)!=0 ){
74151
  if( (pCol = pTable->aCol)!=0 ){
67839
    for(i=0; i<pTable->nCol; i++, pCol++){
74152
    for(i=0; i<pTable->nCol; i++, pCol++){
 Lines 67845-67852   static void sqliteResetColumnNames(Table Link Here 
67845
    }
74158
    }
67846
    sqlite3DbFree(db, pTable->aCol);
74159
    sqlite3DbFree(db, pTable->aCol);
67847
  }
74160
  }
67848
  pTable->aCol = 0;
67849
  pTable->nCol = 0;
67850
}
74161
}
67851
74162
67852
/*
74163
/*
 Lines 67858-67899   static void sqliteResetColumnNames(Table Link Here 
67858
** memory structures of the indices and foreign keys associated with 
74169
** memory structures of the indices and foreign keys associated with 
67859
** the table.
74170
** the table.
67860
*/
74171
*/
67861
SQLITE_PRIVATE void sqlite3DeleteTable(Table *pTable){
74172
SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
67862
  Index *pIndex, *pNext;
74173
  Index *pIndex, *pNext;
67863
  sqlite3 *db;
74174
67864
74175
  assert( !pTable || pTable->nRef>0 );
67865
  if( pTable==0 ) return;
67866
  db = pTable->dbMem;
67867
  testcase( db==0 );
67868
74176
67869
  /* Do not delete the table until the reference count reaches zero. */
74177
  /* Do not delete the table until the reference count reaches zero. */
67870
  pTable->nRef--;
74178
  if( !pTable ) return;
67871
  if( pTable->nRef>0 ){
74179
  if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
67872
    return;
74180
67873
  }
74181
  /* Delete all indices associated with this table. */
67874
  assert( pTable->nRef==0 );
67875
67876
  /* Delete all indices associated with this table
67877
  */
67878
  for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
74182
  for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
67879
    pNext = pIndex->pNext;
74183
    pNext = pIndex->pNext;
67880
    assert( pIndex->pSchema==pTable->pSchema );
74184
    assert( pIndex->pSchema==pTable->pSchema );
67881
    sqlite3DeleteIndex(pIndex);
74185
    if( !db || db->pnBytesFreed==0 ){
74186
      char *zName = pIndex->zName; 
74187
      TESTONLY ( Index *pOld = ) sqlite3HashInsert(
74188
	  &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
74189
      );
74190
      assert( pOld==pIndex || pOld==0 );
74191
    }
74192
    freeIndex(db, pIndex);
67882
  }
74193
  }
67883
74194
67884
  /* Delete any foreign keys attached to this table. */
74195
  /* Delete any foreign keys attached to this table. */
67885
  sqlite3FkDelete(pTable);
74196
  sqlite3FkDelete(db, pTable);
67886
74197
67887
  /* Delete the Table structure itself.
74198
  /* Delete the Table structure itself.
67888
  */
74199
  */
67889
  sqliteResetColumnNames(pTable);
74200
  sqliteDeleteColumnNames(db, pTable);
67890
  sqlite3DbFree(db, pTable->zName);
74201
  sqlite3DbFree(db, pTable->zName);
67891
  sqlite3DbFree(db, pTable->zColAff);
74202
  sqlite3DbFree(db, pTable->zColAff);
67892
  sqlite3SelectDelete(db, pTable->pSelect);
74203
  sqlite3SelectDelete(db, pTable->pSelect);
67893
#ifndef SQLITE_OMIT_CHECK
74204
#ifndef SQLITE_OMIT_CHECK
67894
  sqlite3ExprDelete(db, pTable->pCheck);
74205
  sqlite3ExprDelete(db, pTable->pCheck);
67895
#endif
74206
#endif
67896
  sqlite3VtabClear(pTable);
74207
#ifndef SQLITE_OMIT_VIRTUALTABLE
74208
  sqlite3VtabClear(db, pTable);
74209
#endif
67897
  sqlite3DbFree(db, pTable);
74210
  sqlite3DbFree(db, pTable);
67898
}
74211
}
67899
74212
 Lines 67912-67918   SQLITE_PRIVATE void sqlite3UnlinkAndDele Link Here 
67912
  pDb = &db->aDb[iDb];
74225
  pDb = &db->aDb[iDb];
67913
  p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
74226
  p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
67914
                        sqlite3Strlen30(zTabName),0);
74227
                        sqlite3Strlen30(zTabName),0);
67915
  sqlite3DeleteTable(p);
74228
  sqlite3DeleteTable(db, p);
67916
  db->flags |= SQLITE_InternChanges;
74229
  db->flags |= SQLITE_InternChanges;
67917
}
74230
}
67918
74231
 Lines 68180-68186   SQLITE_PRIVATE void sqlite3StartTable( Link Here 
68180
  pTable->iPKey = -1;
74493
  pTable->iPKey = -1;
68181
  pTable->pSchema = db->aDb[iDb].pSchema;
74494
  pTable->pSchema = db->aDb[iDb].pSchema;
68182
  pTable->nRef = 1;
74495
  pTable->nRef = 1;
68183
  pTable->dbMem = 0;
68184
  assert( pParse->pNewTable==0 );
74496
  assert( pParse->pNewTable==0 );
68185
  pParse->pNewTable = pTable;
74497
  pParse->pNewTable = pTable;
68186
74498
 Lines 68732-68738   static char *createTableStmt(sqlite3 *db Link Here 
68732
    zEnd = "\n)";
75044
    zEnd = "\n)";
68733
  }
75045
  }
68734
  n += 35 + 6*p->nCol;
75046
  n += 35 + 6*p->nCol;
68735
  zStmt = sqlite3Malloc( n );
75047
  zStmt = sqlite3DbMallocRaw(0, n);
68736
  if( zStmt==0 ){
75048
  if( zStmt==0 ){
68737
    db->mallocFailed = 1;
75049
    db->mallocFailed = 1;
68738
    return 0;
75050
    return 0;
 Lines 68913-68919   SQLITE_PRIVATE void sqlite3EndTable( Link Here 
68913
        p->aCol = pSelTab->aCol;
75225
        p->aCol = pSelTab->aCol;
68914
        pSelTab->nCol = 0;
75226
        pSelTab->nCol = 0;
68915
        pSelTab->aCol = 0;
75227
        pSelTab->aCol = 0;
68916
        sqlite3DeleteTable(pSelTab);
75228
        sqlite3DeleteTable(db, pSelTab);
68917
      }
75229
      }
68918
    }
75230
    }
68919
75231
 Lines 69157-69163   SQLITE_PRIVATE int sqlite3ViewGetColumnN Link Here 
69157
      pTable->aCol = pSelTab->aCol;
75469
      pTable->aCol = pSelTab->aCol;
69158
      pSelTab->nCol = 0;
75470
      pSelTab->nCol = 0;
69159
      pSelTab->aCol = 0;
75471
      pSelTab->aCol = 0;
69160
      sqlite3DeleteTable(pSelTab);
75472
      sqlite3DeleteTable(db, pSelTab);
69161
      pTable->pSchema->flags |= DB_UnresetViews;
75473
      pTable->pSchema->flags |= DB_UnresetViews;
69162
    }else{
75474
    }else{
69163
      pTable->nCol = 0;
75475
      pTable->nCol = 0;
 Lines 69182-69188   static void sqliteViewResetAll(sqlite3 * Link Here 
69182
  for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
75494
  for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
69183
    Table *pTab = sqliteHashData(i);
75495
    Table *pTab = sqliteHashData(i);
69184
    if( pTab->pSelect ){
75496
    if( pTab->pSelect ){
69185
      sqliteResetColumnNames(pTab);
75497
      sqliteDeleteColumnNames(db, pTab);
75498
      pTab->aCol = 0;
75499
      pTab->nCol = 0;
69186
    }
75500
    }
69187
  }
75501
  }
69188
  DbClearProperty(db, idx, DB_UnresetViews);
75502
  DbClearProperty(db, idx, DB_UnresetViews);
 Lines 69972-69977   SQLITE_PRIVATE Index *sqlite3CreateIndex Link Here 
69972
    if( j>=pTab->nCol ){
76286
    if( j>=pTab->nCol ){
69973
      sqlite3ErrorMsg(pParse, "table %s has no column named %s",
76287
      sqlite3ErrorMsg(pParse, "table %s has no column named %s",
69974
        pTab->zName, zColName);
76288
        pTab->zName, zColName);
76289
      pParse->checkSchema = 1;
69975
      goto exit_create_index;
76290
      goto exit_create_index;
69976
    }
76291
    }
69977
    pIndex->aiColumn[i] = j;
76292
    pIndex->aiColumn[i] = j;
 Lines 70178-70184   SQLITE_PRIVATE Index *sqlite3CreateIndex Link Here 
70178
  /* Clean up before exiting */
76493
  /* Clean up before exiting */
70179
exit_create_index:
76494
exit_create_index:
70180
  if( pIndex ){
76495
  if( pIndex ){
70181
    sqlite3_free(pIndex->zColAff);
76496
    sqlite3DbFree(db, pIndex->zColAff);
70182
    sqlite3DbFree(db, pIndex);
76497
    sqlite3DbFree(db, pIndex);
70183
  }
76498
  }
70184
  sqlite3ExprListDelete(db, pList);
76499
  sqlite3ExprListDelete(db, pList);
 Lines 70557-70563   SQLITE_PRIVATE void sqlite3SrcListDelete Link Here 
70557
    sqlite3DbFree(db, pItem->zName);
76872
    sqlite3DbFree(db, pItem->zName);
70558
    sqlite3DbFree(db, pItem->zAlias);
76873
    sqlite3DbFree(db, pItem->zAlias);
70559
    sqlite3DbFree(db, pItem->zIndex);
76874
    sqlite3DbFree(db, pItem->zIndex);
70560
    sqlite3DeleteTable(pItem->pTab);
76875
    sqlite3DeleteTable(db, pItem->pTab);
70561
    sqlite3SelectDelete(db, pItem->pSelect);
76876
    sqlite3SelectDelete(db, pItem->pSelect);
70562
    sqlite3ExprDelete(db, pItem->pOn);
76877
    sqlite3ExprDelete(db, pItem->pOn);
70563
    sqlite3IdListDelete(db, pItem->pUsing);
76878
    sqlite3IdListDelete(db, pItem->pUsing);
 Lines 70740-70746   SQLITE_PRIVATE void sqlite3Savepoint(Par Link Here 
70740
  if( zName ){
77055
  if( zName ){
70741
    Vdbe *v = sqlite3GetVdbe(pParse);
77056
    Vdbe *v = sqlite3GetVdbe(pParse);
70742
#ifndef SQLITE_OMIT_AUTHORIZATION
77057
#ifndef SQLITE_OMIT_AUTHORIZATION
70743
    static const char *az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
77058
    static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
70744
    assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
77059
    assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
70745
#endif
77060
#endif
70746
    if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
77061
    if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
 Lines 70780-70786   SQLITE_PRIVATE int sqlite3OpenTempDataba Link Here 
70780
      db->mallocFailed = 1;
77095
      db->mallocFailed = 1;
70781
      return 1;
77096
      return 1;
70782
    }
77097
    }
70783
    sqlite3PagerJournalMode(sqlite3BtreePager(pBt), db->dfltJournalMode);
70784
  }
77098
  }
70785
  return 0;
77099
  return 0;
70786
}
77100
}
 Lines 71420-71433   SQLITE_PRIVATE FuncDef *sqlite3FindFunct Link Here 
71420
77734
71421
  /* If no match is found, search the built-in functions.
77735
  /* If no match is found, search the built-in functions.
71422
  **
77736
  **
77737
  ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
77738
  ** functions even if a prior app-defined function was found.  And give
77739
  ** priority to built-in functions.
77740
  **
71423
  ** Except, if createFlag is true, that means that we are trying to
77741
  ** Except, if createFlag is true, that means that we are trying to
71424
  ** install a new function.  Whatever FuncDef structure is returned will
77742
  ** install a new function.  Whatever FuncDef structure is returned will
71425
  ** have fields overwritten with new information appropriate for the
77743
  ** have fields overwritten with new information appropriate for the
71426
  ** new function.  But the FuncDefs for built-in functions are read-only.
77744
  ** new function.  But the FuncDefs for built-in functions are read-only.
71427
  ** So we must not search for built-ins when creating a new function.
77745
  ** So we must not search for built-ins when creating a new function.
71428
  */ 
77746
  */ 
71429
  if( !createFlag && !pBest ){
77747
  if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
71430
    FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
77748
    FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
77749
    bestScore = 0;
71431
    p = functionSearch(pHash, h, zName, nName);
77750
    p = functionSearch(pHash, h, zName, nName);
71432
    while( p ){
77751
    while( p ){
71433
      int score = matchQuality(p, nArg, enc);
77752
      int score = matchQuality(p, nArg, enc);
 Lines 71484-71491   SQLITE_PRIVATE void sqlite3SchemaFree(vo Link Here 
71484
  sqlite3HashInit(&pSchema->tblHash);
77803
  sqlite3HashInit(&pSchema->tblHash);
71485
  for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
77804
  for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
71486
    Table *pTab = sqliteHashData(pElem);
77805
    Table *pTab = sqliteHashData(pElem);
71487
    assert( pTab->dbMem==0 );
77806
    sqlite3DeleteTable(0, pTab);
71488
    sqlite3DeleteTable(pTab);
71489
  }
77807
  }
71490
  sqlite3HashClear(&temp1);
77808
  sqlite3HashClear(&temp1);
71491
  sqlite3HashClear(&pSchema->fkeyHash);
77809
  sqlite3HashClear(&pSchema->fkeyHash);
 Lines 71502-71508   SQLITE_PRIVATE Schema *sqlite3SchemaGet( Link Here 
71502
  if( pBt ){
77820
  if( pBt ){
71503
    p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaFree);
77821
    p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaFree);
71504
  }else{
77822
  }else{
71505
    p = (Schema *)sqlite3MallocZero(sizeof(Schema));
77823
    p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
71506
  }
77824
  }
71507
  if( !p ){
77825
  if( !p ){
71508
    db->mallocFailed = 1;
77826
    db->mallocFailed = 1;
 Lines 71543-71549   SQLITE_PRIVATE Table *sqlite3SrcListLook Link Here 
71543
  Table *pTab;
77861
  Table *pTab;
71544
  assert( pItem && pSrc->nSrc==1 );
77862
  assert( pItem && pSrc->nSrc==1 );
71545
  pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
77863
  pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
71546
  sqlite3DeleteTable(pItem->pTab);
77864
  sqlite3DeleteTable(pParse->db, pItem->pTab);
71547
  pItem->pTab = pTab;
77865
  pItem->pTab = pTab;
71548
  if( pTab ){
77866
  if( pTab ){
71549
    pTab->nRef++;
77867
    pTab->nRef++;
 Lines 72027-72035   SQLITE_PRIVATE void sqlite3GenerateRowDe Link Here 
72027
    sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
78345
    sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
72028
    for(iCol=0; iCol<pTab->nCol; iCol++){
78346
    for(iCol=0; iCol<pTab->nCol; iCol++){
72029
      if( mask==0xffffffff || mask&(1<<iCol) ){
78347
      if( mask==0xffffffff || mask&(1<<iCol) ){
72030
        int iTarget = iOld + iCol + 1;
78348
        sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, iOld+iCol+1);
72031
        sqlite3VdbeAddOp3(v, OP_Column, iCur, iCol, iTarget);
72032
        sqlite3ColumnDefault(v, pTab, iCol, iTarget);
72033
      }
78349
      }
72034
    }
78350
    }
72035
78351
 Lines 72942-72949   static void compileoptionusedFunc( Link Here 
72942
  const char *zOptName;
79258
  const char *zOptName;
72943
  assert( argc==1 );
79259
  assert( argc==1 );
72944
  UNUSED_PARAMETER(argc);
79260
  UNUSED_PARAMETER(argc);
72945
  /* IMP: R-xxxx This function is an SQL wrapper around the
79261
  /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
72946
  ** sqlite3_compileoption_used() C interface. */
79262
  ** function is a wrapper around the sqlite3_compileoption_used() C/C++
79263
  ** function.
79264
  */
72947
  if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
79265
  if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
72948
    sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
79266
    sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
72949
  }
79267
  }
 Lines 72964-72971   static void compileoptiongetFunc( Link Here 
72964
  int n;
79282
  int n;
72965
  assert( argc==1 );
79283
  assert( argc==1 );
72966
  UNUSED_PARAMETER(argc);
79284
  UNUSED_PARAMETER(argc);
72967
  /* IMP: R-xxxx This function is an SQL wrapper around the
79285
  /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
72968
  ** sqlite3_compileoption_get() C interface. */
79286
  ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
79287
  */
72969
  n = sqlite3_value_int(argv[0]);
79288
  n = sqlite3_value_int(argv[0]);
72970
  sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
79289
  sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
72971
}
79290
}
 Lines 73164-73177   static void replaceFunc( Link Here 
73164
      testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
79483
      testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
73165
      if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
79484
      if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
73166
        sqlite3_result_error_toobig(context);
79485
        sqlite3_result_error_toobig(context);
73167
        sqlite3DbFree(db, zOut);
79486
        sqlite3_free(zOut);
73168
        return;
79487
        return;
73169
      }
79488
      }
73170
      zOld = zOut;
79489
      zOld = zOut;
73171
      zOut = sqlite3_realloc(zOut, (int)nOut);
79490
      zOut = sqlite3_realloc(zOut, (int)nOut);
73172
      if( zOut==0 ){
79491
      if( zOut==0 ){
73173
        sqlite3_result_error_nomem(context);
79492
        sqlite3_result_error_nomem(context);
73174
        sqlite3DbFree(db, zOld);
79493
        sqlite3_free(zOld);
73175
        return;
79494
        return;
73176
      }
79495
      }
73177
      memcpy(&zOut[j], zRep, nRep);
79496
      memcpy(&zOut[j], zRep, nRep);
 Lines 73532-73538   static void groupConcatStep( Link Here 
73532
  if( pAccum ){
79851
  if( pAccum ){
73533
    sqlite3 *db = sqlite3_context_db_handle(context);
79852
    sqlite3 *db = sqlite3_context_db_handle(context);
73534
    int firstTerm = pAccum->useMalloc==0;
79853
    int firstTerm = pAccum->useMalloc==0;
73535
    pAccum->useMalloc = 1;
79854
    pAccum->useMalloc = 2;
73536
    pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
79855
    pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
73537
    if( !firstTerm ){
79856
    if( !firstTerm ){
73538
      if( argc==2 ){
79857
      if( argc==2 ){
 Lines 73565-73584   static void groupConcatFinalize(sqlite3_ Link Here 
73565
}
79884
}
73566
79885
73567
/*
79886
/*
73568
** This function registered all of the above C functions as SQL
79887
** This routine does per-connection function registration.  Most
73569
** functions.  This should be the only routine in this file with
79888
** of the built-in functions above are part of the global function set.
73570
** external linkage.
79889
** This routine only deals with those that are not global.
73571
*/
79890
*/
73572
SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
79891
SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
73573
#ifndef SQLITE_OMIT_ALTERTABLE
79892
  int rc = sqlite3_overload_function(db, "MATCH", 2);
73574
  sqlite3AlterFunctions(db);
79893
  assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
73575
#endif
79894
  if( rc==SQLITE_NOMEM ){
73576
  if( !db->mallocFailed ){
79895
    db->mallocFailed = 1;
73577
    int rc = sqlite3_overload_function(db, "MATCH", 2);
73578
    assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
73579
    if( rc==SQLITE_NOMEM ){
73580
      db->mallocFailed = 1;
73581
    }
73582
  }
79896
  }
73583
}
79897
}
73584
79898
 Lines 73746-73751   SQLITE_PRIVATE void sqlite3RegisterGloba Link Here 
73746
    sqlite3FuncDefInsert(pHash, &aFunc[i]);
80060
    sqlite3FuncDefInsert(pHash, &aFunc[i]);
73747
  }
80061
  }
73748
  sqlite3RegisterDateTimeFunctions();
80062
  sqlite3RegisterDateTimeFunctions();
80063
#ifndef SQLITE_OMIT_ALTERTABLE
80064
  sqlite3AlterFunctions();
80065
#endif
73749
}
80066
}
73750
80067
73751
/************** End of func.c ************************************************/
80068
/************** End of func.c ************************************************/
 Lines 74251-74257   static void fkScanChildren( Link Here 
74251
      if( pIdx ){
80568
      if( pIdx ){
74252
        Column *pCol;
80569
        Column *pCol;
74253
        iCol = pIdx->aiColumn[i];
80570
        iCol = pIdx->aiColumn[i];
74254
        pCol = &pIdx->pTable->aCol[iCol];
80571
        pCol = &pTab->aCol[iCol];
80572
        if( pTab->iPKey==iCol ) iCol = -1;
74255
        pLeft->iTable = regData+iCol+1;
80573
        pLeft->iTable = regData+iCol+1;
74256
        pLeft->affinity = pCol->affinity;
80574
        pLeft->affinity = pCol->affinity;
74257
        pLeft->pColl = sqlite3LocateCollSeq(pParse, pCol->zColl);
80575
        pLeft->pColl = sqlite3LocateCollSeq(pParse, pCol->zColl);
 Lines 74812-74822   static Trigger *fkActionTrigger( Link Here 
74812
      pWhere = 0;
81130
      pWhere = 0;
74813
    }
81131
    }
74814
81132
74815
    /* In the current implementation, pTab->dbMem==0 for all tables except
81133
    /* Disable lookaside memory allocation */
74816
    ** for temporary tables used to describe subqueries.  And temporary
74817
    ** tables do not have foreign key constraints.  Hence, pTab->dbMem
74818
    ** should always be 0 there.
74819
    */
74820
    enableLookaside = db->lookaside.bEnabled;
81134
    enableLookaside = db->lookaside.bEnabled;
74821
    db->lookaside.bEnabled = 0;
81135
    db->lookaside.bEnabled = 0;
74822
81136
 Lines 74906-74942   SQLITE_PRIVATE void sqlite3FkActions( Link Here 
74906
** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
81220
** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
74907
** hash table.
81221
** hash table.
74908
*/
81222
*/
74909
SQLITE_PRIVATE void sqlite3FkDelete(Table *pTab){
81223
SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
74910
  FKey *pFKey;                    /* Iterator variable */
81224
  FKey *pFKey;                    /* Iterator variable */
74911
  FKey *pNext;                    /* Copy of pFKey->pNextFrom */
81225
  FKey *pNext;                    /* Copy of pFKey->pNextFrom */
74912
81226
74913
  for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
81227
  for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
74914
81228
74915
    /* Remove the FK from the fkeyHash hash table. */
81229
    /* Remove the FK from the fkeyHash hash table. */
74916
    if( pFKey->pPrevTo ){
81230
    if( !db || db->pnBytesFreed==0 ){
74917
      pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
81231
      if( pFKey->pPrevTo ){
74918
    }else{
81232
        pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
74919
      void *data = (void *)pFKey->pNextTo;
81233
      }else{
74920
      const char *z = (data ? pFKey->pNextTo->zTo : pFKey->zTo);
81234
        void *p = (void *)pFKey->pNextTo;
74921
      sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), data);
81235
        const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
74922
    }
81236
        sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), p);
74923
    if( pFKey->pNextTo ){
81237
      }
74924
      pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
81238
      if( pFKey->pNextTo ){
74925
    }
81239
        pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
81240
      }
81241
    }
81242
81243
    /* EV: R-30323-21917 Each foreign key constraint in SQLite is
81244
    ** classified as either immediate or deferred.
81245
    */
81246
    assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
74926
81247
74927
    /* Delete any triggers created to implement actions for this FK. */
81248
    /* Delete any triggers created to implement actions for this FK. */
74928
#ifndef SQLITE_OMIT_TRIGGER
81249
#ifndef SQLITE_OMIT_TRIGGER
74929
    fkTriggerDelete(pTab->dbMem, pFKey->apTrigger[0]);
81250
    fkTriggerDelete(db, pFKey->apTrigger[0]);
74930
    fkTriggerDelete(pTab->dbMem, pFKey->apTrigger[1]);
81251
    fkTriggerDelete(db, pFKey->apTrigger[1]);
74931
#endif
81252
#endif
74932
74933
    /* EV: R-30323-21917 Each foreign key constraint in SQLite is
74934
    ** classified as either immediate or deferred.
74935
    */
74936
    assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
74937
81253
74938
    pNext = pFKey->pNextFrom;
81254
    pNext = pFKey->pNextFrom;
74939
    sqlite3DbFree(pTab->dbMem, pFKey);
81255
    sqlite3DbFree(db, pFKey);
74940
  }
81256
  }
74941
}
81257
}
74942
#endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
81258
#endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
 Lines 75011-75017   SQLITE_PRIVATE const char *sqlite3IndexA Link Here 
75011
    int n;
81327
    int n;
75012
    Table *pTab = pIdx->pTable;
81328
    Table *pTab = pIdx->pTable;
75013
    sqlite3 *db = sqlite3VdbeDb(v);
81329
    sqlite3 *db = sqlite3VdbeDb(v);
75014
    pIdx->zColAff = (char *)sqlite3Malloc(pIdx->nColumn+2);
81330
    pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+2);
75015
    if( !pIdx->zColAff ){
81331
    if( !pIdx->zColAff ){
75016
      db->mallocFailed = 1;
81332
      db->mallocFailed = 1;
75017
      return 0;
81333
      return 0;
 Lines 75053-75059   SQLITE_PRIVATE void sqlite3TableAffinity Link Here 
75053
    int i;
81369
    int i;
75054
    sqlite3 *db = sqlite3VdbeDb(v);
81370
    sqlite3 *db = sqlite3VdbeDb(v);
75055
81371
75056
    zColAff = (char *)sqlite3Malloc(pTab->nCol+1);
81372
    zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
75057
    if( !zColAff ){
81373
    if( !zColAff ){
75058
      db->mallocFailed = 1;
81374
      db->mallocFailed = 1;
75059
      return;
81375
      return;
 Lines 75671-75677   SQLITE_PRIVATE void sqlite3Insert( Link Here 
75671
        }else{
81987
        }else{
75672
          sqlite3ErrorMsg(pParse, "table %S has no column named %s",
81988
          sqlite3ErrorMsg(pParse, "table %S has no column named %s",
75673
              pTabList, 0, pColumn->a[i].zName);
81989
              pTabList, 0, pColumn->a[i].zName);
75674
          pParse->nErr++;
81990
          pParse->checkSchema = 1;
75675
          goto insert_cleanup;
81991
          goto insert_cleanup;
75676
        }
81992
        }
75677
      }
81993
      }
 Lines 75790-75796   SQLITE_PRIVATE void sqlite3Insert( Link Here 
75790
          if( pColumn->a[j].idx==i ) break;
82106
          if( pColumn->a[j].idx==i ) break;
75791
        }
82107
        }
75792
      }
82108
      }
75793
      if( pColumn && j>=pColumn->nId ){
82109
      if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
75794
        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
82110
        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
75795
      }else if( useTempTable ){
82111
      }else if( useTempTable ){
75796
        sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1); 
82112
        sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1); 
 Lines 76164-76169   SQLITE_PRIVATE void sqlite3GenerateConst Link Here 
76164
    if( onError==OE_Ignore ){
82480
    if( onError==OE_Ignore ){
76165
      sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
82481
      sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
76166
    }else{
82482
    }else{
82483
      if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
76167
      sqlite3HaltConstraint(pParse, onError, 0, 0);
82484
      sqlite3HaltConstraint(pParse, onError, 0, 0);
76168
    }
82485
    }
76169
    sqlite3VdbeResolveLabel(v, allOk);
82486
    sqlite3VdbeResolveLabel(v, allOk);
 Lines 77678-77690   static int sqlite3LoadExtension( Link Here 
77678
  handle = sqlite3OsDlOpen(pVfs, zFile);
83995
  handle = sqlite3OsDlOpen(pVfs, zFile);
77679
  if( handle==0 ){
83996
  if( handle==0 ){
77680
    if( pzErrMsg ){
83997
    if( pzErrMsg ){
77681
      zErrmsg = sqlite3StackAllocZero(db, nMsg);
83998
      *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
77682
      if( zErrmsg ){
83999
      if( zErrmsg ){
77683
        sqlite3_snprintf(nMsg, zErrmsg, 
84000
        sqlite3_snprintf(nMsg, zErrmsg, 
77684
            "unable to open shared library [%s]", zFile);
84001
            "unable to open shared library [%s]", zFile);
77685
        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
84002
        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
77686
        *pzErrMsg = sqlite3DbStrDup(0, zErrmsg);
77687
        sqlite3StackFree(db, zErrmsg);
77688
      }
84003
      }
77689
    }
84004
    }
77690
    return SQLITE_ERROR;
84005
    return SQLITE_ERROR;
 Lines 77693-77705   static int sqlite3LoadExtension( Link Here 
77693
                   sqlite3OsDlSym(pVfs, handle, zProc);
84008
                   sqlite3OsDlSym(pVfs, handle, zProc);
77694
  if( xInit==0 ){
84009
  if( xInit==0 ){
77695
    if( pzErrMsg ){
84010
    if( pzErrMsg ){
77696
      zErrmsg = sqlite3StackAllocZero(db, nMsg);
84011
      *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
77697
      if( zErrmsg ){
84012
      if( zErrmsg ){
77698
        sqlite3_snprintf(nMsg, zErrmsg,
84013
        sqlite3_snprintf(nMsg, zErrmsg,
77699
            "no entry point [%s] in shared library [%s]", zProc,zFile);
84014
            "no entry point [%s] in shared library [%s]", zProc,zFile);
77700
        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
84015
        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
77701
        *pzErrMsg = sqlite3DbStrDup(0, zErrmsg);
77702
        sqlite3StackFree(db, zErrmsg);
77703
      }
84016
      }
77704
      sqlite3OsDlClose(pVfs, handle);
84017
      sqlite3OsDlClose(pVfs, handle);
77705
    }
84018
    }
 Lines 78086-78091   static int flagPragma(Parse *pParse, con Link Here 
78086
    { "legacy_file_format",       SQLITE_LegacyFileFmt },
84399
    { "legacy_file_format",       SQLITE_LegacyFileFmt },
78087
    { "fullfsync",                SQLITE_FullFSync     },
84400
    { "fullfsync",                SQLITE_FullFSync     },
78088
    { "reverse_unordered_selects", SQLITE_ReverseOrder  },
84401
    { "reverse_unordered_selects", SQLITE_ReverseOrder  },
84402
#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
84403
    { "automatic_index",          SQLITE_AutoIndex     },
84404
#endif
78089
#ifdef SQLITE_DEBUG
84405
#ifdef SQLITE_DEBUG
78090
    { "sql_trace",                SQLITE_SqlTrace      },
84406
    { "sql_trace",                SQLITE_SqlTrace      },
78091
    { "vdbe_listing",             SQLITE_VdbeListing   },
84407
    { "vdbe_listing",             SQLITE_VdbeListing   },
 Lines 78167-78172   static const char *actionName(u8 action) Link Here 
78167
}
84483
}
78168
#endif
84484
#endif
78169
84485
84486
84487
/*
84488
** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
84489
** defined in pager.h. This function returns the associated lowercase
84490
** journal-mode name.
84491
*/
84492
SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
84493
  static char * const azModeName[] = {
84494
    "delete", "persist", "off", "truncate", "memory"
84495
#ifndef SQLITE_OMIT_WAL
84496
     , "wal"
84497
#endif
84498
  };
84499
  assert( PAGER_JOURNALMODE_DELETE==0 );
84500
  assert( PAGER_JOURNALMODE_PERSIST==1 );
84501
  assert( PAGER_JOURNALMODE_OFF==2 );
84502
  assert( PAGER_JOURNALMODE_TRUNCATE==3 );
84503
  assert( PAGER_JOURNALMODE_MEMORY==4 );
84504
  assert( PAGER_JOURNALMODE_WAL==5 );
84505
  assert( eMode>=0 && eMode<=ArraySize(azModeName) );
84506
84507
  if( eMode==ArraySize(azModeName) ) return 0;
84508
  return azModeName[eMode];
84509
}
84510
78170
/*
84511
/*
78171
** Process a pragma statement.  
84512
** Process a pragma statement.  
78172
**
84513
**
 Lines 78239-78249   SQLITE_PRIVATE void sqlite3Pragma( Link Here 
78239
  ** page cache size value and the persistent page cache size value
84580
  ** page cache size value and the persistent page cache size value
78240
  ** stored in the database file.
84581
  ** stored in the database file.
78241
  **
84582
  **
78242
  ** The default cache size is stored in meta-value 2 of page 1 of the
84583
  ** Older versions of SQLite would set the default cache size to a
78243
  ** database file.  The cache size is actually the absolute value of
84584
  ** negative number to indicate synchronous=OFF.  These days, synchronous
78244
  ** this memory location.  The sign of meta-value 2 determines the
84585
  ** is always on by default regardless of the sign of the default cache
78245
  ** synchronous setting.  A negative value means synchronous is off
84586
  ** size.  But continue to take the absolute value of the default cache
78246
  ** and a positive value means synchronous is on.
84587
  ** size of historical compatibility.
78247
  */
84588
  */
78248
  if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
84589
  if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
78249
    static const VdbeOpList getCacheSize[] = {
84590
    static const VdbeOpList getCacheSize[] = {
 Lines 78272-78281   SQLITE_PRIVATE void sqlite3Pragma( Link Here 
78272
      if( size<0 ) size = -size;
84613
      if( size<0 ) size = -size;
78273
      sqlite3BeginWriteOperation(pParse, 0, iDb);
84614
      sqlite3BeginWriteOperation(pParse, 0, iDb);
78274
      sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
84615
      sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
78275
      sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, 2, BTREE_DEFAULT_CACHE_SIZE);
78276
      addr = sqlite3VdbeAddOp2(v, OP_IfPos, 2, 0);
78277
      sqlite3VdbeAddOp2(v, OP_Integer, -size, 1);
78278
      sqlite3VdbeJumpHere(v, addr);
78279
      sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
84616
      sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
78280
      pDb->pSchema->cache_size = size;
84617
      pDb->pSchema->cache_size = size;
78281
      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
84618
      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
 Lines 78420-78481   SQLITE_PRIVATE void sqlite3Pragma( Link Here 
78420
84757
78421
  /*
84758
  /*
78422
  **  PRAGMA [database.]journal_mode
84759
  **  PRAGMA [database.]journal_mode
78423
  **  PRAGMA [database.]journal_mode = (delete|persist|off|truncate|memory)
84760
  **  PRAGMA [database.]journal_mode =
84761
  **                      (delete|persist|off|truncate|memory|wal|off)
78424
  */
84762
  */
78425
  if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
84763
  if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
78426
    int eMode;
84764
    int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
78427
    static char * const azModeName[] = {
84765
    int ii;           /* Loop counter */
78428
      "delete", "persist", "off", "truncate", "memory"
84766
78429
    };
84767
    /* Force the schema to be loaded on all databases.  This cases all
78430
84768
    ** database files to be opened and the journal_modes set. */
78431
    if( zRight==0 ){
84769
    if( sqlite3ReadSchema(pParse) ){
78432
      eMode = PAGER_JOURNALMODE_QUERY;
84770
      goto pragma_out;
78433
    }else{
84771
    }
78434
      int n = sqlite3Strlen30(zRight);
84772
78435
      eMode = sizeof(azModeName)/sizeof(azModeName[0]) - 1;
78436
      while( eMode>=0 && sqlite3StrNICmp(zRight, azModeName[eMode], n)!=0 ){
78437
        eMode--;
78438
      }
78439
    }
78440
    if( pId2->n==0 && eMode==PAGER_JOURNALMODE_QUERY ){
78441
      /* Simple "PRAGMA journal_mode;" statement. This is a query for
78442
      ** the current default journal mode (which may be different to
78443
      ** the journal-mode of the main database).
78444
      */
78445
      eMode = db->dfltJournalMode;
78446
    }else{
78447
      Pager *pPager;
78448
      if( pId2->n==0 ){
78449
        /* This indicates that no database name was specified as part
78450
        ** of the PRAGMA command. In this case the journal-mode must be
78451
        ** set on all attached databases, as well as the main db file.
78452
        **
78453
        ** Also, the sqlite3.dfltJournalMode variable is set so that
78454
        ** any subsequently attached databases also use the specified
78455
        ** journal mode.
78456
        */
78457
        int ii;
78458
        assert(pDb==&db->aDb[0]);
78459
        for(ii=1; ii<db->nDb; ii++){
78460
          if( db->aDb[ii].pBt ){
78461
            pPager = sqlite3BtreePager(db->aDb[ii].pBt);
78462
            sqlite3PagerJournalMode(pPager, eMode);
78463
          }
78464
        }
78465
        db->dfltJournalMode = (u8)eMode;
78466
      }
78467
      pPager = sqlite3BtreePager(pDb->pBt);
78468
      eMode = sqlite3PagerJournalMode(pPager, eMode);
78469
    }
78470
    assert( eMode==PAGER_JOURNALMODE_DELETE
78471
              || eMode==PAGER_JOURNALMODE_TRUNCATE
78472
              || eMode==PAGER_JOURNALMODE_PERSIST
78473
              || eMode==PAGER_JOURNALMODE_OFF
78474
              || eMode==PAGER_JOURNALMODE_MEMORY );
78475
    sqlite3VdbeSetNumCols(v, 1);
84773
    sqlite3VdbeSetNumCols(v, 1);
78476
    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
84774
    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
78477
    sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, 
84775
78478
           azModeName[eMode], P4_STATIC);
84776
    if( zRight==0 ){
84777
      /* If there is no "=MODE" part of the pragma, do a query for the
84778
      ** current mode */
84779
      eMode = PAGER_JOURNALMODE_QUERY;
84780
    }else{
84781
      const char *zMode;
84782
      int n = sqlite3Strlen30(zRight);
84783
      for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
84784
        if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
84785
      }
84786
      if( !zMode ){
84787
        /* If the "=MODE" part does not match any known journal mode,
84788
        ** then do a query */
84789
        eMode = PAGER_JOURNALMODE_QUERY;
84790
      }
84791
    }
84792
    if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
84793
      /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
84794
      iDb = 0;
84795
      pId2->n = 1;
84796
    }
84797
    for(ii=db->nDb-1; ii>=0; ii--){
84798
      if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
84799
        sqlite3VdbeUsesBtree(v, ii);
84800
        sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
84801
      }
84802
    }
78479
    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
84803
    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
78480
  }else
84804
  }else
78481
84805
 Lines 78667-78673   SQLITE_PRIVATE void sqlite3Pragma( Link Here 
78667
      }
84991
      }
78668
      sqlite3_free(sqlite3_temp_directory);
84992
      sqlite3_free(sqlite3_temp_directory);
78669
      if( zRight[0] ){
84993
      if( zRight[0] ){
78670
        sqlite3_temp_directory = sqlite3DbStrDup(0, zRight);
84994
        sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
78671
      }else{
84995
      }else{
78672
        sqlite3_temp_directory = 0;
84996
        sqlite3_temp_directory = 0;
78673
      }
84997
      }
 Lines 79293-79298   SQLITE_PRIVATE void sqlite3Pragma( Link Here 
79293
  }else
85617
  }else
79294
#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
85618
#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
79295
85619
85620
#ifndef SQLITE_OMIT_WAL
85621
  /*
85622
  **   PRAGMA [database.]wal_checkpoint
85623
  **
85624
  ** Checkpoint the database.
85625
  */
85626
  if( sqlite3StrICmp(zLeft, "wal_checkpoint")==0 ){
85627
    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
85628
    sqlite3VdbeAddOp3(v, OP_Checkpoint, pId2->z?iDb:SQLITE_MAX_ATTACHED, 0, 0);
85629
  }else
85630
85631
  /*
85632
  **   PRAGMA wal_autocheckpoint
85633
  **   PRAGMA wal_autocheckpoint = N
85634
  **
85635
  ** Configure a database connection to automatically checkpoint a database
85636
  ** after accumulating N frames in the log. Or query for the current value
85637
  ** of N.
85638
  */
85639
  if( sqlite3StrICmp(zLeft, "wal_autocheckpoint")==0 ){
85640
    if( zRight ){
85641
      int nAuto = atoi(zRight);
85642
      sqlite3_wal_autocheckpoint(db, nAuto);
85643
    }
85644
    returnSingleInt(pParse, "wal_autocheckpoint", 
85645
       db->xWalCallback==sqlite3WalDefaultHook ? 
85646
           SQLITE_PTR_TO_INT(db->pWalArg) : 0);
85647
  }else
85648
#endif
85649
79296
#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
85650
#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
79297
  /*
85651
  /*
79298
  ** Report the current state of file logs for all databases
85652
  ** Report the current state of file logs for all databases
 Lines 79461-79475   SQLITE_PRIVATE int sqlite3InitCallback(v Link Here 
79461
    ** or executed.  All the parser does is build the internal data
85815
    ** or executed.  All the parser does is build the internal data
79462
    ** structures that describe the table, index, or view.
85816
    ** structures that describe the table, index, or view.
79463
    */
85817
    */
79464
    char *zErr;
79465
    int rc;
85818
    int rc;
85819
    sqlite3_stmt *pStmt;
85820
    TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */
85821
79466
    assert( db->init.busy );
85822
    assert( db->init.busy );
79467
    db->init.iDb = iDb;
85823
    db->init.iDb = iDb;
79468
    db->init.newTnum = atoi(argv[1]);
85824
    db->init.newTnum = atoi(argv[1]);
79469
    db->init.orphanTrigger = 0;
85825
    db->init.orphanTrigger = 0;
79470
    rc = sqlite3_exec(db, argv[2], 0, 0, &zErr);
85826
    TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
85827
    rc = db->errCode;
85828
    assert( (rc&0xFF)==(rcp&0xFF) );
79471
    db->init.iDb = 0;
85829
    db->init.iDb = 0;
79472
    assert( rc!=SQLITE_OK || zErr==0 );
79473
    if( SQLITE_OK!=rc ){
85830
    if( SQLITE_OK!=rc ){
79474
      if( db->init.orphanTrigger ){
85831
      if( db->init.orphanTrigger ){
79475
        assert( iDb==1 );
85832
        assert( iDb==1 );
 Lines 79477-79488   SQLITE_PRIVATE int sqlite3InitCallback(v Link Here 
79477
        pData->rc = rc;
85834
        pData->rc = rc;
79478
        if( rc==SQLITE_NOMEM ){
85835
        if( rc==SQLITE_NOMEM ){
79479
          db->mallocFailed = 1;
85836
          db->mallocFailed = 1;
79480
        }else if( rc!=SQLITE_INTERRUPT && rc!=SQLITE_LOCKED ){
85837
        }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
79481
          corruptSchema(pData, argv[0], zErr);
85838
          corruptSchema(pData, argv[0], sqlite3_errmsg(db));
79482
        }
85839
        }
79483
      }
85840
      }
79484
      sqlite3DbFree(db, zErr);
85841
    }
79485
    }
85842
    sqlite3_finalize(pStmt);
79486
  }else if( argv[0]==0 ){
85843
  }else if( argv[0]==0 ){
79487
    corruptSchema(pData, 0, 0);
85844
    corruptSchema(pData, 0, 0);
79488
  }else{
85845
  }else{
 Lines 79967-79972   static int sqlite3Prepare( Link Here 
79967
  sqlite3VtabUnlockList(db);
86324
  sqlite3VtabUnlockList(db);
79968
86325
79969
  pParse->db = db;
86326
  pParse->db = db;
86327
  pParse->nQueryLoop = (double)1;
79970
  if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
86328
  if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
79971
    char *zSqlCopy;
86329
    char *zSqlCopy;
79972
    int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
86330
    int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
 Lines 79988-79993   static int sqlite3Prepare( Link Here 
79988
  }else{
86346
  }else{
79989
    sqlite3RunParser(pParse, zSql, &zErrMsg);
86347
    sqlite3RunParser(pParse, zSql, &zErrMsg);
79990
  }
86348
  }
86349
  assert( 1==(int)pParse->nQueryLoop );
79991
86350
79992
  if( db->mallocFailed ){
86351
  if( db->mallocFailed ){
79993
    pParse->rc = SQLITE_NOMEM;
86352
    pParse->rc = SQLITE_NOMEM;
 Lines 80053-80059   static int sqlite3Prepare( Link Here 
80053
  while( pParse->pTriggerPrg ){
86412
  while( pParse->pTriggerPrg ){
80054
    TriggerPrg *pT = pParse->pTriggerPrg;
86413
    TriggerPrg *pT = pParse->pTriggerPrg;
80055
    pParse->pTriggerPrg = pT->pNext;
86414
    pParse->pTriggerPrg = pT->pNext;
80056
    sqlite3VdbeProgramDelete(db, pT->pProgram, 0);
80057
    sqlite3DbFree(db, pT);
86415
    sqlite3DbFree(db, pT);
80058
  }
86416
  }
80059
86417
 Lines 81544-81559   SQLITE_PRIVATE Table *sqlite3ResultSetOf Link Here 
81544
    return 0;
87902
    return 0;
81545
  }
87903
  }
81546
  /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
87904
  /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
81547
  ** is disabled, so we might as well hard-code pTab->dbMem to NULL. */
87905
  ** is disabled */
81548
  assert( db->lookaside.bEnabled==0 );
87906
  assert( db->lookaside.bEnabled==0 );
81549
  pTab->dbMem = 0;
81550
  pTab->nRef = 1;
87907
  pTab->nRef = 1;
81551
  pTab->zName = 0;
87908
  pTab->zName = 0;
81552
  selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
87909
  selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
81553
  selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
87910
  selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
81554
  pTab->iPKey = -1;
87911
  pTab->iPKey = -1;
81555
  if( db->mallocFailed ){
87912
  if( db->mallocFailed ){
81556
    sqlite3DeleteTable(pTab);
87913
    sqlite3DeleteTable(db, pTab);
81557
    return 0;
87914
    return 0;
81558
  }
87915
  }
81559
  return pTab;
87916
  return pTab;
 Lines 82045-82051   multi_select_end: Link Here 
82045
** regReturn is the number of the register holding the subroutine
88402
** regReturn is the number of the register holding the subroutine
82046
** return address.
88403
** return address.
82047
**
88404
**
82048
** If regPrev>0 then it is a the first register in a vector that
88405
** If regPrev>0 then it is the first register in a vector that
82049
** records the previous output.  mem[regPrev] is a flag that is false
88406
** records the previous output.  mem[regPrev] is a flag that is false
82050
** if there has been no previous output.  If regPrev>0 then code is
88407
** if there has been no previous output.  If regPrev>0 then code is
82051
** generated to suppress duplicates.  pKeyInfo is used for comparing
88408
** generated to suppress duplicates.  pKeyInfo is used for comparing
 Lines 82742-82753   static void substSelect( Link Here 
82742
**   (2)  The subquery is not an aggregate or the outer query is not a join.
89099
**   (2)  The subquery is not an aggregate or the outer query is not a join.
82743
**
89100
**
82744
**   (3)  The subquery is not the right operand of a left outer join
89101
**   (3)  The subquery is not the right operand of a left outer join
82745
**        (Originally ticket #306.  Strenghtened by ticket #3300)
89102
**        (Originally ticket #306.  Strengthened by ticket #3300)
82746
**
89103
**
82747
**   (4)  The subquery is not DISTINCT or the outer query is not a join.
89104
**   (4)  The subquery is not DISTINCT.
82748
**
89105
**
82749
**   (5)  The subquery is not DISTINCT or the outer query does not use
89106
**  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
82750
**        aggregates.
89107
**        sub-queries that were excluded from this optimization. Restriction 
89108
**        (4) has since been expanded to exclude all DISTINCT subqueries.
82751
**
89109
**
82752
**   (6)  The subquery does not use aggregates or the outer query is not
89110
**   (6)  The subquery does not use aggregates or the outer query is not
82753
**        DISTINCT.
89111
**        DISTINCT.
 Lines 82767-82779   static void substSelect( Link Here 
82767
**  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
89125
**  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
82768
**        a separate restriction deriving from ticket #350.
89126
**        a separate restriction deriving from ticket #350.
82769
**
89127
**
82770
**  (13)  The subquery and outer query do not both use LIMIT
89128
**  (13)  The subquery and outer query do not both use LIMIT.
82771
**
89129
**
82772
**  (14)  The subquery does not use OFFSET
89130
**  (14)  The subquery does not use OFFSET.
82773
**
89131
**
82774
**  (15)  The outer query is not part of a compound select or the
89132
**  (15)  The outer query is not part of a compound select or the
82775
**        subquery does not have both an ORDER BY and a LIMIT clause.
89133
**        subquery does not have a LIMIT clause.
82776
**        (See ticket #2339)
89134
**        (See ticket #2339 and ticket [02a8e81d44]).
82777
**
89135
**
82778
**  (16)  The outer query is not an aggregate or the subquery does
89136
**  (16)  The outer query is not an aggregate or the subquery does
82779
**        not contain ORDER BY.  (Ticket #2942)  This used to not matter
89137
**        not contain ORDER BY.  (Ticket #2942)  This used to not matter
 Lines 82856-82868   static int flattenSubquery( Link Here 
82856
  ** and (14). */
89214
  ** and (14). */
82857
  if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
89215
  if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
82858
  if( pSub->pOffset ) return 0;                          /* Restriction (14) */
89216
  if( pSub->pOffset ) return 0;                          /* Restriction (14) */
82859
  if( p->pRightmost && pSub->pLimit && pSub->pOrderBy ){
89217
  if( p->pRightmost && pSub->pLimit ){
82860
    return 0;                                            /* Restriction (15) */
89218
    return 0;                                            /* Restriction (15) */
82861
  }
89219
  }
82862
  if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
89220
  if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
82863
  if( ((pSub->selFlags & SF_Distinct)!=0 || pSub->pLimit) 
89221
  if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */
82864
         && (pSrc->nSrc>1 || isAgg) ){          /* Restrictions (4)(5)(8)(9) */
89222
  if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
82865
     return 0;       
89223
     return 0;         /* Restrictions (8)(9) */
82866
  }
89224
  }
82867
  if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
89225
  if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
82868
     return 0;         /* Restriction (6)  */
89226
     return 0;         /* Restriction (6)  */
 Lines 83266-83271   SQLITE_PRIVATE int sqlite3IndexedByLooku Link Here 
83266
    );
89624
    );
83267
    if( !pIdx ){
89625
    if( !pIdx ){
83268
      sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
89626
      sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
89627
      pParse->checkSchema = 1;
83269
      return SQLITE_ERROR;
89628
      return SQLITE_ERROR;
83270
    }
89629
    }
83271
    pFrom->pIndex = pIdx;
89630
    pFrom->pIndex = pIdx;
 Lines 83341-83347   static int selectExpander(Walker *pWalke Link Here 
83341
      sqlite3WalkSelect(pWalker, pSel);
89700
      sqlite3WalkSelect(pWalker, pSel);
83342
      pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
89701
      pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
83343
      if( pTab==0 ) return WRC_Abort;
89702
      if( pTab==0 ) return WRC_Abort;
83344
      pTab->dbMem = db->lookaside.bEnabled ? db : 0;
83345
      pTab->nRef = 1;
89703
      pTab->nRef = 1;
83346
      pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
89704
      pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
83347
      while( pSel->pPrior ){ pSel = pSel->pPrior; }
89705
      while( pSel->pPrior ){ pSel = pSel->pPrior; }
 Lines 83744-83749   static void updateAccumulator(Parse *pPa Link Here 
83744
      sqlite3ExprCacheClear(pParse);
90102
      sqlite3ExprCacheClear(pParse);
83745
    }
90103
    }
83746
  }
90104
  }
90105
90106
  /* Before populating the accumulator registers, clear the column cache.
90107
  ** Otherwise, if any of the required column values are already present 
90108
  ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
90109
  ** to pC->iMem. But by the time the value is used, the original register
90110
  ** may have been used, invalidating the underlying buffer holding the
90111
  ** text or blob value. See ticket [883034dcb5].
90112
  **
90113
  ** Another solution would be to change the OP_SCopy used to copy cached
90114
  ** values to an OP_Copy.
90115
  */
90116
  sqlite3ExprCacheClear(pParse);
83747
  for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
90117
  for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
83748
    sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
90118
    sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
83749
  }
90119
  }
 Lines 83952-83957   SQLITE_PRIVATE int sqlite3Select( Link Here 
83952
    isDistinct = 0;
90322
    isDistinct = 0;
83953
  }
90323
  }
83954
90324
90325
  /* If there is both a GROUP BY and an ORDER BY clause and they are
90326
  ** identical, then disable the ORDER BY clause since the GROUP BY
90327
  ** will cause elements to come out in the correct order.  This is
90328
  ** an optimization - the correct answer should result regardless.
90329
  ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER
90330
  ** to disable this optimization for testing purposes.
90331
  */
90332
  if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy)==0
90333
         && (db->flags & SQLITE_GroupByOrder)==0 ){
90334
    pOrderBy = 0;
90335
  }
90336
83955
  /* If there is an ORDER BY clause, then this sorting
90337
  /* If there is an ORDER BY clause, then this sorting
83956
  ** index might end up being unused if the data can be 
90338
  ** index might end up being unused if the data can be 
83957
  ** extracted in pre-sorted order.  If that is the case, then the
90339
  ** extracted in pre-sorted order.  If that is the case, then the
 Lines 85227-85232   SQLITE_PRIVATE void sqlite3DropTrigger(P Link Here 
85227
    if( !noErr ){
91609
    if( !noErr ){
85228
      sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
91610
      sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
85229
    }
91611
    }
91612
    pParse->checkSchema = 1;
85230
    goto drop_trigger_cleanup;
91613
    goto drop_trigger_cleanup;
85231
  }
91614
  }
85232
  sqlite3DropTriggerPtr(pParse, pTrigger);
91615
  sqlite3DropTriggerPtr(pParse, pTrigger);
 Lines 85530-85535   static TriggerPrg *codeRowTrigger( Link Here 
85530
  int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
91913
  int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
85531
91914
85532
  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
91915
  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
91916
  assert( pTop->pVdbe );
85533
91917
85534
  /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
91918
  /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
85535
  ** are freed if an error occurs, link them into the Parse.pTriggerPrg 
91919
  ** are freed if an error occurs, link them into the Parse.pTriggerPrg 
 Lines 85540-85546   static TriggerPrg *codeRowTrigger( Link Here 
85540
  pTop->pTriggerPrg = pPrg;
91924
  pTop->pTriggerPrg = pPrg;
85541
  pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
91925
  pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
85542
  if( !pProgram ) return 0;
91926
  if( !pProgram ) return 0;
85543
  pProgram->nRef = 1;
91927
  sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
85544
  pPrg->pTrigger = pTrigger;
91928
  pPrg->pTrigger = pTrigger;
85545
  pPrg->orconf = orconf;
91929
  pPrg->orconf = orconf;
85546
  pPrg->aColmask[0] = 0xffffffff;
91930
  pPrg->aColmask[0] = 0xffffffff;
 Lines 85557-85562   static TriggerPrg *codeRowTrigger( Link Here 
85557
  pSubParse->pToplevel = pTop;
91941
  pSubParse->pToplevel = pTop;
85558
  pSubParse->zAuthContext = pTrigger->zName;
91942
  pSubParse->zAuthContext = pTrigger->zName;
85559
  pSubParse->eTriggerOp = pTrigger->op;
91943
  pSubParse->eTriggerOp = pTrigger->op;
91944
  pSubParse->nQueryLoop = pParse->nQueryLoop;
85560
91945
85561
  v = sqlite3GetVdbe(pSubParse);
91946
  v = sqlite3GetVdbe(pSubParse);
85562
  if( v ){
91947
  if( v ){
 Lines 85673-85680   SQLITE_PRIVATE void sqlite3CodeRowTrigge Link Here 
85673
  /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program 
92058
  /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program 
85674
  ** is a pointer to the sub-vdbe containing the trigger program.  */
92059
  ** is a pointer to the sub-vdbe containing the trigger program.  */
85675
  if( pPrg ){
92060
  if( pPrg ){
92061
    int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
92062
85676
    sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
92063
    sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
85677
    pPrg->pProgram->nRef++;
85678
    sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
92064
    sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
85679
    VdbeComment(
92065
    VdbeComment(
85680
        (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
92066
        (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
 Lines 85684-85690   SQLITE_PRIVATE void sqlite3CodeRowTrigge Link Here 
85684
    ** invocation is disallowed if (a) the sub-program is really a trigger,
92070
    ** invocation is disallowed if (a) the sub-program is really a trigger,
85685
    ** not a foreign key action, and (b) the flag to enable recursive triggers
92071
    ** not a foreign key action, and (b) the flag to enable recursive triggers
85686
    ** is clear.  */
92072
    ** is clear.  */
85687
    sqlite3VdbeChangeP5(v, (u8)(p->zName && !(pParse->db->flags&SQLITE_RecTriggers)));
92073
    sqlite3VdbeChangeP5(v, (u8)bRecursive);
85688
  }
92074
  }
85689
}
92075
}
85690
92076
 Lines 86036-86041   SQLITE_PRIVATE void sqlite3Update( Link Here 
86036
        pRowidExpr = pChanges->a[i].pExpr;
92422
        pRowidExpr = pChanges->a[i].pExpr;
86037
      }else{
92423
      }else{
86038
        sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
92424
        sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
92425
        pParse->checkSchema = 1;
86039
        goto update_cleanup;
92426
        goto update_cleanup;
86040
      }
92427
      }
86041
    }
92428
    }
 Lines 86220-86227   SQLITE_PRIVATE void sqlite3Update( Link Here 
86220
    );
92607
    );
86221
    for(i=0; i<pTab->nCol; i++){
92608
    for(i=0; i<pTab->nCol; i++){
86222
      if( aXRef[i]<0 || oldmask==0xffffffff || (oldmask & (1<<i)) ){
92609
      if( aXRef[i]<0 || oldmask==0xffffffff || (oldmask & (1<<i)) ){
86223
        sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regOld+i);
92610
        sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld+i);
86224
        sqlite3ColumnDefault(v, pTab, i, regOld+i);
86225
      }else{
92611
      }else{
86226
        sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
92612
        sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
86227
      }
92613
      }
 Lines 86594-86600   SQLITE_PRIVATE int sqlite3RunVacuum(char Link Here 
86594
  void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
92980
  void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
86595
  Db *pDb = 0;            /* Database to detach at end of vacuum */
92981
  Db *pDb = 0;            /* Database to detach at end of vacuum */
86596
  int isMemDb;            /* True if vacuuming a :memory: database */
92982
  int isMemDb;            /* True if vacuuming a :memory: database */
86597
  int nRes;
92983
  int nRes;               /* Bytes of reserved space at the end of each page */
92984
  int nDb;                /* Number of attached databases */
86598
92985
86599
  if( !db->autoCommit ){
92986
  if( !db->autoCommit ){
86600
    sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
92987
    sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
 Lines 86608-86614   SQLITE_PRIVATE int sqlite3RunVacuum(char Link Here 
86608
  saved_nChange = db->nChange;
92995
  saved_nChange = db->nChange;
86609
  saved_nTotalChange = db->nTotalChange;
92996
  saved_nTotalChange = db->nTotalChange;
86610
  saved_xTrace = db->xTrace;
92997
  saved_xTrace = db->xTrace;
86611
  db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks;
92998
  db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
86612
  db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
92999
  db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
86613
  db->xTrace = 0;
93000
  db->xTrace = 0;
86614
93001
 Lines 86629-86643   SQLITE_PRIVATE int sqlite3RunVacuum(char Link Here 
86629
  ** time to parse and run the PRAGMA to turn journalling off than it does
93016
  ** time to parse and run the PRAGMA to turn journalling off than it does
86630
  ** to write the journal header file.
93017
  ** to write the journal header file.
86631
  */
93018
  */
93019
  nDb = db->nDb;
86632
  if( sqlite3TempInMemory(db) ){
93020
  if( sqlite3TempInMemory(db) ){
86633
    zSql = "ATTACH ':memory:' AS vacuum_db;";
93021
    zSql = "ATTACH ':memory:' AS vacuum_db;";
86634
  }else{
93022
  }else{
86635
    zSql = "ATTACH '' AS vacuum_db;";
93023
    zSql = "ATTACH '' AS vacuum_db;";
86636
  }
93024
  }
86637
  rc = execSql(db, pzErrMsg, zSql);
93025
  rc = execSql(db, pzErrMsg, zSql);
93026
  if( db->nDb>nDb ){
93027
    pDb = &db->aDb[db->nDb-1];
93028
    assert( strcmp(pDb->zName,"vacuum_db")==0 );
93029
  }
86638
  if( rc!=SQLITE_OK ) goto end_of_vacuum;
93030
  if( rc!=SQLITE_OK ) goto end_of_vacuum;
86639
  pDb = &db->aDb[db->nDb-1];
86640
  assert( strcmp(db->aDb[db->nDb-1].zName,"vacuum_db")==0 );
86641
  pTemp = db->aDb[db->nDb-1].pBt;
93031
  pTemp = db->aDb[db->nDb-1].pBt;
86642
93032
86643
  /* The call to execSql() to attach the temp database has left the file
93033
  /* The call to execSql() to attach the temp database has left the file
 Lines 86659-86664   SQLITE_PRIVATE int sqlite3RunVacuum(char Link Here 
86659
  }
93049
  }
86660
#endif
93050
#endif
86661
93051
93052
  /* Do not attempt to change the page size for a WAL database */
93053
  if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
93054
                                               ==PAGER_JOURNALMODE_WAL ){
93055
    db->nextPagesize = 0;
93056
  }
93057
86662
  if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
93058
  if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
86663
   || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
93059
   || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
86664
   || NEVER(db->mallocFailed)
93060
   || NEVER(db->mallocFailed)
 Lines 86795-86800   end_of_vacuum: Link Here 
86795
  db->nChange = saved_nChange;
93191
  db->nChange = saved_nChange;
86796
  db->nTotalChange = saved_nTotalChange;
93192
  db->nTotalChange = saved_nTotalChange;
86797
  db->xTrace = saved_xTrace;
93193
  db->xTrace = saved_xTrace;
93194
  sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
86798
93195
86799
  /* Currently there is an SQL level transaction open on the vacuum
93196
  /* Currently there is an SQL level transaction open on the vacuum
86800
  ** database. No locks are held on any other files (since the main file
93197
  ** database. No locks are held on any other files (since the main file
 Lines 87041-87054   SQLITE_PRIVATE void sqlite3VtabUnlockLis Link Here 
87041
** in the list are moved to the sqlite3.pDisconnect list of the associated 
93438
** in the list are moved to the sqlite3.pDisconnect list of the associated 
87042
** database connection.
93439
** database connection.
87043
*/
93440
*/
87044
SQLITE_PRIVATE void sqlite3VtabClear(Table *p){
93441
SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
87045
  vtabDisconnectAll(0, p);
93442
  if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
87046
  if( p->azModuleArg ){
93443
  if( p->azModuleArg ){
87047
    int i;
93444
    int i;
87048
    for(i=0; i<p->nModuleArg; i++){
93445
    for(i=0; i<p->nModuleArg; i++){
87049
      sqlite3DbFree(p->dbMem, p->azModuleArg[i]);
93446
      sqlite3DbFree(db, p->azModuleArg[i]);
87050
    }
93447
    }
87051
    sqlite3DbFree(p->dbMem, p->azModuleArg);
93448
    sqlite3DbFree(db, p->azModuleArg);
87052
  }
93449
  }
87053
}
93450
}
87054
93451
 Lines 87213-87219   SQLITE_PRIVATE void sqlite3VtabFinishPar Link Here 
87213
      assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
93610
      assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
87214
      return;
93611
      return;
87215
    }
93612
    }
87216
    pSchema->db = pParse->db;
87217
    pParse->pNewTable = 0;
93613
    pParse->pNewTable = 0;
87218
  }
93614
  }
87219
}
93615
}
 Lines 87287-87293   static int vtabCallConstructor( Link Here 
87287
      *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
93683
      *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
87288
    }else {
93684
    }else {
87289
      *pzErr = sqlite3MPrintf(db, "%s", zErr);
93685
      *pzErr = sqlite3MPrintf(db, "%s", zErr);
87290
      sqlite3DbFree(db, zErr);
93686
      sqlite3_free(zErr);
87291
    }
93687
    }
87292
    sqlite3DbFree(db, pVTable);
93688
    sqlite3DbFree(db, pVTable);
87293
  }else if( ALWAYS(pVTable->pVtab) ){
93689
  }else if( ALWAYS(pVTable->pVtab) ){
 Lines 87477-87482   SQLITE_API int sqlite3_declare_vtab(sqli Link Here 
87477
  }else{
93873
  }else{
87478
    pParse->declareVtab = 1;
93874
    pParse->declareVtab = 1;
87479
    pParse->db = db;
93875
    pParse->db = db;
93876
    pParse->nQueryLoop = 1;
87480
  
93877
  
87481
    if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr) 
93878
    if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr) 
87482
     && pParse->pNewTable
93879
     && pParse->pNewTable
 Lines 87501-87507   SQLITE_API int sqlite3_declare_vtab(sqli Link Here 
87501
    if( pParse->pVdbe ){
93898
    if( pParse->pVdbe ){
87502
      sqlite3VdbeFinalize(pParse->pVdbe);
93899
      sqlite3VdbeFinalize(pParse->pVdbe);
87503
    }
93900
    }
87504
    sqlite3DeleteTable(pParse->pNewTable);
93901
    sqlite3DeleteTable(db, pParse->pNewTable);
87505
    sqlite3StackFree(db, pParse);
93902
    sqlite3StackFree(db, pParse);
87506
  }
93903
  }
87507
93904
 Lines 87588-87595   SQLITE_PRIVATE int sqlite3VtabSync(sqlit Link Here 
87588
    if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
93985
    if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
87589
      rc = x(pVtab);
93986
      rc = x(pVtab);
87590
      sqlite3DbFree(db, *pzErrmsg);
93987
      sqlite3DbFree(db, *pzErrmsg);
87591
      *pzErrmsg = pVtab->zErrMsg;
93988
      *pzErrmsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
87592
      pVtab->zErrMsg = 0;
93989
      sqlite3_free(pVtab->zErrMsg);
87593
    }
93990
    }
87594
  }
93991
  }
87595
  db->aVTrans = aVTrans;
93992
  db->aVTrans = aVTrans;
 Lines 87997-88002   struct WhereCost { Link Here 
87997
#define WHERE_COLUMN_IN    0x00040000  /* x IN (...) */
94394
#define WHERE_COLUMN_IN    0x00040000  /* x IN (...) */
87998
#define WHERE_COLUMN_NULL  0x00080000  /* x IS NULL */
94395
#define WHERE_COLUMN_NULL  0x00080000  /* x IS NULL */
87999
#define WHERE_INDEXED      0x000f0000  /* Anything that uses an index */
94396
#define WHERE_INDEXED      0x000f0000  /* Anything that uses an index */
94397
#define WHERE_NOT_FULLSCAN 0x000f3000  /* Does not do a full table scan */
88000
#define WHERE_IN_ABLE      0x000f1000  /* Able to support an IN operator */
94398
#define WHERE_IN_ABLE      0x000f1000  /* Able to support an IN operator */
88001
#define WHERE_TOP_LIMIT    0x00100000  /* x<EXPR or x<=EXPR constraint */
94399
#define WHERE_TOP_LIMIT    0x00100000  /* x<EXPR or x<=EXPR constraint */
88002
#define WHERE_BTM_LIMIT    0x00200000  /* x>EXPR or x>=EXPR constraint */
94400
#define WHERE_BTM_LIMIT    0x00200000  /* x>EXPR or x>=EXPR constraint */
 Lines 88006-88011   struct WhereCost { Link Here 
88006
#define WHERE_UNIQUE       0x04000000  /* Selects no more than one row */
94404
#define WHERE_UNIQUE       0x04000000  /* Selects no more than one row */
88007
#define WHERE_VIRTUALTABLE 0x08000000  /* Use virtual-table processing */
94405
#define WHERE_VIRTUALTABLE 0x08000000  /* Use virtual-table processing */
88008
#define WHERE_MULTI_OR     0x10000000  /* OR using multiple indices */
94406
#define WHERE_MULTI_OR     0x10000000  /* OR using multiple indices */
94407
#define WHERE_TEMP_INDEX   0x20000000  /* Uses an ephemeral index */
88009
94408
88010
/*
94409
/*
88011
** Initialize a preallocated WhereClause structure.
94410
** Initialize a preallocated WhereClause structure.
 Lines 88087-88092   static void whereClauseClear(WhereClause Link Here 
88087
static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
94486
static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
88088
  WhereTerm *pTerm;
94487
  WhereTerm *pTerm;
88089
  int idx;
94488
  int idx;
94489
  testcase( wtFlags & TERM_VIRTUAL );  /* EV: R-00211-15100 */
88090
  if( pWC->nTerm>=pWC->nSlot ){
94490
  if( pWC->nTerm>=pWC->nSlot ){
88091
    WhereTerm *pOld = pWC->a;
94491
    WhereTerm *pOld = pWC->a;
88092
    sqlite3 *db = pWC->pParse->db;
94492
    sqlite3 *db = pWC->pParse->db;
 Lines 88232-88237   static Bitmask exprSelectTableUsage(Wher Link Here 
88232
** Return TRUE if the given operator is one of the operators that is
94632
** Return TRUE if the given operator is one of the operators that is
88233
** allowed for an indexable WHERE clause term.  The allowed operators are
94633
** allowed for an indexable WHERE clause term.  The allowed operators are
88234
** "=", "<", ">", "<=", ">=", and "IN".
94634
** "=", "<", ">", "<=", ">=", and "IN".
94635
**
94636
** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be
94637
** of one of the following forms: column = expression column > expression
94638
** column >= expression column < expression column <= expression
94639
** expression = column expression > column expression >= column
94640
** expression < column expression <= column column IN
94641
** (expression-list) column IN (subquery) column IS NULL
88235
*/
94642
*/
88236
static int allowedOp(int op){
94643
static int allowedOp(int op){
88237
  assert( TK_GT>TK_EQ && TK_GT<TK_GE );
94644
  assert( TK_GT>TK_EQ && TK_GT<TK_GE );
 Lines 88395-88401   static int isLikeOrGlob( Link Here 
88395
  int c;                     /* One character in z[] */
94802
  int c;                     /* One character in z[] */
88396
  int cnt;                   /* Number of non-wildcard prefix characters */
94803
  int cnt;                   /* Number of non-wildcard prefix characters */
88397
  char wc[3];                /* Wildcard characters */
94804
  char wc[3];                /* Wildcard characters */
88398
  CollSeq *pColl;            /* Collating sequence for LHS */
88399
  sqlite3 *db = pParse->db;  /* Database connection */
94805
  sqlite3 *db = pParse->db;  /* Database connection */
88400
  sqlite3_value *pVal = 0;
94806
  sqlite3_value *pVal = 0;
88401
  int op;                    /* Opcode of pRight */
94807
  int op;                    /* Opcode of pRight */
 Lines 88414-88432   static int isLikeOrGlob( Link Here 
88414
    return 0;
94820
    return 0;
88415
  }
94821
  }
88416
  assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
94822
  assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
88417
  pColl = sqlite3ExprCollSeq(pParse, pLeft);
88418
  if( pColl==0 ) return 0;  /* Happens when LHS has an undefined collation */
88419
  if( (pColl->type!=SQLITE_COLL_BINARY || *pnoCase) &&
88420
      (pColl->type!=SQLITE_COLL_NOCASE || !*pnoCase) ){
88421
    /* IMP: R-09003-32046 For the GLOB operator, the column must use the
88422
    ** default BINARY collating sequence.
88423
    ** IMP: R-41408-28306 For the LIKE operator, if case_sensitive_like mode
88424
    ** is enabled then the column must use the default BINARY collating
88425
    ** sequence, or if case_sensitive_like mode is disabled then the column
88426
    ** must use the built-in NOCASE collating sequence.
88427
    */
88428
    return 0;
88429
  }
88430
94823
88431
  pRight = pList->a[0].pExpr;
94824
  pRight = pList->a[0].pExpr;
88432
  op = pRight->op;
94825
  op = pRight->op;
 Lines 88449-88457   static int isLikeOrGlob( Link Here 
88449
    while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
94842
    while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
88450
      cnt++;
94843
      cnt++;
88451
    }
94844
    }
88452
    if( cnt!=0 && c!=0 && 255!=(u8)z[cnt-1] ){
94845
    if( cnt!=0 && 255!=(u8)z[cnt-1] ){
88453
      Expr *pPrefix;
94846
      Expr *pPrefix;
88454
      *pisComplete = z[cnt]==wc[0] && z[cnt+1]==0;
94847
      *pisComplete = c==wc[0] && z[cnt+1]==0;
88455
      pPrefix = sqlite3Expr(db, TK_STRING, z);
94848
      pPrefix = sqlite3Expr(db, TK_STRING, z);
88456
      if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
94849
      if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
88457
      *ppPrefix = pPrefix;
94850
      *ppPrefix = pPrefix;
 Lines 88790-88795   static void exprAnalyzeOrTerm( Link Here 
88790
    /* At this point, okToChngToIN is true if original pTerm satisfies
95183
    /* At this point, okToChngToIN is true if original pTerm satisfies
88791
    ** case 1.  In that case, construct a new virtual term that is 
95184
    ** case 1.  In that case, construct a new virtual term that is 
88792
    ** pTerm converted into an IN operator.
95185
    ** pTerm converted into an IN operator.
95186
    **
95187
    ** EV: R-00211-15100
88793
    */
95188
    */
88794
    if( okToChngToIN ){
95189
    if( okToChngToIN ){
88795
      Expr *pDup;            /* A transient duplicate expression */
95190
      Expr *pDup;            /* A transient duplicate expression */
 Lines 89006-89011   static void exprAnalyze( Link Here 
89006
    Expr *pNewExpr2;
95401
    Expr *pNewExpr2;
89007
    int idxNew1;
95402
    int idxNew1;
89008
    int idxNew2;
95403
    int idxNew2;
95404
    CollSeq *pColl;    /* Collating sequence to use */
89009
95405
89010
    pLeft = pExpr->x.pList->a[1].pExpr;
95406
    pLeft = pExpr->x.pList->a[1].pExpr;
89011
    pStr2 = sqlite3ExprDup(db, pStr1, 0);
95407
    pStr2 = sqlite3ExprDup(db, pStr1, 0);
 Lines 89020-89036   static void exprAnalyze( Link Here 
89020
        ** inequality.  To avoid this, make sure to also run the full
95416
        ** inequality.  To avoid this, make sure to also run the full
89021
        ** LIKE on all candidate expressions by clearing the isComplete flag
95417
        ** LIKE on all candidate expressions by clearing the isComplete flag
89022
        */
95418
        */
89023
        if( c=='A'-1 ) isComplete = 0;
95419
        if( c=='A'-1 ) isComplete = 0;   /* EV: R-64339-08207 */
95420
89024
95421
89025
        c = sqlite3UpperToLower[c];
95422
        c = sqlite3UpperToLower[c];
89026
      }
95423
      }
89027
      *pC = c + 1;
95424
      *pC = c + 1;
89028
    }
95425
    }
89029
    pNewExpr1 = sqlite3PExpr(pParse, TK_GE, sqlite3ExprDup(db,pLeft,0),pStr1,0);
95426
    pColl = sqlite3FindCollSeq(db, SQLITE_UTF8, noCase ? "NOCASE" : "BINARY",0);
95427
    pNewExpr1 = sqlite3PExpr(pParse, TK_GE, 
95428
                     sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl),
95429
                     pStr1, 0);
89030
    idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
95430
    idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
89031
    testcase( idxNew1==0 );
95431
    testcase( idxNew1==0 );
89032
    exprAnalyze(pSrc, pWC, idxNew1);
95432
    exprAnalyze(pSrc, pWC, idxNew1);
89033
    pNewExpr2 = sqlite3PExpr(pParse, TK_LT, sqlite3ExprDup(db,pLeft,0),pStr2,0);
95433
    pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
95434
                     sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl),
95435
                     pStr2, 0);
89034
    idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
95436
    idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
89035
    testcase( idxNew2==0 );
95437
    testcase( idxNew2==0 );
89036
    exprAnalyze(pSrc, pWC, idxNew2);
95438
    exprAnalyze(pSrc, pWC, idxNew2);
 Lines 89335-89340   static void bestOrClauseIndex( Link Here 
89335
  WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm];        /* End of pWC->a[] */
95737
  WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm];        /* End of pWC->a[] */
89336
  WhereTerm *pTerm;                 /* A single term of the WHERE clause */
95738
  WhereTerm *pTerm;                 /* A single term of the WHERE clause */
89337
95739
95740
  /* No OR-clause optimization allowed if the NOT INDEXED clause is used */
95741
  if( pSrc->notIndexed ){
95742
    return;
95743
  }
95744
89338
  /* Search the WHERE clause terms for a usable WO_OR term. */
95745
  /* Search the WHERE clause terms for a usable WO_OR term. */
89339
  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
95746
  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
89340
    if( pTerm->eOperator==WO_OR 
95747
    if( pTerm->eOperator==WO_OR 
 Lines 89377-89384   static void bestOrClauseIndex( Link Here 
89377
      /* If there is an ORDER BY clause, increase the scan cost to account 
95784
      /* If there is an ORDER BY clause, increase the scan cost to account 
89378
      ** for the cost of the sort. */
95785
      ** for the cost of the sort. */
89379
      if( pOrderBy!=0 ){
95786
      if( pOrderBy!=0 ){
95787
        WHERETRACE(("... sorting increases OR cost %.9g to %.9g\n",
95788
                    rTotal, rTotal+nRow*estLog(nRow)));
89380
        rTotal += nRow*estLog(nRow);
95789
        rTotal += nRow*estLog(nRow);
89381
        WHERETRACE(("... sorting increases OR cost to %.9g\n", rTotal));
89382
      }
95790
      }
89383
95791
89384
      /* If the cost of scanning using this OR term for optimization is
95792
      /* If the cost of scanning using this OR term for optimization is
 Lines 89397-89402   static void bestOrClauseIndex( Link Here 
89397
#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
95805
#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
89398
}
95806
}
89399
95807
95808
#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
95809
/*
95810
** Return TRUE if the WHERE clause term pTerm is of a form where it
95811
** could be used with an index to access pSrc, assuming an appropriate
95812
** index existed.
95813
*/
95814
static int termCanDriveIndex(
95815
  WhereTerm *pTerm,              /* WHERE clause term to check */
95816
  struct SrcList_item *pSrc,     /* Table we are trying to access */
95817
  Bitmask notReady               /* Tables in outer loops of the join */
95818
){
95819
  char aff;
95820
  if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
95821
  if( pTerm->eOperator!=WO_EQ ) return 0;
95822
  if( (pTerm->prereqRight & notReady)!=0 ) return 0;
95823
  aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
95824
  if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
95825
  return 1;
95826
}
95827
#endif
95828
95829
#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
95830
/*
95831
** If the query plan for pSrc specified in pCost is a full table scan
95832
** and indexing is allows (if there is no NOT INDEXED clause) and it
95833
** possible to construct a transient index that would perform better
95834
** than a full table scan even when the cost of constructing the index
95835
** is taken into account, then alter the query plan to use the
95836
** transient index.
95837
*/
95838
static void bestAutomaticIndex(
95839
  Parse *pParse,              /* The parsing context */
95840
  WhereClause *pWC,           /* The WHERE clause */
95841
  struct SrcList_item *pSrc,  /* The FROM clause term to search */
95842
  Bitmask notReady,           /* Mask of cursors that are not available */
95843
  WhereCost *pCost            /* Lowest cost query plan */
95844
){
95845
  double nTableRow;           /* Rows in the input table */
95846
  double logN;                /* log(nTableRow) */
95847
  double costTempIdx;         /* per-query cost of the transient index */
95848
  WhereTerm *pTerm;           /* A single term of the WHERE clause */
95849
  WhereTerm *pWCEnd;          /* End of pWC->a[] */
95850
  Table *pTable;              /* Table tht might be indexed */
95851
95852
  if( (pParse->db->flags & SQLITE_AutoIndex)==0 ){
95853
    /* Automatic indices are disabled at run-time */
95854
    return;
95855
  }
95856
  if( (pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)!=0 ){
95857
    /* We already have some kind of index in use for this query. */
95858
    return;
95859
  }
95860
  if( pSrc->notIndexed ){
95861
    /* The NOT INDEXED clause appears in the SQL. */
95862
    return;
95863
  }
95864
95865
  assert( pParse->nQueryLoop >= (double)1 );
95866
  pTable = pSrc->pTab;
95867
  nTableRow = pTable->pIndex ? pTable->pIndex->aiRowEst[0] : 1000000;
95868
  logN = estLog(nTableRow);
95869
  costTempIdx = 2*logN*(nTableRow/pParse->nQueryLoop + 1);
95870
  if( costTempIdx>=pCost->rCost ){
95871
    /* The cost of creating the transient table would be greater than
95872
    ** doing the full table scan */
95873
    return;
95874
  }
95875
95876
  /* Search for any equality comparison term */
95877
  pWCEnd = &pWC->a[pWC->nTerm];
95878
  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
95879
    if( termCanDriveIndex(pTerm, pSrc, notReady) ){
95880
      WHERETRACE(("auto-index reduces cost from %.2f to %.2f\n",
95881
                    pCost->rCost, costTempIdx));
95882
      pCost->rCost = costTempIdx;
95883
      pCost->nRow = logN + 1;
95884
      pCost->plan.wsFlags = WHERE_TEMP_INDEX;
95885
      pCost->used = pTerm->prereqRight;
95886
      break;
95887
    }
95888
  }
95889
}
95890
#else
95891
# define bestAutomaticIndex(A,B,C,D,E)  /* no-op */
95892
#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
95893
95894
95895
#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
95896
/*
95897
** Generate code to construct the Index object for an automatic index
95898
** and to set up the WhereLevel object pLevel so that the code generator
95899
** makes use of the automatic index.
95900
*/
95901
static void constructAutomaticIndex(
95902
  Parse *pParse,              /* The parsing context */
95903
  WhereClause *pWC,           /* The WHERE clause */
95904
  struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
95905
  Bitmask notReady,           /* Mask of cursors that are not available */
95906
  WhereLevel *pLevel          /* Write new index here */
95907
){
95908
  int nColumn;                /* Number of columns in the constructed index */
95909
  WhereTerm *pTerm;           /* A single term of the WHERE clause */
95910
  WhereTerm *pWCEnd;          /* End of pWC->a[] */
95911
  int nByte;                  /* Byte of memory needed for pIdx */
95912
  Index *pIdx;                /* Object describing the transient index */
95913
  Vdbe *v;                    /* Prepared statement under construction */
95914
  int regIsInit;              /* Register set by initialization */
95915
  int addrInit;               /* Address of the initialization bypass jump */
95916
  Table *pTable;              /* The table being indexed */
95917
  KeyInfo *pKeyinfo;          /* Key information for the index */   
95918
  int addrTop;                /* Top of the index fill loop */
95919
  int regRecord;              /* Register holding an index record */
95920
  int n;                      /* Column counter */
95921
  int i;                      /* Loop counter */
95922
  int mxBitCol;               /* Maximum column in pSrc->colUsed */
95923
  CollSeq *pColl;             /* Collating sequence to on a column */
95924
  Bitmask idxCols;            /* Bitmap of columns used for indexing */
95925
  Bitmask extraCols;          /* Bitmap of additional columns */
95926
95927
  /* Generate code to skip over the creation and initialization of the
95928
  ** transient index on 2nd and subsequent iterations of the loop. */
95929
  v = pParse->pVdbe;
95930
  assert( v!=0 );
95931
  regIsInit = ++pParse->nMem;
95932
  addrInit = sqlite3VdbeAddOp1(v, OP_If, regIsInit);
95933
  sqlite3VdbeAddOp2(v, OP_Integer, 1, regIsInit);
95934
95935
  /* Count the number of columns that will be added to the index
95936
  ** and used to match WHERE clause constraints */
95937
  nColumn = 0;
95938
  pTable = pSrc->pTab;
95939
  pWCEnd = &pWC->a[pWC->nTerm];
95940
  idxCols = 0;
95941
  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
95942
    if( termCanDriveIndex(pTerm, pSrc, notReady) ){
95943
      int iCol = pTerm->u.leftColumn;
95944
      Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
95945
      testcase( iCol==BMS );
95946
      testcase( iCol==BMS-1 );
95947
      if( (idxCols & cMask)==0 ){
95948
        nColumn++;
95949
        idxCols |= cMask;
95950
      }
95951
    }
95952
  }
95953
  assert( nColumn>0 );
95954
  pLevel->plan.nEq = nColumn;
95955
95956
  /* Count the number of additional columns needed to create a
95957
  ** covering index.  A "covering index" is an index that contains all
95958
  ** columns that are needed by the query.  With a covering index, the
95959
  ** original table never needs to be accessed.  Automatic indices must
95960
  ** be a covering index because the index will not be updated if the
95961
  ** original table changes and the index and table cannot both be used
95962
  ** if they go out of sync.
95963
  */
95964
  extraCols = pSrc->colUsed & (~idxCols | (((Bitmask)1)<<(BMS-1)));
95965
  mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
95966
  testcase( pTable->nCol==BMS-1 );
95967
  testcase( pTable->nCol==BMS-2 );
95968
  for(i=0; i<mxBitCol; i++){
95969
    if( extraCols & (((Bitmask)1)<<i) ) nColumn++;
95970
  }
95971
  if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
95972
    nColumn += pTable->nCol - BMS + 1;
95973
  }
95974
  pLevel->plan.wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WO_EQ;
95975
95976
  /* Construct the Index object to describe this index */
95977
  nByte = sizeof(Index);
95978
  nByte += nColumn*sizeof(int);     /* Index.aiColumn */
95979
  nByte += nColumn*sizeof(char*);   /* Index.azColl */
95980
  nByte += nColumn;                 /* Index.aSortOrder */
95981
  pIdx = sqlite3DbMallocZero(pParse->db, nByte);
95982
  if( pIdx==0 ) return;
95983
  pLevel->plan.u.pIdx = pIdx;
95984
  pIdx->azColl = (char**)&pIdx[1];
95985
  pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
95986
  pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
95987
  pIdx->zName = "auto-index";
95988
  pIdx->nColumn = nColumn;
95989
  pIdx->pTable = pTable;
95990
  n = 0;
95991
  idxCols = 0;
95992
  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
95993
    if( termCanDriveIndex(pTerm, pSrc, notReady) ){
95994
      int iCol = pTerm->u.leftColumn;
95995
      Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
95996
      if( (idxCols & cMask)==0 ){
95997
        Expr *pX = pTerm->pExpr;
95998
        idxCols |= cMask;
95999
        pIdx->aiColumn[n] = pTerm->u.leftColumn;
96000
        pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
96001
        pIdx->azColl[n] = pColl->zName;
96002
        n++;
96003
      }
96004
    }
96005
  }
96006
  assert( (u32)n==pLevel->plan.nEq );
96007
96008
  /* Add additional columns needed to make the automatic index into
96009
  ** a covering index */
96010
  for(i=0; i<mxBitCol; i++){
96011
    if( extraCols & (((Bitmask)1)<<i) ){
96012
      pIdx->aiColumn[n] = i;
96013
      pIdx->azColl[n] = "BINARY";
96014
      n++;
96015
    }
96016
  }
96017
  if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
96018
    for(i=BMS-1; i<pTable->nCol; i++){
96019
      pIdx->aiColumn[n] = i;
96020
      pIdx->azColl[n] = "BINARY";
96021
      n++;
96022
    }
96023
  }
96024
  assert( n==nColumn );
96025
96026
  /* Create the automatic index */
96027
  pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
96028
  assert( pLevel->iIdxCur>=0 );
96029
  sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
96030
                    (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
96031
  VdbeComment((v, "for %s", pTable->zName));
96032
96033
  /* Fill the automatic index with content */
96034
  addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
96035
  regRecord = sqlite3GetTempReg(pParse);
96036
  sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1);
96037
  sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
96038
  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
96039
  sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
96040
  sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
96041
  sqlite3VdbeJumpHere(v, addrTop);
96042
  sqlite3ReleaseTempReg(pParse, regRecord);
96043
  
96044
  /* Jump here when skipping the initialization */
96045
  sqlite3VdbeJumpHere(v, addrInit);
96046
}
96047
#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
96048
89400
#ifndef SQLITE_OMIT_VIRTUALTABLE
96049
#ifndef SQLITE_OMIT_VIRTUALTABLE
89401
/*
96050
/*
89402
** Allocate and populate an sqlite3_index_info structure. It is the 
96051
** Allocate and populate an sqlite3_index_info structure. It is the 
 Lines 89535-89541   static int vtabBestIndex(Parse *pParse, Link Here 
89535
      sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
96184
      sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
89536
    }
96185
    }
89537
  }
96186
  }
89538
  sqlite3DbFree(pParse->db, pVtab->zErrMsg);
96187
  sqlite3_free(pVtab->zErrMsg);
89539
  pVtab->zErrMsg = 0;
96188
  pVtab->zErrMsg = 0;
89540
96189
89541
  for(i=0; i<p->nConstraint; i++){
96190
  for(i=0; i<p->nConstraint; i++){
 Lines 89581-89586   static void bestVirtualIndex( Link Here 
89581
  WhereTerm *pTerm;
96230
  WhereTerm *pTerm;
89582
  int i, j;
96231
  int i, j;
89583
  int nOrderBy;
96232
  int nOrderBy;
96233
  double rCost;
89584
96234
89585
  /* Make sure wsFlags is initialized to some sane value. Otherwise, if the 
96235
  /* Make sure wsFlags is initialized to some sane value. Otherwise, if the 
89586
  ** malloc in allocateIndexInfo() fails and this function returns leaving
96236
  ** malloc in allocateIndexInfo() fails and this function returns leaving
 Lines 89667-89672   static void bestVirtualIndex( Link Here 
89667
    }
96317
    }
89668
  }
96318
  }
89669
96319
96320
  /* If there is an ORDER BY clause, and the selected virtual table index
96321
  ** does not satisfy it, increase the cost of the scan accordingly. This
96322
  ** matches the processing for non-virtual tables in bestBtreeIndex().
96323
  */
96324
  rCost = pIdxInfo->estimatedCost;
96325
  if( pOrderBy && pIdxInfo->orderByConsumed==0 ){
96326
    rCost += estLog(rCost)*rCost;
96327
  }
96328
89670
  /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
96329
  /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
89671
  ** inital value of lowestCost in this loop. If it is, then the
96330
  ** inital value of lowestCost in this loop. If it is, then the
89672
  ** (cost<lowestCost) test below will never be true.
96331
  ** (cost<lowestCost) test below will never be true.
 Lines 89674-89683   static void bestVirtualIndex( Link Here 
89674
  ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT 
96333
  ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT 
89675
  ** is defined.
96334
  ** is defined.
89676
  */
96335
  */
89677
  if( (SQLITE_BIG_DBL/((double)2))<pIdxInfo->estimatedCost ){
96336
  if( (SQLITE_BIG_DBL/((double)2))<rCost ){
89678
    pCost->rCost = (SQLITE_BIG_DBL/((double)2));
96337
    pCost->rCost = (SQLITE_BIG_DBL/((double)2));
89679
  }else{
96338
  }else{
89680
    pCost->rCost = pIdxInfo->estimatedCost;
96339
    pCost->rCost = rCost;
89681
  }
96340
  }
89682
  pCost->plan.u.pVtabIdx = pIdxInfo;
96341
  pCost->plan.u.pVtabIdx = pIdxInfo;
89683
  if( pIdxInfo->orderByConsumed ){
96342
  if( pIdxInfo->orderByConsumed ){
 Lines 90078-90091   static void bestBtreeIndex( Link Here 
90078
    **    Set to true if there was at least one "x IN (SELECT ...)" term used 
96737
    **    Set to true if there was at least one "x IN (SELECT ...)" term used 
90079
    **    in determining the value of nInMul.
96738
    **    in determining the value of nInMul.
90080
    **
96739
    **
90081
    **  nBound:
96740
    **  estBound:
90082
    **    An estimate on the amount of the table that must be searched.  A
96741
    **    An estimate on the amount of the table that must be searched.  A
90083
    **    value of 100 means the entire table is searched.  Range constraints
96742
    **    value of 100 means the entire table is searched.  Range constraints
90084
    **    might reduce this to a value less than 100 to indicate that only
96743
    **    might reduce this to a value less than 100 to indicate that only
90085
    **    a fraction of the table needs searching.  In the absence of
96744
    **    a fraction of the table needs searching.  In the absence of
90086
    **    sqlite_stat2 ANALYZE data, a single inequality reduces the search
96745
    **    sqlite_stat2 ANALYZE data, a single inequality reduces the search
90087
    **    space to 1/3rd its original size.  So an x>? constraint reduces
96746
    **    space to 1/3rd its original size.  So an x>? constraint reduces
90088
    **    nBound to 33.  Two constraints (x>? AND x<?) reduce nBound to 11.
96747
    **    estBound to 33.  Two constraints (x>? AND x<?) reduce estBound to 11.
90089
    **
96748
    **
90090
    **  bSort:   
96749
    **  bSort:   
90091
    **    Boolean. True if there is an ORDER BY clause that will require an 
96750
    **    Boolean. True if there is an ORDER BY clause that will require an 
 Lines 90107-90119   static void bestBtreeIndex( Link Here 
90107
    int nEq;
96766
    int nEq;
90108
    int bInEst = 0;
96767
    int bInEst = 0;
90109
    int nInMul = 1;
96768
    int nInMul = 1;
90110
    int nBound = 100;
96769
    int estBound = 100;
96770
    int nBound = 0;             /* Number of range constraints seen */
90111
    int bSort = 0;
96771
    int bSort = 0;
90112
    int bLookup = 0;
96772
    int bLookup = 0;
96773
    WhereTerm *pTerm;           /* A single term of the WHERE clause */
90113
96774
90114
    /* Determine the values of nEq and nInMul */
96775
    /* Determine the values of nEq and nInMul */
90115
    for(nEq=0; nEq<pProbe->nColumn; nEq++){
96776
    for(nEq=0; nEq<pProbe->nColumn; nEq++){
90116
      WhereTerm *pTerm;           /* A single term of the WHERE clause */
90117
      int j = pProbe->aiColumn[nEq];
96777
      int j = pProbe->aiColumn[nEq];
90118
      pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pIdx);
96778
      pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pIdx);
90119
      if( pTerm==0 ) break;
96779
      if( pTerm==0 ) break;
 Lines 90124-90130   static void bestBtreeIndex( Link Here 
90124
        if( ExprHasProperty(pExpr, EP_xIsSelect) ){
96784
        if( ExprHasProperty(pExpr, EP_xIsSelect) ){
90125
          nInMul *= 25;
96785
          nInMul *= 25;
90126
          bInEst = 1;
96786
          bInEst = 1;
90127
        }else if( pExpr->x.pList ){
96787
        }else if( ALWAYS(pExpr->x.pList) ){
90128
          nInMul *= pExpr->x.pList->nExpr + 1;
96788
          nInMul *= pExpr->x.pList->nExpr + 1;
90129
        }
96789
        }
90130
      }else if( pTerm->eOperator & WO_ISNULL ){
96790
      }else if( pTerm->eOperator & WO_ISNULL ){
 Lines 90133-90150   static void bestBtreeIndex( Link Here 
90133
      used |= pTerm->prereqRight;
96793
      used |= pTerm->prereqRight;
90134
    }
96794
    }
90135
96795
90136
    /* Determine the value of nBound. */
96796
    /* Determine the value of estBound. */
90137
    if( nEq<pProbe->nColumn ){
96797
    if( nEq<pProbe->nColumn ){
90138
      int j = pProbe->aiColumn[nEq];
96798
      int j = pProbe->aiColumn[nEq];
90139
      if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
96799
      if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
90140
        WhereTerm *pTop = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pIdx);
96800
        WhereTerm *pTop = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pIdx);
90141
        WhereTerm *pBtm = findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pIdx);
96801
        WhereTerm *pBtm = findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pIdx);
90142
        whereRangeScanEst(pParse, pProbe, nEq, pBtm, pTop, &nBound);
96802
        whereRangeScanEst(pParse, pProbe, nEq, pBtm, pTop, &estBound);
90143
        if( pTop ){
96803
        if( pTop ){
96804
          nBound = 1;
90144
          wsFlags |= WHERE_TOP_LIMIT;
96805
          wsFlags |= WHERE_TOP_LIMIT;
90145
          used |= pTop->prereqRight;
96806
          used |= pTop->prereqRight;
90146
        }
96807
        }
90147
        if( pBtm ){
96808
        if( pBtm ){
96809
          nBound++;
90148
          wsFlags |= WHERE_BTM_LIMIT;
96810
          wsFlags |= WHERE_BTM_LIMIT;
90149
          used |= pBtm->prereqRight;
96811
          used |= pBtm->prereqRight;
90150
        }
96812
        }
 Lines 90175-90181   static void bestBtreeIndex( Link Here 
90175
96837
90176
    /* If currently calculating the cost of using an index (not the IPK
96838
    /* If currently calculating the cost of using an index (not the IPK
90177
    ** index), determine if all required column data may be obtained without 
96839
    ** index), determine if all required column data may be obtained without 
90178
    ** seeking to entries in the main table (i.e. if the index is a covering
96840
    ** using the main table (i.e. if the index is a covering
90179
    ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
96841
    ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
90180
    ** wsFlags. Otherwise, set the bLookup variable to true.  */
96842
    ** wsFlags. Otherwise, set the bLookup variable to true.  */
90181
    if( pIdx && wsFlags ){
96843
    if( pIdx && wsFlags ){
 Lines 90194-90201   static void bestBtreeIndex( Link Here 
90194
      }
96856
      }
90195
    }
96857
    }
90196
96858
90197
    /**** Begin adding up the cost of using this index (Needs improvements)
96859
    /*
90198
    **
90199
    ** Estimate the number of rows of output.  For an IN operator,
96860
    ** Estimate the number of rows of output.  For an IN operator,
90200
    ** do not let the estimate exceed half the rows in the table.
96861
    ** do not let the estimate exceed half the rows in the table.
90201
    */
96862
    */
 Lines 90214-90221   static void bestBtreeIndex( Link Here 
90214
    /* Adjust the number of rows and the cost downward to reflect rows
96875
    /* Adjust the number of rows and the cost downward to reflect rows
90215
    ** that are excluded by range constraints.
96876
    ** that are excluded by range constraints.
90216
    */
96877
    */
90217
    nRow = (nRow * (double)nBound) / (double)100;
96878
    nRow = (nRow * (double)estBound) / (double)100;
90218
    cost = (cost * (double)nBound) / (double)100;
96879
    cost = (cost * (double)estBound) / (double)100;
90219
96880
90220
    /* Add in the estimated cost of sorting the result
96881
    /* Add in the estimated cost of sorting the result
90221
    */
96882
    */
 Lines 90232-90248   static void bestBtreeIndex( Link Here 
90232
    }
96893
    }
90233
    /**** Cost of using this index has now been computed ****/
96894
    /**** Cost of using this index has now been computed ****/
90234
96895
96896
    /* If there are additional constraints on this table that cannot
96897
    ** be used with the current index, but which might lower the number
96898
    ** of output rows, adjust the nRow value accordingly.  This only 
96899
    ** matters if the current index is the least costly, so do not bother
96900
    ** with this step if we already know this index will not be chosen.
96901
    ** Also, never reduce the output row count below 2 using this step.
96902
    **
96903
    ** Do not reduce the output row count if pSrc is the only table that
96904
    ** is notReady; if notReady is a power of two.  This will be the case
96905
    ** when the main sqlite3WhereBegin() loop is scanning for a table with
96906
    ** and "optimal" index, and on such a scan the output row count
96907
    ** reduction is not valid because it does not update the "pCost->used"
96908
    ** bitmap.  The notReady bitmap will also be a power of two when we
96909
    ** are scanning for the last table in a 64-way join.  We are willing
96910
    ** to bypass this optimization in that corner case.
96911
    */
96912
    if( nRow>2 && cost<=pCost->rCost && (notReady & (notReady-1))!=0 ){
96913
      int k;                       /* Loop counter */
96914
      int nSkipEq = nEq;           /* Number of == constraints to skip */
96915
      int nSkipRange = nBound;     /* Number of < constraints to skip */
96916
      Bitmask thisTab;             /* Bitmap for pSrc */
96917
96918
      thisTab = getMask(pWC->pMaskSet, iCur);
96919
      for(pTerm=pWC->a, k=pWC->nTerm; nRow>2 && k; k--, pTerm++){
96920
        if( pTerm->wtFlags & TERM_VIRTUAL ) continue;
96921
        if( (pTerm->prereqAll & notReady)!=thisTab ) continue;
96922
        if( pTerm->eOperator & (WO_EQ|WO_IN|WO_ISNULL) ){
96923
          if( nSkipEq ){
96924
            /* Ignore the first nEq equality matches since the index
96925
            ** has already accounted for these */
96926
            nSkipEq--;
96927
          }else{
96928
            /* Assume each additional equality match reduces the result
96929
            ** set size by a factor of 10 */
96930
            nRow /= 10;
96931
          }
96932
        }else if( pTerm->eOperator & (WO_LT|WO_LE|WO_GT|WO_GE) ){
96933
          if( nSkipRange ){
96934
            /* Ignore the first nBound range constraints since the index
96935
            ** has already accounted for these */
96936
            nSkipRange--;
96937
          }else{
96938
            /* Assume each additional range constraint reduces the result
96939
            ** set size by a factor of 3 */
96940
            nRow /= 3;
96941
          }
96942
        }else{
96943
          /* Any other expression lowers the output row count by half */
96944
          nRow /= 2;
96945
        }
96946
      }
96947
      if( nRow<2 ) nRow = 2;
96948
    }
96949
96950
90235
    WHERETRACE((
96951
    WHERETRACE((
90236
      "tbl=%s idx=%s nEq=%d nInMul=%d nBound=%d bSort=%d bLookup=%d"
96952
      "%s(%s): nEq=%d nInMul=%d estBound=%d bSort=%d bLookup=%d wsFlags=0x%x\n"
90237
      " wsFlags=%d   (nRow=%.2f cost=%.2f)\n",
96953
      "         notReady=0x%llx nRow=%.2f cost=%.2f used=0x%llx\n",
90238
      pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk"), 
96954
      pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk"), 
90239
      nEq, nInMul, nBound, bSort, bLookup, wsFlags, nRow, cost
96955
      nEq, nInMul, estBound, bSort, bLookup, wsFlags,
96956
      notReady, nRow, cost, used
90240
    ));
96957
    ));
90241
96958
90242
    /* If this index is the best we have seen so far, then record this
96959
    /* If this index is the best we have seen so far, then record this
90243
    ** index and its cost in the pCost structure.
96960
    ** index and its cost in the pCost structure.
90244
    */
96961
    */
90245
    if( (!pIdx || wsFlags) && cost<pCost->rCost ){
96962
    if( (!pIdx || wsFlags)
96963
     && (cost<pCost->rCost || (cost<=pCost->rCost && nRow<pCost->nRow))
96964
    ){
90246
      pCost->rCost = cost;
96965
      pCost->rCost = cost;
90247
      pCost->nRow = nRow;
96966
      pCost->nRow = nRow;
90248
      pCost->used = used;
96967
      pCost->used = used;
 Lines 90277-90286   static void bestBtreeIndex( Link Here 
90277
  );
96996
  );
90278
96997
90279
  WHERETRACE(("best index is: %s\n", 
96998
  WHERETRACE(("best index is: %s\n", 
90280
    (pCost->plan.u.pIdx ? pCost->plan.u.pIdx->zName : "ipk")
96999
    ((pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ? "none" : 
97000
         pCost->plan.u.pIdx ? pCost->plan.u.pIdx->zName : "ipk")
90281
  ));
97001
  ));
90282
  
97002
  
90283
  bestOrClauseIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
97003
  bestOrClauseIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
97004
  bestAutomaticIndex(pParse, pWC, pSrc, notReady, pCost);
90284
  pCost->plan.wsFlags |= eqTermMask;
97005
  pCost->plan.wsFlags |= eqTermMask;
90285
}
97006
}
90286
97007
 Lines 90328-90333   static void bestIndex( Link Here 
90328
** in the ON clause.  The term is disabled in (3) because it is not part
97049
** in the ON clause.  The term is disabled in (3) because it is not part
90329
** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
97050
** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
90330
**
97051
**
97052
** IMPLEMENTATION-OF: R-24597-58655 No tests are done for terms that are
97053
** completely satisfied by indices.
97054
**
90331
** Disabling a term causes that term to not be tested in the inner loop
97055
** Disabling a term causes that term to not be tested in the inner loop
90332
** of the join.  Disabling is an optimization.  When terms are satisfied
97056
** of the join.  Disabling is an optimization.  When terms are satisfied
90333
** by indices, we disable them to prevent redundant tests in the inner
97057
** by indices, we disable them to prevent redundant tests in the inner
 Lines 90338-90344   static void bestIndex( Link Here 
90338
*/
97062
*/
90339
static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
97063
static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
90340
  if( pTerm
97064
  if( pTerm
90341
      && ALWAYS((pTerm->wtFlags & TERM_CODED)==0)
97065
      && (pTerm->wtFlags & TERM_CODED)==0
90342
      && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
97066
      && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
90343
  ){
97067
  ){
90344
    pTerm->wtFlags |= TERM_CODED;
97068
    pTerm->wtFlags |= TERM_CODED;
 Lines 90536-90542   static int codeAllEqualityTerms( Link Here 
90536
    int k = pIdx->aiColumn[j];
97260
    int k = pIdx->aiColumn[j];
90537
    pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
97261
    pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
90538
    if( NEVER(pTerm==0) ) break;
97262
    if( NEVER(pTerm==0) ) break;
90539
    assert( (pTerm->wtFlags & TERM_CODED)==0 );
97263
    /* The following true for indices with redundant columns. 
97264
    ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
97265
    testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
97266
    testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
90540
    r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
97267
    r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
90541
    if( r1!=regBase+j ){
97268
    if( r1!=regBase+j ){
90542
      if( nReg==1 ){
97269
      if( nReg==1 ){
 Lines 90680-90685   static Bitmask codeOneLoopStart( Link Here 
90680
    assert( pTerm->pExpr!=0 );
97407
    assert( pTerm->pExpr!=0 );
90681
    assert( pTerm->leftCursor==iCur );
97408
    assert( pTerm->leftCursor==iCur );
90682
    assert( omitTable==0 );
97409
    assert( omitTable==0 );
97410
    testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
90683
    iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, iReleaseReg);
97411
    iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, iReleaseReg);
90684
    addrNxt = pLevel->addrNxt;
97412
    addrNxt = pLevel->addrNxt;
90685
    sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
97413
    sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
 Lines 90720-90725   static Bitmask codeOneLoopStart( Link Here 
90720
      assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
97448
      assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
90721
      assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
97449
      assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
90722
97450
97451
      testcase( pStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
90723
      pX = pStart->pExpr;
97452
      pX = pStart->pExpr;
90724
      assert( pX!=0 );
97453
      assert( pX!=0 );
90725
      assert( pStart->leftCursor==iCur );
97454
      assert( pStart->leftCursor==iCur );
 Lines 90737-90742   static Bitmask codeOneLoopStart( Link Here 
90737
      pX = pEnd->pExpr;
97466
      pX = pEnd->pExpr;
90738
      assert( pX!=0 );
97467
      assert( pX!=0 );
90739
      assert( pEnd->leftCursor==iCur );
97468
      assert( pEnd->leftCursor==iCur );
97469
      testcase( pEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
90740
      memEndValue = ++pParse->nMem;
97470
      memEndValue = ++pParse->nMem;
90741
      sqlite3ExprCode(pParse, pX->pRight, memEndValue);
97471
      sqlite3ExprCode(pParse, pX->pRight, memEndValue);
90742
      if( pX->op==TK_LT || pX->op==TK_GT ){
97472
      if( pX->op==TK_LT || pX->op==TK_GT ){
 Lines 90750-90756   static Bitmask codeOneLoopStart( Link Here 
90750
    pLevel->op = bRev ? OP_Prev : OP_Next;
97480
    pLevel->op = bRev ? OP_Prev : OP_Next;
90751
    pLevel->p1 = iCur;
97481
    pLevel->p1 = iCur;
90752
    pLevel->p2 = start;
97482
    pLevel->p2 = start;
90753
    pLevel->p5 = (pStart==0 && pEnd==0) ?1:0;
97483
    if( pStart==0 && pEnd==0 ){
97484
      pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
97485
    }else{
97486
      assert( pLevel->p5==0 );
97487
    }
90754
    if( testOp!=OP_Noop ){
97488
    if( testOp!=OP_Noop ){
90755
      iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
97489
      iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
90756
      sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
97490
      sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
 Lines 90790-90796   static Bitmask codeOneLoopStart( Link Here 
90790
    **         constraints but an index is selected anyway, in order
97524
    **         constraints but an index is selected anyway, in order
90791
    **         to force the output order to conform to an ORDER BY.
97525
    **         to force the output order to conform to an ORDER BY.
90792
    */  
97526
    */  
90793
    int aStartOp[] = {
97527
    static const u8 aStartOp[] = {
90794
      0,
97528
      0,
90795
      0,
97529
      0,
90796
      OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
97530
      OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
 Lines 90800-90811   static Bitmask codeOneLoopStart( Link Here 
90800
      OP_SeekGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
97534
      OP_SeekGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
90801
      OP_SeekLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
97535
      OP_SeekLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
90802
    };
97536
    };
90803
    int aEndOp[] = {
97537
    static const u8 aEndOp[] = {
90804
      OP_Noop,             /* 0: (!end_constraints) */
97538
      OP_Noop,             /* 0: (!end_constraints) */
90805
      OP_IdxGE,            /* 1: (end_constraints && !bRev) */
97539
      OP_IdxGE,            /* 1: (end_constraints && !bRev) */
90806
      OP_IdxLT             /* 2: (end_constraints && bRev) */
97540
      OP_IdxLT             /* 2: (end_constraints && bRev) */
90807
    };
97541
    };
90808
    int nEq = pLevel->plan.nEq;
97542
    int nEq = pLevel->plan.nEq;  /* Number of == or IN terms */
90809
    int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
97543
    int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
90810
    int regBase;                 /* Base register holding constraint values */
97544
    int regBase;                 /* Base register holding constraint values */
90811
    int r1;                      /* Temp register */
97545
    int r1;                      /* Temp register */
 Lines 90815-90825   static Bitmask codeOneLoopStart( Link Here 
90815
    int endEq;                   /* True if range end uses ==, >= or <= */
97549
    int endEq;                   /* True if range end uses ==, >= or <= */
90816
    int start_constraints;       /* Start of range is constrained */
97550
    int start_constraints;       /* Start of range is constrained */
90817
    int nConstraint;             /* Number of constraint terms */
97551
    int nConstraint;             /* Number of constraint terms */
90818
    Index *pIdx;         /* The index we will be using */
97552
    Index *pIdx;                 /* The index we will be using */
90819
    int iIdxCur;         /* The VDBE cursor for the index */
97553
    int iIdxCur;                 /* The VDBE cursor for the index */
90820
    int nExtraReg = 0;   /* Number of extra registers needed */
97554
    int nExtraReg = 0;           /* Number of extra registers needed */
90821
    int op;              /* Instruction opcode */
97555
    int op;                      /* Instruction opcode */
90822
    char *zAff;
97556
    char *zStartAff;             /* Affinity for start of range constraint */
97557
    char *zEndAff;               /* Affinity for end of range constraint */
90823
97558
90824
    pIdx = pLevel->plan.u.pIdx;
97559
    pIdx = pLevel->plan.u.pIdx;
90825
    iIdxCur = pLevel->iIdxCur;
97560
    iIdxCur = pLevel->iIdxCur;
 Lines 90860-90874   static Bitmask codeOneLoopStart( Link Here 
90860
    ** starting at regBase.
97595
    ** starting at regBase.
90861
    */
97596
    */
90862
    regBase = codeAllEqualityTerms(
97597
    regBase = codeAllEqualityTerms(
90863
        pParse, pLevel, pWC, notReady, nExtraReg, &zAff
97598
        pParse, pLevel, pWC, notReady, nExtraReg, &zStartAff
90864
    );
97599
    );
97600
    zEndAff = sqlite3DbStrDup(pParse->db, zStartAff);
90865
    addrNxt = pLevel->addrNxt;
97601
    addrNxt = pLevel->addrNxt;
90866
97602
90867
    /* If we are doing a reverse order scan on an ascending index, or
97603
    /* If we are doing a reverse order scan on an ascending index, or
90868
    ** a forward order scan on a descending index, interchange the 
97604
    ** a forward order scan on a descending index, interchange the 
90869
    ** start and end terms (pRangeStart and pRangeEnd).
97605
    ** start and end terms (pRangeStart and pRangeEnd).
90870
    */
97606
    */
90871
    if( bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC) ){
97607
    if( nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC) ){
90872
      SWAP(WhereTerm *, pRangeEnd, pRangeStart);
97608
      SWAP(WhereTerm *, pRangeEnd, pRangeStart);
90873
    }
97609
    }
90874
97610
 Lines 90886-90910   static Bitmask codeOneLoopStart( Link Here 
90886
      Expr *pRight = pRangeStart->pExpr->pRight;
97622
      Expr *pRight = pRangeStart->pExpr->pRight;
90887
      sqlite3ExprCode(pParse, pRight, regBase+nEq);
97623
      sqlite3ExprCode(pParse, pRight, regBase+nEq);
90888
      sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
97624
      sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
90889
      if( zAff ){
97625
      if( zStartAff ){
90890
        if( sqlite3CompareAffinity(pRight, zAff[nConstraint])==SQLITE_AFF_NONE){
97626
        if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
90891
          /* Since the comparison is to be performed with no conversions
97627
          /* Since the comparison is to be performed with no conversions
90892
          ** applied to the operands, set the affinity to apply to pRight to 
97628
          ** applied to the operands, set the affinity to apply to pRight to 
90893
          ** SQLITE_AFF_NONE.  */
97629
          ** SQLITE_AFF_NONE.  */
90894
          zAff[nConstraint] = SQLITE_AFF_NONE;
97630
          zStartAff[nEq] = SQLITE_AFF_NONE;
90895
        }
97631
        }
90896
        if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[nConstraint]) ){
97632
        if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
90897
          zAff[nConstraint] = SQLITE_AFF_NONE;
97633
          zStartAff[nEq] = SQLITE_AFF_NONE;
90898
        }
97634
        }
90899
      }  
97635
      }  
90900
      nConstraint++;
97636
      nConstraint++;
97637
      testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
90901
    }else if( isMinQuery ){
97638
    }else if( isMinQuery ){
90902
      sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
97639
      sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
90903
      nConstraint++;
97640
      nConstraint++;
90904
      startEq = 0;
97641
      startEq = 0;
90905
      start_constraints = 1;
97642
      start_constraints = 1;
90906
    }
97643
    }
90907
    codeApplyAffinity(pParse, regBase, nConstraint, zAff);
97644
    codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
90908
    op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
97645
    op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
90909
    assert( op!=0 );
97646
    assert( op!=0 );
90910
    testcase( op==OP_Rewind );
97647
    testcase( op==OP_Rewind );
 Lines 90924-90944   static Bitmask codeOneLoopStart( Link Here 
90924
      sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
97661
      sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
90925
      sqlite3ExprCode(pParse, pRight, regBase+nEq);
97662
      sqlite3ExprCode(pParse, pRight, regBase+nEq);
90926
      sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
97663
      sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
90927
      if( zAff ){
97664
      if( zEndAff ){
90928
        if( sqlite3CompareAffinity(pRight, zAff[nConstraint])==SQLITE_AFF_NONE){
97665
        if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
90929
          /* Since the comparison is to be performed with no conversions
97666
          /* Since the comparison is to be performed with no conversions
90930
          ** applied to the operands, set the affinity to apply to pRight to 
97667
          ** applied to the operands, set the affinity to apply to pRight to 
90931
          ** SQLITE_AFF_NONE.  */
97668
          ** SQLITE_AFF_NONE.  */
90932
          zAff[nConstraint] = SQLITE_AFF_NONE;
97669
          zEndAff[nEq] = SQLITE_AFF_NONE;
90933
        }
97670
        }
90934
        if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[nConstraint]) ){
97671
        if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
90935
          zAff[nConstraint] = SQLITE_AFF_NONE;
97672
          zEndAff[nEq] = SQLITE_AFF_NONE;
90936
        }
97673
        }
90937
      }  
97674
      }  
90938
      codeApplyAffinity(pParse, regBase, nEq+1, zAff);
97675
      codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
90939
      nConstraint++;
97676
      nConstraint++;
90940
    }
97677
      testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
90941
    sqlite3DbFree(pParse->db, zAff);
97678
    }
97679
    sqlite3DbFree(pParse->db, zStartAff);
97680
    sqlite3DbFree(pParse->db, zEndAff);
90942
97681
90943
    /* Top of the loop body */
97682
    /* Top of the loop body */
90944
    pLevel->p2 = sqlite3VdbeCurrentAddr(v);
97683
    pLevel->p2 = sqlite3VdbeCurrentAddr(v);
 Lines 91142-91152   static Bitmask codeOneLoopStart( Link Here 
91142
97881
91143
  /* Insert code to test every subexpression that can be completely
97882
  /* Insert code to test every subexpression that can be completely
91144
  ** computed using the current set of tables.
97883
  ** computed using the current set of tables.
97884
  **
97885
  ** IMPLEMENTATION-OF: R-49525-50935 Terms that cannot be satisfied through
97886
  ** the use of indices become tests that are evaluated against each row of
97887
  ** the relevant input tables.
91145
  */
97888
  */
91146
  k = 0;
97889
  k = 0;
91147
  for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
97890
  for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
91148
    Expr *pE;
97891
    Expr *pE;
91149
    testcase( pTerm->wtFlags & TERM_VIRTUAL );
97892
    testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
91150
    testcase( pTerm->wtFlags & TERM_CODED );
97893
    testcase( pTerm->wtFlags & TERM_CODED );
91151
    if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
97894
    if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
91152
    if( (pTerm->prereqAll & notReady)!=0 ){
97895
    if( (pTerm->prereqAll & notReady)!=0 ){
 Lines 91174-91180   static Bitmask codeOneLoopStart( Link Here 
91174
    VdbeComment((v, "record LEFT JOIN hit"));
97917
    VdbeComment((v, "record LEFT JOIN hit"));
91175
    sqlite3ExprCacheClear(pParse);
97918
    sqlite3ExprCacheClear(pParse);
91176
    for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
97919
    for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
91177
      testcase( pTerm->wtFlags & TERM_VIRTUAL );
97920
      testcase( pTerm->wtFlags & TERM_VIRTUAL );  /* IMP: R-30575-11662 */
91178
      testcase( pTerm->wtFlags & TERM_CODED );
97921
      testcase( pTerm->wtFlags & TERM_CODED );
91179
      if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
97922
      if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
91180
      if( (pTerm->prereqAll & notReady)!=0 ){
97923
      if( (pTerm->prereqAll & notReady)!=0 ){
 Lines 91208-91214   static int nQPlan = 0; /* N Link Here 
91208
** Free a WhereInfo structure
97951
** Free a WhereInfo structure
91209
*/
97952
*/
91210
static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
97953
static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
91211
  if( pWInfo ){
97954
  if( ALWAYS(pWInfo) ){
91212
    int i;
97955
    int i;
91213
    for(i=0; i<pWInfo->nLevel; i++){
97956
    for(i=0; i<pWInfo->nLevel; i++){
91214
      sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
97957
      sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
 Lines 91219-91224   static void whereInfoFree(sqlite3 *db, W Link Here 
91219
        }
97962
        }
91220
        sqlite3DbFree(db, pInfo);
97963
        sqlite3DbFree(db, pInfo);
91221
      }
97964
      }
97965
      if( pWInfo->a[i].plan.wsFlags & WHERE_TEMP_INDEX ){
97966
        Index *pIdx = pWInfo->a[i].plan.u.pIdx;
97967
        if( pIdx ){
97968
          sqlite3DbFree(db, pIdx->zColAff);
97969
          sqlite3DbFree(db, pIdx);
97970
        }
97971
      }
91222
    }
97972
    }
91223
    whereClauseClear(pWInfo->pWC);
97973
    whereClauseClear(pWInfo->pWC);
91224
    sqlite3DbFree(db, pWInfo);
97974
    sqlite3DbFree(db, pWInfo);
 Lines 91338-91343   SQLITE_PRIVATE WhereInfo *sqlite3WhereBe Link Here 
91338
  /* The number of tables in the FROM clause is limited by the number of
98088
  /* The number of tables in the FROM clause is limited by the number of
91339
  ** bits in a Bitmask 
98089
  ** bits in a Bitmask 
91340
  */
98090
  */
98091
  testcase( pTabList->nSrc==BMS );
91341
  if( pTabList->nSrc>BMS ){
98092
  if( pTabList->nSrc>BMS ){
91342
    sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
98093
    sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
91343
    return 0;
98094
    return 0;
 Lines 91365-91370   SQLITE_PRIVATE WhereInfo *sqlite3WhereBe Link Here 
91365
      sizeof(WhereMaskSet)
98116
      sizeof(WhereMaskSet)
91366
  );
98117
  );
91367
  if( db->mallocFailed ){
98118
  if( db->mallocFailed ){
98119
    sqlite3DbFree(db, pWInfo);
98120
    pWInfo = 0;
91368
    goto whereBeginError;
98121
    goto whereBeginError;
91369
  }
98122
  }
91370
  pWInfo->nLevel = nTabList;
98123
  pWInfo->nLevel = nTabList;
 Lines 91373-91378   SQLITE_PRIVATE WhereInfo *sqlite3WhereBe Link Here 
91373
  pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
98126
  pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
91374
  pWInfo->pWC = pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
98127
  pWInfo->pWC = pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
91375
  pWInfo->wctrlFlags = wctrlFlags;
98128
  pWInfo->wctrlFlags = wctrlFlags;
98129
  pWInfo->savedNQueryLoop = pParse->nQueryLoop;
91376
  pMaskSet = (WhereMaskSet*)&pWC[1];
98130
  pMaskSet = (WhereMaskSet*)&pWC[1];
91377
98131
91378
  /* Split the WHERE clause into separate subexpressions where each
98132
  /* Split the WHERE clause into separate subexpressions where each
 Lines 91381-91387   SQLITE_PRIVATE WhereInfo *sqlite3WhereBe Link Here 
91381
  initMaskSet(pMaskSet);
98135
  initMaskSet(pMaskSet);
91382
  whereClauseInit(pWC, pParse, pMaskSet);
98136
  whereClauseInit(pWC, pParse, pMaskSet);
91383
  sqlite3ExprCodeConstants(pParse, pWhere);
98137
  sqlite3ExprCodeConstants(pParse, pWhere);
91384
  whereSplit(pWC, pWhere, TK_AND);
98138
  whereSplit(pWC, pWhere, TK_AND);   /* IMP: R-15842-53296 */
91385
    
98139
    
91386
  /* Special case: a WHERE clause that is constant.  Evaluate the
98140
  /* Special case: a WHERE clause that is constant.  Evaluate the
91387
  ** expression and either jump over all of the code or fall thru.
98141
  ** expression and either jump over all of the code or fall thru.
 Lines 91469-91493   SQLITE_PRIVATE WhereInfo *sqlite3WhereBe Link Here 
91469
    int bestJ = -1;             /* The value of j */
98223
    int bestJ = -1;             /* The value of j */
91470
    Bitmask m;                  /* Bitmask value for j or bestJ */
98224
    Bitmask m;                  /* Bitmask value for j or bestJ */
91471
    int isOptimal;              /* Iterator for optimal/non-optimal search */
98225
    int isOptimal;              /* Iterator for optimal/non-optimal search */
98226
    int nUnconstrained;         /* Number tables without INDEXED BY */
98227
    Bitmask notIndexed;         /* Mask of tables that cannot use an index */
91472
98228
91473
    memset(&bestPlan, 0, sizeof(bestPlan));
98229
    memset(&bestPlan, 0, sizeof(bestPlan));
91474
    bestPlan.rCost = SQLITE_BIG_DBL;
98230
    bestPlan.rCost = SQLITE_BIG_DBL;
91475
98231
91476
    /* Loop through the remaining entries in the FROM clause to find the
98232
    /* Loop through the remaining entries in the FROM clause to find the
91477
    ** next nested loop. The FROM clause entries may be iterated through
98233
    ** next nested loop. The loop tests all FROM clause entries
91478
    ** either once or twice. 
98234
    ** either once or twice. 
91479
    **
98235
    **
91480
    ** The first iteration, which is always performed, searches for the
98236
    ** The first test is always performed if there are two or more entries
91481
    ** FROM clause entry that permits the lowest-cost, "optimal" scan. In
98237
    ** remaining and never performed if there is only one FROM clause entry
98238
    ** to choose from.  The first test looks for an "optimal" scan.  In
91482
    ** this context an optimal scan is one that uses the same strategy
98239
    ** this context an optimal scan is one that uses the same strategy
91483
    ** for the given FROM clause entry as would be selected if the entry
98240
    ** for the given FROM clause entry as would be selected if the entry
91484
    ** were used as the innermost nested loop.  In other words, a table
98241
    ** were used as the innermost nested loop.  In other words, a table
91485
    ** is chosen such that the cost of running that table cannot be reduced
98242
    ** is chosen such that the cost of running that table cannot be reduced
91486
    ** by waiting for other tables to run first.
98243
    ** by waiting for other tables to run first.  This "optimal" test works
91487
    **
98244
    ** by first assuming that the FROM clause is on the inner loop and finding
91488
    ** The second iteration is only performed if no optimal scan strategies
98245
    ** its query plan, then checking to see if that query plan uses any
91489
    ** were found by the first. This iteration is used to search for the
98246
    ** other FROM clause terms that are notReady.  If no notReady terms are
91490
    ** lowest cost scan overall.
98247
    ** used then the "optimal" query plan works.
98248
    **
98249
    ** The second loop iteration is only performed if no optimal scan
98250
    ** strategies were found by the first loop. This 2nd iteration is used to
98251
    ** search for the lowest cost scan overall.
91491
    **
98252
    **
91492
    ** Previous versions of SQLite performed only the second iteration -
98253
    ** Previous versions of SQLite performed only the second iteration -
91493
    ** the next outermost loop was always that with the lowest overall
98254
    ** the next outermost loop was always that with the lowest overall
 Lines 91505-91513   SQLITE_PRIVATE WhereInfo *sqlite3WhereBe Link Here 
91505
    ** algorithm may choose to use t2 for the outer loop, which is a much
98266
    ** algorithm may choose to use t2 for the outer loop, which is a much
91506
    ** costlier approach.
98267
    ** costlier approach.
91507
    */
98268
    */
91508
    for(isOptimal=1; isOptimal>=0 && bestJ<0; isOptimal--){
98269
    nUnconstrained = 0;
91509
      Bitmask mask = (isOptimal ? 0 : notReady);
98270
    notIndexed = 0;
91510
      assert( (nTabList-iFrom)>1 || isOptimal );
98271
    for(isOptimal=(iFrom<nTabList-1); isOptimal>=0; isOptimal--){
98272
      Bitmask mask;             /* Mask of tables not yet ready */
91511
      for(j=iFrom, pTabItem=&pTabList->a[j]; j<nTabList; j++, pTabItem++){
98273
      for(j=iFrom, pTabItem=&pTabList->a[j]; j<nTabList; j++, pTabItem++){
91512
        int doNotReorder;    /* True if this table should not be reordered */
98274
        int doNotReorder;    /* True if this table should not be reordered */
91513
        WhereCost sCost;     /* Cost information from best[Virtual]Index() */
98275
        WhereCost sCost;     /* Cost information from best[Virtual]Index() */
 Lines 91520-91526   SQLITE_PRIVATE WhereInfo *sqlite3WhereBe Link Here 
91520
          if( j==iFrom ) iFrom++;
98282
          if( j==iFrom ) iFrom++;
91521
          continue;
98283
          continue;
91522
        }
98284
        }
98285
        mask = (isOptimal ? m : notReady);
91523
        pOrderBy = ((i==0 && ppOrderBy )?*ppOrderBy:0);
98286
        pOrderBy = ((i==0 && ppOrderBy )?*ppOrderBy:0);
98287
        if( pTabItem->pIndex==0 ) nUnconstrained++;
91524
  
98288
  
91525
        assert( pTabItem->pTab );
98289
        assert( pTabItem->pTab );
91526
#ifndef SQLITE_OMIT_VIRTUALTABLE
98290
#ifndef SQLITE_OMIT_VIRTUALTABLE
 Lines 91534-91542   SQLITE_PRIVATE WhereInfo *sqlite3WhereBe Link Here 
91534
        }
98298
        }
91535
        assert( isOptimal || (sCost.used&notReady)==0 );
98299
        assert( isOptimal || (sCost.used&notReady)==0 );
91536
98300
91537
        if( (sCost.used&notReady)==0
98301
        /* If an INDEXED BY clause is present, then the plan must use that
91538
         && (j==iFrom || sCost.rCost<bestPlan.rCost) 
98302
        ** index if it uses any index at all */
98303
        assert( pTabItem->pIndex==0 
98304
                  || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
98305
                  || sCost.plan.u.pIdx==pTabItem->pIndex );
98306
98307
        if( isOptimal && (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
98308
          notIndexed |= m;
98309
        }
98310
98311
        /* Conditions under which this table becomes the best so far:
98312
        **
98313
        **   (1) The table must not depend on other tables that have not
98314
        **       yet run.
98315
        **
98316
        **   (2) A full-table-scan plan cannot supercede another plan unless
98317
        **       it is an "optimal" plan as defined above.
98318
        **
98319
        **   (3) All tables have an INDEXED BY clause or this table lacks an
98320
        **       INDEXED BY clause or this table uses the specific
98321
        **       index specified by its INDEXED BY clause.  This rule ensures
98322
        **       that a best-so-far is always selected even if an impossible
98323
        **       combination of INDEXED BY clauses are given.  The error
98324
        **       will be detected and relayed back to the application later.
98325
        **       The NEVER() comes about because rule (2) above prevents
98326
        **       An indexable full-table-scan from reaching rule (3).
98327
        **
98328
        **   (4) The plan cost must be lower than prior plans or else the
98329
        **       cost must be the same and the number of rows must be lower.
98330
        */
98331
        if( (sCost.used&notReady)==0                       /* (1) */
98332
            && (bestJ<0 || (notIndexed&m)!=0               /* (2) */
98333
                || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0)
98334
            && (nUnconstrained==0 || pTabItem->pIndex==0   /* (3) */
98335
                || NEVER((sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0))
98336
            && (bestJ<0 || sCost.rCost<bestPlan.rCost      /* (4) */
98337
                || (sCost.rCost<=bestPlan.rCost && sCost.nRow<bestPlan.nRow))
91539
        ){
98338
        ){
98339
          WHERETRACE(("... best so far with cost=%g and nRow=%g\n",
98340
                      sCost.rCost, sCost.nRow));
91540
          bestPlan = sCost;
98341
          bestPlan = sCost;
91541
          bestJ = j;
98342
          bestJ = j;
91542
        }
98343
        }
 Lines 91552-91564   SQLITE_PRIVATE WhereInfo *sqlite3WhereBe Link Here 
91552
    }
98353
    }
91553
    andFlags &= bestPlan.plan.wsFlags;
98354
    andFlags &= bestPlan.plan.wsFlags;
91554
    pLevel->plan = bestPlan.plan;
98355
    pLevel->plan = bestPlan.plan;
91555
    if( bestPlan.plan.wsFlags & WHERE_INDEXED ){
98356
    testcase( bestPlan.plan.wsFlags & WHERE_INDEXED );
98357
    testcase( bestPlan.plan.wsFlags & WHERE_TEMP_INDEX );
98358
    if( bestPlan.plan.wsFlags & (WHERE_INDEXED|WHERE_TEMP_INDEX) ){
91556
      pLevel->iIdxCur = pParse->nTab++;
98359
      pLevel->iIdxCur = pParse->nTab++;
91557
    }else{
98360
    }else{
91558
      pLevel->iIdxCur = -1;
98361
      pLevel->iIdxCur = -1;
91559
    }
98362
    }
91560
    notReady &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
98363
    notReady &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
91561
    pLevel->iFrom = (u8)bestJ;
98364
    pLevel->iFrom = (u8)bestJ;
98365
    if( bestPlan.nRow>=(double)1 ) pParse->nQueryLoop *= bestPlan.nRow;
91562
98366
91563
    /* Check that if the table scanned by this loop iteration had an
98367
    /* Check that if the table scanned by this loop iteration had an
91564
    ** INDEXED BY clause attached to it, that the named index is being
98368
    ** INDEXED BY clause attached to it, that the named index is being
 Lines 91605-91610   SQLITE_PRIVATE WhereInfo *sqlite3WhereBe Link Here 
91605
  ** searching those tables.
98409
  ** searching those tables.
91606
  */
98410
  */
91607
  sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
98411
  sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
98412
  notReady = ~(Bitmask)0;
91608
  for(i=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
98413
  for(i=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
91609
    Table *pTab;     /* Table to open */
98414
    Table *pTab;     /* Table to open */
91610
    int iDb;         /* Index of database containing table/index */
98415
    int iDb;         /* Index of database containing table/index */
 Lines 91617-91623   SQLITE_PRIVATE WhereInfo *sqlite3WhereBe Link Here 
91617
      if( pItem->zAlias ){
98422
      if( pItem->zAlias ){
91618
        zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
98423
        zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
91619
      }
98424
      }
91620
      if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
98425
      if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
98426
        zMsg = sqlite3MAppendf(db, zMsg, "%s WITH AUTOMATIC INDEX", zMsg);
98427
      }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
91621
        zMsg = sqlite3MAppendf(db, zMsg, "%s WITH INDEX %s",
98428
        zMsg = sqlite3MAppendf(db, zMsg, "%s WITH INDEX %s",
91622
           zMsg, pLevel->plan.u.pIdx->zName);
98429
           zMsg, pLevel->plan.u.pIdx->zName);
91623
      }else if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
98430
      }else if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
 Lines 91640-91647   SQLITE_PRIVATE WhereInfo *sqlite3WhereBe Link Here 
91640
#endif /* SQLITE_OMIT_EXPLAIN */
98447
#endif /* SQLITE_OMIT_EXPLAIN */
91641
    pTabItem = &pTabList->a[pLevel->iFrom];
98448
    pTabItem = &pTabList->a[pLevel->iFrom];
91642
    pTab = pTabItem->pTab;
98449
    pTab = pTabItem->pTab;
98450
    pLevel->iTabCur = pTabItem->iCursor;
91643
    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
98451
    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
91644
    if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ) continue;
98452
    if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
98453
      /* Do nothing */
98454
    }else
91645
#ifndef SQLITE_OMIT_VIRTUALTABLE
98455
#ifndef SQLITE_OMIT_VIRTUALTABLE
91646
    if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
98456
    if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
91647
      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
98457
      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
 Lines 91653-91658   SQLITE_PRIVATE WhereInfo *sqlite3WhereBe Link Here 
91653
         && (wctrlFlags & WHERE_OMIT_OPEN)==0 ){
98463
         && (wctrlFlags & WHERE_OMIT_OPEN)==0 ){
91654
      int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
98464
      int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
91655
      sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
98465
      sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
98466
      testcase( pTab->nCol==BMS-1 );
98467
      testcase( pTab->nCol==BMS );
91656
      if( !pWInfo->okOnePass && pTab->nCol<BMS ){
98468
      if( !pWInfo->okOnePass && pTab->nCol<BMS ){
91657
        Bitmask b = pTabItem->colUsed;
98469
        Bitmask b = pTabItem->colUsed;
91658
        int n = 0;
98470
        int n = 0;
 Lines 91664-91670   SQLITE_PRIVATE WhereInfo *sqlite3WhereBe Link Here 
91664
    }else{
98476
    }else{
91665
      sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
98477
      sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
91666
    }
98478
    }
91667
    pLevel->iTabCur = pTabItem->iCursor;
98479
#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
98480
    if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
98481
      constructAutomaticIndex(pParse, pWC, pTabItem, notReady, pLevel);
98482
    }else
98483
#endif
91668
    if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
98484
    if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
91669
      Index *pIx = pLevel->plan.u.pIdx;
98485
      Index *pIx = pLevel->plan.u.pIdx;
91670
      KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
98486
      KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
 Lines 91676-91683   SQLITE_PRIVATE WhereInfo *sqlite3WhereBe Link Here 
91676
      VdbeComment((v, "%s", pIx->zName));
98492
      VdbeComment((v, "%s", pIx->zName));
91677
    }
98493
    }
91678
    sqlite3CodeVerifySchema(pParse, iDb);
98494
    sqlite3CodeVerifySchema(pParse, iDb);
98495
    notReady &= ~getMask(pWC->pMaskSet, pTabItem->iCursor);
91679
  }
98496
  }
91680
  pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
98497
  pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
98498
  if( db->mallocFailed ) goto whereBeginError;
91681
98499
91682
  /* Generate the code to do the search.  Each iteration of the for
98500
  /* Generate the code to do the search.  Each iteration of the for
91683
  ** loop below generates code for a single nested loop of the VM
98501
  ** loop below generates code for a single nested loop of the VM
 Lines 91745-91751   SQLITE_PRIVATE WhereInfo *sqlite3WhereBe Link Here 
91745
98563
91746
  /* Jump here if malloc fails */
98564
  /* Jump here if malloc fails */
91747
whereBeginError:
98565
whereBeginError:
91748
  whereInfoFree(db, pWInfo);
98566
  if( pWInfo ){
98567
    pParse->nQueryLoop = pWInfo->savedNQueryLoop;
98568
    whereInfoFree(db, pWInfo);
98569
  }
91749
  return 0;
98570
  return 0;
91750
}
98571
}
91751
98572
 Lines 91815-91826   SQLITE_PRIVATE void sqlite3WhereEnd(Wher Link Here 
91815
    struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
98636
    struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
91816
    Table *pTab = pTabItem->pTab;
98637
    Table *pTab = pTabItem->pTab;
91817
    assert( pTab!=0 );
98638
    assert( pTab!=0 );
91818
    if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ) continue;
98639
    if( (pTab->tabFlags & TF_Ephemeral)==0
91819
    if( (pWInfo->wctrlFlags & WHERE_OMIT_CLOSE)==0 ){
98640
     && pTab->pSelect==0
91820
      if( !pWInfo->okOnePass && (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
98641
     && (pWInfo->wctrlFlags & WHERE_OMIT_CLOSE)==0
98642
    ){
98643
      int ws = pLevel->plan.wsFlags;
98644
      if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
91821
        sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
98645
        sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
91822
      }
98646
      }
91823
      if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
98647
      if( (ws & WHERE_INDEXED)!=0 && (ws & WHERE_TEMP_INDEX)==0 ){
91824
        sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
98648
        sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
91825
      }
98649
      }
91826
    }
98650
    }
 Lines 91868-91873   SQLITE_PRIVATE void sqlite3WhereEnd(Wher Link Here 
91868
98692
91869
  /* Final cleanup
98693
  /* Final cleanup
91870
  */
98694
  */
98695
  pParse->nQueryLoop = pWInfo->savedNQueryLoop;
91871
  whereInfoFree(db, pWInfo);
98696
  whereInfoFree(db, pWInfo);
91872
  return;
98697
  return;
91873
}
98698
}
 Lines 92055-92080   struct AttachKey { int type; Token key; Link Here 
92055
**                       defined, then do no error processing.
98880
**                       defined, then do no error processing.
92056
*/
98881
*/
92057
#define YYCODETYPE unsigned char
98882
#define YYCODETYPE unsigned char
92058
#define YYNOCODE 254
98883
#define YYNOCODE 253
92059
#define YYACTIONTYPE unsigned short int
98884
#define YYACTIONTYPE unsigned short int
92060
#define YYWILDCARD 67
98885
#define YYWILDCARD 67
92061
#define sqlite3ParserTOKENTYPE Token
98886
#define sqlite3ParserTOKENTYPE Token
92062
typedef union {
98887
typedef union {
92063
  int yyinit;
98888
  int yyinit;
92064
  sqlite3ParserTOKENTYPE yy0;
98889
  sqlite3ParserTOKENTYPE yy0;
92065
  Select* yy3;
98890
  int yy4;
92066
  ExprList* yy14;
98891
  struct TrigEvent yy90;
92067
  SrcList* yy65;
98892
  ExprSpan yy118;
92068
  struct LikeOp yy96;
98893
  TriggerStep* yy203;
92069
  Expr* yy132;
98894
  u8 yy210;
92070
  u8 yy186;
98895
  struct {int value; int mask;} yy215;
92071
  int yy328;
98896
  SrcList* yy259;
92072
  ExprSpan yy346;
98897
  struct LimitVal yy292;
92073
  struct TrigEvent yy378;
98898
  Expr* yy314;
92074
  IdList* yy408;
98899
  ExprList* yy322;
92075
  struct {int value; int mask;} yy429;
98900
  struct LikeOp yy342;
92076
  TriggerStep* yy473;
98901
  IdList* yy384;
92077
  struct LimitVal yy476;
98902
  Select* yy387;
92078
} YYMINORTYPE;
98903
} YYMINORTYPE;
92079
#ifndef YYSTACKDEPTH
98904
#ifndef YYSTACKDEPTH
92080
#define YYSTACKDEPTH 100
98905
#define YYSTACKDEPTH 100
 Lines 92083-92090   typedef union { Link Here 
92083
#define sqlite3ParserARG_PDECL ,Parse *pParse
98908
#define sqlite3ParserARG_PDECL ,Parse *pParse
92084
#define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
98909
#define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
92085
#define sqlite3ParserARG_STORE yypParser->pParse = pParse
98910
#define sqlite3ParserARG_STORE yypParser->pParse = pParse
92086
#define YYNSTATE 631
98911
#define YYNSTATE 630
92087
#define YYNRULE 330
98912
#define YYNRULE 329
92088
#define YYFALLBACK 1
98913
#define YYFALLBACK 1
92089
#define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
98914
#define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
92090
#define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
98915
#define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
 Lines 92154-92625   static const YYMINORTYPE yyzerominor = { Link Here 
92154
**                     shifting non-terminals after a reduce.
98979
**                     shifting non-terminals after a reduce.
92155
**  yy_default[]       Default action for each state.
98980
**  yy_default[]       Default action for each state.
92156
*/
98981
*/
92157
#define YY_ACTTAB_COUNT (1550)
98982
#define YY_ACTTAB_COUNT (1557)
92158
static const YYACTIONTYPE yy_action[] = {
98983
static const YYACTIONTYPE yy_action[] = {
92159
 /*     0 */   313,   49,  556,   46,  147,  172,  628,  598,   55,   55,
98984
 /*     0 */   313,  960,  186,  419,    2,  172,  627,  597,   55,   55,
92160
 /*    10 */    55,   55,  302,   53,   53,   53,   53,   52,   52,   51,
98985
 /*    10 */    55,   55,   48,   53,   53,   53,   53,   52,   52,   51,
92161
 /*    20 */    51,   51,   50,  238,  603,   66,  624,  623,  604,  598,
98986
 /*    20 */    51,   51,   50,  238,  302,  283,  623,  622,  516,  515,
92162
 /*    30 */   591,  585,   48,   53,   53,   53,   53,   52,   52,   51,
98987
 /*    30 */   590,  584,   55,   55,   55,   55,  282,   53,   53,   53,
92163
 /*    40 */    51,   51,   50,  238,   51,   51,   51,   50,  238,   56,
98988
 /*    40 */    53,   52,   52,   51,   51,   51,   50,  238,    6,   56,
92164
 /*    50 */    57,   47,  583,  582,  584,  584,   54,   54,   55,   55,
98989
 /*    50 */    57,   47,  582,  581,  583,  583,   54,   54,   55,   55,
92165
 /*    60 */    55,   55,  609,   53,   53,   53,   53,   52,   52,   51,
98990
 /*    60 */    55,   55,  608,   53,   53,   53,   53,   52,   52,   51,
92166
 /*    70 */    51,   51,   50,  238,  313,  598,  672,  330,  411,  217,
98991
 /*    70 */    51,   51,   50,  238,  313,  597,  409,  330,  579,  579,
92167
 /*    80 */    32,   53,   53,   53,   53,   52,   52,   51,   51,   51,
98992
 /*    80 */    32,   53,   53,   53,   53,   52,   52,   51,   51,   51,
92168
 /*    90 */    50,  238,  330,  414,  621,  620,  166,  598,  673,  382,
98993
 /*    90 */    50,  238,  330,  217,  620,  619,  166,  411,  624,  382,
92169
 /*   100 */   379,  378,  602,   73,  591,  585,  307,  424,  166,   58,
98994
 /*   100 */   379,  378,    7,  491,  590,  584,  200,  199,  198,   58,
92170
 /*   110 */   377,  382,  379,  378,  516,  515,  624,  623,  254,  200,
98995
 /*   110 */   377,  300,  414,  621,  481,   66,  623,  622,  621,  580,
92171
 /*   120 */   199,  198,  377,   56,   57,   47,  583,  582,  584,  584,
98996
 /*   120 */   254,  601,   94,   56,   57,   47,  582,  581,  583,  583,
92172
 /*   130 */    54,   54,   55,   55,   55,   55,  581,   53,   53,   53,
98997
 /*   130 */    54,   54,   55,   55,   55,   55,  671,   53,   53,   53,
92173
 /*   140 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  270,
98998
 /*   140 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  532,
92174
 /*   150 */   226,  422,  283,  133,  177,  139,  284,  385,  279,  384,
98999
 /*   150 */   226,  506,  507,  133,  177,  139,  284,  385,  279,  384,
92175
 /*   160 */   169,  197,  251,  282,  253,  226,  411,  275,  440,  167,
99000
 /*   160 */   169,  197,  342,  398,  251,  226,  253,  275,  388,  167,
92176
 /*   170 */   139,  284,  385,  279,  384,  169,  571,  236,  591,  585,
99001
 /*   170 */   139,  284,  385,  279,  384,  169,  570,  236,  590,  584,
92177
 /*   180 */   240,  414,  275,  622,  621,  620,  674,  437,  441,  442,
99002
 /*   180 */   672,  240,  275,  157,  620,  619,  554,  437,   51,   51,
92178
 /*   190 */   602,   88,  352,  266,  439,  268,  438,   56,   57,   47,
99003
 /*   190 */    51,   50,  238,  343,  439,  553,  438,   56,   57,   47,
92179
 /*   200 */   583,  582,  584,  584,   54,   54,   55,   55,   55,   55,
99004
 /*   200 */   582,  581,  583,  583,   54,   54,   55,   55,   55,   55,
92180
 /*   210 */   465,   53,   53,   53,   53,   52,   52,   51,   51,   51,
99005
 /*   210 */   465,   53,   53,   53,   53,   52,   52,   51,   51,   51,
92181
 /*   220 */    50,  238,  313,  471,   52,   52,   51,   51,   51,   50,
99006
 /*   220 */    50,  238,  313,  390,   52,   52,   51,   51,   51,   50,
92182
 /*   230 */   238,  234,  166,  491,  567,  382,  379,  378,    1,  440,
99007
 /*   230 */   238,  391,  166,  491,  566,  382,  379,  378,  409,  440,
92183
 /*   240 */   252,  176,  624,  623,  608,   67,  377,  513,  622,  443,
99008
 /*   240 */   579,  579,  252,  440,  607,   66,  377,  513,  621,   49,
92184
 /*   250 */   237,  577,  591,  585,  622,  172,  466,  598,  554,  441,
99009
 /*   250 */    46,  147,  590,  584,  621,   16,  466,  189,  621,  441,
92185
 /*   260 */   340,  409,  526,  580,  580,  349,  596,  553,  194,  482,
99010
 /*   260 */   442,  673,  526,  441,  340,  577,  595,   64,  194,  482,
92186
 /*   270 */   175,   56,   57,   47,  583,  582,  584,  584,   54,   54,
99011
 /*   270 */   434,   56,   57,   47,  582,  581,  583,  583,   54,   54,
92187
 /*   280 */    55,   55,   55,   55,  562,   53,   53,   53,   53,   52,
99012
 /*   280 */    55,   55,   55,   55,   30,   53,   53,   53,   53,   52,
92188
 /*   290 */    52,   51,   51,   51,   50,  238,  313,  594,  594,  594,
99013
 /*   290 */    52,   51,   51,   51,   50,  238,  313,  593,  593,  593,
92189
 /*   300 */   561,  578,  469,   65,  259,  351,  258,  411,  624,  623,
99014
 /*   300 */   387,  578,  606,  493,  259,  351,  258,  411,    1,  623,
92190
 /*   310 */   621,  620,  332,  576,  575,  240,  560,  568,  520,  411,
99015
 /*   310 */   622,  496,  623,  622,   65,  240,  623,  622,  597,  443,
92191
 /*   320 */   341,  237,  414,  624,  623,  598,  591,  585,  542,  519,
99016
 /*   320 */   237,  239,  414,  341,  237,  602,  590,  584,   18,  603,
92192
 /*   330 */   171,  602,   95,   68,  414,  624,  623,  624,  623,   38,
99017
 /*   330 */   166,  601,   87,  382,  379,  378,   67,  623,  622,   38,
92193
 /*   340 */   877,  506,  507,  602,   88,   56,   57,   47,  583,  582,
99018
 /*   340 */   623,  622,  176,  270,  377,   56,   57,   47,  582,  581,
92194
 /*   350 */   584,  584,   54,   54,   55,   55,   55,   55,  532,   53,
99019
 /*   350 */   583,  583,   54,   54,   55,   55,   55,   55,  175,   53,
92195
 /*   360 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
99020
 /*   360 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
92196
 /*   370 */   313,  411,  579,  398,  531,  237,  621,  620,  388,  625,
99021
 /*   370 */   313,  396,  233,  411,  531,  565,  317,  620,  619,   44,
92197
 /*   380 */   500,  206,  167,  396,  233,  312,  414,  387,  569,  492,
99022
 /*   380 */   620,  619,  240,  206,  620,  619,  597,  266,  414,  268,
92198
 /*   390 */   216,  621,  620,  566,  622,  602,   74,  533,  210,  491,
99023
 /*   390 */   409,  597,  579,  579,  352,  184,  505,  601,   73,  533,
92199
 /*   400 */   591,  585,  548,  621,  620,  621,  620,  300,  598,  466,
99024
 /*   400 */   590,  584,  466,  548,  190,  620,  619,  576,  620,  619,
92200
 /*   410 */   481,   67,  603,   35,  622,  601,  604,  547,    6,   56,
99025
 /*   410 */   547,  383,  551,   35,  332,  575,  574,  600,  504,   56,
92201
 /*   420 */    57,   47,  583,  582,  584,  584,   54,   54,   55,   55,
99026
 /*   420 */    57,   47,  582,  581,  583,  583,   54,   54,   55,   55,
92202
 /*   430 */    55,   55,  601,   53,   53,   53,   53,   52,   52,   51,
99027
 /*   430 */    55,   55,  567,   53,   53,   53,   53,   52,   52,   51,
92203
 /*   440 */    51,   51,   50,  238,  313,  411,  184,  409,  528,  580,
99028
 /*   440 */    51,   51,   50,  238,  313,  411,  561,  561,  528,  364,
92204
 /*   450 */   580,  551,  962,  186,  419,    2,  353,  259,  351,  258,
99029
 /*   450 */   259,  351,  258,  183,  361,  549,  524,  374,  411,  597,
92205
 /*   460 */   414,  409,  411,  580,  580,   44,  411,  544,  240,  602,
99030
 /*   460 */   414,  240,  560,  560,  409,  604,  579,  579,  328,  601,
92206
 /*   470 */    94,  190,    7,   62,  591,  585,  598,  414,  350,  607,
99031
 /*   470 */    93,  623,  622,  414,  590,  584,  237,  564,  559,  559,
92207
 /*   480 */   493,  414,  409,  317,  580,  580,  602,   95,  496,  565,
99032
 /*   480 */   520,  402,  601,   87,  409,  210,  579,  579,  168,  421,
92208
 /*   490 */   602,   80,  203,   56,   57,   47,  583,  582,  584,  584,
99033
 /*   490 */   950,  519,  950,   56,   57,   47,  582,  581,  583,  583,
92209
 /*   500 */    54,   54,   55,   55,   55,   55,  535,   53,   53,   53,
99034
 /*   500 */    54,   54,   55,   55,   55,   55,  192,   53,   53,   53,
92210
 /*   510 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  202,
99035
 /*   510 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  600,
92211
 /*   520 */   564,  293,  511,   49,  562,   46,  147,  411,  394,  183,
99036
 /*   520 */   293,  563,  511,  234,  357,  146,  475,  475,  367,  411,
92212
 /*   530 */   563,  549,  505,  549,  174,  409,  322,  580,  580,   39,
99037
 /*   530 */   562,  411,  358,  542,  425,  171,  411,  215,  144,  620,
92213
 /*   540 */   561,   37,  414,  624,  623,  192,  473,  383,  591,  585,
99038
 /*   540 */   619,  544,  318,  353,  414,  203,  414,  275,  590,  584,
92214
 /*   550 */   474,  602,   80,  601,  504,  544,  560,  364,  402,  210,
99039
 /*   550 */   549,  414,  174,  601,   94,  601,   79,  558,  471,   61,
92215
 /*   560 */   421,  952,  361,  952,  365,  201,  144,   56,   57,   47,
99040
 /*   560 */   601,   79,  421,  949,  350,  949,   34,   56,   57,   47,
92216
 /*   570 */   583,  582,  584,  584,   54,   54,   55,   55,   55,   55,
99041
 /*   570 */   582,  581,  583,  583,   54,   54,   55,   55,   55,   55,
92217
 /*   580 */   559,   53,   53,   53,   53,   52,   52,   51,   51,   51,
99042
 /*   580 */   535,   53,   53,   53,   53,   52,   52,   51,   51,   51,
92218
 /*   590 */    50,  238,  313,  601,  232,  264,  272,  321,  374,  484,
99043
 /*   590 */    50,  238,  313,  307,  424,  394,  272,   49,   46,  147,
92219
 /*   600 */   510,  146,  342,  146,  328,  425,  485,  407,  576,  575,
99044
 /*   600 */   349,  322,    4,  411,  491,  312,  321,  425,  568,  492,
92220
 /*   610 */   622,  621,  620,   49,  168,   46,  147,  353,  546,  491,
99045
 /*   610 */   216,  264,  407,  575,  574,  429,   66,  549,  414,  621,
92221
 /*   620 */   204,  240,  591,  585,  421,  951,  549,  951,  549,  168,
99046
 /*   620 */   540,  602,  590,  584,   13,  603,  621,  601,   72,   12,
92222
 /*   630 */   429,   67,  390,  343,  622,  434,  307,  423,  338,  360,
99047
 /*   630 */   618,  617,  616,  202,  210,  621,  546,  469,  422,  319,
92223
 /*   640 */   391,   56,   57,   47,  583,  582,  584,  584,   54,   54,
99048
 /*   640 */   148,   56,   57,   47,  582,  581,  583,  583,   54,   54,
92224
 /*   650 */    55,   55,   55,   55,  601,   53,   53,   53,   53,   52,
99049
 /*   650 */    55,   55,   55,   55,  338,   53,   53,   53,   53,   52,
92225
 /*   660 */    52,   51,   51,   51,   50,  238,  313,   34,  318,  425,
99050
 /*   660 */    52,   51,   51,   51,   50,  238,  313,  600,  600,  411,
92226
 /*   670 */   237,   21,  359,  273,  411,  167,  411,  276,  411,  540,
99051
 /*   670 */    39,   21,   37,  170,  237,  875,  411,  572,  572,  201,
92227
 /*   680 */   411,  422,   13,  318,  619,  618,  617,  622,  275,  414,
99052
 /*   680 */   144,  473,  538,  331,  414,  474,  143,  146,  630,  628,
92228
 /*   690 */   336,  414,  622,  414,  622,  414,  591,  585,  602,   69,
99053
 /*   690 */   334,  414,  353,  601,   68,  168,  590,  584,  132,  365,
92229
 /*   700 */   602,   97,  602,  100,  602,   98,  631,  629,  334,  475,
99054
 /*   700 */   601,   96,  307,  423,  530,  336,   49,   46,  147,  568,
92230
 /*   710 */   475,  367,  319,  148,  327,   56,   57,   47,  583,  582,
99055
 /*   710 */   406,  216,  549,  360,  529,   56,   57,   47,  582,  581,
92231
 /*   720 */   584,  584,   54,   54,   55,   55,   55,   55,  411,   53,
99056
 /*   720 */   583,  583,   54,   54,   55,   55,   55,   55,  411,   53,
92232
 /*   730 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
99057
 /*   730 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
92233
 /*   740 */   313,  411,  331,  414,  411,   49,  276,   46,  147,  569,
99058
 /*   740 */   313,  411,  605,  414,  484,  510,  172,  422,  597,  318,
92234
 /*   750 */   406,  216,  602,  106,  573,  573,  414,  354,  524,  414,
99059
 /*   750 */   496,  485,  601,   99,  411,  142,  414,  411,  231,  411,
92235
 /*   760 */   411,  622,  411,  224,    4,  602,  104,  605,  602,  108,
99060
 /*   760 */   540,  411,  359,  629,    2,  601,   97,  426,  308,  414,
92236
 /*   770 */   591,  585,  622,   20,  375,  414,  167,  414,  215,  144,
99061
 /*   770 */   590,  584,  414,   20,  414,  621,  414,  621,  601,  106,
92237
 /*   780 */   470,  239,  167,  225,  602,  109,  602,  134,   18,   56,
99062
 /*   780 */   503,  601,  105,  601,  108,  601,  109,  204,   28,   56,
92238
 /*   790 */    57,   47,  583,  582,  584,  584,   54,   54,   55,   55,
99063
 /*   790 */    57,   47,  582,  581,  583,  583,   54,   54,   55,   55,
92239
 /*   800 */    55,   55,  411,   53,   53,   53,   53,   52,   52,   51,
99064
 /*   800 */    55,   55,  411,   53,   53,   53,   53,   52,   52,   51,
92240
 /*   810 */    51,   51,   50,  238,  313,  411,  276,  414,   12,  459,
99065
 /*   810 */    51,   51,   50,  238,  313,  411,  597,  414,  411,  276,
92241
 /*   820 */   276,  171,  411,   16,  223,  189,  602,  135,  354,  170,
99066
 /*   820 */   214,  600,  411,  366,  213,  381,  601,  134,  274,  500,
92242
 /*   830 */   414,  622,  630,    2,  411,  622,  540,  414,  143,  602,
99067
 /*   830 */   414,  167,  130,  414,  621,  411,  354,  414,  376,  601,
92243
 /*   840 */    61,  359,  132,  622,  591,  585,  602,  105,  458,  414,
99068
 /*   840 */   135,  129,  601,  100,  590,  584,  601,  104,  522,  521,
92244
 /*   850 */    23,  622,  446,  326,   23,  538,  622,  325,  602,  103,
99069
 /*   850 */   414,  621,  224,  273,  600,  167,  327,  282,  600,  601,
92245
 /*   860 */   427,  530,  309,   56,   57,   47,  583,  582,  584,  584,
99070
 /*   860 */   103,  468,  521,   56,   57,   47,  582,  581,  583,  583,
92246
 /*   870 */    54,   54,   55,   55,   55,   55,  411,   53,   53,   53,
99071
 /*   870 */    54,   54,   55,   55,   55,   55,  411,   53,   53,   53,
92247
 /*   880 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  411,
99072
 /*   880 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  411,
92248
 /*   890 */   264,  414,  411,  276,  359,  219,  157,  214,  357,  366,
99073
 /*   890 */    27,  414,  411,  375,  276,  167,  359,  544,   50,  238,
92249
 /*   900 */   602,   96,  522,  521,  414,  622,  358,  414,  622,  622,
99074
 /*   900 */   601,   95,  128,  223,  414,  411,  165,  414,  411,  621,
92250
 /*   910 */   411,  613,  612,  602,  102,  142,  602,   77,  591,  585,
99075
 /*   910 */   411,  621,  612,  601,  102,  372,  601,   76,  590,  584,
92251
 /*   920 */   529,  540,  231,  426,  308,  414,  622,  622,  468,  521,
99076
 /*   920 */   414,  570,  236,  414,  470,  414,  167,  621,  188,  601,
92252
 /*   930 */   324,  601,  257,  263,  602,   99,  622,   56,   45,   47,
99077
 /*   930 */    98,  225,  601,  138,  601,  137,  232,   56,   45,   47,
92253
 /*   940 */   583,  582,  584,  584,   54,   54,   55,   55,   55,   55,
99078
 /*   940 */   582,  581,  583,  583,   54,   54,   55,   55,   55,   55,
92254
 /*   950 */   411,   53,   53,   53,   53,   52,   52,   51,   51,   51,
99079
 /*   950 */   411,   53,   53,   53,   53,   52,   52,   51,   51,   51,
92255
 /*   960 */    50,  238,  313,  264,  264,  414,  411,  213,  209,  544,
99080
 /*   960 */    50,  238,  313,  276,  276,  414,  411,  276,  544,  459,
92256
 /*   970 */   544,  207,  611,   28,  602,  138,   50,  238,  622,  622,
99081
 /*   970 */   359,  171,  209,  479,  601,  136,  628,  334,  621,  621,
92257
 /*   980 */   381,  414,  503,  140,  323,  222,  274,  622,  590,  589,
99082
 /*   980 */   125,  414,  621,  368,  411,  621,  257,  540,  589,  588,
92258
 /*   990 */   602,  137,  591,  585,  629,  334,  606,   30,  622,  571,
99083
 /*   990 */   601,   75,  590,  584,  458,  446,   23,   23,  124,  414,
92259
 /*  1000 */   236,  601,  601,  130,  496,  601,  453,  451,  288,  286,
99084
 /*  1000 */   326,  325,  621,  427,  324,  309,  600,  288,  601,   92,
92260
 /*  1010 */   587,  586,   57,   47,  583,  582,  584,  584,   54,   54,
99085
 /*  1010 */   586,  585,   57,   47,  582,  581,  583,  583,   54,   54,
92261
 /*  1020 */    55,   55,   55,   55,  411,   53,   53,   53,   53,   52,
99086
 /*  1020 */    55,   55,   55,   55,  411,   53,   53,   53,   53,   52,
92262
 /*  1030 */    52,   51,   51,   51,   50,  238,  313,  588,  411,  414,
99087
 /*  1030 */    52,   51,   51,   51,   50,  238,  313,  587,  411,  414,
92263
 /*  1040 */   411,  264,  410,  129,  595,  400,   27,  376,  602,  136,
99088
 /*  1040 */   411,  207,  611,  476,  171,  472,  160,  123,  601,   91,
92264
 /*  1050 */   128,  165,  479,  414,  282,  414,  622,  622,  411,  622,
99089
 /*  1050 */   323,  261,   15,  414,  464,  414,  411,  621,  411,  354,
92265
 /*  1060 */   622,  411,  602,   76,  602,   93,  591,  585,  188,  372,
99090
 /*  1060 */   222,  411,  601,   74,  601,   90,  590,  584,  159,  264,
92266
 /*  1070 */   368,  125,  476,  414,  261,  160,  414,  171,  124,  472,
99091
 /*  1070 */   158,  414,  461,  414,  621,  600,  414,  121,  120,   25,
92267
 /*  1080 */   123,   15,  602,   92,  450,  602,   75,   47,  583,  582,
99092
 /*  1080 */   601,   89,  601,  101,  621,  601,   88,   47,  582,  581,
92268
 /*  1090 */   584,  584,   54,   54,   55,   55,   55,   55,  464,   53,
99093
 /*  1090 */   583,  583,   54,   54,   55,   55,   55,   55,  544,   53,
92269
 /*  1100 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
99094
 /*  1100 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
92270
 /*  1110 */    43,  405,  264,    3,  558,  264,  545,  415,  623,  159,
99095
 /*  1110 */    43,  405,  263,    3,  610,  264,  140,  415,  622,   24,
92271
 /*  1120 */   541,  158,  539,  278,   25,  461,  121,  622,  408,  622,
99096
 /*  1120 */   410,   11,  456,  594,  118,  155,  219,  452,  408,  621,
92272
 /*  1130 */   622,  622,   24,   43,  405,  622,    3,  622,  622,  120,
99097
 /*  1130 */   621,  621,  156,   43,  405,  621,    3,  286,  621,  113,
92273
 /*  1140 */   415,  623,   11,  456,  411,  156,  452,  403,  509,  277,
99098
 /*  1140 */   415,  622,  111,  445,  411,  400,  557,  403,  545,   10,
92274
 /*  1150 */   118,  408,  489,  113,  205,  449,  271,  567,  221,  414,
99099
 /*  1150 */   411,  408,  264,  110,  205,  436,  541,  566,  453,  414,
92275
 /*  1160 */   269,  267,  155,  622,  622,  111,  411,  622,  602,   95,
99100
 /*  1160 */   621,  621,   63,  621,  435,  414,  411,  621,  601,   94,
92276
 /*  1170 */   403,  622,  411,  110,   10,  622,  622,   40,   41,  534,
99101
 /*  1170 */   403,  621,  411,  337,  601,   86,  150,   40,   41,  534,
92277
 /*  1180 */   567,  414,   64,  264,   42,  413,  412,  414,  601,  596,
99102
 /*  1180 */   566,  414,  242,  264,   42,  413,  412,  414,  600,  595,
92278
 /*  1190 */   602,   91,  445,  436,  150,  435,  602,   90,  622,  265,
99103
 /*  1190 */   601,   85,  191,  333,  107,  451,  601,   84,  621,  539,
92279
 /*  1200 */    40,   41,  337,  242,  411,  191,  333,   42,  413,  412,
99104
 /*  1200 */    40,   41,  420,  230,  411,  149,  316,   42,  413,  412,
92280
 /*  1210 */   398,  420,  596,  316,  622,  399,  260,  107,  230,  414,
99105
 /*  1210 */   398,  127,  595,  315,  621,  399,  278,  625,  181,  414,
92281
 /*  1220 */   594,  594,  594,  593,  592,   14,  220,  411,  602,  101,
99106
 /*  1220 */   593,  593,  593,  592,  591,   14,  450,  411,  601,   71,
92282
 /*  1230 */   240,  622,   43,  405,  362,    3,  149,  315,  626,  415,
99107
 /*  1230 */   240,  621,   43,  405,  264,    3,  615,  180,  264,  415,
92283
 /*  1240 */   623,  127,  414,  594,  594,  594,  593,  592,   14,  622,
99108
 /*  1240 */   622,  614,  414,  593,  593,  593,  592,  591,   14,  621,
92284
 /*  1250 */   408,  602,   89,  411,  181,   33,  405,  463,    3,  411,
99109
 /*  1250 */   408,  601,   70,  621,  417,   33,  405,  613,    3,  411,
92285
 /*  1260 */   264,  462,  415,  623,  616,  615,  614,  355,  414,  403,
99110
 /*  1260 */   264,  411,  415,  622,  418,  626,  178,  509,    8,  403,
92286
 /*  1270 */   417,  416,  622,  408,  414,  622,  622,  602,   87,  567,
99111
 /*  1270 */   241,  416,  126,  408,  414,  621,  414,  449,  208,  566,
92287
 /*  1280 */   418,  627,  622,  602,   86,    8,  241,  180,  126,  255,
99112
 /*  1280 */   240,  221,  621,  601,   83,  601,   82,  599,  297,  277,
92288
 /*  1290 */   600,  178,  403,  240,  208,  455,  395,  294,  444,   40,
99113
 /*  1290 */   296,   30,  403,   31,  395,  264,  295,  397,  489,   40,
92289
 /*  1300 */    41,  297,  567,  248,  622,  296,   42,  413,  412,  247,
99114
 /*  1300 */    41,  411,  566,  220,  621,  294,   42,  413,  412,  271,
92290
 /*  1310 */   622,  596,  244,  622,   30,   60,   31,  243,  430,  624,
99115
 /*  1310 */   621,  595,  600,  621,   59,   60,  414,  269,  267,  623,
92291
 /*  1320 */   623,  292,   40,   41,  622,  295,  145,  622,  601,   42,
99116
 /*  1320 */   622,   36,   40,   41,  621,  601,   81,  598,  235,   42,
92292
 /*  1330 */   413,  412,  622,  622,  596,  393,  622,  397,  599,   59,
99117
 /*  1330 */   413,  412,  621,  621,  595,  265,  344,  411,  248,  556,
92293
 /*  1340 */   235,  622,  594,  594,  594,  593,  592,   14,  218,  291,
99118
 /*  1340 */   173,  185,  593,  593,  593,  592,  591,   14,  218,   29,
92294
 /*  1350 */   622,   36,  344,  305,  304,  303,  179,  301,  411,  567,
99119
 /*  1350 */   621,  543,  414,  305,  304,  303,  179,  301,  411,  566,
92295
 /*  1360 */   454,  557,  173,  185,  622,  594,  594,  594,  593,  592,
99120
 /*  1360 */   454,  601,   80,  289,  335,  593,  593,  593,  592,  591,
92296
 /*  1370 */    14,  411,   29,  414,  151,  289,  246,  523,  411,  196,
99121
 /*  1370 */    14,  411,  287,  414,  151,  392,  246,  260,  411,  196,
92297
 /*  1380 */   195,  335,  602,   85,  411,  245,  414,  526,  392,  543,
99122
 /*  1380 */   195,  523,  601,   69,  411,  245,  414,  526,  537,  285,
92298
 /*  1390 */   411,  596,  287,  414,  285,  602,   72,  537,  153,  414,
99123
 /*  1390 */   389,  595,  621,  414,  536,  601,   17,  362,  153,  414,
92299
 /*  1400 */   466,  411,  602,   71,  154,  414,  411,  152,  602,   84,
99124
 /*  1400 */   466,  463,  601,   78,  154,  414,  462,  152,  601,   77,
92300
 /*  1410 */   386,  536,  329,  411,  602,   83,  414,  518,  280,  411,
99125
 /*  1410 */   355,  255,  621,  455,  601,    9,  621,  386,  444,  517,
92301
 /*  1420 */   513,  414,  594,  594,  594,  602,   82,  517,  414,  311,
99126
 /*  1420 */   247,  621,  593,  593,  593,  621,  621,  244,  621,  243,
92302
 /*  1430 */   602,   81,  411,  514,  414,  512,  131,  602,   70,  229,
99127
 /*  1430 */   430,  518,  292,  621,  329,  621,  145,  393,  280,  513,
92303
 /*  1440 */   228,  227,  494,  602,   17,  411,  488,  414,  259,  346,
99128
 /*  1440 */   291,  131,  621,  514,  621,  621,  311,  621,  259,  346,
92304
 /*  1450 */   249,  389,  487,  486,  314,  164,  602,   79,  310,  240,
99129
 /*  1450 */   249,  621,  621,  229,  314,  621,  228,  512,  227,  240,
92305
 /*  1460 */   414,  373,  480,  163,  262,  371,  414,  162,  369,  602,
99130
 /*  1460 */   494,  488,  310,  164,  487,  486,  373,  480,  163,  262,
92306
 /*  1470 */    78,  212,  478,   26,  477,  602,    9,  161,  467,  363,
99131
 /*  1470 */   369,  371,  162,   26,  212,  478,  477,  161,  141,  363,
92307
 /*  1480 */   141,  122,  339,  187,  119,  457,  348,  347,  117,  116,
99132
 /*  1480 */   467,  122,  339,  187,  119,  348,  347,  117,  116,  115,
92308
 /*  1490 */   115,  112,  114,  448,  182,   22,  320,  433,  432,  431,
99133
 /*  1490 */   114,  112,  182,  457,  320,   22,  433,  432,  448,   19,
92309
 /*  1500 */    19,  428,  610,  597,  574,  193,  572,   63,  298,  404,
99134
 /*  1500 */   609,  431,  428,   62,  193,  596,  573,  298,  555,  552,
92310
 /*  1510 */   555,  552,  290,  281,  510,  460,  498,  499,  495,  447,
99135
 /*  1510 */   571,  404,  290,  380,  498,  510,  495,  306,  281,  499,
92311
 /*  1520 */   356,  497,  256,  380,  306,  570,    5,  250,  345,  238,
99136
 /*  1520 */   250,    5,  497,  460,  345,  447,  569,  550,  238,  299,
92312
 /*  1530 */   299,  550,  527,  490,  508,  525,  502,  401,  501,  963,
99137
 /*  1530 */   527,  525,  508,  961,  502,  501,  961,  401,  961,  211,
92313
 /*  1540 */   211,  963,  483,  963,  963,  963,  963,  963,  963,  370,
99138
 /*  1540 */   490,  356,  256,  961,  483,  961,  961,  961,  961,  961,
99139
 /*  1550 */   961,  961,  961,  961,  961,  961,  370,
92314
};
99140
};
92315
static const YYCODETYPE yy_lookahead[] = {
99141
static const YYCODETYPE yy_lookahead[] = {
92316
 /*     0 */    19,  222,  223,  224,  225,   24,    1,   26,   77,   78,
99142
 /*     0 */    19,  142,  143,  144,  145,   24,    1,   26,   77,   78,
92317
 /*    10 */    79,   80,   15,   82,   83,   84,   85,   86,   87,   88,
99143
 /*    10 */    79,   80,   81,   82,   83,   84,   85,   86,   87,   88,
92318
 /*    20 */    89,   90,   91,   92,  113,   22,   26,   27,  117,   26,
99144
 /*    20 */    89,   90,   91,   92,   15,   98,   26,   27,    7,    8,
92319
 /*    30 */    49,   50,   81,   82,   83,   84,   85,   86,   87,   88,
99145
 /*    30 */    49,   50,   77,   78,   79,   80,  109,   82,   83,   84,
92320
 /*    40 */    89,   90,   91,   92,   88,   89,   90,   91,   92,   68,
99146
 /*    40 */    85,   86,   87,   88,   89,   90,   91,   92,   22,   68,
92321
 /*    50 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
99147
 /*    50 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
92322
 /*    60 */    79,   80,   23,   82,   83,   84,   85,   86,   87,   88,
99148
 /*    60 */    79,   80,   23,   82,   83,   84,   85,   86,   87,   88,
92323
 /*    70 */    89,   90,   91,   92,   19,   94,  118,   19,  150,   22,
99149
 /*    70 */    89,   90,   91,   92,   19,   94,  112,   19,  114,  115,
92324
 /*    80 */    25,   82,   83,   84,   85,   86,   87,   88,   89,   90,
99150
 /*    80 */    25,   82,   83,   84,   85,   86,   87,   88,   89,   90,
92325
 /*    90 */    91,   92,   19,  165,   94,   95,   96,   94,  118,   99,
99151
 /*    90 */    91,   92,   19,   22,   94,   95,   96,  150,  150,   99,
92326
 /*   100 */   100,  101,  174,  175,   49,   50,   22,   23,   96,   54,
99152
 /*   100 */   100,  101,   76,  150,   49,   50,  105,  106,  107,   54,
92327
 /*   110 */   110,   99,  100,  101,    7,    8,   26,   27,   16,  105,
99153
 /*   110 */   110,  158,  165,  165,  161,  162,   26,   27,  165,  113,
92328
 /*   120 */   106,  107,  110,   68,   69,   70,   71,   72,   73,   74,
99154
 /*   120 */    16,  174,  175,   68,   69,   70,   71,   72,   73,   74,
92329
 /*   130 */    75,   76,   77,   78,   79,   80,  113,   82,   83,   84,
99155
 /*   130 */    75,   76,   77,   78,   79,   80,  118,   82,   83,   84,
92330
 /*   140 */    85,   86,   87,   88,   89,   90,   91,   92,   19,   16,
99156
 /*   140 */    85,   86,   87,   88,   89,   90,   91,   92,   19,   23,
92331
 /*   150 */    92,   67,   98,   24,   96,   97,   98,   99,  100,  101,
99157
 /*   150 */    92,   97,   98,   24,   96,   97,   98,   99,  100,  101,
92332
 /*   160 */   102,   25,   60,  109,   62,   92,  150,  109,  150,   25,
99158
 /*   160 */   102,   25,   97,  216,   60,   92,   62,  109,  221,   25,
92333
 /*   170 */    97,   98,   99,  100,  101,  102,   86,   87,   49,   50,
99159
 /*   170 */    97,   98,   99,  100,  101,  102,   86,   87,   49,   50,
92334
 /*   180 */   116,  165,  109,  165,   94,   95,  118,   97,  170,  171,
99160
 /*   180 */   118,  116,  109,   25,   94,   95,   32,   97,   88,   89,
92335
 /*   190 */   174,  175,  128,   60,  104,   62,  106,   68,   69,   70,
99161
 /*   190 */    90,   91,   92,  128,  104,   41,  106,   68,   69,   70,
92336
 /*   200 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
99162
 /*   200 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
92337
 /*   210 */    11,   82,   83,   84,   85,   86,   87,   88,   89,   90,
99163
 /*   210 */    11,   82,   83,   84,   85,   86,   87,   88,   89,   90,
92338
 /*   220 */    91,   92,   19,   21,   86,   87,   88,   89,   90,   91,
99164
 /*   220 */    91,   92,   19,   19,   86,   87,   88,   89,   90,   91,
92339
 /*   230 */    92,  215,   96,  150,   66,   99,  100,  101,   22,  150,
99165
 /*   230 */    92,   27,   96,  150,   66,   99,  100,  101,  112,  150,
92340
 /*   240 */   138,  118,   26,   27,  161,  162,  110,  103,  165,  231,
99166
 /*   240 */   114,  115,  138,  150,  161,  162,  110,  103,  165,  222,
92341
 /*   250 */   232,   23,   49,   50,  165,   24,   57,   26,   32,  170,
99167
 /*   250 */   223,  224,   49,   50,  165,   22,   57,   24,  165,  170,
92342
 /*   260 */   171,  112,   94,  114,  115,   63,   98,   41,  185,  186,
99168
 /*   260 */   171,  118,   94,  170,  171,   23,   98,   25,  185,  186,
92343
 /*   270 */   118,   68,   69,   70,   71,   72,   73,   74,   75,   76,
99169
 /*   270 */   243,   68,   69,   70,   71,   72,   73,   74,   75,   76,
92344
 /*   280 */    77,   78,   79,   80,   12,   82,   83,   84,   85,   86,
99170
 /*   280 */    77,   78,   79,   80,  126,   82,   83,   84,   85,   86,
92345
 /*   290 */    87,   88,   89,   90,   91,   92,   19,  129,  130,  131,
99171
 /*   290 */    87,   88,   89,   90,   91,   92,   19,  129,  130,  131,
92346
 /*   300 */    28,   23,  100,   25,  105,  106,  107,  150,   26,   27,
99172
 /*   300 */    88,   23,  172,  173,  105,  106,  107,  150,   22,   26,
92347
 /*   310 */    94,   95,  169,  170,  171,  116,   44,   23,   46,  150,
99173
 /*   310 */    27,  181,   26,   27,   22,  116,   26,   27,   26,  230,
92348
 /*   320 */   231,  232,  165,   26,   27,   94,   49,   50,   23,   57,
99174
 /*   320 */   231,  197,  165,  230,  231,  113,   49,   50,  204,  117,
92349
 /*   330 */    25,  174,  175,   22,  165,   26,   27,   26,   27,  136,
99175
 /*   330 */    96,  174,  175,   99,  100,  101,   22,   26,   27,  136,
92350
 /*   340 */   138,   97,   98,  174,  175,   68,   69,   70,   71,   72,
99176
 /*   340 */    26,   27,  118,   16,  110,   68,   69,   70,   71,   72,
92351
 /*   350 */    73,   74,   75,   76,   77,   78,   79,   80,   23,   82,
99177
 /*   350 */    73,   74,   75,   76,   77,   78,   79,   80,  118,   82,
92352
 /*   360 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
99178
 /*   360 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
92353
 /*   370 */    19,  150,   23,  216,   23,  232,   94,   95,  221,  150,
99179
 /*   370 */    19,  214,  215,  150,   23,   23,  155,   94,   95,   22,
92354
 /*   380 */    23,  160,   25,  214,  215,  163,  165,   88,  166,  167,
99180
 /*   380 */    94,   95,  116,  160,   94,   95,   94,   60,  165,   62,
92355
 /*   390 */   168,   94,   95,   23,  165,  174,  175,   88,  160,  150,
99181
 /*   390 */   112,   26,  114,  115,  128,   23,   36,  174,  175,   88,
92356
 /*   400 */    49,   50,  120,   94,   95,   94,   95,  158,   26,   57,
99182
 /*   400 */    49,   50,   57,  120,   22,   94,   95,   23,   94,   95,
92357
 /*   410 */   161,  162,  113,  136,  165,  194,  117,  120,   22,   68,
99183
 /*   410 */   120,   51,   25,  136,  169,  170,  171,  194,   58,   68,
92358
 /*   420 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
99184
 /*   420 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
92359
 /*   430 */    79,   80,  194,   82,   83,   84,   85,   86,   87,   88,
99185
 /*   430 */    79,   80,   23,   82,   83,   84,   85,   86,   87,   88,
92360
 /*   440 */    89,   90,   91,   92,   19,  150,   23,  112,   23,  114,
99186
 /*   440 */    89,   90,   91,   92,   19,  150,   12,   12,   23,  228,
92361
 /*   450 */   115,   25,  142,  143,  144,  145,  218,  105,  106,  107,
99187
 /*   450 */   105,  106,  107,   23,  233,   25,  165,   19,  150,   94,
92362
 /*   460 */   165,  112,  150,  114,  115,   22,  150,  166,  116,  174,
99188
 /*   460 */   165,  116,   28,   28,  112,  174,  114,  115,  108,  174,
92363
 /*   470 */   175,   22,   76,  235,   49,   50,   94,  165,  240,  172,
99189
 /*   470 */   175,   26,   27,  165,   49,   50,  231,   11,   44,   44,
92364
 /*   480 */   173,  165,  112,  155,  114,  115,  174,  175,  181,   11,
99190
 /*   480 */    46,   46,  174,  175,  112,  160,  114,  115,   50,   22,
92365
 /*   490 */   174,  175,   22,   68,   69,   70,   71,   72,   73,   74,
99191
 /*   490 */    23,   57,   25,   68,   69,   70,   71,   72,   73,   74,
92366
 /*   500 */    75,   76,   77,   78,   79,   80,  205,   82,   83,   84,
99192
 /*   500 */    75,   76,   77,   78,   79,   80,  119,   82,   83,   84,
92367
 /*   510 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  160,
99193
 /*   510 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  194,
92368
 /*   520 */    23,  226,   23,  222,   12,  224,  225,  150,  216,   23,
99194
 /*   520 */   225,   23,   23,  215,   19,   95,  105,  106,  107,  150,
92369
 /*   530 */    23,   25,   36,   25,   25,  112,  220,  114,  115,  135,
99195
 /*   530 */    23,  150,   27,   23,   67,   25,  150,  206,  207,   94,
92370
 /*   540 */    28,  137,  165,   26,   27,  119,   30,   51,   49,   50,
99196
 /*   540 */    95,  166,  104,  218,  165,   22,  165,  109,   49,   50,
92371
 /*   550 */    34,  174,  175,  194,   58,  166,   44,  229,   46,  160,
99197
 /*   550 */   120,  165,   25,  174,  175,  174,  175,   23,   21,  234,
92372
 /*   560 */    22,   23,  234,   25,   48,  206,  207,   68,   69,   70,
99198
 /*   560 */   174,  175,   22,   23,  239,   25,   25,   68,   69,   70,
92373
 /*   570 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
99199
 /*   570 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
92374
 /*   580 */    23,   82,   83,   84,   85,   86,   87,   88,   89,   90,
99200
 /*   580 */   205,   82,   83,   84,   85,   86,   87,   88,   89,   90,
92375
 /*   590 */    91,   92,   19,  194,  205,  150,   23,  220,   19,  181,
99201
 /*   590 */    91,   92,   19,   22,   23,  216,   23,  222,  223,  224,
92376
 /*   600 */   182,   95,   97,   95,  108,   67,  188,  169,  170,  171,
99202
 /*   600 */    63,  220,   35,  150,  150,  163,  220,   67,  166,  167,
92377
 /*   610 */   165,   94,   95,  222,   50,  224,  225,  218,  120,  150,
99203
 /*   610 */   168,  150,  169,  170,  171,  161,  162,   25,  165,  165,
92378
 /*   620 */   160,  116,   49,   50,   22,   23,  120,   25,  120,   50,
99204
 /*   620 */   150,  113,   49,   50,   25,  117,  165,  174,  175,   35,
92379
 /*   630 */   161,  162,   19,  128,  165,  244,   22,   23,  193,  240,
99205
 /*   630 */     7,    8,    9,  160,  160,  165,  120,  100,   67,  247,
92380
 /*   640 */    27,   68,   69,   70,   71,   72,   73,   74,   75,   76,
99206
 /*   640 */   248,   68,   69,   70,   71,   72,   73,   74,   75,   76,
92381
 /*   650 */    77,   78,   79,   80,  194,   82,   83,   84,   85,   86,
99207
 /*   650 */    77,   78,   79,   80,  193,   82,   83,   84,   85,   86,
92382
 /*   660 */    87,   88,   89,   90,   91,   92,   19,   25,  104,   67,
99208
 /*   660 */    87,   88,   89,   90,   91,   92,   19,  194,  194,  150,
92383
 /*   670 */   232,   24,  150,   23,  150,   25,  150,  150,  150,  150,
99209
 /*   670 */   135,   24,  137,   35,  231,  138,  150,  129,  130,  206,
92384
 /*   680 */   150,   67,   25,  104,    7,    8,    9,  165,  109,  165,
99210
 /*   680 */   207,   30,   27,  213,  165,   34,  118,   95,    0,    1,
92385
 /*   690 */   245,  165,  165,  165,  165,  165,   49,   50,  174,  175,
99211
 /*   690 */     2,  165,  218,  174,  175,   50,   49,   50,   22,   48,
92386
 /*   700 */   174,  175,  174,  175,  174,  175,    0,    1,    2,  105,
99212
 /*   700 */   174,  175,   22,   23,   23,  244,  222,  223,  224,  166,
92387
 /*   710 */   106,  107,  248,  249,  187,   68,   69,   70,   71,   72,
99213
 /*   710 */   167,  168,  120,  239,   23,   68,   69,   70,   71,   72,
92388
 /*   720 */    73,   74,   75,   76,   77,   78,   79,   80,  150,   82,
99214
 /*   720 */    73,   74,   75,   76,   77,   78,   79,   80,  150,   82,
92389
 /*   730 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
99215
 /*   730 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
92390
 /*   740 */    19,  150,  213,  165,  150,  222,  150,  224,  225,  166,
99216
 /*   740 */    19,  150,  173,  165,  181,  182,   24,   67,   26,  104,
92391
 /*   750 */   167,  168,  174,  175,  129,  130,  165,  150,  165,  165,
99217
 /*   750 */   181,  188,  174,  175,  150,   39,  165,  150,   52,  150,
92392
 /*   760 */   150,  165,  150,  241,   35,  174,  175,  174,  174,  175,
99218
 /*   760 */   150,  150,  150,  144,  145,  174,  175,  249,  250,  165,
92393
 /*   770 */    49,   50,  165,   52,   23,  165,   25,  165,  206,  207,
99219
 /*   770 */    49,   50,  165,   52,  165,  165,  165,  165,  174,  175,
92394
 /*   780 */    23,  197,   25,  187,  174,  175,  174,  175,  204,   68,
99220
 /*   780 */    29,  174,  175,  174,  175,  174,  175,  160,   22,   68,
92395
 /*   790 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
99221
 /*   790 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
92396
 /*   800 */    79,   80,  150,   82,   83,   84,   85,   86,   87,   88,
99222
 /*   800 */    79,   80,  150,   82,   83,   84,   85,   86,   87,   88,
92397
 /*   810 */    89,   90,   91,   92,   19,  150,  150,  165,   35,   23,
99223
 /*   810 */    89,   90,   91,   92,   19,  150,   94,  165,  150,  150,
92398
 /*   820 */   150,   25,  150,   22,  217,   24,  174,  175,  150,   35,
99224
 /*   820 */   160,  194,  150,  213,  160,   52,  174,  175,   23,   23,
92399
 /*   830 */   165,  165,  144,  145,  150,  165,  150,  165,  118,  174,
99225
 /*   830 */   165,   25,   22,  165,  165,  150,  150,  165,   52,  174,
92400
 /*   840 */   175,  150,   22,  165,   49,   50,  174,  175,   23,  165,
99226
 /*   840 */   175,   22,  174,  175,   49,   50,  174,  175,  190,  191,
92401
 /*   850 */    25,  165,   23,  187,   25,   27,  165,  187,  174,  175,
99227
 /*   850 */   165,  165,  240,   23,  194,   25,  187,  109,  194,  174,
92402
 /*   860 */    23,   23,   25,   68,   69,   70,   71,   72,   73,   74,
99228
 /*   860 */   175,  190,  191,   68,   69,   70,   71,   72,   73,   74,
92403
 /*   870 */    75,   76,   77,   78,   79,   80,  150,   82,   83,   84,
99229
 /*   870 */    75,   76,   77,   78,   79,   80,  150,   82,   83,   84,
92404
 /*   880 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  150,
99230
 /*   880 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  150,
92405
 /*   890 */   150,  165,  150,  150,  150,  217,   25,  160,   19,  213,
99231
 /*   890 */    22,  165,  150,   23,  150,   25,  150,  166,   91,   92,
92406
 /*   900 */   174,  175,  190,  191,  165,  165,   27,  165,  165,  165,
99232
 /*   900 */   174,  175,   22,  217,  165,  150,  102,  165,  150,  165,
92407
 /*   910 */   150,  150,  150,  174,  175,   39,  174,  175,   49,   50,
99233
 /*   910 */   150,  165,  150,  174,  175,   19,  174,  175,   49,   50,
92408
 /*   920 */    23,  150,   52,  250,  251,  165,  165,  165,  190,  191,
99234
 /*   920 */   165,   86,   87,  165,   23,  165,   25,  165,   24,  174,
92409
 /*   930 */   187,  194,  241,  193,  174,  175,  165,   68,   69,   70,
99235
 /*   930 */   175,  187,  174,  175,  174,  175,  205,   68,   69,   70,
92410
 /*   940 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
99236
 /*   940 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
92411
 /*   950 */   150,   82,   83,   84,   85,   86,   87,   88,   89,   90,
99237
 /*   950 */   150,   82,   83,   84,   85,   86,   87,   88,   89,   90,
92412
 /*   960 */    91,   92,   19,  150,  150,  165,  150,  160,  160,  166,
99238
 /*   960 */    91,   92,   19,  150,  150,  165,  150,  150,  166,   23,
92413
 /*   970 */   166,  160,  150,   22,  174,  175,   91,   92,  165,  165,
99239
 /*   970 */   150,   25,  160,   20,  174,  175,    1,    2,  165,  165,
92414
 /*   980 */    52,  165,   29,  150,  213,  241,   23,  165,   49,   50,
99240
 /*   980 */   104,  165,  165,   43,  150,  165,  240,  150,   49,   50,
92415
 /*   990 */   174,  175,   49,   50,    1,    2,  173,  126,  165,   86,
99241
 /*   990 */   174,  175,   49,   50,   23,   23,   25,   25,   53,  165,
92416
 /*  1000 */    87,  194,  194,   22,  181,  194,  193,  193,  205,  205,
99242
 /*  1000 */   187,  187,  165,   23,  187,   25,  194,  205,  174,  175,
92417
 /*  1010 */    71,   72,   69,   70,   71,   72,   73,   74,   75,   76,
99243
 /*  1010 */    71,   72,   69,   70,   71,   72,   73,   74,   75,   76,
92418
 /*  1020 */    77,   78,   79,   80,  150,   82,   83,   84,   85,   86,
99244
 /*  1020 */    77,   78,   79,   80,  150,   82,   83,   84,   85,   86,
92419
 /*  1030 */    87,   88,   89,   90,   91,   92,   19,   98,  150,  165,
99245
 /*  1030 */    87,   88,   89,   90,   91,   92,   19,   98,  150,  165,
92420
 /*  1040 */   150,  150,  150,   22,  150,  150,   22,   52,  174,  175,
99246
 /*  1040 */   150,  160,  150,   59,   25,   53,  104,   22,  174,  175,
92421
 /*  1050 */    22,  102,   20,  165,  109,  165,  165,  165,  150,  165,
99247
 /*  1050 */   213,  138,    5,  165,    1,  165,  150,  165,  150,  150,
92422
 /*  1060 */   165,  150,  174,  175,  174,  175,   49,   50,   24,   19,
99248
 /*  1060 */   240,  150,  174,  175,  174,  175,   49,   50,  118,  150,
92423
 /*  1070 */    43,  104,   59,  165,  138,  104,  165,   25,   53,   53,
99249
 /*  1070 */    35,  165,   27,  165,  165,  194,  165,  108,  127,   76,
92424
 /*  1080 */    22,    5,  174,  175,  193,  174,  175,   70,   71,   72,
99250
 /*  1080 */   174,  175,  174,  175,  165,  174,  175,   70,   71,   72,
92425
 /*  1090 */    73,   74,   75,   76,   77,   78,   79,   80,    1,   82,
99251
 /*  1090 */    73,   74,   75,   76,   77,   78,   79,   80,  166,   82,
92426
 /*  1100 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
99252
 /*  1100 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
92427
 /*  1110 */    19,   20,  150,   22,  150,  150,  150,   26,   27,  118,
99253
 /*  1110 */    19,   20,  193,   22,  150,  150,  150,   26,   27,   76,
92428
 /*  1120 */   150,   35,  150,  150,   76,   27,  108,  165,   37,  165,
99254
 /*  1120 */   150,   22,    1,  150,  119,  121,  217,   20,   37,  165,
92429
 /*  1130 */   165,  165,   76,   19,   20,  165,   22,  165,  165,  127,
99255
 /*  1130 */   165,  165,   16,   19,   20,  165,   22,  205,  165,  119,
92430
 /*  1140 */    26,   27,   22,    1,  150,   16,   20,   56,  150,  150,
99256
 /*  1140 */    26,   27,  108,  128,  150,  150,  150,   56,  150,   22,
92431
 /*  1150 */   119,   37,  150,  119,  160,  193,  150,   66,  193,  165,
99257
 /*  1150 */   150,   37,  150,  127,  160,   23,  150,   66,  193,  165,
92432
 /*  1160 */   150,  150,  121,  165,  165,  108,  150,  165,  174,  175,
99258
 /*  1160 */   165,  165,   16,  165,   23,  165,  150,  165,  174,  175,
92433
 /*  1170 */    56,  165,  150,  127,   22,  165,  165,   86,   87,   88,
99259
 /*  1170 */    56,  165,  150,   65,  174,  175,   15,   86,   87,   88,
92434
 /*  1180 */    66,  165,   16,  150,   93,   94,   95,  165,  194,   98,
99260
 /*  1180 */    66,  165,  140,  150,   93,   94,   95,  165,  194,   98,
92435
 /*  1190 */   174,  175,  128,   23,   15,   23,  174,  175,  165,  150,
99261
 /*  1190 */   174,  175,   22,    3,  164,  193,  174,  175,  165,  150,
92436
 /*  1200 */    86,   87,   65,  140,  150,   22,    3,   93,   94,   95,
99262
 /*  1200 */    86,   87,    4,  180,  150,  248,  251,   93,   94,   95,
92437
 /*  1210 */   216,    4,   98,  252,  165,  221,  150,  164,  180,  165,
99263
 /*  1210 */   216,  180,   98,  251,  165,  221,  150,  149,    6,  165,
92438
 /*  1220 */   129,  130,  131,  132,  133,  134,  193,  150,  174,  175,
99264
 /*  1220 */   129,  130,  131,  132,  133,  134,  193,  150,  174,  175,
92439
 /*  1230 */   116,  165,   19,   20,  150,   22,  249,  252,  149,   26,
99265
 /*  1230 */   116,  165,   19,   20,  150,   22,  149,  151,  150,   26,
92440
 /*  1240 */    27,  180,  165,  129,  130,  131,  132,  133,  134,  165,
99266
 /*  1240 */    27,  149,  165,  129,  130,  131,  132,  133,  134,  165,
92441
 /*  1250 */    37,  174,  175,  150,    6,   19,   20,  150,   22,  150,
99267
 /*  1250 */    37,  174,  175,  165,  149,   19,   20,   13,   22,  150,
92442
 /*  1260 */   150,  150,   26,   27,  149,  149,   13,  150,  165,   56,
99268
 /*  1260 */   150,  150,   26,   27,  146,  147,  151,  150,   25,   56,
92443
 /*  1270 */   149,  159,  165,   37,  165,  165,  165,  174,  175,   66,
99269
 /*  1270 */   152,  159,  154,   37,  165,  165,  165,  193,  160,   66,
92444
 /*  1280 */   146,  147,  165,  174,  175,   25,  152,  151,  154,  150,
99270
 /*  1280 */   116,  193,  165,  174,  175,  174,  175,  194,  199,  150,
92445
 /*  1290 */   194,  151,   56,  116,  160,  150,  123,  202,  150,   86,
99271
 /*  1290 */   200,  126,   56,  124,  123,  150,  201,  122,  150,   86,
92446
 /*  1300 */    87,  199,   66,  193,  165,  200,   93,   94,   95,  150,
99272
 /*  1300 */    87,  150,   66,  193,  165,  202,   93,   94,   95,  150,
92447
 /*  1310 */   165,   98,  150,  165,  126,   22,  124,  150,  150,   26,
99273
 /*  1310 */   165,   98,  194,  165,  125,   22,  165,  150,  150,   26,
92448
 /*  1320 */    27,  150,   86,   87,  165,  201,  150,  165,  194,   93,
99274
 /*  1320 */    27,  135,   86,   87,  165,  174,  175,  203,  226,   93,
92449
 /*  1330 */    94,   95,  165,  165,   98,  150,  165,  122,  203,  125,
99275
 /*  1330 */    94,   95,  165,  165,   98,  150,  218,  150,  193,  157,
92450
 /*  1340 */   227,  165,  129,  130,  131,  132,  133,  134,    5,  150,
99276
 /*  1340 */   118,  157,  129,  130,  131,  132,  133,  134,    5,  104,
92451
 /*  1350 */   165,  135,  218,   10,   11,   12,   13,   14,  150,   66,
99277
 /*  1350 */   165,  211,  165,   10,   11,   12,   13,   14,  150,   66,
92452
 /*  1360 */    17,  157,  118,  157,  165,  129,  130,  131,  132,  133,
99278
 /*  1360 */    17,  174,  175,  210,  246,  129,  130,  131,  132,  133,
92453
 /*  1370 */   134,  150,  104,  165,   31,  210,   33,  176,  150,   86,
99279
 /*  1370 */   134,  150,  210,  165,   31,  121,   33,  150,  150,   86,
92454
 /*  1380 */    87,  247,  174,  175,  150,   42,  165,   94,  121,  211,
99280
 /*  1380 */    87,  176,  174,  175,  150,   42,  165,   94,  211,  210,
92455
 /*  1390 */   150,   98,  210,  165,  210,  174,  175,  211,   55,  165,
99281
 /*  1390 */   150,   98,  165,  165,  211,  174,  175,  150,   55,  165,
92456
 /*  1400 */    57,  150,  174,  175,   61,  165,  150,   64,  174,  175,
99282
 /*  1400 */    57,  150,  174,  175,   61,  165,  150,   64,  174,  175,
92457
 /*  1410 */   104,  211,   47,  150,  174,  175,  165,  176,  176,  150,
99283
 /*  1410 */   150,  150,  165,  150,  174,  175,  165,  104,  150,  184,
92458
 /*  1420 */   103,  165,  129,  130,  131,  174,  175,  184,  165,  179,
99284
 /*  1420 */   150,  165,  129,  130,  131,  165,  165,  150,  165,  150,
92459
 /*  1430 */   174,  175,  150,  178,  165,  176,   22,  174,  175,  230,
99285
 /*  1430 */   150,  176,  150,  165,   47,  165,  150,  150,  176,  103,
92460
 /*  1440 */    92,  230,  184,  174,  175,  150,  176,  165,  105,  106,
99286
 /*  1440 */   150,   22,  165,  178,  165,  165,  179,  165,  105,  106,
92461
 /*  1450 */   107,  150,  176,  176,  111,  156,  174,  175,  179,  116,
99287
 /*  1450 */   107,  165,  165,  229,  111,  165,   92,  176,  229,  116,
92462
 /*  1460 */   165,   18,  157,  156,  238,  157,  165,  156,   45,  174,
99288
 /*  1460 */   184,  176,  179,  156,  176,  176,   18,  157,  156,  237,
92463
 /*  1470 */   175,  157,  157,  135,  239,  174,  175,  156,  189,  157,
99289
 /*  1470 */    45,  157,  156,  135,  157,  157,  238,  156,   68,  157,
92464
 /*  1480 */    68,  189,  139,  219,   22,  199,  157,   18,  192,  192,
99290
 /*  1480 */   189,  189,  139,  219,   22,  157,   18,  192,  192,  192,
92465
 /*  1490 */   192,  189,  192,  199,  219,  243,  157,   40,  157,  157,
99291
 /*  1490 */   192,  189,  219,  199,  157,  242,   40,  157,  199,  242,
92466
 /*  1500 */   243,   38,  153,  166,  233,  196,  233,  246,  198,  228,
99292
 /*  1500 */   153,  157,   38,  245,  196,  166,  232,  198,  177,  177,
92467
 /*  1510 */   177,  177,  209,  177,  182,  199,  166,  177,  166,  199,
99293
 /*  1510 */   232,  227,  209,  178,  166,  182,  166,  148,  177,  177,
92468
 /*  1520 */   242,  177,  242,  178,  148,  166,  196,  209,  209,   92,
99294
 /*  1520 */   209,  196,  177,  199,  209,  199,  166,  208,   92,  195,
92469
 /*  1530 */   195,  208,  174,  186,  183,  174,  183,  191,  183,  253,
99295
 /*  1530 */   174,  174,  183,  252,  183,  183,  252,  191,  252,  235,
92470
 /*  1540 */   236,  253,  186,  253,  253,  253,  253,  253,  253,  237,
99296
 /*  1540 */   186,  241,  241,  252,  186,  252,  252,  252,  252,  252,
92471
};
99297
 /*  1550 */   252,  252,  252,  252,  252,  252,  236,
92472
#define YY_SHIFT_USE_DFLT (-90)
99298
};
99299
#define YY_SHIFT_USE_DFLT (-74)
92473
#define YY_SHIFT_COUNT (418)
99300
#define YY_SHIFT_COUNT (418)
92474
#define YY_SHIFT_MIN   (-89)
99301
#define YY_SHIFT_MIN   (-73)
92475
#define YY_SHIFT_MAX   (1469)
99302
#define YY_SHIFT_MAX   (1468)
92476
static const short yy_shift_ofst[] = {
99303
static const short yy_shift_ofst[] = {
92477
 /*     0 */   993, 1114, 1343, 1114, 1213, 1213,   90,   90,    0,  -19,
99304
 /*     0 */   975, 1114, 1343, 1114, 1213, 1213,   90,   90,    0,  -19,
92478
 /*    10 */  1213, 1213, 1213, 1213, 1213,  352,  517,  721, 1091, 1213,
99305
 /*    10 */  1213, 1213, 1213, 1213, 1213,  345,  445,  721, 1091, 1213,
92479
 /*    20 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
99306
 /*    20 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
92480
 /*    30 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
99307
 /*    30 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
92481
 /*    40 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1236, 1213, 1213,
99308
 /*    40 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1236, 1213, 1213,
92482
 /*    50 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
99309
 /*    50 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
92483
 /*    60 */  1213,  -49,  199,  517,  517,  913,  913,  382, 1177,   55,
99310
 /*    60 */  1213,  199,  445,  445,  835,  835,  365, 1164,   55,  647,
92484
 /*    70 */   647,  573,  499,  425,  351,  277,  203,  129,  795,  795,
99311
 /*    70 */   573,  499,  425,  351,  277,  203,  129,  795,  795,  795,
92485
 /*    80 */   795,  795,  795,  795,  795,  795,  795,  795,  795,  795,
99312
 /*    80 */   795,  795,  795,  795,  795,  795,  795,  795,  795,  795,
92486
 /*    90 */   795,  795,  795,  795,  795,  795,  869,  795,  943, 1017,
99313
 /*    90 */   795,  795,  795,  795,  795,  869,  795,  943, 1017, 1017,
92487
 /*   100 */  1017,  -69,  -69,  -69,  -69,   -1,   -1,   58,  138,  -44,
99314
 /*   100 */   -69,  -45,  -45,  -45,  -45,  -45,   -1,   58,  138,  100,
92488
 /*   110 */   517,  517,  517,  517,  517,  517,  517,  517,  517,  517,
99315
 /*   110 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
92489
 /*   120 */   517,  517,  517,  517,  517,  517,  202,  579,  517,  517,
99316
 /*   120 */   445,  445,  445,  445,  445,  445,  537,  438,  445,  445,
92490
 /*   130 */   517,  517,  517,  382,  885, 1437,  -90,  -90,  -90, 1293,
99317
 /*   130 */   445,  445,  445,  365,  807, 1436,  -74,  -74,  -74, 1293,
92491
 /*   140 */    73,  272,  272,  309,  311,  297,  282,  216,  602,  538,
99318
 /*   140 */    73,  434,  434,  311,  314,  290,  283,  286,  540,  467,
92492
 /*   150 */   517,  517,  517,  517,  517,  517,  517,  517,  517,  517,
99319
 /*   150 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
92493
 /*   160 */   517,  517,  517,  517,  517,  517,  517,  517,  517,  517,
99320
 /*   160 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
92494
 /*   170 */   517,  517,  517,  517,  517,  517,  517,  517,  517,  517,
99321
 /*   170 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
92495
 /*   180 */   517,  517,  505,  231,  231,  231,  706,   64, 1177, 1177,
99322
 /*   180 */   445,  445,   65,  722,  722,  722,  688,  266, 1164, 1164,
92496
 /*   190 */  1177,  -90,  -90,  -90,  136,  168,  168,   12,  496,  496,
99323
 /*   190 */  1164,  -74,  -74,  -74,  136,  168,  168,  234,  360,  360,
92497
 /*   200 */   496,  506,  423,  512,  370,  349,  335,  149,  149,  149,
99324
 /*   200 */   360,  430,  372,  435,  352,  278,  126,  -36,  -36,  -36,
92498
 /*   210 */   149,  604,  516,  149,  149,  508,    3,  299,  677,  871,
99325
 /*   210 */   -36,  421,  651,  -36,  -36,  592,  292,  212,  623,  158,
92499
 /*   220 */   613,  613,  879,  871,  879,  144,  382,  226,  382,  226,
99326
 /*   220 */   204,  204,  505,  158,  505,  144,  365,  154,  365,  154,
92500
 /*   230 */   564,  226,  613,  226,  226,  404,  625,  625,  382,  426,
99327
 /*   230 */   645,  154,  204,  154,  154,  535,  548,  548,  365,  387,
92501
 /*   240 */   -89,  801, 1463, 1244, 1244, 1457, 1457, 1244, 1462, 1412,
99328
 /*   240 */   508,  233, 1464, 1222, 1222, 1456, 1456, 1222, 1462, 1410,
92502
 /*   250 */  1188, 1469, 1469, 1469, 1469, 1244, 1188, 1462, 1412, 1412,
99329
 /*   250 */  1165, 1468, 1468, 1468, 1468, 1222, 1165, 1462, 1410, 1410,
92503
 /*   260 */  1244, 1443, 1338, 1423, 1244, 1244, 1443, 1244, 1443, 1244,
99330
 /*   260 */  1222, 1448, 1338, 1425, 1222, 1222, 1448, 1222, 1448, 1222,
92504
 /*   270 */  1443, 1414, 1306, 1306, 1306, 1365, 1348, 1348, 1414, 1306,
99331
 /*   270 */  1448, 1419, 1313, 1313, 1313, 1387, 1364, 1364, 1419, 1313,
92505
 /*   280 */  1317, 1306, 1365, 1306, 1306, 1267, 1268, 1267, 1268, 1267,
99332
 /*   280 */  1336, 1313, 1387, 1313, 1313, 1254, 1245, 1254, 1245, 1254,
92506
 /*   290 */  1268, 1244, 1244, 1216, 1214, 1215, 1192, 1173, 1188, 1177,
99333
 /*   290 */  1245, 1222, 1222, 1186, 1189, 1175, 1169, 1171, 1165, 1164,
92507
 /*   300 */  1260, 1253, 1253, 1248, 1248, 1248, 1248,  -90,  -90,  -90,
99334
 /*   300 */  1243, 1244, 1244, 1212, 1212, 1212, 1212,  -74,  -74,  -74,
92508
 /*   310 */   -90,  -90,  -90,  939,  102,  614,   84,  133,   14,  837,
99335
 /*   310 */   -74,  -74,  -74,  939,  104,  680,  571,  327,    1,  980,
92509
 /*   320 */   396,  829,  825,  796,  757,  751,  650,  357,  244,  107,
99336
 /*   320 */    26,  972,  971,  946,  901,  870,  830,  806,   54,   21,
92510
 /*   330 */    54,  305,  278, 1207, 1203, 1183, 1063, 1179, 1137, 1166,
99337
 /*   330 */   -73,  510,  242, 1198, 1190, 1170, 1042, 1161, 1108, 1146,
92511
 /*   340 */  1172, 1170, 1064, 1152, 1046, 1057, 1034, 1126, 1041, 1129,
99338
 /*   340 */  1141, 1132, 1015, 1127, 1026, 1034, 1020, 1107, 1004, 1116,
92512
 /*   350 */  1142, 1031, 1120, 1012, 1056, 1048, 1018, 1098, 1086, 1001,
99339
 /*   350 */  1121, 1005, 1099,  951, 1043, 1003,  969, 1045, 1035,  950,
92513
 /*   360 */  1097, 1076, 1058,  971,  936, 1026, 1052, 1025, 1013, 1027,
99340
 /*   360 */  1053, 1047, 1025,  942,  913,  992, 1019,  945,  984,  940,
92514
 /*   370 */   967, 1044, 1032, 1050,  945,  949, 1028,  995, 1024, 1021,
99341
 /*   370 */   876,  904,  953,  896,  748,  804,  880,  786,  868,  819,
92515
 /*   380 */   963,  981,  928,  953,  951,  870,  876,  897,  838,  720,
99342
 /*   380 */   805,  810,  773,  751,  766,  706,  716,  691,  681,  568,
92516
 /*   390 */   828,  794,  820,  498,  642,  783,  657,  729,  642,  557,
99343
 /*   390 */   655,  638,  676,  516,  541,  594,  599,  567,  541,  534,
92517
 /*   400 */   507,  509,  497,  470,  478,  449,  294,  228,  443,   23,
99344
 /*   400 */   507,  527,  498,  523,  466,  382,  409,  384,  357,    6,
92518
 /*   410 */   152,  123,   68,  -20,  -42,   57,   39,   -3,    5,
99345
 /*   410 */   240,  224,  143,   62,   18,   71,   39,    9,    5,
92519
};
99346
};
92520
#define YY_REDUCE_USE_DFLT (-222)
99347
#define YY_REDUCE_USE_DFLT (-142)
92521
#define YY_REDUCE_COUNT (312)
99348
#define YY_REDUCE_COUNT (312)
92522
#define YY_REDUCE_MIN   (-221)
99349
#define YY_REDUCE_MIN   (-141)
92523
#define YY_REDUCE_MAX   (1376)
99350
#define YY_REDUCE_MAX   (1369)
92524
static const short yy_reduce_ofst[] = {
99351
static const short yy_reduce_ofst[] = {
92525
 /*     0 */   310,  994, 1134,  221,  169,  157,   89,   18,   83,  301,
99352
 /*     0 */  -141,  994, 1118,  223,  157,  -53,   93,   89,   83,  375,
92526
 /*    10 */   377,  316,  312,   16,  295,  238,  249,  391, 1301, 1295,
99353
 /*    10 */   386,  381,  379,  308,  295,  325,  -47,   27, 1240, 1234,
92527
 /*    20 */  1282, 1269, 1263, 1256, 1251, 1240, 1234, 1228, 1221, 1208,
99354
 /*    20 */  1228, 1221, 1208, 1187, 1151, 1111, 1109, 1077, 1054, 1022,
92528
 /*    30 */  1109, 1103, 1077, 1054, 1022, 1016,  911,  908,  890,  888,
99355
 /*    30 */  1016, 1000,  911,  908,  906,  890,  888,  874,  834,  816,
92529
 /*    40 */   874,  816,  800,  760,  742,  739,  726,  684,  672,  665,
99356
 /*    40 */   800,  760,  758,  755,  742,  739,  726,  685,  672,  668,
92530
 /*    50 */   652,  612,  610,  594,  591,  578,  530,  528,  526,  524,
99357
 /*    50 */   665,  652,  611,  609,  607,  604,  591,  578,  526,  519,
92531
 /*    60 */   -72, -221,  399,  469,  445,  438,  143,  222,  359,  523,
99358
 /*    60 */   453,  474,  454,  461,  443,  245,  442,  473,  484,  484,
92532
 /*    70 */   523,  523,  523,  523,  523,  523,  523,  523,  523,  523,
99359
 /*    70 */   484,  484,  484,  484,  484,  484,  484,  484,  484,  484,
92533
 /*    80 */   523,  523,  523,  523,  523,  523,  523,  523,  523,  523,
99360
 /*    80 */   484,  484,  484,  484,  484,  484,  484,  484,  484,  484,
92534
 /*    90 */   523,  523,  523,  523,  523,  523,  523,  523,  523,  523,
99361
 /*    90 */   484,  484,  484,  484,  484,  484,  484,  484,  484,  484,
92535
 /*   100 */   523,  523,  523,  523,  523,  523,  523,  307,  523,  523,
99362
 /*   100 */   484,  484,  484,  484,  484,  484,  484,  130,  484,  484,
92536
 /*   110 */  1110,  678, 1033,  965,  962,  891,  814,  813,  744,  771,
99363
 /*   110 */  1145,  909, 1110, 1088, 1084, 1033, 1002,  965,  820,  837,
92537
 /*   120 */   691,  607,  522,  743,  686,  740,  328,  418,  670,  666,
99364
 /*   120 */   746,  686,  612,  817,  610,  919,  221,  563,  814,  813,
92538
 /*   130 */   596,  527,  529,  583,  523,  523,  523,  523,  523,  593,
99365
 /*   130 */   744,  669,  470,  543,  484,  484,  484,  484,  484,  291,
92539
 /*   140 */   823,  738,  712,  892, 1199, 1185, 1176, 1171,  673,  673,
99366
 /*   140 */   569,  671,  658,  970, 1290, 1287, 1286, 1282,  518,  518,
92540
 /*   150 */  1168, 1167, 1162, 1159, 1148, 1145, 1139, 1117, 1111, 1107,
99367
 /*   150 */  1280, 1279, 1277, 1270, 1268, 1263, 1261, 1260, 1256, 1251,
92541
 /*   160 */  1084, 1066, 1049, 1011, 1010, 1006, 1002,  999,  998,  973,
99368
 /*   160 */  1247, 1227, 1185, 1168, 1167, 1159, 1148, 1139, 1117, 1066,
92542
 /*   170 */   972,  970,  966,  964,  895,  894,  892,  833,  822,  762,
99369
 /*   170 */  1049, 1006,  998,  996,  995,  973,  970,  966,  964,  892,
92543
 /*   180 */   761,  229,  811,  804,  803,  389,  688,  808,  807,  737,
99370
 /*   180 */   762,  -52,  881,  932,  802,  731,  619,  812,  664,  660,
92544
 /*   190 */   460,  464,  572,  584, 1356, 1361, 1358, 1347, 1355, 1353,
99371
 /*   190 */   627,  392,  331,  124, 1358, 1357, 1356, 1354, 1352, 1351,
92545
 /*   200 */  1351, 1323, 1335, 1346, 1335, 1335, 1335, 1335, 1335, 1335,
99372
 /*   200 */  1349, 1319, 1334, 1346, 1334, 1334, 1334, 1334, 1334, 1334,
92546
 /*   210 */  1335, 1312, 1304, 1335, 1335, 1323, 1359, 1330, 1376, 1320,
99373
 /*   210 */  1334, 1320, 1304, 1334, 1334, 1319, 1360, 1325, 1369, 1326,
92547
 /*   220 */  1319, 1318, 1280, 1316, 1278, 1345, 1352, 1344, 1350, 1340,
99374
 /*   220 */  1315, 1311, 1301, 1324, 1300, 1335, 1350, 1345, 1348, 1342,
92548
 /*   230 */  1332, 1336, 1303, 1334, 1333, 1281, 1273, 1271, 1337, 1310,
99375
 /*   230 */  1333, 1341, 1303, 1332, 1331, 1284, 1278, 1274, 1339, 1309,
92549
 /*   240 */  1309, 1349, 1261, 1342, 1341, 1257, 1252, 1339, 1275, 1302,
99376
 /*   240 */  1308, 1347, 1258, 1344, 1340, 1257, 1253, 1337, 1273, 1302,
92550
 /*   250 */  1294, 1300, 1298, 1297, 1296, 1329, 1286, 1264, 1292, 1289,
99377
 /*   250 */  1299, 1298, 1297, 1296, 1295, 1328, 1294, 1264, 1292, 1291,
92551
 /*   260 */  1322, 1321, 1235, 1226, 1315, 1314, 1311, 1308, 1307, 1305,
99378
 /*   260 */  1322, 1321, 1238, 1232, 1318, 1317, 1316, 1314, 1312, 1310,
92552
 /*   270 */  1299, 1279, 1277, 1276, 1270, 1258, 1211, 1209, 1250, 1259,
99379
 /*   270 */  1307, 1283, 1289, 1288, 1285, 1276, 1229, 1224, 1267, 1281,
92553
 /*   280 */  1255, 1242, 1243, 1241, 1201, 1200, 1184, 1186, 1182, 1178,
99380
 /*   280 */  1265, 1262, 1235, 1255, 1205, 1183, 1179, 1177, 1162, 1140,
92554
 /*   290 */  1165, 1206, 1204, 1113, 1135, 1095, 1124, 1105, 1102, 1096,
99381
 /*   290 */  1153, 1184, 1182, 1102, 1124, 1103, 1095, 1090, 1089, 1093,
92555
 /*   300 */  1112, 1140, 1136, 1121, 1116, 1115, 1089,  985,  961,  987,
99382
 /*   300 */  1112, 1115, 1086, 1105, 1092, 1087, 1068,  962,  955,  957,
92556
 /*   310 */  1061, 1038, 1053,
99383
 /*   310 */  1031, 1023, 1030,
92557
};
99384
};
92558
static const YYACTIONTYPE yy_default[] = {
99385
static const YYACTIONTYPE yy_default[] = {
92559
 /*     0 */   636,  872,  961,  961,  961,  872,  901,  901,  961,  760,
99386
 /*     0 */   635,  870,  959,  959,  959,  870,  899,  899,  959,  759,
92560
 /*    10 */   961,  961,  961,  961,  870,  961,  961,  935,  961,  961,
99387
 /*    10 */   959,  959,  959,  959,  868,  959,  959,  933,  959,  959,
92561
 /*    20 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
99388
 /*    20 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
92562
 /*    30 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
99389
 /*    30 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
92563
 /*    40 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
99390
 /*    40 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
92564
 /*    50 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
99391
 /*    50 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
92565
 /*    60 */   961,  844,  961,  961,  961,  901,  901,  675,  764,  795,
99392
 /*    60 */   959,  959,  959,  959,  899,  899,  674,  763,  794,  959,
92566
 /*    70 */   961,  961,  961,  961,  961,  961,  961,  961,  934,  936,
99393
 /*    70 */   959,  959,  959,  959,  959,  959,  959,  932,  934,  809,
92567
 /*    80 */   810,  809,  803,  802,  914,  775,  800,  793,  786,  797,
99394
 /*    80 */   808,  802,  801,  912,  774,  799,  792,  785,  796,  871,
92568
 /*    90 */   873,  866,  867,  865,  869,  874,  961,  796,  832,  850,
99395
 /*    90 */   864,  865,  863,  867,  872,  959,  795,  831,  848,  830,
92569
 /*   100 */   831,  849,  856,  848,  834,  843,  833,  667,  835,  836,
99396
 /*   100 */   842,  847,  854,  846,  843,  833,  832,  666,  834,  835,
92570
 /*   110 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
99397
 /*   110 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
92571
 /*   120 */   961,  961,  961,  961,  961,  961,  662,  729,  961,  961,
99398
 /*   120 */   959,  959,  959,  959,  959,  959,  661,  728,  959,  959,
92572
 /*   130 */   961,  961,  961,  961,  837,  838,  853,  852,  851,  961,
99399
 /*   130 */   959,  959,  959,  959,  836,  837,  851,  850,  849,  959,
92573
 /*   140 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
99400
 /*   140 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
92574
 /*   150 */   961,  941,  939,  961,  885,  961,  961,  961,  961,  961,
99401
 /*   150 */   959,  939,  937,  959,  883,  959,  959,  959,  959,  959,
92575
 /*   160 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
99402
 /*   160 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
92576
 /*   170 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
99403
 /*   170 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
92577
 /*   180 */   961,  642,  961,  760,  760,  760,  636,  961,  961,  961,
99404
 /*   180 */   959,  641,  959,  759,  759,  759,  635,  959,  959,  959,
92578
 /*   190 */   961,  953,  764,  754,  720,  961,  961,  961,  961,  961,
99405
 /*   190 */   959,  951,  763,  753,  719,  959,  959,  959,  959,  959,
92579
 /*   200 */   961,  961,  961,  961,  961,  961,  961,  805,  743,  924,
99406
 /*   200 */   959,  959,  959,  959,  959,  959,  959,  804,  742,  922,
92580
 /*   210 */   926,  961,  907,  741,  664,  762,  677,  752,  644,  799,
99407
 /*   210 */   924,  959,  905,  740,  663,  761,  676,  751,  643,  798,
92581
 /*   220 */   777,  777,  919,  799,  919,  701,  961,  789,  961,  789,
99408
 /*   220 */   776,  776,  917,  798,  917,  700,  959,  788,  959,  788,
92582
 /*   230 */   698,  789,  777,  789,  789,  868,  961,  961,  961,  761,
99409
 /*   230 */   697,  788,  776,  788,  788,  866,  959,  959,  959,  760,
92583
 /*   240 */   752,  961,  946,  768,  768,  938,  938,  768,  811,  733,
99410
 /*   240 */   751,  959,  944,  767,  767,  936,  936,  767,  810,  732,
92584
 /*   250 */   799,  740,  740,  740,  740,  768,  799,  811,  733,  733,
99411
 /*   250 */   798,  739,  739,  739,  739,  767,  798,  810,  732,  732,
92585
 /*   260 */   768,  659,  913,  911,  768,  768,  659,  768,  659,  768,
99412
 /*   260 */   767,  658,  911,  909,  767,  767,  658,  767,  658,  767,
92586
 /*   270 */   659,  878,  731,  731,  731,  716,  882,  882,  878,  731,
99413
 /*   270 */   658,  876,  730,  730,  730,  715,  880,  880,  876,  730,
92587
 /*   280 */   701,  731,  716,  731,  731,  781,  776,  781,  776,  781,
99414
 /*   280 */   700,  730,  715,  730,  730,  780,  775,  780,  775,  780,
92588
 /*   290 */   776,  768,  768,  961,  794,  782,  792,  790,  799,  961,
99415
 /*   290 */   775,  767,  767,  959,  793,  781,  791,  789,  798,  959,
92589
 /*   300 */   719,  652,  652,  641,  641,  641,  641,  958,  958,  953,
99416
 /*   300 */   718,  651,  651,  640,  640,  640,  640,  956,  956,  951,
92590
 /*   310 */   703,  703,  685,  961,  961,  961,  961,  961,  961,  961,
99417
 /*   310 */   702,  702,  684,  959,  959,  959,  959,  959,  959,  959,
92591
 /*   320 */   887,  961,  961,  961,  961,  961,  961,  961,  961,  961,
99418
 /*   320 */   885,  959,  959,  959,  959,  959,  959,  959,  959,  959,
92592
 /*   330 */   961,  961,  961,  961,  637,  948,  961,  961,  945,  961,
99419
 /*   330 */   959,  959,  959,  959,  636,  946,  959,  959,  943,  959,
92593
 /*   340 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
99420
 /*   340 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
92594
 /*   350 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  917,
99421
 /*   350 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  915,
92595
 /*   360 */   961,  961,  961,  961,  961,  961,  910,  909,  961,  961,
99422
 /*   360 */   959,  959,  959,  959,  959,  959,  908,  907,  959,  959,
92596
 /*   370 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
99423
 /*   370 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
92597
 /*   380 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
99424
 /*   380 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
92598
 /*   390 */   961,  961,  961,  961,  791,  961,  783,  961,  871,  961,
99425
 /*   390 */   959,  959,  959,  959,  790,  959,  782,  959,  869,  959,
92599
 /*   400 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  746,
99426
 /*   400 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  745,
92600
 /*   410 */   820,  961,  819,  823,  818,  669,  961,  650,  961,  633,
99427
 /*   410 */   819,  959,  818,  822,  817,  668,  959,  649,  959,  632,
92601
 /*   420 */   638,  957,  960,  959,  956,  955,  954,  949,  947,  944,
99428
 /*   420 */   637,  955,  958,  957,  954,  953,  952,  947,  945,  942,
92602
 /*   430 */   943,  942,  940,  937,  933,  891,  889,  896,  895,  894,
99429
 /*   430 */   941,  940,  938,  935,  931,  889,  887,  894,  893,  892,
92603
 /*   440 */   893,  892,  890,  888,  886,  806,  804,  801,  798,  932,
99430
 /*   440 */   891,  890,  888,  886,  884,  805,  803,  800,  797,  930,
92604
 /*   450 */   884,  742,  739,  738,  658,  950,  916,  925,  923,  812,
99431
 /*   450 */   882,  741,  738,  737,  657,  948,  914,  923,  921,  811,
92605
 /*   460 */   922,  921,  920,  918,  915,  902,  808,  807,  734,  876,
99432
 /*   460 */   920,  919,  918,  916,  913,  900,  807,  806,  733,  874,
92606
 /*   470 */   875,  661,  906,  905,  904,  908,  912,  903,  770,  660,
99433
 /*   470 */   873,  660,  904,  903,  902,  906,  910,  901,  769,  659,
92607
 /*   480 */   657,  666,  723,  722,  730,  728,  727,  726,  725,  724,
99434
 /*   480 */   656,  665,  722,  721,  729,  727,  726,  725,  724,  723,
92608
 /*   490 */   721,  668,  676,  687,  715,  700,  699,  881,  883,  880,
99435
 /*   490 */   720,  667,  675,  686,  714,  699,  698,  879,  881,  878,
92609
 /*   500 */   879,  708,  707,  713,  712,  711,  710,  709,  706,  705,
99436
 /*   500 */   877,  707,  706,  712,  711,  710,  709,  708,  705,  704,
92610
 /*   510 */   704,  697,  696,  702,  695,  718,  717,  714,  694,  737,
99437
 /*   510 */   703,  696,  695,  701,  694,  717,  716,  713,  693,  736,
92611
 /*   520 */   736,  735,  732,  693,  692,  691,  823,  690,  689,  829,
99438
 /*   520 */   735,  734,  731,  692,  691,  690,  822,  689,  688,  828,
92612
 /*   530 */   828,  816,  860,  757,  756,  755,  767,  766,  779,  778,
99439
 /*   530 */   827,  815,  858,  756,  755,  754,  766,  765,  778,  777,
92613
 /*   540 */   814,  813,  780,  765,  759,  758,  774,  773,  772,  771,
99440
 /*   540 */   813,  812,  779,  764,  758,  757,  773,  772,  771,  770,
92614
 /*   550 */   763,  753,  785,  788,  787,  784,  845,  862,  769,  859,
99441
 /*   550 */   762,  752,  784,  787,  786,  783,  860,  768,  857,  929,
92615
 /*   560 */   931,  930,  929,  928,  927,  864,  863,  830,  827,  680,
99442
 /*   560 */   928,  927,  926,  925,  862,  861,  829,  826,  679,  680,
92616
 /*   570 */   681,  900,  898,  899,  897,  683,  682,  679,  678,  861,
99443
 /*   570 */   898,  896,  897,  895,  682,  681,  678,  677,  859,  747,
92617
 /*   580 */   748,  747,  857,  854,  846,  841,  858,  855,  847,  842,
99444
 /*   580 */   746,  855,  852,  844,  840,  856,  853,  845,  841,  839,
92618
 /*   590 */   840,  839,  825,  824,  822,  821,  817,  826,  671,  749,
99445
 /*   590 */   838,  824,  823,  821,  820,  816,  825,  670,  748,  744,
92619
 /*   600 */   745,  744,  815,  751,  750,  688,  686,  684,  665,  663,
99446
 /*   600 */   743,  814,  750,  749,  687,  685,  683,  664,  662,  655,
92620
 /*   610 */   656,  654,  653,  655,  651,  649,  648,  647,  646,  645,
99447
 /*   610 */   653,  652,  654,  650,  648,  647,  646,  645,  644,  673,
92621
 /*   620 */   674,  673,  672,  670,  669,  643,  640,  639,  635,  634,
99448
 /*   620 */   672,  671,  669,  668,  642,  639,  638,  634,  633,  631,
92622
 /*   630 */   632,
92623
};
99449
};
92624
99450
92625
/* The next table maps tokens into fallback tokens.  If a construct
99451
/* The next table maps tokens into fallback tokens.  If a construct
 Lines 92833-92847   static const char *const yyTokenName[] = Link Here 
92833
  "joinop",        "indexed_opt",   "on_opt",        "using_opt",   
99659
  "joinop",        "indexed_opt",   "on_opt",        "using_opt",   
92834
  "joinop2",       "inscollist",    "sortlist",      "sortitem",    
99660
  "joinop2",       "inscollist",    "sortlist",      "sortitem",    
92835
  "nexprlist",     "setlist",       "insert_cmd",    "inscollist_opt",
99661
  "nexprlist",     "setlist",       "insert_cmd",    "inscollist_opt",
92836
  "itemlist",      "exprlist",      "likeop",        "escape",      
99662
  "itemlist",      "exprlist",      "likeop",        "between_op",  
92837
  "between_op",    "in_op",         "case_operand",  "case_exprlist",
99663
  "in_op",         "case_operand",  "case_exprlist",  "case_else",   
92838
  "case_else",     "uniqueflag",    "collate",       "nmnum",       
99664
  "uniqueflag",    "collate",       "nmnum",         "plus_opt",    
92839
  "plus_opt",      "number",        "trigger_decl",  "trigger_cmd_list",
99665
  "number",        "trigger_decl",  "trigger_cmd_list",  "trigger_time",
92840
  "trigger_time",  "trigger_event",  "foreach_clause",  "when_clause", 
99666
  "trigger_event",  "foreach_clause",  "when_clause",   "trigger_cmd", 
92841
  "trigger_cmd",   "trnm",          "tridxby",       "database_kw_opt",
99667
  "trnm",          "tridxby",       "database_kw_opt",  "key_opt",     
92842
  "key_opt",       "add_column_fullname",  "kwcolumn_opt",  "create_vtab", 
99668
  "add_column_fullname",  "kwcolumn_opt",  "create_vtab",   "vtabarglist", 
92843
  "vtabarglist",   "vtabarg",       "vtabargtoken",  "lp",          
99669
  "vtabarg",       "vtabargtoken",  "lp",            "anylist",     
92844
  "anylist",     
92845
};
99670
};
92846
#endif /* NDEBUG */
99671
#endif /* NDEBUG */
92847
99672
 Lines 93061-93184   static const char *const yyRuleName[] = Link Here 
93061
 /* 209 */ "likeop ::= NOT LIKE_KW",
99886
 /* 209 */ "likeop ::= NOT LIKE_KW",
93062
 /* 210 */ "likeop ::= MATCH",
99887
 /* 210 */ "likeop ::= MATCH",
93063
 /* 211 */ "likeop ::= NOT MATCH",
99888
 /* 211 */ "likeop ::= NOT MATCH",
93064
 /* 212 */ "escape ::= ESCAPE expr",
99889
 /* 212 */ "expr ::= expr likeop expr",
93065
 /* 213 */ "escape ::=",
99890
 /* 213 */ "expr ::= expr likeop expr ESCAPE expr",
93066
 /* 214 */ "expr ::= expr likeop expr escape",
99891
 /* 214 */ "expr ::= expr ISNULL|NOTNULL",
93067
 /* 215 */ "expr ::= expr ISNULL|NOTNULL",
99892
 /* 215 */ "expr ::= expr NOT NULL",
93068
 /* 216 */ "expr ::= expr NOT NULL",
99893
 /* 216 */ "expr ::= expr IS expr",
93069
 /* 217 */ "expr ::= expr IS expr",
99894
 /* 217 */ "expr ::= expr IS NOT expr",
93070
 /* 218 */ "expr ::= expr IS NOT expr",
99895
 /* 218 */ "expr ::= NOT expr",
93071
 /* 219 */ "expr ::= NOT expr",
99896
 /* 219 */ "expr ::= BITNOT expr",
93072
 /* 220 */ "expr ::= BITNOT expr",
99897
 /* 220 */ "expr ::= MINUS expr",
93073
 /* 221 */ "expr ::= MINUS expr",
99898
 /* 221 */ "expr ::= PLUS expr",
93074
 /* 222 */ "expr ::= PLUS expr",
99899
 /* 222 */ "between_op ::= BETWEEN",
93075
 /* 223 */ "between_op ::= BETWEEN",
99900
 /* 223 */ "between_op ::= NOT BETWEEN",
93076
 /* 224 */ "between_op ::= NOT BETWEEN",
99901
 /* 224 */ "expr ::= expr between_op expr AND expr",
93077
 /* 225 */ "expr ::= expr between_op expr AND expr",
99902
 /* 225 */ "in_op ::= IN",
93078
 /* 226 */ "in_op ::= IN",
99903
 /* 226 */ "in_op ::= NOT IN",
93079
 /* 227 */ "in_op ::= NOT IN",
99904
 /* 227 */ "expr ::= expr in_op LP exprlist RP",
93080
 /* 228 */ "expr ::= expr in_op LP exprlist RP",
99905
 /* 228 */ "expr ::= LP select RP",
93081
 /* 229 */ "expr ::= LP select RP",
99906
 /* 229 */ "expr ::= expr in_op LP select RP",
93082
 /* 230 */ "expr ::= expr in_op LP select RP",
99907
 /* 230 */ "expr ::= expr in_op nm dbnm",
93083
 /* 231 */ "expr ::= expr in_op nm dbnm",
99908
 /* 231 */ "expr ::= EXISTS LP select RP",
93084
 /* 232 */ "expr ::= EXISTS LP select RP",
99909
 /* 232 */ "expr ::= CASE case_operand case_exprlist case_else END",
93085
 /* 233 */ "expr ::= CASE case_operand case_exprlist case_else END",
99910
 /* 233 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
93086
 /* 234 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
99911
 /* 234 */ "case_exprlist ::= WHEN expr THEN expr",
93087
 /* 235 */ "case_exprlist ::= WHEN expr THEN expr",
99912
 /* 235 */ "case_else ::= ELSE expr",
93088
 /* 236 */ "case_else ::= ELSE expr",
99913
 /* 236 */ "case_else ::=",
93089
 /* 237 */ "case_else ::=",
99914
 /* 237 */ "case_operand ::= expr",
93090
 /* 238 */ "case_operand ::= expr",
99915
 /* 238 */ "case_operand ::=",
93091
 /* 239 */ "case_operand ::=",
99916
 /* 239 */ "exprlist ::= nexprlist",
93092
 /* 240 */ "exprlist ::= nexprlist",
99917
 /* 240 */ "exprlist ::=",
93093
 /* 241 */ "exprlist ::=",
99918
 /* 241 */ "nexprlist ::= nexprlist COMMA expr",
93094
 /* 242 */ "nexprlist ::= nexprlist COMMA expr",
99919
 /* 242 */ "nexprlist ::= expr",
93095
 /* 243 */ "nexprlist ::= expr",
99920
 /* 243 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
93096
 /* 244 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
99921
 /* 244 */ "uniqueflag ::= UNIQUE",
93097
 /* 245 */ "uniqueflag ::= UNIQUE",
99922
 /* 245 */ "uniqueflag ::=",
93098
 /* 246 */ "uniqueflag ::=",
99923
 /* 246 */ "idxlist_opt ::=",
93099
 /* 247 */ "idxlist_opt ::=",
99924
 /* 247 */ "idxlist_opt ::= LP idxlist RP",
93100
 /* 248 */ "idxlist_opt ::= LP idxlist RP",
99925
 /* 248 */ "idxlist ::= idxlist COMMA nm collate sortorder",
93101
 /* 249 */ "idxlist ::= idxlist COMMA nm collate sortorder",
99926
 /* 249 */ "idxlist ::= nm collate sortorder",
93102
 /* 250 */ "idxlist ::= nm collate sortorder",
99927
 /* 250 */ "collate ::=",
93103
 /* 251 */ "collate ::=",
99928
 /* 251 */ "collate ::= COLLATE ids",
93104
 /* 252 */ "collate ::= COLLATE ids",
99929
 /* 252 */ "cmd ::= DROP INDEX ifexists fullname",
93105
 /* 253 */ "cmd ::= DROP INDEX ifexists fullname",
99930
 /* 253 */ "cmd ::= VACUUM",
93106
 /* 254 */ "cmd ::= VACUUM",
99931
 /* 254 */ "cmd ::= VACUUM nm",
93107
 /* 255 */ "cmd ::= VACUUM nm",
99932
 /* 255 */ "cmd ::= PRAGMA nm dbnm",
93108
 /* 256 */ "cmd ::= PRAGMA nm dbnm",
99933
 /* 256 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
93109
 /* 257 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
99934
 /* 257 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
93110
 /* 258 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
99935
 /* 258 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
93111
 /* 259 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
99936
 /* 259 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
93112
 /* 260 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
99937
 /* 260 */ "nmnum ::= plus_num",
93113
 /* 261 */ "nmnum ::= plus_num",
99938
 /* 261 */ "nmnum ::= nm",
93114
 /* 262 */ "nmnum ::= nm",
99939
 /* 262 */ "nmnum ::= ON",
93115
 /* 263 */ "nmnum ::= ON",
99940
 /* 263 */ "nmnum ::= DELETE",
93116
 /* 264 */ "nmnum ::= DELETE",
99941
 /* 264 */ "nmnum ::= DEFAULT",
93117
 /* 265 */ "nmnum ::= DEFAULT",
99942
 /* 265 */ "plus_num ::= plus_opt number",
93118
 /* 266 */ "plus_num ::= plus_opt number",
99943
 /* 266 */ "minus_num ::= MINUS number",
93119
 /* 267 */ "minus_num ::= MINUS number",
99944
 /* 267 */ "number ::= INTEGER|FLOAT",
93120
 /* 268 */ "number ::= INTEGER|FLOAT",
99945
 /* 268 */ "plus_opt ::= PLUS",
93121
 /* 269 */ "plus_opt ::= PLUS",
99946
 /* 269 */ "plus_opt ::=",
93122
 /* 270 */ "plus_opt ::=",
99947
 /* 270 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
93123
 /* 271 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
99948
 /* 271 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
93124
 /* 272 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
99949
 /* 272 */ "trigger_time ::= BEFORE",
93125
 /* 273 */ "trigger_time ::= BEFORE",
99950
 /* 273 */ "trigger_time ::= AFTER",
93126
 /* 274 */ "trigger_time ::= AFTER",
99951
 /* 274 */ "trigger_time ::= INSTEAD OF",
93127
 /* 275 */ "trigger_time ::= INSTEAD OF",
99952
 /* 275 */ "trigger_time ::=",
93128
 /* 276 */ "trigger_time ::=",
99953
 /* 276 */ "trigger_event ::= DELETE|INSERT",
93129
 /* 277 */ "trigger_event ::= DELETE|INSERT",
99954
 /* 277 */ "trigger_event ::= UPDATE",
93130
 /* 278 */ "trigger_event ::= UPDATE",
99955
 /* 278 */ "trigger_event ::= UPDATE OF inscollist",
93131
 /* 279 */ "trigger_event ::= UPDATE OF inscollist",
99956
 /* 279 */ "foreach_clause ::=",
93132
 /* 280 */ "foreach_clause ::=",
99957
 /* 280 */ "foreach_clause ::= FOR EACH ROW",
93133
 /* 281 */ "foreach_clause ::= FOR EACH ROW",
99958
 /* 281 */ "when_clause ::=",
93134
 /* 282 */ "when_clause ::=",
99959
 /* 282 */ "when_clause ::= WHEN expr",
93135
 /* 283 */ "when_clause ::= WHEN expr",
99960
 /* 283 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
93136
 /* 284 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
99961
 /* 284 */ "trigger_cmd_list ::= trigger_cmd SEMI",
93137
 /* 285 */ "trigger_cmd_list ::= trigger_cmd SEMI",
99962
 /* 285 */ "trnm ::= nm",
93138
 /* 286 */ "trnm ::= nm",
99963
 /* 286 */ "trnm ::= nm DOT nm",
93139
 /* 287 */ "trnm ::= nm DOT nm",
99964
 /* 287 */ "tridxby ::=",
93140
 /* 288 */ "tridxby ::=",
99965
 /* 288 */ "tridxby ::= INDEXED BY nm",
93141
 /* 289 */ "tridxby ::= INDEXED BY nm",
99966
 /* 289 */ "tridxby ::= NOT INDEXED",
93142
 /* 290 */ "tridxby ::= NOT INDEXED",
99967
 /* 290 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
93143
 /* 291 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
99968
 /* 291 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP",
93144
 /* 292 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP",
99969
 /* 292 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
93145
 /* 293 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
99970
 /* 293 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
93146
 /* 294 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
99971
 /* 294 */ "trigger_cmd ::= select",
93147
 /* 295 */ "trigger_cmd ::= select",
99972
 /* 295 */ "expr ::= RAISE LP IGNORE RP",
93148
 /* 296 */ "expr ::= RAISE LP IGNORE RP",
99973
 /* 296 */ "expr ::= RAISE LP raisetype COMMA nm RP",
93149
 /* 297 */ "expr ::= RAISE LP raisetype COMMA nm RP",
99974
 /* 297 */ "raisetype ::= ROLLBACK",
93150
 /* 298 */ "raisetype ::= ROLLBACK",
99975
 /* 298 */ "raisetype ::= ABORT",
93151
 /* 299 */ "raisetype ::= ABORT",
99976
 /* 299 */ "raisetype ::= FAIL",
93152
 /* 300 */ "raisetype ::= FAIL",
99977
 /* 300 */ "cmd ::= DROP TRIGGER ifexists fullname",
93153
 /* 301 */ "cmd ::= DROP TRIGGER ifexists fullname",
99978
 /* 301 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
93154
 /* 302 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
99979
 /* 302 */ "cmd ::= DETACH database_kw_opt expr",
93155
 /* 303 */ "cmd ::= DETACH database_kw_opt expr",
99980
 /* 303 */ "key_opt ::=",
93156
 /* 304 */ "key_opt ::=",
99981
 /* 304 */ "key_opt ::= KEY expr",
93157
 /* 305 */ "key_opt ::= KEY expr",
99982
 /* 305 */ "database_kw_opt ::= DATABASE",
93158
 /* 306 */ "database_kw_opt ::= DATABASE",
99983
 /* 306 */ "database_kw_opt ::=",
93159
 /* 307 */ "database_kw_opt ::=",
99984
 /* 307 */ "cmd ::= REINDEX",
93160
 /* 308 */ "cmd ::= REINDEX",
99985
 /* 308 */ "cmd ::= REINDEX nm dbnm",
93161
 /* 309 */ "cmd ::= REINDEX nm dbnm",
99986
 /* 309 */ "cmd ::= ANALYZE",
93162
 /* 310 */ "cmd ::= ANALYZE",
99987
 /* 310 */ "cmd ::= ANALYZE nm dbnm",
93163
 /* 311 */ "cmd ::= ANALYZE nm dbnm",
99988
 /* 311 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
93164
 /* 312 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
99989
 /* 312 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
93165
 /* 313 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
99990
 /* 313 */ "add_column_fullname ::= fullname",
93166
 /* 314 */ "add_column_fullname ::= fullname",
99991
 /* 314 */ "kwcolumn_opt ::=",
93167
 /* 315 */ "kwcolumn_opt ::=",
99992
 /* 315 */ "kwcolumn_opt ::= COLUMNKW",
93168
 /* 316 */ "kwcolumn_opt ::= COLUMNKW",
99993
 /* 316 */ "cmd ::= create_vtab",
93169
 /* 317 */ "cmd ::= create_vtab",
99994
 /* 317 */ "cmd ::= create_vtab LP vtabarglist RP",
93170
 /* 318 */ "cmd ::= create_vtab LP vtabarglist RP",
99995
 /* 318 */ "create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm",
93171
 /* 319 */ "create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm",
99996
 /* 319 */ "vtabarglist ::= vtabarg",
93172
 /* 320 */ "vtabarglist ::= vtabarg",
99997
 /* 320 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
93173
 /* 321 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
99998
 /* 321 */ "vtabarg ::=",
93174
 /* 322 */ "vtabarg ::=",
99999
 /* 322 */ "vtabarg ::= vtabarg vtabargtoken",
93175
 /* 323 */ "vtabarg ::= vtabarg vtabargtoken",
100000
 /* 323 */ "vtabargtoken ::= ANY",
93176
 /* 324 */ "vtabargtoken ::= ANY",
100001
 /* 324 */ "vtabargtoken ::= lp anylist RP",
93177
 /* 325 */ "vtabargtoken ::= lp anylist RP",
100002
 /* 325 */ "lp ::= LP",
93178
 /* 326 */ "lp ::= LP",
100003
 /* 326 */ "anylist ::=",
93179
 /* 327 */ "anylist ::=",
100004
 /* 327 */ "anylist ::= anylist LP anylist RP",
93180
 /* 328 */ "anylist ::= anylist LP anylist RP",
100005
 /* 328 */ "anylist ::= anylist ANY",
93181
 /* 329 */ "anylist ::= anylist ANY",
93182
};
100006
};
93183
#endif /* NDEBUG */
100007
#endif /* NDEBUG */
93184
100008
 Lines 93260-93273   static void yy_destructor( Link Here 
93260
    case 160: /* select */
100084
    case 160: /* select */
93261
    case 194: /* oneselect */
100085
    case 194: /* oneselect */
93262
{
100086
{
93263
sqlite3SelectDelete(pParse->db, (yypminor->yy3));
100087
sqlite3SelectDelete(pParse->db, (yypminor->yy387));
93264
}
100088
}
93265
      break;
100089
      break;
93266
    case 174: /* term */
100090
    case 174: /* term */
93267
    case 175: /* expr */
100091
    case 175: /* expr */
93268
    case 223: /* escape */
93269
{
100092
{
93270
sqlite3ExprDelete(pParse->db, (yypminor->yy346).pExpr);
100093
sqlite3ExprDelete(pParse->db, (yypminor->yy118).pExpr);
93271
}
100094
}
93272
      break;
100095
      break;
93273
    case 179: /* idxlist_opt */
100096
    case 179: /* idxlist_opt */
 Lines 93281-93289   sqlite3ExprDelete(pParse->db, (yypminor- Link Here 
93281
    case 217: /* setlist */
100104
    case 217: /* setlist */
93282
    case 220: /* itemlist */
100105
    case 220: /* itemlist */
93283
    case 221: /* exprlist */
100106
    case 221: /* exprlist */
93284
    case 227: /* case_exprlist */
100107
    case 226: /* case_exprlist */
93285
{
100108
{
93286
sqlite3ExprListDelete(pParse->db, (yypminor->yy14));
100109
sqlite3ExprListDelete(pParse->db, (yypminor->yy322));
93287
}
100110
}
93288
      break;
100111
      break;
93289
    case 193: /* fullname */
100112
    case 193: /* fullname */
 Lines 93291-93327   sqlite3ExprListDelete(pParse->db, (yypmi Link Here 
93291
    case 206: /* seltablist */
100114
    case 206: /* seltablist */
93292
    case 207: /* stl_prefix */
100115
    case 207: /* stl_prefix */
93293
{
100116
{
93294
sqlite3SrcListDelete(pParse->db, (yypminor->yy65));
100117
sqlite3SrcListDelete(pParse->db, (yypminor->yy259));
93295
}
100118
}
93296
      break;
100119
      break;
93297
    case 199: /* where_opt */
100120
    case 199: /* where_opt */
93298
    case 201: /* having_opt */
100121
    case 201: /* having_opt */
93299
    case 210: /* on_opt */
100122
    case 210: /* on_opt */
93300
    case 215: /* sortitem */
100123
    case 215: /* sortitem */
93301
    case 226: /* case_operand */
100124
    case 225: /* case_operand */
93302
    case 228: /* case_else */
100125
    case 227: /* case_else */
93303
    case 239: /* when_clause */
100126
    case 238: /* when_clause */
93304
    case 244: /* key_opt */
100127
    case 243: /* key_opt */
93305
{
100128
{
93306
sqlite3ExprDelete(pParse->db, (yypminor->yy132));
100129
sqlite3ExprDelete(pParse->db, (yypminor->yy314));
93307
}
100130
}
93308
      break;
100131
      break;
93309
    case 211: /* using_opt */
100132
    case 211: /* using_opt */
93310
    case 213: /* inscollist */
100133
    case 213: /* inscollist */
93311
    case 219: /* inscollist_opt */
100134
    case 219: /* inscollist_opt */
93312
{
100135
{
93313
sqlite3IdListDelete(pParse->db, (yypminor->yy408));
100136
sqlite3IdListDelete(pParse->db, (yypminor->yy384));
93314
}
100137
}
93315
      break;
100138
      break;
93316
    case 235: /* trigger_cmd_list */
100139
    case 234: /* trigger_cmd_list */
93317
    case 240: /* trigger_cmd */
100140
    case 239: /* trigger_cmd */
93318
{
100141
{
93319
sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy473));
100142
sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy203));
93320
}
100143
}
93321
      break;
100144
      break;
93322
    case 237: /* trigger_event */
100145
    case 236: /* trigger_event */
93323
{
100146
{
93324
sqlite3IdListDelete(pParse->db, (yypminor->yy378).b);
100147
sqlite3IdListDelete(pParse->db, (yypminor->yy90).b);
93325
}
100148
}
93326
      break;
100149
      break;
93327
    default:  break;   /* If no destructor action specified: do nothing */
100150
    default:  break;   /* If no destructor action specified: do nothing */
 Lines 93779-93787   static const struct { Link Here 
93779
  { 222, 2 },
100602
  { 222, 2 },
93780
  { 222, 1 },
100603
  { 222, 1 },
93781
  { 222, 2 },
100604
  { 222, 2 },
93782
  { 223, 2 },
100605
  { 175, 3 },
93783
  { 223, 0 },
100606
  { 175, 5 },
93784
  { 175, 4 },
93785
  { 175, 2 },
100607
  { 175, 2 },
93786
  { 175, 3 },
100608
  { 175, 3 },
93787
  { 175, 3 },
100609
  { 175, 3 },
 Lines 93790-93825   static const struct { Link Here 
93790
  { 175, 2 },
100612
  { 175, 2 },
93791
  { 175, 2 },
100613
  { 175, 2 },
93792
  { 175, 2 },
100614
  { 175, 2 },
100615
  { 223, 1 },
100616
  { 223, 2 },
100617
  { 175, 5 },
93793
  { 224, 1 },
100618
  { 224, 1 },
93794
  { 224, 2 },
100619
  { 224, 2 },
93795
  { 175, 5 },
100620
  { 175, 5 },
93796
  { 225, 1 },
93797
  { 225, 2 },
93798
  { 175, 5 },
93799
  { 175, 3 },
100621
  { 175, 3 },
93800
  { 175, 5 },
100622
  { 175, 5 },
93801
  { 175, 4 },
100623
  { 175, 4 },
93802
  { 175, 4 },
100624
  { 175, 4 },
93803
  { 175, 5 },
100625
  { 175, 5 },
93804
  { 227, 5 },
100626
  { 226, 5 },
93805
  { 227, 4 },
100627
  { 226, 4 },
93806
  { 228, 2 },
100628
  { 227, 2 },
93807
  { 228, 0 },
100629
  { 227, 0 },
93808
  { 226, 1 },
100630
  { 225, 1 },
93809
  { 226, 0 },
100631
  { 225, 0 },
93810
  { 221, 1 },
100632
  { 221, 1 },
93811
  { 221, 0 },
100633
  { 221, 0 },
93812
  { 216, 3 },
100634
  { 216, 3 },
93813
  { 216, 1 },
100635
  { 216, 1 },
93814
  { 147, 11 },
100636
  { 147, 11 },
93815
  { 229, 1 },
100637
  { 228, 1 },
93816
  { 229, 0 },
100638
  { 228, 0 },
93817
  { 179, 0 },
100639
  { 179, 0 },
93818
  { 179, 3 },
100640
  { 179, 3 },
93819
  { 187, 5 },
100641
  { 187, 5 },
93820
  { 187, 3 },
100642
  { 187, 3 },
93821
  { 230, 0 },
100643
  { 229, 0 },
93822
  { 230, 2 },
100644
  { 229, 2 },
93823
  { 147, 4 },
100645
  { 147, 4 },
93824
  { 147, 1 },
100646
  { 147, 1 },
93825
  { 147, 2 },
100647
  { 147, 2 },
 Lines 93828-93868   static const struct { Link Here 
93828
  { 147, 6 },
100650
  { 147, 6 },
93829
  { 147, 5 },
100651
  { 147, 5 },
93830
  { 147, 6 },
100652
  { 147, 6 },
93831
  { 231, 1 },
100653
  { 230, 1 },
93832
  { 231, 1 },
100654
  { 230, 1 },
93833
  { 231, 1 },
100655
  { 230, 1 },
93834
  { 231, 1 },
100656
  { 230, 1 },
93835
  { 231, 1 },
100657
  { 230, 1 },
93836
  { 170, 2 },
100658
  { 170, 2 },
93837
  { 171, 2 },
100659
  { 171, 2 },
93838
  { 233, 1 },
93839
  { 232, 1 },
100660
  { 232, 1 },
93840
  { 232, 0 },
100661
  { 231, 1 },
100662
  { 231, 0 },
93841
  { 147, 5 },
100663
  { 147, 5 },
93842
  { 234, 11 },
100664
  { 233, 11 },
100665
  { 235, 1 },
100666
  { 235, 1 },
100667
  { 235, 2 },
100668
  { 235, 0 },
93843
  { 236, 1 },
100669
  { 236, 1 },
93844
  { 236, 1 },
100670
  { 236, 1 },
93845
  { 236, 2 },
100671
  { 236, 3 },
93846
  { 236, 0 },
100672
  { 237, 0 },
93847
  { 237, 1 },
93848
  { 237, 1 },
93849
  { 237, 3 },
100673
  { 237, 3 },
93850
  { 238, 0 },
100674
  { 238, 0 },
93851
  { 238, 3 },
100675
  { 238, 2 },
93852
  { 239, 0 },
100676
  { 234, 3 },
93853
  { 239, 2 },
100677
  { 234, 2 },
93854
  { 235, 3 },
100678
  { 240, 1 },
93855
  { 235, 2 },
100679
  { 240, 3 },
93856
  { 241, 1 },
100680
  { 241, 0 },
93857
  { 241, 3 },
100681
  { 241, 3 },
93858
  { 242, 0 },
100682
  { 241, 2 },
93859
  { 242, 3 },
100683
  { 239, 7 },
93860
  { 242, 2 },
100684
  { 239, 8 },
93861
  { 240, 7 },
100685
  { 239, 5 },
93862
  { 240, 8 },
100686
  { 239, 5 },
93863
  { 240, 5 },
100687
  { 239, 1 },
93864
  { 240, 5 },
93865
  { 240, 1 },
93866
  { 175, 4 },
100688
  { 175, 4 },
93867
  { 175, 6 },
100689
  { 175, 6 },
93868
  { 191, 1 },
100690
  { 191, 1 },
 Lines 93871-93902   static const struct { Link Here 
93871
  { 147, 4 },
100693
  { 147, 4 },
93872
  { 147, 6 },
100694
  { 147, 6 },
93873
  { 147, 3 },
100695
  { 147, 3 },
93874
  { 244, 0 },
93875
  { 244, 2 },
93876
  { 243, 1 },
93877
  { 243, 0 },
100696
  { 243, 0 },
100697
  { 243, 2 },
100698
  { 242, 1 },
100699
  { 242, 0 },
93878
  { 147, 1 },
100700
  { 147, 1 },
93879
  { 147, 3 },
100701
  { 147, 3 },
93880
  { 147, 1 },
100702
  { 147, 1 },
93881
  { 147, 3 },
100703
  { 147, 3 },
93882
  { 147, 6 },
100704
  { 147, 6 },
93883
  { 147, 6 },
100705
  { 147, 6 },
100706
  { 244, 1 },
100707
  { 245, 0 },
93884
  { 245, 1 },
100708
  { 245, 1 },
93885
  { 246, 0 },
93886
  { 246, 1 },
93887
  { 147, 1 },
100709
  { 147, 1 },
93888
  { 147, 4 },
100710
  { 147, 4 },
93889
  { 247, 7 },
100711
  { 246, 7 },
93890
  { 248, 1 },
100712
  { 247, 1 },
93891
  { 248, 3 },
100713
  { 247, 3 },
93892
  { 249, 0 },
100714
  { 248, 0 },
93893
  { 249, 2 },
100715
  { 248, 2 },
100716
  { 249, 1 },
100717
  { 249, 3 },
93894
  { 250, 1 },
100718
  { 250, 1 },
93895
  { 250, 3 },
100719
  { 251, 0 },
93896
  { 251, 1 },
100720
  { 251, 4 },
93897
  { 252, 0 },
100721
  { 251, 2 },
93898
  { 252, 4 },
93899
  { 252, 2 },
93900
};
100722
};
93901
100723
93902
static void yy_accept(yyParser*);  /* Forward Declaration */
100724
static void yy_accept(yyParser*);  /* Forward Declaration */
 Lines 93964-93980   static void yy_reduce( Link Here 
93964
{ sqlite3FinishCoding(pParse); }
100786
{ sqlite3FinishCoding(pParse); }
93965
        break;
100787
        break;
93966
      case 9: /* cmd ::= BEGIN transtype trans_opt */
100788
      case 9: /* cmd ::= BEGIN transtype trans_opt */
93967
{sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy328);}
100789
{sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy4);}
93968
        break;
100790
        break;
93969
      case 13: /* transtype ::= */
100791
      case 13: /* transtype ::= */
93970
{yygotominor.yy328 = TK_DEFERRED;}
100792
{yygotominor.yy4 = TK_DEFERRED;}
93971
        break;
100793
        break;
93972
      case 14: /* transtype ::= DEFERRED */
100794
      case 14: /* transtype ::= DEFERRED */
93973
      case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
100795
      case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
93974
      case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
100796
      case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
93975
      case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
100797
      case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
93976
      case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
100798
      case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
93977
{yygotominor.yy328 = yymsp[0].major;}
100799
{yygotominor.yy4 = yymsp[0].major;}
93978
        break;
100800
        break;
93979
      case 17: /* cmd ::= COMMIT trans_opt */
100801
      case 17: /* cmd ::= COMMIT trans_opt */
93980
      case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
100802
      case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
 Lines 94000-94006   static void yy_reduce( Link Here 
94000
        break;
100822
        break;
94001
      case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
100823
      case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
94002
{
100824
{
94003
   sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy328,0,0,yymsp[-2].minor.yy328);
100825
   sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy4,0,0,yymsp[-2].minor.yy4);
94004
}
100826
}
94005
        break;
100827
        break;
94006
      case 27: /* createkw ::= CREATE */
100828
      case 27: /* createkw ::= CREATE */
 Lines 94019-94027   static void yy_reduce( Link Here 
94019
      case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
100841
      case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
94020
      case 120: /* distinct ::= ALL */ yytestcase(yyruleno==120);
100842
      case 120: /* distinct ::= ALL */ yytestcase(yyruleno==120);
94021
      case 121: /* distinct ::= */ yytestcase(yyruleno==121);
100843
      case 121: /* distinct ::= */ yytestcase(yyruleno==121);
94022
      case 223: /* between_op ::= BETWEEN */ yytestcase(yyruleno==223);
100844
      case 222: /* between_op ::= BETWEEN */ yytestcase(yyruleno==222);
94023
      case 226: /* in_op ::= IN */ yytestcase(yyruleno==226);
100845
      case 225: /* in_op ::= IN */ yytestcase(yyruleno==225);
94024
{yygotominor.yy328 = 0;}
100846
{yygotominor.yy4 = 0;}
94025
        break;
100847
        break;
94026
      case 29: /* ifnotexists ::= IF NOT EXISTS */
100848
      case 29: /* ifnotexists ::= IF NOT EXISTS */
94027
      case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
100849
      case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
 Lines 94029-94037   static void yy_reduce( Link Here 
94029
      case 86: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==86);
100851
      case 86: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==86);
94030
      case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
100852
      case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
94031
      case 119: /* distinct ::= DISTINCT */ yytestcase(yyruleno==119);
100853
      case 119: /* distinct ::= DISTINCT */ yytestcase(yyruleno==119);
94032
      case 224: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==224);
100854
      case 223: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==223);
94033
      case 227: /* in_op ::= NOT IN */ yytestcase(yyruleno==227);
100855
      case 226: /* in_op ::= NOT IN */ yytestcase(yyruleno==226);
94034
{yygotominor.yy328 = 1;}
100856
{yygotominor.yy4 = 1;}
94035
        break;
100857
        break;
94036
      case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
100858
      case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
94037
{
100859
{
 Lines 94040-94047   static void yy_reduce( Link Here 
94040
        break;
100862
        break;
94041
      case 33: /* create_table_args ::= AS select */
100863
      case 33: /* create_table_args ::= AS select */
94042
{
100864
{
94043
  sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy3);
100865
  sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy387);
94044
  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
100866
  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy387);
94045
}
100867
}
94046
        break;
100868
        break;
94047
      case 36: /* column ::= columnid type carglist */
100869
      case 36: /* column ::= columnid type carglist */
 Lines 94068-94083   static void yy_reduce( Link Here 
94068
      case 128: /* as ::= ids */ yytestcase(yyruleno==128);
100890
      case 128: /* as ::= ids */ yytestcase(yyruleno==128);
94069
      case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
100891
      case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
94070
      case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
100892
      case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
94071
      case 252: /* collate ::= COLLATE ids */ yytestcase(yyruleno==252);
100893
      case 251: /* collate ::= COLLATE ids */ yytestcase(yyruleno==251);
94072
      case 261: /* nmnum ::= plus_num */ yytestcase(yyruleno==261);
100894
      case 260: /* nmnum ::= plus_num */ yytestcase(yyruleno==260);
94073
      case 262: /* nmnum ::= nm */ yytestcase(yyruleno==262);
100895
      case 261: /* nmnum ::= nm */ yytestcase(yyruleno==261);
94074
      case 263: /* nmnum ::= ON */ yytestcase(yyruleno==263);
100896
      case 262: /* nmnum ::= ON */ yytestcase(yyruleno==262);
94075
      case 264: /* nmnum ::= DELETE */ yytestcase(yyruleno==264);
100897
      case 263: /* nmnum ::= DELETE */ yytestcase(yyruleno==263);
94076
      case 265: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==265);
100898
      case 264: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==264);
94077
      case 266: /* plus_num ::= plus_opt number */ yytestcase(yyruleno==266);
100899
      case 265: /* plus_num ::= plus_opt number */ yytestcase(yyruleno==265);
94078
      case 267: /* minus_num ::= MINUS number */ yytestcase(yyruleno==267);
100900
      case 266: /* minus_num ::= MINUS number */ yytestcase(yyruleno==266);
94079
      case 268: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==268);
100901
      case 267: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==267);
94080
      case 286: /* trnm ::= nm */ yytestcase(yyruleno==286);
100902
      case 285: /* trnm ::= nm */ yytestcase(yyruleno==285);
94081
{yygotominor.yy0 = yymsp[0].minor.yy0;}
100903
{yygotominor.yy0 = yymsp[0].minor.yy0;}
94082
        break;
100904
        break;
94083
      case 45: /* type ::= typetoken */
100905
      case 45: /* type ::= typetoken */
 Lines 94100-94116   static void yy_reduce( Link Here 
94100
        break;
100922
        break;
94101
      case 57: /* ccons ::= DEFAULT term */
100923
      case 57: /* ccons ::= DEFAULT term */
94102
      case 59: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==59);
100924
      case 59: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==59);
94103
{sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy346);}
100925
{sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy118);}
94104
        break;
100926
        break;
94105
      case 58: /* ccons ::= DEFAULT LP expr RP */
100927
      case 58: /* ccons ::= DEFAULT LP expr RP */
94106
{sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy346);}
100928
{sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy118);}
94107
        break;
100929
        break;
94108
      case 60: /* ccons ::= DEFAULT MINUS term */
100930
      case 60: /* ccons ::= DEFAULT MINUS term */
94109
{
100931
{
94110
  ExprSpan v;
100932
  ExprSpan v;
94111
  v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy346.pExpr, 0, 0);
100933
  v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy118.pExpr, 0, 0);
94112
  v.zStart = yymsp[-1].minor.yy0.z;
100934
  v.zStart = yymsp[-1].minor.yy0.z;
94113
  v.zEnd = yymsp[0].minor.yy346.zEnd;
100935
  v.zEnd = yymsp[0].minor.yy118.zEnd;
94114
  sqlite3AddDefaultValue(pParse,&v);
100936
  sqlite3AddDefaultValue(pParse,&v);
94115
}
100937
}
94116
        break;
100938
        break;
 Lines 94122-94183   static void yy_reduce( Link Here 
94122
}
100944
}
94123
        break;
100945
        break;
94124
      case 63: /* ccons ::= NOT NULL onconf */
100946
      case 63: /* ccons ::= NOT NULL onconf */
94125
{sqlite3AddNotNull(pParse, yymsp[0].minor.yy328);}
100947
{sqlite3AddNotNull(pParse, yymsp[0].minor.yy4);}
94126
        break;
100948
        break;
94127
      case 64: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
100949
      case 64: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
94128
{sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy328,yymsp[0].minor.yy328,yymsp[-2].minor.yy328);}
100950
{sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy4,yymsp[0].minor.yy4,yymsp[-2].minor.yy4);}
94129
        break;
100951
        break;
94130
      case 65: /* ccons ::= UNIQUE onconf */
100952
      case 65: /* ccons ::= UNIQUE onconf */
94131
{sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy328,0,0,0,0);}
100953
{sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy4,0,0,0,0);}
94132
        break;
100954
        break;
94133
      case 66: /* ccons ::= CHECK LP expr RP */
100955
      case 66: /* ccons ::= CHECK LP expr RP */
94134
{sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy346.pExpr);}
100956
{sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy118.pExpr);}
94135
        break;
100957
        break;
94136
      case 67: /* ccons ::= REFERENCES nm idxlist_opt refargs */
100958
      case 67: /* ccons ::= REFERENCES nm idxlist_opt refargs */
94137
{sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy14,yymsp[0].minor.yy328);}
100959
{sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy322,yymsp[0].minor.yy4);}
94138
        break;
100960
        break;
94139
      case 68: /* ccons ::= defer_subclause */
100961
      case 68: /* ccons ::= defer_subclause */
94140
{sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy328);}
100962
{sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy4);}
94141
        break;
100963
        break;
94142
      case 69: /* ccons ::= COLLATE ids */
100964
      case 69: /* ccons ::= COLLATE ids */
94143
{sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
100965
{sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
94144
        break;
100966
        break;
94145
      case 72: /* refargs ::= */
100967
      case 72: /* refargs ::= */
94146
{ yygotominor.yy328 = OE_None*0x0101; /* EV: R-19803-45884 */}
100968
{ yygotominor.yy4 = OE_None*0x0101; /* EV: R-19803-45884 */}
94147
        break;
100969
        break;
94148
      case 73: /* refargs ::= refargs refarg */
100970
      case 73: /* refargs ::= refargs refarg */
94149
{ yygotominor.yy328 = (yymsp[-1].minor.yy328 & ~yymsp[0].minor.yy429.mask) | yymsp[0].minor.yy429.value; }
100971
{ yygotominor.yy4 = (yymsp[-1].minor.yy4 & ~yymsp[0].minor.yy215.mask) | yymsp[0].minor.yy215.value; }
94150
        break;
100972
        break;
94151
      case 74: /* refarg ::= MATCH nm */
100973
      case 74: /* refarg ::= MATCH nm */
94152
      case 75: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==75);
100974
      case 75: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==75);
94153
{ yygotominor.yy429.value = 0;     yygotominor.yy429.mask = 0x000000; }
100975
{ yygotominor.yy215.value = 0;     yygotominor.yy215.mask = 0x000000; }
94154
        break;
100976
        break;
94155
      case 76: /* refarg ::= ON DELETE refact */
100977
      case 76: /* refarg ::= ON DELETE refact */
94156
{ yygotominor.yy429.value = yymsp[0].minor.yy328;     yygotominor.yy429.mask = 0x0000ff; }
100978
{ yygotominor.yy215.value = yymsp[0].minor.yy4;     yygotominor.yy215.mask = 0x0000ff; }
94157
        break;
100979
        break;
94158
      case 77: /* refarg ::= ON UPDATE refact */
100980
      case 77: /* refarg ::= ON UPDATE refact */
94159
{ yygotominor.yy429.value = yymsp[0].minor.yy328<<8;  yygotominor.yy429.mask = 0x00ff00; }
100981
{ yygotominor.yy215.value = yymsp[0].minor.yy4<<8;  yygotominor.yy215.mask = 0x00ff00; }
94160
        break;
100982
        break;
94161
      case 78: /* refact ::= SET NULL */
100983
      case 78: /* refact ::= SET NULL */
94162
{ yygotominor.yy328 = OE_SetNull;  /* EV: R-33326-45252 */}
100984
{ yygotominor.yy4 = OE_SetNull;  /* EV: R-33326-45252 */}
94163
        break;
100985
        break;
94164
      case 79: /* refact ::= SET DEFAULT */
100986
      case 79: /* refact ::= SET DEFAULT */
94165
{ yygotominor.yy328 = OE_SetDflt;  /* EV: R-33326-45252 */}
100987
{ yygotominor.yy4 = OE_SetDflt;  /* EV: R-33326-45252 */}
94166
        break;
100988
        break;
94167
      case 80: /* refact ::= CASCADE */
100989
      case 80: /* refact ::= CASCADE */
94168
{ yygotominor.yy328 = OE_Cascade;  /* EV: R-33326-45252 */}
100990
{ yygotominor.yy4 = OE_Cascade;  /* EV: R-33326-45252 */}
94169
        break;
100991
        break;
94170
      case 81: /* refact ::= RESTRICT */
100992
      case 81: /* refact ::= RESTRICT */
94171
{ yygotominor.yy328 = OE_Restrict; /* EV: R-33326-45252 */}
100993
{ yygotominor.yy4 = OE_Restrict; /* EV: R-33326-45252 */}
94172
        break;
100994
        break;
94173
      case 82: /* refact ::= NO ACTION */
100995
      case 82: /* refact ::= NO ACTION */
94174
{ yygotominor.yy328 = OE_None;     /* EV: R-33326-45252 */}
100996
{ yygotominor.yy4 = OE_None;     /* EV: R-33326-45252 */}
94175
        break;
100997
        break;
94176
      case 84: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
100998
      case 84: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
94177
      case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
100999
      case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
94178
      case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
101000
      case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
94179
      case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
101001
      case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
94180
{yygotominor.yy328 = yymsp[0].minor.yy328;}
101002
{yygotominor.yy4 = yymsp[0].minor.yy4;}
94181
        break;
101003
        break;
94182
      case 88: /* conslist_opt ::= */
101004
      case 88: /* conslist_opt ::= */
94183
{yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
101005
{yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
 Lines 94186-94286   static void yy_reduce( Link Here 
94186
{yygotominor.yy0 = yymsp[-1].minor.yy0;}
101008
{yygotominor.yy0 = yymsp[-1].minor.yy0;}
94187
        break;
101009
        break;
94188
      case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
101010
      case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
94189
{sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy14,yymsp[0].minor.yy328,yymsp[-2].minor.yy328,0);}
101011
{sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy322,yymsp[0].minor.yy4,yymsp[-2].minor.yy4,0);}
94190
        break;
101012
        break;
94191
      case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
101013
      case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
94192
{sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy14,yymsp[0].minor.yy328,0,0,0,0);}
101014
{sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy322,yymsp[0].minor.yy4,0,0,0,0);}
94193
        break;
101015
        break;
94194
      case 96: /* tcons ::= CHECK LP expr RP onconf */
101016
      case 96: /* tcons ::= CHECK LP expr RP onconf */
94195
{sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy346.pExpr);}
101017
{sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy118.pExpr);}
94196
        break;
101018
        break;
94197
      case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
101019
      case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
94198
{
101020
{
94199
    sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy14, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy14, yymsp[-1].minor.yy328);
101021
    sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy322, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy322, yymsp[-1].minor.yy4);
94200
    sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy328);
101022
    sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy4);
94201
}
101023
}
94202
        break;
101024
        break;
94203
      case 100: /* onconf ::= */
101025
      case 100: /* onconf ::= */
94204
{yygotominor.yy328 = OE_Default;}
101026
{yygotominor.yy4 = OE_Default;}
94205
        break;
101027
        break;
94206
      case 102: /* orconf ::= */
101028
      case 102: /* orconf ::= */
94207
{yygotominor.yy186 = OE_Default;}
101029
{yygotominor.yy210 = OE_Default;}
94208
        break;
101030
        break;
94209
      case 103: /* orconf ::= OR resolvetype */
101031
      case 103: /* orconf ::= OR resolvetype */
94210
{yygotominor.yy186 = (u8)yymsp[0].minor.yy328;}
101032
{yygotominor.yy210 = (u8)yymsp[0].minor.yy4;}
94211
        break;
101033
        break;
94212
      case 105: /* resolvetype ::= IGNORE */
101034
      case 105: /* resolvetype ::= IGNORE */
94213
{yygotominor.yy328 = OE_Ignore;}
101035
{yygotominor.yy4 = OE_Ignore;}
94214
        break;
101036
        break;
94215
      case 106: /* resolvetype ::= REPLACE */
101037
      case 106: /* resolvetype ::= REPLACE */
94216
{yygotominor.yy328 = OE_Replace;}
101038
{yygotominor.yy4 = OE_Replace;}
94217
        break;
101039
        break;
94218
      case 107: /* cmd ::= DROP TABLE ifexists fullname */
101040
      case 107: /* cmd ::= DROP TABLE ifexists fullname */
94219
{
101041
{
94220
  sqlite3DropTable(pParse, yymsp[0].minor.yy65, 0, yymsp[-1].minor.yy328);
101042
  sqlite3DropTable(pParse, yymsp[0].minor.yy259, 0, yymsp[-1].minor.yy4);
94221
}
101043
}
94222
        break;
101044
        break;
94223
      case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
101045
      case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
94224
{
101046
{
94225
  sqlite3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, yymsp[0].minor.yy3, yymsp[-6].minor.yy328, yymsp[-4].minor.yy328);
101047
  sqlite3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, yymsp[0].minor.yy387, yymsp[-6].minor.yy4, yymsp[-4].minor.yy4);
94226
}
101048
}
94227
        break;
101049
        break;
94228
      case 111: /* cmd ::= DROP VIEW ifexists fullname */
101050
      case 111: /* cmd ::= DROP VIEW ifexists fullname */
94229
{
101051
{
94230
  sqlite3DropTable(pParse, yymsp[0].minor.yy65, 1, yymsp[-1].minor.yy328);
101052
  sqlite3DropTable(pParse, yymsp[0].minor.yy259, 1, yymsp[-1].minor.yy4);
94231
}
101053
}
94232
        break;
101054
        break;
94233
      case 112: /* cmd ::= select */
101055
      case 112: /* cmd ::= select */
94234
{
101056
{
94235
  SelectDest dest = {SRT_Output, 0, 0, 0, 0};
101057
  SelectDest dest = {SRT_Output, 0, 0, 0, 0};
94236
  sqlite3Select(pParse, yymsp[0].minor.yy3, &dest);
101058
  sqlite3Select(pParse, yymsp[0].minor.yy387, &dest);
94237
  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
101059
  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy387);
94238
}
101060
}
94239
        break;
101061
        break;
94240
      case 113: /* select ::= oneselect */
101062
      case 113: /* select ::= oneselect */
94241
{yygotominor.yy3 = yymsp[0].minor.yy3;}
101063
{yygotominor.yy387 = yymsp[0].minor.yy387;}
94242
        break;
101064
        break;
94243
      case 114: /* select ::= select multiselect_op oneselect */
101065
      case 114: /* select ::= select multiselect_op oneselect */
94244
{
101066
{
94245
  if( yymsp[0].minor.yy3 ){
101067
  if( yymsp[0].minor.yy387 ){
94246
    yymsp[0].minor.yy3->op = (u8)yymsp[-1].minor.yy328;
101068
    yymsp[0].minor.yy387->op = (u8)yymsp[-1].minor.yy4;
94247
    yymsp[0].minor.yy3->pPrior = yymsp[-2].minor.yy3;
101069
    yymsp[0].minor.yy387->pPrior = yymsp[-2].minor.yy387;
94248
  }else{
101070
  }else{
94249
    sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy3);
101071
    sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy387);
94250
  }
101072
  }
94251
  yygotominor.yy3 = yymsp[0].minor.yy3;
101073
  yygotominor.yy387 = yymsp[0].minor.yy387;
94252
}
101074
}
94253
        break;
101075
        break;
94254
      case 116: /* multiselect_op ::= UNION ALL */
101076
      case 116: /* multiselect_op ::= UNION ALL */
94255
{yygotominor.yy328 = TK_ALL;}
101077
{yygotominor.yy4 = TK_ALL;}
94256
        break;
101078
        break;
94257
      case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
101079
      case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
94258
{
101080
{
94259
  yygotominor.yy3 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy14,yymsp[-5].minor.yy65,yymsp[-4].minor.yy132,yymsp[-3].minor.yy14,yymsp[-2].minor.yy132,yymsp[-1].minor.yy14,yymsp[-7].minor.yy328,yymsp[0].minor.yy476.pLimit,yymsp[0].minor.yy476.pOffset);
101081
  yygotominor.yy387 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy322,yymsp[-5].minor.yy259,yymsp[-4].minor.yy314,yymsp[-3].minor.yy322,yymsp[-2].minor.yy314,yymsp[-1].minor.yy322,yymsp[-7].minor.yy4,yymsp[0].minor.yy292.pLimit,yymsp[0].minor.yy292.pOffset);
94260
}
101082
}
94261
        break;
101083
        break;
94262
      case 122: /* sclp ::= selcollist COMMA */
101084
      case 122: /* sclp ::= selcollist COMMA */
94263
      case 248: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==248);
101085
      case 247: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==247);
94264
{yygotominor.yy14 = yymsp[-1].minor.yy14;}
101086
{yygotominor.yy322 = yymsp[-1].minor.yy322;}
94265
        break;
101087
        break;
94266
      case 123: /* sclp ::= */
101088
      case 123: /* sclp ::= */
94267
      case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
101089
      case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
94268
      case 159: /* groupby_opt ::= */ yytestcase(yyruleno==159);
101090
      case 159: /* groupby_opt ::= */ yytestcase(yyruleno==159);
94269
      case 241: /* exprlist ::= */ yytestcase(yyruleno==241);
101091
      case 240: /* exprlist ::= */ yytestcase(yyruleno==240);
94270
      case 247: /* idxlist_opt ::= */ yytestcase(yyruleno==247);
101092
      case 246: /* idxlist_opt ::= */ yytestcase(yyruleno==246);
94271
{yygotominor.yy14 = 0;}
101093
{yygotominor.yy322 = 0;}
94272
        break;
101094
        break;
94273
      case 124: /* selcollist ::= sclp expr as */
101095
      case 124: /* selcollist ::= sclp expr as */
94274
{
101096
{
94275
   yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy14, yymsp[-1].minor.yy346.pExpr);
101097
   yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy322, yymsp[-1].minor.yy118.pExpr);
94276
   if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[0].minor.yy0, 1);
101098
   if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[0].minor.yy0, 1);
94277
   sqlite3ExprListSetSpan(pParse,yygotominor.yy14,&yymsp[-1].minor.yy346);
101099
   sqlite3ExprListSetSpan(pParse,yygotominor.yy322,&yymsp[-1].minor.yy118);
94278
}
101100
}
94279
        break;
101101
        break;
94280
      case 125: /* selcollist ::= sclp STAR */
101102
      case 125: /* selcollist ::= sclp STAR */
94281
{
101103
{
94282
  Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
101104
  Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
94283
  yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy14, p);
101105
  yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy322, p);
94284
}
101106
}
94285
        break;
101107
        break;
94286
      case 126: /* selcollist ::= sclp nm DOT STAR */
101108
      case 126: /* selcollist ::= sclp nm DOT STAR */
 Lines 94288-94337   static void yy_reduce( Link Here 
94288
  Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
101110
  Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
94289
  Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
101111
  Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
94290
  Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
101112
  Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
94291
  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14, pDot);
101113
  yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322, pDot);
94292
}
101114
}
94293
        break;
101115
        break;
94294
      case 129: /* as ::= */
101116
      case 129: /* as ::= */
94295
{yygotominor.yy0.n = 0;}
101117
{yygotominor.yy0.n = 0;}
94296
        break;
101118
        break;
94297
      case 130: /* from ::= */
101119
      case 130: /* from ::= */
94298
{yygotominor.yy65 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy65));}
101120
{yygotominor.yy259 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy259));}
94299
        break;
101121
        break;
94300
      case 131: /* from ::= FROM seltablist */
101122
      case 131: /* from ::= FROM seltablist */
94301
{
101123
{
94302
  yygotominor.yy65 = yymsp[0].minor.yy65;
101124
  yygotominor.yy259 = yymsp[0].minor.yy259;
94303
  sqlite3SrcListShiftJoinType(yygotominor.yy65);
101125
  sqlite3SrcListShiftJoinType(yygotominor.yy259);
94304
}
101126
}
94305
        break;
101127
        break;
94306
      case 132: /* stl_prefix ::= seltablist joinop */
101128
      case 132: /* stl_prefix ::= seltablist joinop */
94307
{
101129
{
94308
   yygotominor.yy65 = yymsp[-1].minor.yy65;
101130
   yygotominor.yy259 = yymsp[-1].minor.yy259;
94309
   if( ALWAYS(yygotominor.yy65 && yygotominor.yy65->nSrc>0) ) yygotominor.yy65->a[yygotominor.yy65->nSrc-1].jointype = (u8)yymsp[0].minor.yy328;
101131
   if( ALWAYS(yygotominor.yy259 && yygotominor.yy259->nSrc>0) ) yygotominor.yy259->a[yygotominor.yy259->nSrc-1].jointype = (u8)yymsp[0].minor.yy4;
94310
}
101132
}
94311
        break;
101133
        break;
94312
      case 133: /* stl_prefix ::= */
101134
      case 133: /* stl_prefix ::= */
94313
{yygotominor.yy65 = 0;}
101135
{yygotominor.yy259 = 0;}
94314
        break;
101136
        break;
94315
      case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
101137
      case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
94316
{
101138
{
94317
  yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
101139
  yygotominor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
94318
  sqlite3SrcListIndexedBy(pParse, yygotominor.yy65, &yymsp[-2].minor.yy0);
101140
  sqlite3SrcListIndexedBy(pParse, yygotominor.yy259, &yymsp[-2].minor.yy0);
94319
}
101141
}
94320
        break;
101142
        break;
94321
      case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
101143
      case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
94322
{
101144
{
94323
    yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy3,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
101145
    yygotominor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy387,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
94324
  }
101146
  }
94325
        break;
101147
        break;
94326
      case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
101148
      case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
94327
{
101149
{
94328
    if( yymsp[-6].minor.yy65==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy132==0 && yymsp[0].minor.yy408==0 ){
101150
    if( yymsp[-6].minor.yy259==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy314==0 && yymsp[0].minor.yy384==0 ){
94329
      yygotominor.yy65 = yymsp[-4].minor.yy65;
101151
      yygotominor.yy259 = yymsp[-4].minor.yy259;
94330
    }else{
101152
    }else{
94331
      Select *pSubquery;
101153
      Select *pSubquery;
94332
      sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy65);
101154
      sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy259);
94333
      pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy65,0,0,0,0,0,0,0);
101155
      pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy259,0,0,0,0,0,0,0);
94334
      yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
101156
      yygotominor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
94335
    }
101157
    }
94336
  }
101158
  }
94337
        break;
101159
        break;
 Lines 94340-94497   static void yy_reduce( Link Here 
94340
{yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
101162
{yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
94341
        break;
101163
        break;
94342
      case 139: /* fullname ::= nm dbnm */
101164
      case 139: /* fullname ::= nm dbnm */
94343
{yygotominor.yy65 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
101165
{yygotominor.yy259 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
94344
        break;
101166
        break;
94345
      case 140: /* joinop ::= COMMA|JOIN */
101167
      case 140: /* joinop ::= COMMA|JOIN */
94346
{ yygotominor.yy328 = JT_INNER; }
101168
{ yygotominor.yy4 = JT_INNER; }
94347
        break;
101169
        break;
94348
      case 141: /* joinop ::= JOIN_KW JOIN */
101170
      case 141: /* joinop ::= JOIN_KW JOIN */
94349
{ yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
101171
{ yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
94350
        break;
101172
        break;
94351
      case 142: /* joinop ::= JOIN_KW nm JOIN */
101173
      case 142: /* joinop ::= JOIN_KW nm JOIN */
94352
{ yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
101174
{ yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
94353
        break;
101175
        break;
94354
      case 143: /* joinop ::= JOIN_KW nm nm JOIN */
101176
      case 143: /* joinop ::= JOIN_KW nm nm JOIN */
94355
{ yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
101177
{ yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
94356
        break;
101178
        break;
94357
      case 144: /* on_opt ::= ON expr */
101179
      case 144: /* on_opt ::= ON expr */
94358
      case 155: /* sortitem ::= expr */ yytestcase(yyruleno==155);
101180
      case 155: /* sortitem ::= expr */ yytestcase(yyruleno==155);
94359
      case 162: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==162);
101181
      case 162: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==162);
94360
      case 169: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==169);
101182
      case 169: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==169);
94361
      case 236: /* case_else ::= ELSE expr */ yytestcase(yyruleno==236);
101183
      case 235: /* case_else ::= ELSE expr */ yytestcase(yyruleno==235);
94362
      case 238: /* case_operand ::= expr */ yytestcase(yyruleno==238);
101184
      case 237: /* case_operand ::= expr */ yytestcase(yyruleno==237);
94363
{yygotominor.yy132 = yymsp[0].minor.yy346.pExpr;}
101185
{yygotominor.yy314 = yymsp[0].minor.yy118.pExpr;}
94364
        break;
101186
        break;
94365
      case 145: /* on_opt ::= */
101187
      case 145: /* on_opt ::= */
94366
      case 161: /* having_opt ::= */ yytestcase(yyruleno==161);
101188
      case 161: /* having_opt ::= */ yytestcase(yyruleno==161);
94367
      case 168: /* where_opt ::= */ yytestcase(yyruleno==168);
101189
      case 168: /* where_opt ::= */ yytestcase(yyruleno==168);
94368
      case 237: /* case_else ::= */ yytestcase(yyruleno==237);
101190
      case 236: /* case_else ::= */ yytestcase(yyruleno==236);
94369
      case 239: /* case_operand ::= */ yytestcase(yyruleno==239);
101191
      case 238: /* case_operand ::= */ yytestcase(yyruleno==238);
94370
{yygotominor.yy132 = 0;}
101192
{yygotominor.yy314 = 0;}
94371
        break;
101193
        break;
94372
      case 148: /* indexed_opt ::= NOT INDEXED */
101194
      case 148: /* indexed_opt ::= NOT INDEXED */
94373
{yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
101195
{yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
94374
        break;
101196
        break;
94375
      case 149: /* using_opt ::= USING LP inscollist RP */
101197
      case 149: /* using_opt ::= USING LP inscollist RP */
94376
      case 181: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==181);
101198
      case 181: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==181);
94377
{yygotominor.yy408 = yymsp[-1].minor.yy408;}
101199
{yygotominor.yy384 = yymsp[-1].minor.yy384;}
94378
        break;
101200
        break;
94379
      case 150: /* using_opt ::= */
101201
      case 150: /* using_opt ::= */
94380
      case 180: /* inscollist_opt ::= */ yytestcase(yyruleno==180);
101202
      case 180: /* inscollist_opt ::= */ yytestcase(yyruleno==180);
94381
{yygotominor.yy408 = 0;}
101203
{yygotominor.yy384 = 0;}
94382
        break;
101204
        break;
94383
      case 152: /* orderby_opt ::= ORDER BY sortlist */
101205
      case 152: /* orderby_opt ::= ORDER BY sortlist */
94384
      case 160: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==160);
101206
      case 160: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==160);
94385
      case 240: /* exprlist ::= nexprlist */ yytestcase(yyruleno==240);
101207
      case 239: /* exprlist ::= nexprlist */ yytestcase(yyruleno==239);
94386
{yygotominor.yy14 = yymsp[0].minor.yy14;}
101208
{yygotominor.yy322 = yymsp[0].minor.yy322;}
94387
        break;
101209
        break;
94388
      case 153: /* sortlist ::= sortlist COMMA sortitem sortorder */
101210
      case 153: /* sortlist ::= sortlist COMMA sortitem sortorder */
94389
{
101211
{
94390
  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14,yymsp[-1].minor.yy132);
101212
  yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322,yymsp[-1].minor.yy314);
94391
  if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
101213
  if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
94392
}
101214
}
94393
        break;
101215
        break;
94394
      case 154: /* sortlist ::= sortitem sortorder */
101216
      case 154: /* sortlist ::= sortitem sortorder */
94395
{
101217
{
94396
  yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy132);
101218
  yygotominor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy314);
94397
  if( yygotominor.yy14 && ALWAYS(yygotominor.yy14->a) ) yygotominor.yy14->a[0].sortOrder = (u8)yymsp[0].minor.yy328;
101219
  if( yygotominor.yy322 && ALWAYS(yygotominor.yy322->a) ) yygotominor.yy322->a[0].sortOrder = (u8)yymsp[0].minor.yy4;
94398
}
101220
}
94399
        break;
101221
        break;
94400
      case 156: /* sortorder ::= ASC */
101222
      case 156: /* sortorder ::= ASC */
94401
      case 158: /* sortorder ::= */ yytestcase(yyruleno==158);
101223
      case 158: /* sortorder ::= */ yytestcase(yyruleno==158);
94402
{yygotominor.yy328 = SQLITE_SO_ASC;}
101224
{yygotominor.yy4 = SQLITE_SO_ASC;}
94403
        break;
101225
        break;
94404
      case 157: /* sortorder ::= DESC */
101226
      case 157: /* sortorder ::= DESC */
94405
{yygotominor.yy328 = SQLITE_SO_DESC;}
101227
{yygotominor.yy4 = SQLITE_SO_DESC;}
94406
        break;
101228
        break;
94407
      case 163: /* limit_opt ::= */
101229
      case 163: /* limit_opt ::= */
94408
{yygotominor.yy476.pLimit = 0; yygotominor.yy476.pOffset = 0;}
101230
{yygotominor.yy292.pLimit = 0; yygotominor.yy292.pOffset = 0;}
94409
        break;
101231
        break;
94410
      case 164: /* limit_opt ::= LIMIT expr */
101232
      case 164: /* limit_opt ::= LIMIT expr */
94411
{yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr; yygotominor.yy476.pOffset = 0;}
101233
{yygotominor.yy292.pLimit = yymsp[0].minor.yy118.pExpr; yygotominor.yy292.pOffset = 0;}
94412
        break;
101234
        break;
94413
      case 165: /* limit_opt ::= LIMIT expr OFFSET expr */
101235
      case 165: /* limit_opt ::= LIMIT expr OFFSET expr */
94414
{yygotominor.yy476.pLimit = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pOffset = yymsp[0].minor.yy346.pExpr;}
101236
{yygotominor.yy292.pLimit = yymsp[-2].minor.yy118.pExpr; yygotominor.yy292.pOffset = yymsp[0].minor.yy118.pExpr;}
94415
        break;
101237
        break;
94416
      case 166: /* limit_opt ::= LIMIT expr COMMA expr */
101238
      case 166: /* limit_opt ::= LIMIT expr COMMA expr */
94417
{yygotominor.yy476.pOffset = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr;}
101239
{yygotominor.yy292.pOffset = yymsp[-2].minor.yy118.pExpr; yygotominor.yy292.pLimit = yymsp[0].minor.yy118.pExpr;}
94418
        break;
101240
        break;
94419
      case 167: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
101241
      case 167: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
94420
{
101242
{
94421
  sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy65, &yymsp[-1].minor.yy0);
101243
  sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy259, &yymsp[-1].minor.yy0);
94422
  sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy65,yymsp[0].minor.yy132);
101244
  sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy259,yymsp[0].minor.yy314);
94423
}
101245
}
94424
        break;
101246
        break;
94425
      case 170: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
101247
      case 170: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
94426
{
101248
{
94427
  sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy65, &yymsp[-3].minor.yy0);
101249
  sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy259, &yymsp[-3].minor.yy0);
94428
  sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy14,"set list"); 
101250
  sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy322,"set list"); 
94429
  sqlite3Update(pParse,yymsp[-4].minor.yy65,yymsp[-1].minor.yy14,yymsp[0].minor.yy132,yymsp[-5].minor.yy186);
101251
  sqlite3Update(pParse,yymsp[-4].minor.yy259,yymsp[-1].minor.yy322,yymsp[0].minor.yy314,yymsp[-5].minor.yy210);
94430
}
101252
}
94431
        break;
101253
        break;
94432
      case 171: /* setlist ::= setlist COMMA nm EQ expr */
101254
      case 171: /* setlist ::= setlist COMMA nm EQ expr */
94433
{
101255
{
94434
  yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy14, yymsp[0].minor.yy346.pExpr);
101256
  yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy322, yymsp[0].minor.yy118.pExpr);
94435
  sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
101257
  sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
94436
}
101258
}
94437
        break;
101259
        break;
94438
      case 172: /* setlist ::= nm EQ expr */
101260
      case 172: /* setlist ::= nm EQ expr */
94439
{
101261
{
94440
  yygotominor.yy14 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy346.pExpr);
101262
  yygotominor.yy322 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy118.pExpr);
94441
  sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
101263
  sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
94442
}
101264
}
94443
        break;
101265
        break;
94444
      case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP */
101266
      case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP */
94445
{sqlite3Insert(pParse, yymsp[-5].minor.yy65, yymsp[-1].minor.yy14, 0, yymsp[-4].minor.yy408, yymsp[-7].minor.yy186);}
101267
{sqlite3Insert(pParse, yymsp[-5].minor.yy259, yymsp[-1].minor.yy322, 0, yymsp[-4].minor.yy384, yymsp[-7].minor.yy210);}
94446
        break;
101268
        break;
94447
      case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
101269
      case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
94448
{sqlite3Insert(pParse, yymsp[-2].minor.yy65, 0, yymsp[0].minor.yy3, yymsp[-1].minor.yy408, yymsp[-4].minor.yy186);}
101270
{sqlite3Insert(pParse, yymsp[-2].minor.yy259, 0, yymsp[0].minor.yy387, yymsp[-1].minor.yy384, yymsp[-4].minor.yy210);}
94449
        break;
101271
        break;
94450
      case 175: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
101272
      case 175: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
94451
{sqlite3Insert(pParse, yymsp[-3].minor.yy65, 0, 0, yymsp[-2].minor.yy408, yymsp[-5].minor.yy186);}
101273
{sqlite3Insert(pParse, yymsp[-3].minor.yy259, 0, 0, yymsp[-2].minor.yy384, yymsp[-5].minor.yy210);}
94452
        break;
101274
        break;
94453
      case 176: /* insert_cmd ::= INSERT orconf */
101275
      case 176: /* insert_cmd ::= INSERT orconf */
94454
{yygotominor.yy186 = yymsp[0].minor.yy186;}
101276
{yygotominor.yy210 = yymsp[0].minor.yy210;}
94455
        break;
101277
        break;
94456
      case 177: /* insert_cmd ::= REPLACE */
101278
      case 177: /* insert_cmd ::= REPLACE */
94457
{yygotominor.yy186 = OE_Replace;}
101279
{yygotominor.yy210 = OE_Replace;}
94458
        break;
101280
        break;
94459
      case 178: /* itemlist ::= itemlist COMMA expr */
101281
      case 178: /* itemlist ::= itemlist COMMA expr */
94460
      case 242: /* nexprlist ::= nexprlist COMMA expr */ yytestcase(yyruleno==242);
101282
      case 241: /* nexprlist ::= nexprlist COMMA expr */ yytestcase(yyruleno==241);
94461
{yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[0].minor.yy346.pExpr);}
101283
{yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy322,yymsp[0].minor.yy118.pExpr);}
94462
        break;
101284
        break;
94463
      case 179: /* itemlist ::= expr */
101285
      case 179: /* itemlist ::= expr */
94464
      case 243: /* nexprlist ::= expr */ yytestcase(yyruleno==243);
101286
      case 242: /* nexprlist ::= expr */ yytestcase(yyruleno==242);
94465
{yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy346.pExpr);}
101287
{yygotominor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy118.pExpr);}
94466
        break;
101288
        break;
94467
      case 182: /* inscollist ::= inscollist COMMA nm */
101289
      case 182: /* inscollist ::= inscollist COMMA nm */
94468
{yygotominor.yy408 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy408,&yymsp[0].minor.yy0);}
101290
{yygotominor.yy384 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy384,&yymsp[0].minor.yy0);}
94469
        break;
101291
        break;
94470
      case 183: /* inscollist ::= nm */
101292
      case 183: /* inscollist ::= nm */
94471
{yygotominor.yy408 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
101293
{yygotominor.yy384 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
94472
        break;
101294
        break;
94473
      case 184: /* expr ::= term */
101295
      case 184: /* expr ::= term */
94474
      case 212: /* escape ::= ESCAPE expr */ yytestcase(yyruleno==212);
101296
{yygotominor.yy118 = yymsp[0].minor.yy118;}
94475
{yygotominor.yy346 = yymsp[0].minor.yy346;}
94476
        break;
101297
        break;
94477
      case 185: /* expr ::= LP expr RP */
101298
      case 185: /* expr ::= LP expr RP */
94478
{yygotominor.yy346.pExpr = yymsp[-1].minor.yy346.pExpr; spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
101299
{yygotominor.yy118.pExpr = yymsp[-1].minor.yy118.pExpr; spanSet(&yygotominor.yy118,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
94479
        break;
101300
        break;
94480
      case 186: /* term ::= NULL */
101301
      case 186: /* term ::= NULL */
94481
      case 191: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==191);
101302
      case 191: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==191);
94482
      case 192: /* term ::= STRING */ yytestcase(yyruleno==192);
101303
      case 192: /* term ::= STRING */ yytestcase(yyruleno==192);
94483
{spanExpr(&yygotominor.yy346, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
101304
{spanExpr(&yygotominor.yy118, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
94484
        break;
101305
        break;
94485
      case 187: /* expr ::= id */
101306
      case 187: /* expr ::= id */
94486
      case 188: /* expr ::= JOIN_KW */ yytestcase(yyruleno==188);
101307
      case 188: /* expr ::= JOIN_KW */ yytestcase(yyruleno==188);
94487
{spanExpr(&yygotominor.yy346, pParse, TK_ID, &yymsp[0].minor.yy0);}
101308
{spanExpr(&yygotominor.yy118, pParse, TK_ID, &yymsp[0].minor.yy0);}
94488
        break;
101309
        break;
94489
      case 189: /* expr ::= nm DOT nm */
101310
      case 189: /* expr ::= nm DOT nm */
94490
{
101311
{
94491
  Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
101312
  Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
94492
  Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
101313
  Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
94493
  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
101314
  yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
94494
  spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
101315
  spanSet(&yygotominor.yy118,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
94495
}
101316
}
94496
        break;
101317
        break;
94497
      case 190: /* expr ::= nm DOT nm DOT nm */
101318
      case 190: /* expr ::= nm DOT nm DOT nm */
 Lines 94500-94507   static void yy_reduce( Link Here 
94500
  Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
101321
  Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
94501
  Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
101322
  Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
94502
  Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
101323
  Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
94503
  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
101324
  yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
94504
  spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
101325
  spanSet(&yygotominor.yy118,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
94505
}
101326
}
94506
        break;
101327
        break;
94507
      case 193: /* expr ::= REGISTER */
101328
      case 193: /* expr ::= REGISTER */
 Lines 94511-94571   static void yy_reduce( Link Here 
94511
  ** in the virtual machine.  #N is the N-th register. */
101332
  ** in the virtual machine.  #N is the N-th register. */
94512
  if( pParse->nested==0 ){
101333
  if( pParse->nested==0 ){
94513
    sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
101334
    sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
94514
    yygotominor.yy346.pExpr = 0;
101335
    yygotominor.yy118.pExpr = 0;
94515
  }else{
101336
  }else{
94516
    yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
101337
    yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
94517
    if( yygotominor.yy346.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy346.pExpr->iTable);
101338
    if( yygotominor.yy118.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy118.pExpr->iTable);
94518
  }
101339
  }
94519
  spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
101340
  spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
94520
}
101341
}
94521
        break;
101342
        break;
94522
      case 194: /* expr ::= VARIABLE */
101343
      case 194: /* expr ::= VARIABLE */
94523
{
101344
{
94524
  spanExpr(&yygotominor.yy346, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
101345
  spanExpr(&yygotominor.yy118, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
94525
  sqlite3ExprAssignVarNumber(pParse, yygotominor.yy346.pExpr);
101346
  sqlite3ExprAssignVarNumber(pParse, yygotominor.yy118.pExpr);
94526
  spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
101347
  spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
94527
}
101348
}
94528
        break;
101349
        break;
94529
      case 195: /* expr ::= expr COLLATE ids */
101350
      case 195: /* expr ::= expr COLLATE ids */
94530
{
101351
{
94531
  yygotominor.yy346.pExpr = sqlite3ExprSetColl(pParse, yymsp[-2].minor.yy346.pExpr, &yymsp[0].minor.yy0);
101352
  yygotominor.yy118.pExpr = sqlite3ExprSetCollByToken(pParse, yymsp[-2].minor.yy118.pExpr, &yymsp[0].minor.yy0);
94532
  yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart;
101353
  yygotominor.yy118.zStart = yymsp[-2].minor.yy118.zStart;
94533
  yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
101354
  yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
94534
}
101355
}
94535
        break;
101356
        break;
94536
      case 196: /* expr ::= CAST LP expr AS typetoken RP */
101357
      case 196: /* expr ::= CAST LP expr AS typetoken RP */
94537
{
101358
{
94538
  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy346.pExpr, 0, &yymsp[-1].minor.yy0);
101359
  yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy118.pExpr, 0, &yymsp[-1].minor.yy0);
94539
  spanSet(&yygotominor.yy346,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
101360
  spanSet(&yygotominor.yy118,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
94540
}
101361
}
94541
        break;
101362
        break;
94542
      case 197: /* expr ::= ID LP distinct exprlist RP */
101363
      case 197: /* expr ::= ID LP distinct exprlist RP */
94543
{
101364
{
94544
  if( yymsp[-1].minor.yy14 && yymsp[-1].minor.yy14->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
101365
  if( yymsp[-1].minor.yy322 && yymsp[-1].minor.yy322->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
94545
    sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
101366
    sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
94546
  }
101367
  }
94547
  yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy14, &yymsp[-4].minor.yy0);
101368
  yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy322, &yymsp[-4].minor.yy0);
94548
  spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
101369
  spanSet(&yygotominor.yy118,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
94549
  if( yymsp[-2].minor.yy328 && yygotominor.yy346.pExpr ){
101370
  if( yymsp[-2].minor.yy4 && yygotominor.yy118.pExpr ){
94550
    yygotominor.yy346.pExpr->flags |= EP_Distinct;
101371
    yygotominor.yy118.pExpr->flags |= EP_Distinct;
94551
  }
101372
  }
94552
}
101373
}
94553
        break;
101374
        break;
94554
      case 198: /* expr ::= ID LP STAR RP */
101375
      case 198: /* expr ::= ID LP STAR RP */
94555
{
101376
{
94556
  yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
101377
  yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
94557
  spanSet(&yygotominor.yy346,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
101378
  spanSet(&yygotominor.yy118,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
94558
}
101379
}
94559
        break;
101380
        break;
94560
      case 199: /* term ::= CTIME_KW */
101381
      case 199: /* term ::= CTIME_KW */
94561
{
101382
{
94562
  /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
101383
  /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
94563
  ** treated as functions that return constants */
101384
  ** treated as functions that return constants */
94564
  yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
101385
  yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
94565
  if( yygotominor.yy346.pExpr ){
101386
  if( yygotominor.yy118.pExpr ){
94566
    yygotominor.yy346.pExpr->op = TK_CONST_FUNC;  
101387
    yygotominor.yy118.pExpr->op = TK_CONST_FUNC;  
94567
  }
101388
  }
94568
  spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
101389
  spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
94569
}
101390
}
94570
        break;
101391
        break;
94571
      case 200: /* expr ::= expr AND expr */
101392
      case 200: /* expr ::= expr AND expr */
 Lines 94576-94870   static void yy_reduce( Link Here 
94576
      case 205: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==205);
101397
      case 205: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==205);
94577
      case 206: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==206);
101398
      case 206: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==206);
94578
      case 207: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==207);
101399
      case 207: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==207);
94579
{spanBinaryExpr(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);}
101400
{spanBinaryExpr(&yygotominor.yy118,pParse,yymsp[-1].major,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy118);}
94580
        break;
101401
        break;
94581
      case 208: /* likeop ::= LIKE_KW */
101402
      case 208: /* likeop ::= LIKE_KW */
94582
      case 210: /* likeop ::= MATCH */ yytestcase(yyruleno==210);
101403
      case 210: /* likeop ::= MATCH */ yytestcase(yyruleno==210);
94583
{yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.not = 0;}
101404
{yygotominor.yy342.eOperator = yymsp[0].minor.yy0; yygotominor.yy342.not = 0;}
94584
        break;
101405
        break;
94585
      case 209: /* likeop ::= NOT LIKE_KW */
101406
      case 209: /* likeop ::= NOT LIKE_KW */
94586
      case 211: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==211);
101407
      case 211: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==211);
94587
{yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.not = 1;}
101408
{yygotominor.yy342.eOperator = yymsp[0].minor.yy0; yygotominor.yy342.not = 1;}
94588
        break;
101409
        break;
94589
      case 213: /* escape ::= */
101410
      case 212: /* expr ::= expr likeop expr */
94590
{memset(&yygotominor.yy346,0,sizeof(yygotominor.yy346));}
94591
        break;
94592
      case 214: /* expr ::= expr likeop expr escape */
94593
{
101411
{
94594
  ExprList *pList;
101412
  ExprList *pList;
94595
  pList = sqlite3ExprListAppend(pParse,0, yymsp[-1].minor.yy346.pExpr);
101413
  pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy118.pExpr);
94596
  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-3].minor.yy346.pExpr);
101414
  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy118.pExpr);
94597
  if( yymsp[0].minor.yy346.pExpr ){
101415
  yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy342.eOperator);
94598
    pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
101416
  if( yymsp[-1].minor.yy342.not ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
94599
  }
101417
  yygotominor.yy118.zStart = yymsp[-2].minor.yy118.zStart;
94600
  yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-2].minor.yy96.eOperator);
101418
  yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
94601
  if( yymsp[-2].minor.yy96.not ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
101419
  if( yygotominor.yy118.pExpr ) yygotominor.yy118.pExpr->flags |= EP_InfixFunc;
94602
  yygotominor.yy346.zStart = yymsp[-3].minor.yy346.zStart;
101420
}
94603
  yygotominor.yy346.zEnd = yymsp[-1].minor.yy346.zEnd;
101421
        break;
94604
  if( yygotominor.yy346.pExpr ) yygotominor.yy346.pExpr->flags |= EP_InfixFunc;
101422
      case 213: /* expr ::= expr likeop expr ESCAPE expr */
94605
}
94606
        break;
94607
      case 215: /* expr ::= expr ISNULL|NOTNULL */
94608
{spanUnaryPostfix(&yygotominor.yy346,pParse,yymsp[0].major,&yymsp[-1].minor.yy346,&yymsp[0].minor.yy0);}
94609
        break;
94610
      case 216: /* expr ::= expr NOT NULL */
94611
{spanUnaryPostfix(&yygotominor.yy346,pParse,TK_NOTNULL,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy0);}
94612
        break;
94613
      case 217: /* expr ::= expr IS expr */
94614
{
101423
{
94615
  spanBinaryExpr(&yygotominor.yy346,pParse,TK_IS,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);
101424
  ExprList *pList;
94616
  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_ISNULL);
101425
  pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
94617
}
101426
  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy118.pExpr);
94618
        break;
101427
  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy118.pExpr);
94619
      case 218: /* expr ::= expr IS NOT expr */
101428
  yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy342.eOperator);
101429
  if( yymsp[-3].minor.yy342.not ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
101430
  yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
101431
  yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
101432
  if( yygotominor.yy118.pExpr ) yygotominor.yy118.pExpr->flags |= EP_InfixFunc;
101433
}
101434
        break;
101435
      case 214: /* expr ::= expr ISNULL|NOTNULL */
101436
{spanUnaryPostfix(&yygotominor.yy118,pParse,yymsp[0].major,&yymsp[-1].minor.yy118,&yymsp[0].minor.yy0);}
101437
        break;
101438
      case 215: /* expr ::= expr NOT NULL */
101439
{spanUnaryPostfix(&yygotominor.yy118,pParse,TK_NOTNULL,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy0);}
101440
        break;
101441
      case 216: /* expr ::= expr IS expr */
94620
{
101442
{
94621
  spanBinaryExpr(&yygotominor.yy346,pParse,TK_ISNOT,&yymsp[-3].minor.yy346,&yymsp[0].minor.yy346);
101443
  spanBinaryExpr(&yygotominor.yy118,pParse,TK_IS,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy118);
94622
  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_NOTNULL);
101444
  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy118.pExpr, yygotominor.yy118.pExpr, TK_ISNULL);
94623
}
101445
}
94624
        break;
101446
        break;
94625
      case 219: /* expr ::= NOT expr */
101447
      case 217: /* expr ::= expr IS NOT expr */
94626
      case 220: /* expr ::= BITNOT expr */ yytestcase(yyruleno==220);
94627
{spanUnaryPrefix(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
94628
        break;
94629
      case 221: /* expr ::= MINUS expr */
94630
{spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UMINUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
94631
        break;
94632
      case 222: /* expr ::= PLUS expr */
94633
{spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UPLUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
94634
        break;
94635
      case 225: /* expr ::= expr between_op expr AND expr */
94636
{
101448
{
94637
  ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
101449
  spanBinaryExpr(&yygotominor.yy118,pParse,TK_ISNOT,&yymsp[-3].minor.yy118,&yymsp[0].minor.yy118);
94638
  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
101450
  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy118.pExpr, yygotominor.yy118.pExpr, TK_NOTNULL);
94639
  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy346.pExpr, 0, 0);
101451
}
94640
  if( yygotominor.yy346.pExpr ){
101452
        break;
94641
    yygotominor.yy346.pExpr->x.pList = pList;
101453
      case 218: /* expr ::= NOT expr */
101454
      case 219: /* expr ::= BITNOT expr */ yytestcase(yyruleno==219);
101455
{spanUnaryPrefix(&yygotominor.yy118,pParse,yymsp[-1].major,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
101456
        break;
101457
      case 220: /* expr ::= MINUS expr */
101458
{spanUnaryPrefix(&yygotominor.yy118,pParse,TK_UMINUS,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
101459
        break;
101460
      case 221: /* expr ::= PLUS expr */
101461
{spanUnaryPrefix(&yygotominor.yy118,pParse,TK_UPLUS,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
101462
        break;
101463
      case 224: /* expr ::= expr between_op expr AND expr */
101464
{
101465
  ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
101466
  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy118.pExpr);
101467
  yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy118.pExpr, 0, 0);
101468
  if( yygotominor.yy118.pExpr ){
101469
    yygotominor.yy118.pExpr->x.pList = pList;
94642
  }else{
101470
  }else{
94643
    sqlite3ExprListDelete(pParse->db, pList);
101471
    sqlite3ExprListDelete(pParse->db, pList);
94644
  } 
101472
  } 
94645
  if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
101473
  if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
94646
  yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
101474
  yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
94647
  yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
101475
  yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
94648
}
101476
}
94649
        break;
101477
        break;
94650
      case 228: /* expr ::= expr in_op LP exprlist RP */
101478
      case 227: /* expr ::= expr in_op LP exprlist RP */
94651
{
101479
{
94652
    yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
101480
    if( yymsp[-1].minor.yy322==0 ){
94653
    if( yygotominor.yy346.pExpr ){
101481
      /* Expressions of the form
94654
      yygotominor.yy346.pExpr->x.pList = yymsp[-1].minor.yy14;
101482
      **
94655
      sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
101483
      **      expr1 IN ()
94656
    }else{
101484
      **      expr1 NOT IN ()
94657
      sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
101485
      **
94658
    }
101486
      ** simplify to constants 0 (false) and 1 (true), respectively,
94659
    if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
101487
      ** regardless of the value of expr1.
94660
    yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
101488
      */
94661
    yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
101489
      yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy4]);
94662
  }
101490
      sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy118.pExpr);
94663
        break;
101491
    }else{
94664
      case 229: /* expr ::= LP select RP */
101492
      yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy118.pExpr, 0, 0);
101493
      if( yygotominor.yy118.pExpr ){
101494
        yygotominor.yy118.pExpr->x.pList = yymsp[-1].minor.yy322;
101495
        sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
101496
      }else{
101497
        sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy322);
101498
      }
101499
      if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
101500
    }
101501
    yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
101502
    yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
101503
  }
101504
        break;
101505
      case 228: /* expr ::= LP select RP */
94665
{
101506
{
94666
    yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
101507
    yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
94667
    if( yygotominor.yy346.pExpr ){
101508
    if( yygotominor.yy118.pExpr ){
94668
      yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
101509
      yygotominor.yy118.pExpr->x.pSelect = yymsp[-1].minor.yy387;
94669
      ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
101510
      ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
94670
      sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
101511
      sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
94671
    }else{
101512
    }else{
94672
      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
101513
      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
94673
    }
101514
    }
94674
    yygotominor.yy346.zStart = yymsp[-2].minor.yy0.z;
101515
    yygotominor.yy118.zStart = yymsp[-2].minor.yy0.z;
94675
    yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
101516
    yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
94676
  }
101517
  }
94677
        break;
101518
        break;
94678
      case 230: /* expr ::= expr in_op LP select RP */
101519
      case 229: /* expr ::= expr in_op LP select RP */
94679
{
101520
{
94680
    yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
101521
    yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy118.pExpr, 0, 0);
94681
    if( yygotominor.yy346.pExpr ){
101522
    if( yygotominor.yy118.pExpr ){
94682
      yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
101523
      yygotominor.yy118.pExpr->x.pSelect = yymsp[-1].minor.yy387;
94683
      ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
101524
      ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
94684
      sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
101525
      sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
94685
    }else{
101526
    }else{
94686
      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
101527
      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
94687
    }
101528
    }
94688
    if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
101529
    if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
94689
    yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
101530
    yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
94690
    yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
101531
    yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
94691
  }
101532
  }
94692
        break;
101533
        break;
94693
      case 231: /* expr ::= expr in_op nm dbnm */
101534
      case 230: /* expr ::= expr in_op nm dbnm */
94694
{
101535
{
94695
    SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
101536
    SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
94696
    yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy346.pExpr, 0, 0);
101537
    yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy118.pExpr, 0, 0);
94697
    if( yygotominor.yy346.pExpr ){
101538
    if( yygotominor.yy118.pExpr ){
94698
      yygotominor.yy346.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
101539
      yygotominor.yy118.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
94699
      ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
101540
      ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
94700
      sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
101541
      sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
94701
    }else{
101542
    }else{
94702
      sqlite3SrcListDelete(pParse->db, pSrc);
101543
      sqlite3SrcListDelete(pParse->db, pSrc);
94703
    }
101544
    }
94704
    if( yymsp[-2].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
101545
    if( yymsp[-2].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
94705
    yygotominor.yy346.zStart = yymsp[-3].minor.yy346.zStart;
101546
    yygotominor.yy118.zStart = yymsp[-3].minor.yy118.zStart;
94706
    yygotominor.yy346.zEnd = yymsp[0].minor.yy0.z ? &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] : &yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n];
101547
    yygotominor.yy118.zEnd = yymsp[0].minor.yy0.z ? &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] : &yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n];
94707
  }
101548
  }
94708
        break;
101549
        break;
94709
      case 232: /* expr ::= EXISTS LP select RP */
101550
      case 231: /* expr ::= EXISTS LP select RP */
94710
{
101551
{
94711
    Expr *p = yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
101552
    Expr *p = yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
94712
    if( p ){
101553
    if( p ){
94713
      p->x.pSelect = yymsp[-1].minor.yy3;
101554
      p->x.pSelect = yymsp[-1].minor.yy387;
94714
      ExprSetProperty(p, EP_xIsSelect);
101555
      ExprSetProperty(p, EP_xIsSelect);
94715
      sqlite3ExprSetHeight(pParse, p);
101556
      sqlite3ExprSetHeight(pParse, p);
94716
    }else{
101557
    }else{
94717
      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
101558
      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
94718
    }
101559
    }
94719
    yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
101560
    yygotominor.yy118.zStart = yymsp[-3].minor.yy0.z;
94720
    yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
101561
    yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
94721
  }
101562
  }
94722
        break;
101563
        break;
94723
      case 233: /* expr ::= CASE case_operand case_exprlist case_else END */
101564
      case 232: /* expr ::= CASE case_operand case_exprlist case_else END */
94724
{
101565
{
94725
  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy132, yymsp[-1].minor.yy132, 0);
101566
  yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy314, yymsp[-1].minor.yy314, 0);
94726
  if( yygotominor.yy346.pExpr ){
101567
  if( yygotominor.yy118.pExpr ){
94727
    yygotominor.yy346.pExpr->x.pList = yymsp[-2].minor.yy14;
101568
    yygotominor.yy118.pExpr->x.pList = yymsp[-2].minor.yy322;
94728
    sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
101569
    sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
94729
  }else{
101570
  }else{
94730
    sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy14);
101571
    sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy322);
94731
  }
101572
  }
94732
  yygotominor.yy346.zStart = yymsp[-4].minor.yy0.z;
101573
  yygotominor.yy118.zStart = yymsp[-4].minor.yy0.z;
94733
  yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
101574
  yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
94734
}
101575
}
94735
        break;
101576
        break;
94736
      case 234: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
101577
      case 233: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
94737
{
101578
{
94738
  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, yymsp[-2].minor.yy346.pExpr);
101579
  yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, yymsp[-2].minor.yy118.pExpr);
94739
  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
101580
  yygotominor.yy322 = sqlite3ExprListAppend(pParse,yygotominor.yy322, yymsp[0].minor.yy118.pExpr);
94740
}
101581
}
94741
        break;
101582
        break;
94742
      case 235: /* case_exprlist ::= WHEN expr THEN expr */
101583
      case 234: /* case_exprlist ::= WHEN expr THEN expr */
94743
{
101584
{
94744
  yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
101585
  yygotominor.yy322 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
94745
  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
101586
  yygotominor.yy322 = sqlite3ExprListAppend(pParse,yygotominor.yy322, yymsp[0].minor.yy118.pExpr);
94746
}
101587
}
94747
        break;
101588
        break;
94748
      case 244: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
101589
      case 243: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
94749
{
101590
{
94750
  sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0, 
101591
  sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0, 
94751
                     sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy14, yymsp[-9].minor.yy328,
101592
                     sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy322, yymsp[-9].minor.yy4,
94752
                      &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy328);
101593
                      &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy4);
94753
}
101594
}
94754
        break;
101595
        break;
94755
      case 245: /* uniqueflag ::= UNIQUE */
101596
      case 244: /* uniqueflag ::= UNIQUE */
94756
      case 299: /* raisetype ::= ABORT */ yytestcase(yyruleno==299);
101597
      case 298: /* raisetype ::= ABORT */ yytestcase(yyruleno==298);
94757
{yygotominor.yy328 = OE_Abort;}
101598
{yygotominor.yy4 = OE_Abort;}
94758
        break;
101599
        break;
94759
      case 246: /* uniqueflag ::= */
101600
      case 245: /* uniqueflag ::= */
94760
{yygotominor.yy328 = OE_None;}
101601
{yygotominor.yy4 = OE_None;}
94761
        break;
101602
        break;
94762
      case 249: /* idxlist ::= idxlist COMMA nm collate sortorder */
101603
      case 248: /* idxlist ::= idxlist COMMA nm collate sortorder */
94763
{
101604
{
94764
  Expr *p = 0;
101605
  Expr *p = 0;
94765
  if( yymsp[-1].minor.yy0.n>0 ){
101606
  if( yymsp[-1].minor.yy0.n>0 ){
94766
    p = sqlite3Expr(pParse->db, TK_COLUMN, 0);
101607
    p = sqlite3Expr(pParse->db, TK_COLUMN, 0);
94767
    sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy0);
101608
    sqlite3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);
94768
  }
101609
  }
94769
  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, p);
101610
  yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, p);
94770
  sqlite3ExprListSetName(pParse,yygotominor.yy14,&yymsp[-2].minor.yy0,1);
101611
  sqlite3ExprListSetName(pParse,yygotominor.yy322,&yymsp[-2].minor.yy0,1);
94771
  sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
101612
  sqlite3ExprListCheckLength(pParse, yygotominor.yy322, "index");
94772
  if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
101613
  if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
94773
}
101614
}
94774
        break;
101615
        break;
94775
      case 250: /* idxlist ::= nm collate sortorder */
101616
      case 249: /* idxlist ::= nm collate sortorder */
94776
{
101617
{
94777
  Expr *p = 0;
101618
  Expr *p = 0;
94778
  if( yymsp[-1].minor.yy0.n>0 ){
101619
  if( yymsp[-1].minor.yy0.n>0 ){
94779
    p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
101620
    p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
94780
    sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy0);
101621
    sqlite3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);
94781
  }
101622
  }
94782
  yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, p);
101623
  yygotominor.yy322 = sqlite3ExprListAppend(pParse,0, p);
94783
  sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
101624
  sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
94784
  sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
101625
  sqlite3ExprListCheckLength(pParse, yygotominor.yy322, "index");
94785
  if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
101626
  if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
94786
}
101627
}
94787
        break;
101628
        break;
94788
      case 251: /* collate ::= */
101629
      case 250: /* collate ::= */
94789
{yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
101630
{yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
94790
        break;
101631
        break;
94791
      case 253: /* cmd ::= DROP INDEX ifexists fullname */
101632
      case 252: /* cmd ::= DROP INDEX ifexists fullname */
94792
{sqlite3DropIndex(pParse, yymsp[0].minor.yy65, yymsp[-1].minor.yy328);}
101633
{sqlite3DropIndex(pParse, yymsp[0].minor.yy259, yymsp[-1].minor.yy4);}
94793
        break;
101634
        break;
94794
      case 254: /* cmd ::= VACUUM */
101635
      case 253: /* cmd ::= VACUUM */
94795
      case 255: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==255);
101636
      case 254: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==254);
94796
{sqlite3Vacuum(pParse);}
101637
{sqlite3Vacuum(pParse);}
94797
        break;
101638
        break;
94798
      case 256: /* cmd ::= PRAGMA nm dbnm */
101639
      case 255: /* cmd ::= PRAGMA nm dbnm */
94799
{sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
101640
{sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
94800
        break;
101641
        break;
94801
      case 257: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
101642
      case 256: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
94802
{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
101643
{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
94803
        break;
101644
        break;
94804
      case 258: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
101645
      case 257: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
94805
{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
101646
{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
94806
        break;
101647
        break;
94807
      case 259: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
101648
      case 258: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
94808
{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
101649
{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
94809
        break;
101650
        break;
94810
      case 260: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
101651
      case 259: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
94811
{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
101652
{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
94812
        break;
101653
        break;
94813
      case 271: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
101654
      case 270: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
94814
{
101655
{
94815
  Token all;
101656
  Token all;
94816
  all.z = yymsp[-3].minor.yy0.z;
101657
  all.z = yymsp[-3].minor.yy0.z;
94817
  all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
101658
  all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
94818
  sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy473, &all);
101659
  sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy203, &all);
94819
}
101660
}
94820
        break;
101661
        break;
94821
      case 272: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
101662
      case 271: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
94822
{
101663
{
94823
  sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy328, yymsp[-4].minor.yy378.a, yymsp[-4].minor.yy378.b, yymsp[-2].minor.yy65, yymsp[0].minor.yy132, yymsp[-10].minor.yy328, yymsp[-8].minor.yy328);
101664
  sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy4, yymsp[-4].minor.yy90.a, yymsp[-4].minor.yy90.b, yymsp[-2].minor.yy259, yymsp[0].minor.yy314, yymsp[-10].minor.yy4, yymsp[-8].minor.yy4);
94824
  yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
101665
  yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
94825
}
101666
}
94826
        break;
101667
        break;
94827
      case 273: /* trigger_time ::= BEFORE */
101668
      case 272: /* trigger_time ::= BEFORE */
94828
      case 276: /* trigger_time ::= */ yytestcase(yyruleno==276);
101669
      case 275: /* trigger_time ::= */ yytestcase(yyruleno==275);
94829
{ yygotominor.yy328 = TK_BEFORE; }
101670
{ yygotominor.yy4 = TK_BEFORE; }
94830
        break;
101671
        break;
94831
      case 274: /* trigger_time ::= AFTER */
101672
      case 273: /* trigger_time ::= AFTER */
94832
{ yygotominor.yy328 = TK_AFTER;  }
101673
{ yygotominor.yy4 = TK_AFTER;  }
94833
        break;
101674
        break;
94834
      case 275: /* trigger_time ::= INSTEAD OF */
101675
      case 274: /* trigger_time ::= INSTEAD OF */
94835
{ yygotominor.yy328 = TK_INSTEAD;}
101676
{ yygotominor.yy4 = TK_INSTEAD;}
94836
        break;
101677
        break;
94837
      case 277: /* trigger_event ::= DELETE|INSERT */
101678
      case 276: /* trigger_event ::= DELETE|INSERT */
94838
      case 278: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==278);
101679
      case 277: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==277);
94839
{yygotominor.yy378.a = yymsp[0].major; yygotominor.yy378.b = 0;}
101680
{yygotominor.yy90.a = yymsp[0].major; yygotominor.yy90.b = 0;}
94840
        break;
101681
        break;
94841
      case 279: /* trigger_event ::= UPDATE OF inscollist */
101682
      case 278: /* trigger_event ::= UPDATE OF inscollist */
94842
{yygotominor.yy378.a = TK_UPDATE; yygotominor.yy378.b = yymsp[0].minor.yy408;}
101683
{yygotominor.yy90.a = TK_UPDATE; yygotominor.yy90.b = yymsp[0].minor.yy384;}
94843
        break;
101684
        break;
94844
      case 282: /* when_clause ::= */
101685
      case 281: /* when_clause ::= */
94845
      case 304: /* key_opt ::= */ yytestcase(yyruleno==304);
101686
      case 303: /* key_opt ::= */ yytestcase(yyruleno==303);
94846
{ yygotominor.yy132 = 0; }
101687
{ yygotominor.yy314 = 0; }
94847
        break;
101688
        break;
94848
      case 283: /* when_clause ::= WHEN expr */
101689
      case 282: /* when_clause ::= WHEN expr */
94849
      case 305: /* key_opt ::= KEY expr */ yytestcase(yyruleno==305);
101690
      case 304: /* key_opt ::= KEY expr */ yytestcase(yyruleno==304);
94850
{ yygotominor.yy132 = yymsp[0].minor.yy346.pExpr; }
101691
{ yygotominor.yy314 = yymsp[0].minor.yy118.pExpr; }
94851
        break;
101692
        break;
94852
      case 284: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
101693
      case 283: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
94853
{
101694
{
94854
  assert( yymsp[-2].minor.yy473!=0 );
101695
  assert( yymsp[-2].minor.yy203!=0 );
94855
  yymsp[-2].minor.yy473->pLast->pNext = yymsp[-1].minor.yy473;
101696
  yymsp[-2].minor.yy203->pLast->pNext = yymsp[-1].minor.yy203;
94856
  yymsp[-2].minor.yy473->pLast = yymsp[-1].minor.yy473;
101697
  yymsp[-2].minor.yy203->pLast = yymsp[-1].minor.yy203;
94857
  yygotominor.yy473 = yymsp[-2].minor.yy473;
101698
  yygotominor.yy203 = yymsp[-2].minor.yy203;
94858
}
101699
}
94859
        break;
101700
        break;
94860
      case 285: /* trigger_cmd_list ::= trigger_cmd SEMI */
101701
      case 284: /* trigger_cmd_list ::= trigger_cmd SEMI */
94861
{ 
101702
{ 
94862
  assert( yymsp[-1].minor.yy473!=0 );
101703
  assert( yymsp[-1].minor.yy203!=0 );
94863
  yymsp[-1].minor.yy473->pLast = yymsp[-1].minor.yy473;
101704
  yymsp[-1].minor.yy203->pLast = yymsp[-1].minor.yy203;
94864
  yygotominor.yy473 = yymsp[-1].minor.yy473;
101705
  yygotominor.yy203 = yymsp[-1].minor.yy203;
94865
}
101706
}
94866
        break;
101707
        break;
94867
      case 287: /* trnm ::= nm DOT nm */
101708
      case 286: /* trnm ::= nm DOT nm */
94868
{
101709
{
94869
  yygotominor.yy0 = yymsp[0].minor.yy0;
101710
  yygotominor.yy0 = yymsp[0].minor.yy0;
94870
  sqlite3ErrorMsg(pParse, 
101711
  sqlite3ErrorMsg(pParse, 
 Lines 94872-94992   static void yy_reduce( Link Here 
94872
        "statements within triggers");
101713
        "statements within triggers");
94873
}
101714
}
94874
        break;
101715
        break;
94875
      case 289: /* tridxby ::= INDEXED BY nm */
101716
      case 288: /* tridxby ::= INDEXED BY nm */
94876
{
101717
{
94877
  sqlite3ErrorMsg(pParse,
101718
  sqlite3ErrorMsg(pParse,
94878
        "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
101719
        "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
94879
        "within triggers");
101720
        "within triggers");
94880
}
101721
}
94881
        break;
101722
        break;
94882
      case 290: /* tridxby ::= NOT INDEXED */
101723
      case 289: /* tridxby ::= NOT INDEXED */
94883
{
101724
{
94884
  sqlite3ErrorMsg(pParse,
101725
  sqlite3ErrorMsg(pParse,
94885
        "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
101726
        "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
94886
        "within triggers");
101727
        "within triggers");
94887
}
101728
}
94888
        break;
101729
        break;
94889
      case 291: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
101730
      case 290: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
94890
{ yygotominor.yy473 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy14, yymsp[0].minor.yy132, yymsp[-5].minor.yy186); }
101731
{ yygotominor.yy203 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy322, yymsp[0].minor.yy314, yymsp[-5].minor.yy210); }
94891
        break;
101732
        break;
94892
      case 292: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP */
101733
      case 291: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP */
94893
{yygotominor.yy473 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy408, yymsp[-1].minor.yy14, 0, yymsp[-7].minor.yy186);}
101734
{yygotominor.yy203 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy384, yymsp[-1].minor.yy322, 0, yymsp[-7].minor.yy210);}
94894
        break;
101735
        break;
94895
      case 293: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
101736
      case 292: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
94896
{yygotominor.yy473 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy408, 0, yymsp[0].minor.yy3, yymsp[-4].minor.yy186);}
101737
{yygotominor.yy203 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy384, 0, yymsp[0].minor.yy387, yymsp[-4].minor.yy210);}
94897
        break;
101738
        break;
94898
      case 294: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
101739
      case 293: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
94899
{yygotominor.yy473 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy132);}
101740
{yygotominor.yy203 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy314);}
94900
        break;
101741
        break;
94901
      case 295: /* trigger_cmd ::= select */
101742
      case 294: /* trigger_cmd ::= select */
94902
{yygotominor.yy473 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy3); }
101743
{yygotominor.yy203 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy387); }
94903
        break;
101744
        break;
94904
      case 296: /* expr ::= RAISE LP IGNORE RP */
101745
      case 295: /* expr ::= RAISE LP IGNORE RP */
94905
{
101746
{
94906
  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0); 
101747
  yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0); 
94907
  if( yygotominor.yy346.pExpr ){
101748
  if( yygotominor.yy118.pExpr ){
94908
    yygotominor.yy346.pExpr->affinity = OE_Ignore;
101749
    yygotominor.yy118.pExpr->affinity = OE_Ignore;
94909
  }
101750
  }
94910
  yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
101751
  yygotominor.yy118.zStart = yymsp[-3].minor.yy0.z;
94911
  yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
101752
  yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
94912
}
101753
}
94913
        break;
101754
        break;
94914
      case 297: /* expr ::= RAISE LP raisetype COMMA nm RP */
101755
      case 296: /* expr ::= RAISE LP raisetype COMMA nm RP */
94915
{
101756
{
94916
  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0); 
101757
  yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0); 
94917
  if( yygotominor.yy346.pExpr ) {
101758
  if( yygotominor.yy118.pExpr ) {
94918
    yygotominor.yy346.pExpr->affinity = (char)yymsp[-3].minor.yy328;
101759
    yygotominor.yy118.pExpr->affinity = (char)yymsp[-3].minor.yy4;
94919
  }
101760
  }
94920
  yygotominor.yy346.zStart = yymsp[-5].minor.yy0.z;
101761
  yygotominor.yy118.zStart = yymsp[-5].minor.yy0.z;
94921
  yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
101762
  yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
94922
}
101763
}
94923
        break;
101764
        break;
94924
      case 298: /* raisetype ::= ROLLBACK */
101765
      case 297: /* raisetype ::= ROLLBACK */
94925
{yygotominor.yy328 = OE_Rollback;}
101766
{yygotominor.yy4 = OE_Rollback;}
94926
        break;
101767
        break;
94927
      case 300: /* raisetype ::= FAIL */
101768
      case 299: /* raisetype ::= FAIL */
94928
{yygotominor.yy328 = OE_Fail;}
101769
{yygotominor.yy4 = OE_Fail;}
94929
        break;
101770
        break;
94930
      case 301: /* cmd ::= DROP TRIGGER ifexists fullname */
101771
      case 300: /* cmd ::= DROP TRIGGER ifexists fullname */
94931
{
101772
{
94932
  sqlite3DropTrigger(pParse,yymsp[0].minor.yy65,yymsp[-1].minor.yy328);
101773
  sqlite3DropTrigger(pParse,yymsp[0].minor.yy259,yymsp[-1].minor.yy4);
94933
}
101774
}
94934
        break;
101775
        break;
94935
      case 302: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
101776
      case 301: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
94936
{
101777
{
94937
  sqlite3Attach(pParse, yymsp[-3].minor.yy346.pExpr, yymsp[-1].minor.yy346.pExpr, yymsp[0].minor.yy132);
101778
  sqlite3Attach(pParse, yymsp[-3].minor.yy118.pExpr, yymsp[-1].minor.yy118.pExpr, yymsp[0].minor.yy314);
94938
}
101779
}
94939
        break;
101780
        break;
94940
      case 303: /* cmd ::= DETACH database_kw_opt expr */
101781
      case 302: /* cmd ::= DETACH database_kw_opt expr */
94941
{
101782
{
94942
  sqlite3Detach(pParse, yymsp[0].minor.yy346.pExpr);
101783
  sqlite3Detach(pParse, yymsp[0].minor.yy118.pExpr);
94943
}
101784
}
94944
        break;
101785
        break;
94945
      case 308: /* cmd ::= REINDEX */
101786
      case 307: /* cmd ::= REINDEX */
94946
{sqlite3Reindex(pParse, 0, 0);}
101787
{sqlite3Reindex(pParse, 0, 0);}
94947
        break;
101788
        break;
94948
      case 309: /* cmd ::= REINDEX nm dbnm */
101789
      case 308: /* cmd ::= REINDEX nm dbnm */
94949
{sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
101790
{sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
94950
        break;
101791
        break;
94951
      case 310: /* cmd ::= ANALYZE */
101792
      case 309: /* cmd ::= ANALYZE */
94952
{sqlite3Analyze(pParse, 0, 0);}
101793
{sqlite3Analyze(pParse, 0, 0);}
94953
        break;
101794
        break;
94954
      case 311: /* cmd ::= ANALYZE nm dbnm */
101795
      case 310: /* cmd ::= ANALYZE nm dbnm */
94955
{sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
101796
{sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
94956
        break;
101797
        break;
94957
      case 312: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
101798
      case 311: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
94958
{
101799
{
94959
  sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy65,&yymsp[0].minor.yy0);
101800
  sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy259,&yymsp[0].minor.yy0);
94960
}
101801
}
94961
        break;
101802
        break;
94962
      case 313: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
101803
      case 312: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
94963
{
101804
{
94964
  sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
101805
  sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
94965
}
101806
}
94966
        break;
101807
        break;
94967
      case 314: /* add_column_fullname ::= fullname */
101808
      case 313: /* add_column_fullname ::= fullname */
94968
{
101809
{
94969
  pParse->db->lookaside.bEnabled = 0;
101810
  pParse->db->lookaside.bEnabled = 0;
94970
  sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy65);
101811
  sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy259);
94971
}
101812
}
94972
        break;
101813
        break;
94973
      case 317: /* cmd ::= create_vtab */
101814
      case 316: /* cmd ::= create_vtab */
94974
{sqlite3VtabFinishParse(pParse,0);}
101815
{sqlite3VtabFinishParse(pParse,0);}
94975
        break;
101816
        break;
94976
      case 318: /* cmd ::= create_vtab LP vtabarglist RP */
101817
      case 317: /* cmd ::= create_vtab LP vtabarglist RP */
94977
{sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
101818
{sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
94978
        break;
101819
        break;
94979
      case 319: /* create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm */
101820
      case 318: /* create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm */
94980
{
101821
{
94981
    sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
101822
    sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
94982
}
101823
}
94983
        break;
101824
        break;
94984
      case 322: /* vtabarg ::= */
101825
      case 321: /* vtabarg ::= */
94985
{sqlite3VtabArgInit(pParse);}
101826
{sqlite3VtabArgInit(pParse);}
94986
        break;
101827
        break;
94987
      case 324: /* vtabargtoken ::= ANY */
101828
      case 323: /* vtabargtoken ::= ANY */
94988
      case 325: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==325);
101829
      case 324: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==324);
94989
      case 326: /* lp ::= LP */ yytestcase(yyruleno==326);
101830
      case 325: /* lp ::= LP */ yytestcase(yyruleno==325);
94990
{sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
101831
{sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
94991
        break;
101832
        break;
94992
      default:
101833
      default:
 Lines 95015-95035   static void yy_reduce( Link Here 
95015
      /* (91) conslist ::= conslist tcons */ yytestcase(yyruleno==91);
101856
      /* (91) conslist ::= conslist tcons */ yytestcase(yyruleno==91);
95016
      /* (92) conslist ::= tcons */ yytestcase(yyruleno==92);
101857
      /* (92) conslist ::= tcons */ yytestcase(yyruleno==92);
95017
      /* (93) tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
101858
      /* (93) tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
95018
      /* (269) plus_opt ::= PLUS */ yytestcase(yyruleno==269);
101859
      /* (268) plus_opt ::= PLUS */ yytestcase(yyruleno==268);
95019
      /* (270) plus_opt ::= */ yytestcase(yyruleno==270);
101860
      /* (269) plus_opt ::= */ yytestcase(yyruleno==269);
95020
      /* (280) foreach_clause ::= */ yytestcase(yyruleno==280);
101861
      /* (279) foreach_clause ::= */ yytestcase(yyruleno==279);
95021
      /* (281) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==281);
101862
      /* (280) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==280);
95022
      /* (288) tridxby ::= */ yytestcase(yyruleno==288);
101863
      /* (287) tridxby ::= */ yytestcase(yyruleno==287);
95023
      /* (306) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==306);
101864
      /* (305) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==305);
95024
      /* (307) database_kw_opt ::= */ yytestcase(yyruleno==307);
101865
      /* (306) database_kw_opt ::= */ yytestcase(yyruleno==306);
95025
      /* (315) kwcolumn_opt ::= */ yytestcase(yyruleno==315);
101866
      /* (314) kwcolumn_opt ::= */ yytestcase(yyruleno==314);
95026
      /* (316) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==316);
101867
      /* (315) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==315);
95027
      /* (320) vtabarglist ::= vtabarg */ yytestcase(yyruleno==320);
101868
      /* (319) vtabarglist ::= vtabarg */ yytestcase(yyruleno==319);
95028
      /* (321) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==321);
101869
      /* (320) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==320);
95029
      /* (323) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==323);
101870
      /* (322) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==322);
95030
      /* (327) anylist ::= */ yytestcase(yyruleno==327);
101871
      /* (326) anylist ::= */ yytestcase(yyruleno==326);
95031
      /* (328) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==328);
101872
      /* (327) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==327);
95032
      /* (329) anylist ::= anylist ANY */ yytestcase(yyruleno==329);
101873
      /* (328) anylist ::= anylist ANY */ yytestcase(yyruleno==328);
95033
        break;
101874
        break;
95034
  };
101875
  };
95035
  yygoto = yyRuleInfo[yyruleno].lhs;
101876
  yygoto = yyRuleInfo[yyruleno].lhs;
 Lines 96057-96063   abort_parse: Link Here 
96057
  }
102898
  }
96058
#endif
102899
#endif
96059
#ifndef SQLITE_OMIT_VIRTUALTABLE
102900
#ifndef SQLITE_OMIT_VIRTUALTABLE
96060
  sqlite3DbFree(db, pParse->apVtabLock);
102901
  sqlite3_free(pParse->apVtabLock);
96061
#endif
102902
#endif
96062
102903
96063
  if( !IN_DECLARE_VTAB ){
102904
  if( !IN_DECLARE_VTAB ){
 Lines 96065-96071   abort_parse: Link Here 
96065
    ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
102906
    ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
96066
    ** will take responsibility for freeing the Table structure.
102907
    ** will take responsibility for freeing the Table structure.
96067
    */
102908
    */
96068
    sqlite3DeleteTable(pParse->pNewTable);
102909
    sqlite3DeleteTable(db, pParse->pNewTable);
96069
  }
102910
  }
96070
102911
96071
  sqlite3DeleteTrigger(db, pParse->pNewTrigger);
102912
  sqlite3DeleteTrigger(db, pParse->pNewTrigger);
 Lines 96079-96085   abort_parse: Link Here 
96079
  while( pParse->pZombieTab ){
102920
  while( pParse->pZombieTab ){
96080
    Table *p = pParse->pZombieTab;
102921
    Table *p = pParse->pZombieTab;
96081
    pParse->pZombieTab = p->pNextZombie;
102922
    pParse->pZombieTab = p->pNextZombie;
96082
    sqlite3DeleteTable(p);
102923
    sqlite3DeleteTable(db, p);
96083
  }
102924
  }
96084
  if( nErr>0 && pParse->rc==SQLITE_OK ){
102925
  if( nErr>0 && pParse->rc==SQLITE_OK ){
96085
    pParse->rc = SQLITE_ERROR;
102926
    pParse->rc = SQLITE_ERROR;
 Lines 97239-97245   SQLITE_PRIVATE const char *sqlite3ErrStr Link Here 
97239
    /* SQLITE_NOTFOUND    */ 0,
104080
    /* SQLITE_NOTFOUND    */ 0,
97240
    /* SQLITE_FULL        */ "database or disk is full",
104081
    /* SQLITE_FULL        */ "database or disk is full",
97241
    /* SQLITE_CANTOPEN    */ "unable to open database file",
104082
    /* SQLITE_CANTOPEN    */ "unable to open database file",
97242
    /* SQLITE_PROTOCOL    */ 0,
104083
    /* SQLITE_PROTOCOL    */ "locking protocol",
97243
    /* SQLITE_EMPTY       */ "table contains no data",
104084
    /* SQLITE_EMPTY       */ "table contains no data",
97244
    /* SQLITE_SCHEMA      */ "database schema has changed",
104085
    /* SQLITE_SCHEMA      */ "database schema has changed",
97245
    /* SQLITE_TOOBIG      */ "string or blob too big",
104086
    /* SQLITE_TOOBIG      */ "string or blob too big",
 Lines 97649-97654   SQLITE_API void *sqlite3_rollback_hook( Link Here 
97649
  return pRet;
104490
  return pRet;
97650
}
104491
}
97651
104492
104493
#ifndef SQLITE_OMIT_WAL
104494
/*
104495
** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
104496
** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
104497
** is greater than sqlite3.pWalArg cast to an integer (the value configured by
104498
** wal_autocheckpoint()).
104499
*/ 
104500
SQLITE_PRIVATE int sqlite3WalDefaultHook(
104501
  void *pClientData,     /* Argument */
104502
  sqlite3 *db,           /* Connection */
104503
  const char *zDb,       /* Database */
104504
  int nFrame             /* Size of WAL */
104505
){
104506
  if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
104507
    sqlite3BeginBenignMalloc();
104508
    sqlite3_wal_checkpoint(db, zDb);
104509
    sqlite3EndBenignMalloc();
104510
  }
104511
  return SQLITE_OK;
104512
}
104513
#endif /* SQLITE_OMIT_WAL */
104514
104515
/*
104516
** Configure an sqlite3_wal_hook() callback to automatically checkpoint
104517
** a database after committing a transaction if there are nFrame or
104518
** more frames in the log file. Passing zero or a negative value as the
104519
** nFrame parameter disables automatic checkpoints entirely.
104520
**
104521
** The callback registered by this function replaces any existing callback
104522
** registered using sqlite3_wal_hook(). Likewise, registering a callback
104523
** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
104524
** configured by this function.
104525
*/
104526
SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
104527
#ifndef SQLITE_OMIT_WAL
104528
  if( nFrame>0 ){
104529
    sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
104530
  }else{
104531
    sqlite3_wal_hook(db, 0, 0);
104532
  }
104533
#endif
104534
  return SQLITE_OK;
104535
}
104536
104537
/*
104538
** Register a callback to be invoked each time a transaction is written
104539
** into the write-ahead-log by this database connection.
104540
*/
104541
SQLITE_API void *sqlite3_wal_hook(
104542
  sqlite3 *db,                    /* Attach the hook to this db handle */
104543
  int(*xCallback)(void *, sqlite3*, const char*, int),
104544
  void *pArg                      /* First argument passed to xCallback() */
104545
){
104546
#ifndef SQLITE_OMIT_WAL
104547
  void *pRet;
104548
  sqlite3_mutex_enter(db->mutex);
104549
  pRet = db->pWalArg;
104550
  db->xWalCallback = xCallback;
104551
  db->pWalArg = pArg;
104552
  sqlite3_mutex_leave(db->mutex);
104553
  return pRet;
104554
#else
104555
  return 0;
104556
#endif
104557
}
104558
104559
104560
/*
104561
** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
104562
** to contains a zero-length string, all attached databases are 
104563
** checkpointed.
104564
*/
104565
SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
104566
#ifdef SQLITE_OMIT_WAL
104567
  return SQLITE_OK;
104568
#else
104569
  int rc;                         /* Return code */
104570
  int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
104571
104572
  sqlite3_mutex_enter(db->mutex);
104573
  if( zDb && zDb[0] ){
104574
    iDb = sqlite3FindDbName(db, zDb);
104575
  }
104576
  if( iDb<0 ){
104577
    rc = SQLITE_ERROR;
104578
    sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb);
104579
  }else{
104580
    rc = sqlite3Checkpoint(db, iDb);
104581
    sqlite3Error(db, rc, 0);
104582
  }
104583
  rc = sqlite3ApiExit(db, rc);
104584
  sqlite3_mutex_leave(db->mutex);
104585
  return rc;
104586
#endif
104587
}
104588
104589
#ifndef SQLITE_OMIT_WAL
104590
/*
104591
** Run a checkpoint on database iDb. This is a no-op if database iDb is
104592
** not currently open in WAL mode.
104593
**
104594
** If a transaction is open on the database being checkpointed, this 
104595
** function returns SQLITE_LOCKED and a checkpoint is not attempted. If 
104596
** an error occurs while running the checkpoint, an SQLite error code is 
104597
** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
104598
**
104599
** The mutex on database handle db should be held by the caller. The mutex
104600
** associated with the specific b-tree being checkpointed is taken by
104601
** this function while the checkpoint is running.
104602
**
104603
** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
104604
** checkpointed. If an error is encountered it is returned immediately -
104605
** no attempt is made to checkpoint any remaining databases.
104606
*/
104607
SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb){
104608
  int rc = SQLITE_OK;             /* Return code */
104609
  int i;                          /* Used to iterate through attached dbs */
104610
104611
  assert( sqlite3_mutex_held(db->mutex) );
104612
104613
  for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
104614
    if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
104615
      rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt);
104616
    }
104617
  }
104618
104619
  return rc;
104620
}
104621
#endif /* SQLITE_OMIT_WAL */
104622
97652
/*
104623
/*
97653
** This function returns true if main-memory should be used instead of
104624
** This function returns true if main-memory should be used instead of
97654
** a temporary file for transient pager files and statement journals.
104625
** a temporary file for transient pager files and statement journals.
 Lines 98071-98077   static int openDatabase( Link Here 
98071
  db->autoCommit = 1;
105042
  db->autoCommit = 1;
98072
  db->nextAutovac = -1;
105043
  db->nextAutovac = -1;
98073
  db->nextPagesize = 0;
105044
  db->nextPagesize = 0;
98074
  db->flags |= SQLITE_ShortColNames
105045
  db->flags |= SQLITE_ShortColNames | SQLITE_AutoIndex
98075
#if SQLITE_DEFAULT_FILE_FORMAT<4
105046
#if SQLITE_DEFAULT_FILE_FORMAT<4
98076
                 | SQLITE_LegacyFileFmt
105047
                 | SQLITE_LegacyFileFmt
98077
#endif
105048
#endif
 Lines 98209-98214   static int openDatabase( Link Here 
98209
  setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
105180
  setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
98210
                        sqlite3GlobalConfig.nLookaside);
105181
                        sqlite3GlobalConfig.nLookaside);
98211
105182
105183
  sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
105184
98212
opendb_out:
105185
opendb_out:
98213
  if( db ){
105186
  if( db ){
98214
    assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
105187
    assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
 Lines 98383-98389   SQLITE_API int sqlite3_collation_needed1 Link Here 
98383
}
105356
}
98384
#endif /* SQLITE_OMIT_UTF16 */
105357
#endif /* SQLITE_OMIT_UTF16 */
98385
105358
98386
#ifndef SQLITE_OMIT_GLOBALRECOVER
98387
#ifndef SQLITE_OMIT_DEPRECATED
105359
#ifndef SQLITE_OMIT_DEPRECATED
98388
/*
105360
/*
98389
** This function is now an anachronism. It used to be used to recover from a
105361
** This function is now an anachronism. It used to be used to recover from a
 Lines 98393-98399   SQLITE_API int sqlite3_global_recover(vo Link Here 
98393
  return SQLITE_OK;
105365
  return SQLITE_OK;
98394
}
105366
}
98395
#endif
105367
#endif
98396
#endif
98397
105368
98398
/*
105369
/*
98399
** Test to see whether or not the database connection is in autocommit
105370
** Test to see whether or not the database connection is in autocommit
 Lines 98421-98437   SQLITE_API int sqlite3_get_autocommit(sq Link Here 
98421
SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
105392
SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
98422
  testcase( sqlite3GlobalConfig.xLog!=0 );
105393
  testcase( sqlite3GlobalConfig.xLog!=0 );
98423
  sqlite3_log(SQLITE_CORRUPT,
105394
  sqlite3_log(SQLITE_CORRUPT,
98424
              "database corruption found by source line %d", lineno);
105395
              "database corruption at line %d of [%.10s]",
105396
              lineno, 20+sqlite3_sourceid());
98425
  return SQLITE_CORRUPT;
105397
  return SQLITE_CORRUPT;
98426
}
105398
}
98427
SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
105399
SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
98428
  testcase( sqlite3GlobalConfig.xLog!=0 );
105400
  testcase( sqlite3GlobalConfig.xLog!=0 );
98429
  sqlite3_log(SQLITE_MISUSE, "misuse detected by source line %d", lineno);
105401
  sqlite3_log(SQLITE_MISUSE, 
105402
              "misuse at line %d of [%.10s]",
105403
              lineno, 20+sqlite3_sourceid());
98430
  return SQLITE_MISUSE;
105404
  return SQLITE_MISUSE;
98431
}
105405
}
98432
SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
105406
SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
98433
  testcase( sqlite3GlobalConfig.xLog!=0 );
105407
  testcase( sqlite3GlobalConfig.xLog!=0 );
98434
  sqlite3_log(SQLITE_CANTOPEN, "cannot open file at source line %d", lineno);
105408
  sqlite3_log(SQLITE_CANTOPEN, 
105409
              "cannot open file at line %d of [%.10s]",
105410
              lineno, 20+sqlite3_sourceid());
98435
  return SQLITE_CANTOPEN;
105411
  return SQLITE_CANTOPEN;
98436
}
105412
}
98437
105413
 Lines 98703-98711   SQLITE_API int sqlite3_test_control(int Link Here 
98703
    ** dileterious behavior.
105679
    ** dileterious behavior.
98704
    */
105680
    */
98705
    case SQLITE_TESTCTRL_PENDING_BYTE: {
105681
    case SQLITE_TESTCTRL_PENDING_BYTE: {
98706
      unsigned int newVal = va_arg(ap, unsigned int);
105682
      rc = PENDING_BYTE;
98707
      rc = sqlite3PendingByte;
105683
#ifndef SQLITE_OMIT_WSD
98708
      if( newVal ) sqlite3PendingByte = newVal;
105684
      {
105685
        unsigned int newVal = va_arg(ap, unsigned int);
105686
        if( newVal ) sqlite3PendingByte = newVal;
105687
      }
105688
#endif
98709
      break;
105689
      break;
98710
    }
105690
    }
98711
105691
 Lines 98809-98814   SQLITE_API int sqlite3_test_control(int Link Here 
98809
    }
105789
    }
98810
#endif 
105790
#endif 
98811
105791
105792
    /* sqlite3_test_control(SQLITE_TESTCTRL_PGHDRSZ)
105793
    **
105794
    ** Return the size of a pcache header in bytes.
105795
    */
105796
    case SQLITE_TESTCTRL_PGHDRSZ: {
105797
      rc = sizeof(PgHdr);
105798
      break;
105799
    }
105800
98812
  }
105801
  }
98813
  va_end(ap);
105802
  va_end(ap);
98814
#endif /* SQLITE_OMIT_BUILTIN_TEST */
105803
#endif /* SQLITE_OMIT_BUILTIN_TEST */
 Lines 98974-98979   SQLITE_API int sqlite3_unlock_notify( Link Here 
98974
105963
98975
  if( xNotify==0 ){
105964
  if( xNotify==0 ){
98976
    removeFromBlockedList(db);
105965
    removeFromBlockedList(db);
105966
    db->pBlockingConnection = 0;
98977
    db->pUnlockConnection = 0;
105967
    db->pUnlockConnection = 0;
98978
    db->xUnlockNotify = 0;
105968
    db->xUnlockNotify = 0;
98979
    db->pUnlockArg = 0;
105969
    db->pUnlockArg = 0;
 Lines 99071-99077   SQLITE_PRIVATE void sqlite3ConnectionUnl Link Here 
99071
      assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
106061
      assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
99072
      assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
106062
      assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
99073
      if( (!aDyn && nArg==(int)ArraySize(aStatic))
106063
      if( (!aDyn && nArg==(int)ArraySize(aStatic))
99074
       || (aDyn && nArg==(int)(sqlite3DbMallocSize(db, aDyn)/sizeof(void*)))
106064
       || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
99075
      ){
106065
      ){
99076
        /* The aArg[] array needs to grow. */
106066
        /* The aArg[] array needs to grow. */
99077
        void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
106067
        void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
 Lines 99199-99205   SQLITE_PRIVATE void sqlite3ConnectionClo Link Here 
99199
** This is similar in concept to how sqlite encodes "varints" but
106189
** This is similar in concept to how sqlite encodes "varints" but
99200
** the encoding is not the same.  SQLite varints are big-endian
106190
** the encoding is not the same.  SQLite varints are big-endian
99201
** are are limited to 9 bytes in length whereas FTS3 varints are
106191
** are are limited to 9 bytes in length whereas FTS3 varints are
99202
** little-endian and can be upt to 10 bytes in length (in theory).
106192
** little-endian and can be up to 10 bytes in length (in theory).
99203
**
106193
**
99204
** Example encodings:
106194
** Example encodings:
99205
**
106195
**
 Lines 99210-99235   SQLITE_PRIVATE void sqlite3ConnectionClo Link Here 
99210
**
106200
**
99211
**** Document lists ****
106201
**** Document lists ****
99212
** A doclist (document list) holds a docid-sorted list of hits for a
106202
** A doclist (document list) holds a docid-sorted list of hits for a
99213
** given term.  Doclists hold docids, and can optionally associate
106203
** given term.  Doclists hold docids and associated token positions.
99214
** token positions and offsets with docids.  A position is the index
106204
** A docid is the unique integer identifier for a single document.
99215
** of a word within the document.  The first word of the document has
106205
** A position is the index of a word within the document.  The first 
99216
** a position of 0.
106206
** word of the document has a position of 0.
99217
**
106207
**
99218
** FTS3 used to optionally store character offsets using a compile-time
106208
** FTS3 used to optionally store character offsets using a compile-time
99219
** option.  But that functionality is no longer supported.
106209
** option.  But that functionality is no longer supported.
99220
**
106210
**
99221
** A DL_POSITIONS_OFFSETS doclist is stored like this:
106211
** A doclist is stored like this:
99222
**
106212
**
99223
** array {
106213
** array {
99224
**   varint docid;
106214
**   varint docid;
99225
**   array {                (position list for column 0)
106215
**   array {                (position list for column 0)
99226
**     varint position;     (delta from previous position plus POS_BASE)
106216
**     varint position;     (2 more than the delta from previous position)
99227
**   }
106217
**   }
99228
**   array {
106218
**   array {
99229
**     varint POS_COLUMN;   (marks start of position list for new column)
106219
**     varint POS_COLUMN;   (marks start of position list for new column)
99230
**     varint column;       (index of new column)
106220
**     varint column;       (index of new column)
99231
**     array {
106221
**     array {
99232
**       varint position;   (delta from previous position plus POS_BASE)
106222
**       varint position;   (2 more than the delta from previous position)
99233
**     }
106223
**     }
99234
**   }
106224
**   }
99235
**   varint POS_END;        (marks end of positions for this document.
106225
**   varint POS_END;        (marks end of positions for this document.
 Lines 99241-99247   SQLITE_PRIVATE void sqlite3ConnectionClo Link Here 
99241
** in the same logical place as the position element, and act as sentinals
106231
** in the same logical place as the position element, and act as sentinals
99242
** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
106232
** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
99243
** The positions numbers are not stored literally but rather as two more
106233
** The positions numbers are not stored literally but rather as two more
99244
** the difference from the prior position, or the just the position plus
106234
** than the difference from the prior position, or the just the position plus
99245
** 2 for the first position.  Example:
106235
** 2 for the first position.  Example:
99246
**
106236
**
99247
**   label:       A B C D E  F  G H   I  J K
106237
**   label:       A B C D E  F  G H   I  J K
 Lines 99255-99268   SQLITE_PRIVATE void sqlite3ConnectionClo Link Here 
99255
** 234 at I is the next docid.  It has one position 72 (72-2) and then
106245
** 234 at I is the next docid.  It has one position 72 (72-2) and then
99256
** terminates with the 0 at K.
106246
** terminates with the 0 at K.
99257
**
106247
**
99258
** A DL_POSITIONS doclist omits the startOffset and endOffset
106248
** A "position-list" is the list of positions for multiple columns for
99259
** information.  A DL_DOCIDS doclist omits both the position and
106249
** a single docid.  A "column-list" is the set of positions for a single
99260
** offset information, becoming an array of varint-encoded docids.
106250
** column.  Hence, a position-list consists of one or more column-lists,
99261
**
106251
** a document record consists of a docid followed by a position-list and
99262
** On-disk data is stored as type DL_DEFAULT, so we don't serialize
106252
** a doclist consists of one or more document records.
99263
** the type.  Due to how deletion is implemented in the segmentation
106253
**
99264
** system, on-disk doclists MUST store at least positions.
106254
** A bare doclist omits the position information, becoming an 
99265
**
106255
** array of varint-encoded docids.
99266
**
106256
**
99267
**** Segment leaf nodes ****
106257
**** Segment leaf nodes ****
99268
** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
106258
** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
 Lines 99777-99782   SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3 Link Here 
99777
#define FTS3_VARINT_MAX 10
106767
#define FTS3_VARINT_MAX 10
99778
106768
99779
/*
106769
/*
106770
** The testcase() macro is only used by the amalgamation.  If undefined,
106771
** make it a no-op.
106772
*/
106773
#ifndef testcase
106774
# define testcase(X)
106775
#endif
106776
106777
/*
106778
** Terminator values for position-lists and column-lists.
106779
*/
106780
#define POS_COLUMN  (1)     /* Column-list terminator */
106781
#define POS_END     (0)     /* Position-list terminator */ 
106782
106783
/*
99780
** This section provides definitions to allow the
106784
** This section provides definitions to allow the
99781
** FTS3 extension to be compiled outside of the 
106785
** FTS3 extension to be compiled outside of the 
99782
** amalgamation.
106786
** amalgamation.
 Lines 100087-100094   SQLITE_PRIVATE int sqlite3Fts3GetVarint3 Link Here 
100087
}
107091
}
100088
107092
100089
/*
107093
/*
100090
** Return the number of bytes required to store the value passed as the
107094
** Return the number of bytes required to encode v as a varint
100091
** first argument in varint form.
100092
*/
107095
*/
100093
SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
107096
SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
100094
  int i = 0;
107097
  int i = 0;
 Lines 100139-100145   SQLITE_PRIVATE void sqlite3Fts3Dequote(c Link Here 
100139
107142
100140
/*
107143
/*
100141
** Read a single varint from the doclist at *pp and advance *pp to point
107144
** Read a single varint from the doclist at *pp and advance *pp to point
100142
** to the next element of the varlist.  Add the value of the varint
107145
** to the first byte past the end of the varint.  Add the value of the varint
100143
** to *pVal.
107146
** to *pVal.
100144
*/
107147
*/
100145
static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
107148
static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
 Lines 100195-100201   static int fts3DisconnectMethod(sqlite3_ Link Here 
100195
**
107198
**
100196
** If *pRc is initially non-zero then this routine is a no-op.
107199
** If *pRc is initially non-zero then this routine is a no-op.
100197
*/
107200
*/
100198
void fts3DbExec(
107201
static void fts3DbExec(
100199
  int *pRc,              /* Success code */
107202
  int *pRc,              /* Success code */
100200
  sqlite3 *db,           /* Database in which to run SQL */
107203
  sqlite3 *db,           /* Database in which to run SQL */
100201
  const char *zFormat,   /* Format string for SQL */
107204
  const char *zFormat,   /* Format string for SQL */
 Lines 100275-100280   static int fts3DeclareVtab(Fts3Table *p) Link Here 
100275
** Create the backing store tables (%_content, %_segments and %_segdir)
107278
** Create the backing store tables (%_content, %_segments and %_segdir)
100276
** required by the FTS3 table passed as the only argument. This is done
107279
** required by the FTS3 table passed as the only argument. This is done
100277
** as part of the vtab xCreate() method.
107280
** as part of the vtab xCreate() method.
107281
**
107282
** If the p->bHasDocsize boolean is true (indicating that this is an
107283
** FTS4 table, not an FTS3 table) then also create the %_docsize and
107284
** %_stat tables required by FTS4.
100278
*/
107285
*/
100279
static int fts3CreateTables(Fts3Table *p){
107286
static int fts3CreateTables(Fts3Table *p){
100280
  int rc = SQLITE_OK;             /* Return code */
107287
  int rc = SQLITE_OK;             /* Return code */
 Lines 100332-100337   static int fts3CreateTables(Fts3Table *p Link Here 
100332
** An sqlite3_exec() callback for fts3TableExists.
107339
** An sqlite3_exec() callback for fts3TableExists.
100333
*/
107340
*/
100334
static int fts3TableExistsCallback(void *pArg, int n, char **pp1, char **pp2){
107341
static int fts3TableExistsCallback(void *pArg, int n, char **pp1, char **pp2){
107342
  UNUSED_PARAMETER(n);
107343
  UNUSED_PARAMETER(pp1);
107344
  UNUSED_PARAMETER(pp2);
100335
  *(int*)pArg = 1;
107345
  *(int*)pArg = 1;
100336
  return 1;
107346
  return 1;
100337
}
107347
}
 Lines 100357-100363   static void fts3TableExists( Link Here 
100357
  );    
107367
  );    
100358
  rc = sqlite3_exec(db, zSql, fts3TableExistsCallback, &res, 0);
107368
  rc = sqlite3_exec(db, zSql, fts3TableExistsCallback, &res, 0);
100359
  sqlite3_free(zSql);
107369
  sqlite3_free(zSql);
100360
  *pResult = res & 0xff;
107370
  *pResult = (u8)(res & 0xff);
100361
  if( rc!=SQLITE_ABORT ) *pRc = rc;
107371
  if( rc!=SQLITE_ABORT ) *pRc = rc;
100362
}
107372
}
100363
107373
 Lines 100367-100373   static void fts3TableExists( Link Here 
100367
**
107377
**
100368
** The argv[] array contains the following:
107378
** The argv[] array contains the following:
100369
**
107379
**
100370
**   argv[0]   -> module name
107380
**   argv[0]   -> module name  ("fts3" or "fts4")
100371
**   argv[1]   -> database name
107381
**   argv[1]   -> database name
100372
**   argv[2]   -> table name
107382
**   argv[2]   -> table name
100373
**   argv[...] -> "column name" and other module argument fields.
107383
**   argv[...] -> "column name" and other module argument fields.
 Lines 100386-100397   static int fts3InitVtab( Link Here 
100386
  int rc;                         /* Return code */
107396
  int rc;                         /* Return code */
100387
  int i;                          /* Iterator variable */
107397
  int i;                          /* Iterator variable */
100388
  int nByte;                      /* Size of allocation used for *p */
107398
  int nByte;                      /* Size of allocation used for *p */
100389
  int iCol;
107399
  int iCol;                       /* Column index */
100390
  int nString = 0;
107400
  int nString = 0;                /* Bytes required to hold all column names */
100391
  int nCol = 0;
107401
  int nCol = 0;                   /* Number of columns in the FTS table */
100392
  char *zCsr;
107402
  char *zCsr;                     /* Space for holding column names */
100393
  int nDb;
107403
  int nDb;                        /* Bytes required to hold database name */
100394
  int nName;
107404
  int nName;                      /* Bytes required to hold table name */
100395
107405
100396
  const char *zTokenizer = 0;               /* Name of tokenizer to use */
107406
  const char *zTokenizer = 0;               /* Name of tokenizer to use */
100397
  sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
107407
  sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
 Lines 100621-100626   static int fulltextClose(sqlite3_vtab_cu Link Here 
100621
  return SQLITE_OK;
107631
  return SQLITE_OK;
100622
}
107632
}
100623
107633
107634
/*
107635
** Position the pCsr->pStmt statement so that it is on the row
107636
** of the %_content table that contains the last match.  Return
107637
** SQLITE_OK on success.  
107638
*/
100624
static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
107639
static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
100625
  if( pCsr->isRequireSeek ){
107640
  if( pCsr->isRequireSeek ){
100626
    pCsr->isRequireSeek = 0;
107641
    pCsr->isRequireSeek = 0;
 Lines 100647-100652   static int fts3CursorSeek(sqlite3_contex Link Here 
100647
  }
107662
  }
100648
}
107663
}
100649
107664
107665
/*
107666
** Advance the cursor to the next row in the %_content table that
107667
** matches the search criteria.  For a MATCH search, this will be
107668
** the next row that matches.  For a full-table scan, this will be
107669
** simply the next row in the %_content table.  For a docid lookup,
107670
** this routine simply sets the EOF flag.
107671
**
107672
** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
107673
** even if we reach end-of-file.  The fts3EofMethod() will be called
107674
** subsequently to determine whether or not an EOF was hit.
107675
*/
100650
static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
107676
static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
100651
  int rc = SQLITE_OK;             /* Return code */
107677
  int rc = SQLITE_OK;             /* Return code */
100652
  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
107678
  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
 Lines 100783-100788   static void fts3PutDeltaVarint( Link Here 
100783
** start of a position-list. After it returns, *ppPoslist points to the
107809
** start of a position-list. After it returns, *ppPoslist points to the
100784
** first byte after the position-list.
107810
** first byte after the position-list.
100785
**
107811
**
107812
** A position list is list of positions (delta encoded) and columns for 
107813
** a single document record of a doclist.  So, in other words, this
107814
** routine advances *ppPoslist so that it points to the next docid in
107815
** the doclist, or to the first byte past the end of the doclist.
107816
**
100786
** If pp is not NULL, then the contents of the position list are copied
107817
** If pp is not NULL, then the contents of the position list are copied
100787
** to *pp. *pp is set to point to the first byte past the last byte copied
107818
** to *pp. *pp is set to point to the first byte past the last byte copied
100788
** before this function returns.
107819
** before this function returns.
 Lines 100792-100808   static void fts3PoslistCopy(char **pp, c Link Here 
100792
  char c = 0;
107823
  char c = 0;
100793
107824
100794
  /* The end of a position list is marked by a zero encoded as an FTS3 
107825
  /* The end of a position list is marked by a zero encoded as an FTS3 
100795
  ** varint. A single 0x00 byte. Except, if the 0x00 byte is preceded by
107826
  ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
100796
  ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
107827
  ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
100797
  ** of some other, multi-byte, value.
107828
  ** of some other, multi-byte, value.
100798
  **
107829
  **
100799
  ** The following block moves pEnd to point to the first byte that is not 
107830
  ** The following while-loop moves pEnd to point to the first byte that is not 
100800
  ** immediately preceded by a byte with the 0x80 bit set. Then increments
107831
  ** immediately preceded by a byte with the 0x80 bit set. Then increments
100801
  ** pEnd once more so that it points to the byte immediately following the
107832
  ** pEnd once more so that it points to the byte immediately following the
100802
  ** last byte in the position-list.
107833
  ** last byte in the position-list.
100803
  */
107834
  */
100804
  while( *pEnd | c ) c = *pEnd++ & 0x80;
107835
  while( *pEnd | c ){
100805
  pEnd++;
107836
    c = *pEnd++ & 0x80;
107837
    testcase( c!=0 && (*pEnd)==0 );
107838
  }
107839
  pEnd++;  /* Advance past the POS_END terminator byte */
100806
107840
100807
  if( pp ){
107841
  if( pp ){
100808
    int n = (int)(pEnd - *ppPoslist);
107842
    int n = (int)(pEnd - *ppPoslist);
 Lines 100814-100825   static void fts3PoslistCopy(char **pp, c Link Here 
100814
  *ppPoslist = pEnd;
107848
  *ppPoslist = pEnd;
100815
}
107849
}
100816
107850
107851
/*
107852
** When this function is called, *ppPoslist is assumed to point to the 
107853
** start of a column-list. After it returns, *ppPoslist points to the
107854
** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
107855
**
107856
** A column-list is list of delta-encoded positions for a single column
107857
** within a single document within a doclist.
107858
**
107859
** The column-list is terminated either by a POS_COLUMN varint (1) or
107860
** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
107861
** the POS_COLUMN or POS_END that terminates the column-list.
107862
**
107863
** If pp is not NULL, then the contents of the column-list are copied
107864
** to *pp. *pp is set to point to the first byte past the last byte copied
107865
** before this function returns.  The POS_COLUMN or POS_END terminator
107866
** is not copied into *pp.
107867
*/
100817
static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
107868
static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
100818
  char *pEnd = *ppPoslist;
107869
  char *pEnd = *ppPoslist;
100819
  char c = 0;
107870
  char c = 0;
100820
107871
100821
  /* A column-list is terminated by either a 0x01 or 0x00. */
107872
  /* A column-list is terminated by either a 0x01 or 0x00 byte that is
100822
  while( 0xFE & (*pEnd | c) ) c = *pEnd++ & 0x80;
107873
  ** not part of a multi-byte varint.
107874
  */
107875
  while( 0xFE & (*pEnd | c) ){
107876
    c = *pEnd++ & 0x80;
107877
    testcase( c!=0 && ((*pEnd)&0xfe)==0 );
107878
  }
100823
  if( pp ){
107879
  if( pp ){
100824
    int n = (int)(pEnd - *ppPoslist);
107880
    int n = (int)(pEnd - *ppPoslist);
100825
    char *p = *pp;
107881
    char *p = *pp;
 Lines 100831-100867   static void fts3ColumnlistCopy(char **pp Link Here 
100831
}
107887
}
100832
107888
100833
/*
107889
/*
100834
** Value used to signify the end of an offset-list. This is safe because
107890
** Value used to signify the end of an position-list. This is safe because
100835
** it is not possible to have a document with 2^31 terms.
107891
** it is not possible to have a document with 2^31 terms.
100836
*/
107892
*/
100837
#define OFFSET_LIST_END 0x7fffffff
107893
#define POSITION_LIST_END 0x7fffffff
100838
107894
100839
/*
107895
/*
100840
** This function is used to help parse offset-lists. When this function is
107896
** This function is used to help parse position-lists. When this function is
100841
** called, *pp may point to the start of the next varint in the offset-list
107897
** called, *pp may point to the start of the next varint in the position-list
100842
** being parsed, or it may point to 1 byte past the end of the offset-list
107898
** being parsed, or it may point to 1 byte past the end of the position-list
100843
** (in which case **pp will be 0x00 or 0x01).
107899
** (in which case **pp will be a terminator bytes POS_END (0) or
100844
**
107900
** (1)).
100845
** If *pp points past the end of the current offset list, set *pi to 
107901
**
100846
** OFFSET_LIST_END and return. Otherwise, read the next varint from *pp,
107902
** If *pp points past the end of the current position-list, set *pi to 
107903
** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
100847
** increment the current value of *pi by the value read, and set *pp to
107904
** increment the current value of *pi by the value read, and set *pp to
100848
** point to the next value before returning.
107905
** point to the next value before returning.
107906
**
107907
** Before calling this routine *pi must be initialized to the value of
107908
** the previous position, or zero if we are reading the first position
107909
** in the position-list.  Because positions are delta-encoded, the value
107910
** of the previous position is needed in order to compute the value of
107911
** the next position.
100849
*/
107912
*/
100850
static void fts3ReadNextPos(
107913
static void fts3ReadNextPos(
100851
  char **pp,                      /* IN/OUT: Pointer into offset-list buffer */
107914
  char **pp,                    /* IN/OUT: Pointer into position-list buffer */
100852
  sqlite3_int64 *pi               /* IN/OUT: Value read from offset-list */
107915
  sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */
100853
){
107916
){
100854
  if( **pp&0xFE ){
107917
  if( (**pp)&0xFE ){
100855
    fts3GetDeltaVarint(pp, pi);
107918
    fts3GetDeltaVarint(pp, pi);
100856
    *pi -= 2;
107919
    *pi -= 2;
100857
  }else{
107920
  }else{
100858
    *pi = OFFSET_LIST_END;
107921
    *pi = POSITION_LIST_END;
100859
  }
107922
  }
100860
}
107923
}
100861
107924
100862
/*
107925
/*
100863
** If parameter iCol is not 0, write an 0x01 byte followed by the value of
107926
** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
100864
** iCol encoded as a varint to *pp. 
107927
** the value of iCol encoded as a varint to *pp.   This will start a new
107928
** column list.
100865
**
107929
**
100866
** Set *pp to point to the byte just after the last byte written before 
107930
** Set *pp to point to the byte just after the last byte written before 
100867
** returning (do not modify it if iCol==0). Return the total number of bytes
107931
** returning (do not modify it if iCol==0). Return the total number of bytes
 Lines 100879-100885   static int fts3PutColNumber(char **pp, i Link Here 
100879
}
107943
}
100880
107944
100881
/*
107945
/*
100882
**
107946
** Compute the union of two position lists.  The output written
107947
** into *pp contains all positions of both *pp1 and *pp2 in sorted
107948
** order and with any duplicates removed.  All pointers are
107949
** updated appropriately.   The caller is responsible for insuring
107950
** that there is enough space in *pp to hold the complete output.
100883
*/
107951
*/
100884
static void fts3PoslistMerge(
107952
static void fts3PoslistMerge(
100885
  char **pp,                      /* Output buffer */
107953
  char **pp,                      /* Output buffer */
 Lines 100891-100922   static void fts3PoslistMerge( Link Here 
100891
  char *p2 = *pp2;
107959
  char *p2 = *pp2;
100892
107960
100893
  while( *p1 || *p2 ){
107961
  while( *p1 || *p2 ){
100894
    int iCol1;
107962
    int iCol1;         /* The current column index in pp1 */
100895
    int iCol2;
107963
    int iCol2;         /* The current column index in pp2 */
100896
107964
100897
    if( *p1==0x01 ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);
107965
    if( *p1==POS_COLUMN ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);
100898
    else if( *p1==0x00 ) iCol1 = OFFSET_LIST_END;
107966
    else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
100899
    else iCol1 = 0;
107967
    else iCol1 = 0;
100900
107968
100901
    if( *p2==0x01 ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);
107969
    if( *p2==POS_COLUMN ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);
100902
    else if( *p2==0x00 ) iCol2 = OFFSET_LIST_END;
107970
    else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
100903
    else iCol2 = 0;
107971
    else iCol2 = 0;
100904
107972
100905
    if( iCol1==iCol2 ){
107973
    if( iCol1==iCol2 ){
100906
      sqlite3_int64 i1 = 0;
107974
      sqlite3_int64 i1 = 0;       /* Last position from pp1 */
100907
      sqlite3_int64 i2 = 0;
107975
      sqlite3_int64 i2 = 0;       /* Last position from pp2 */
100908
      sqlite3_int64 iPrev = 0;
107976
      sqlite3_int64 iPrev = 0;
100909
      int n = fts3PutColNumber(&p, iCol1);
107977
      int n = fts3PutColNumber(&p, iCol1);
100910
      p1 += n;
107978
      p1 += n;
100911
      p2 += n;
107979
      p2 += n;
100912
107980
100913
      /* At this point, both p1 and p2 point to the start of offset-lists.
107981
      /* At this point, both p1 and p2 point to the start of column-lists
100914
      ** An offset-list is a list of non-negative delta-encoded varints, each 
107982
      ** for the same column (the column with index iCol1 and iCol2).
100915
      ** incremented by 2 before being stored. Each list is terminated by a 0 
107983
      ** A column-list is a list of non-negative delta-encoded varints, each 
100916
      ** or 1 value (0x00 or 0x01). The following block merges the two lists
107984
      ** incremented by 2 before being stored. Each list is terminated by a
107985
      ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
100917
      ** and writes the results to buffer p. p is left pointing to the byte
107986
      ** and writes the results to buffer p. p is left pointing to the byte
100918
      ** after the list written. No terminator (0x00 or 0x01) is written to
107987
      ** after the list written. No terminator (POS_END or POS_COLUMN) is
100919
      ** the output.
107988
      ** written to the output.
100920
      */
107989
      */
100921
      fts3GetDeltaVarint(&p1, &i1);
107990
      fts3GetDeltaVarint(&p1, &i1);
100922
      fts3GetDeltaVarint(&p2, &i2);
107991
      fts3GetDeltaVarint(&p2, &i2);
 Lines 100931-100937   static void fts3PoslistMerge( Link Here 
100931
        }else{
108000
        }else{
100932
          fts3ReadNextPos(&p2, &i2);
108001
          fts3ReadNextPos(&p2, &i2);
100933
        }
108002
        }
100934
      }while( i1!=OFFSET_LIST_END || i2!=OFFSET_LIST_END );
108003
      }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
100935
    }else if( iCol1<iCol2 ){
108004
    }else if( iCol1<iCol2 ){
100936
      p1 += fts3PutColNumber(&p, iCol1);
108005
      p1 += fts3PutColNumber(&p, iCol1);
100937
      fts3ColumnlistCopy(&p, &p1);
108006
      fts3ColumnlistCopy(&p, &p1);
 Lines 100941-100947   static void fts3PoslistMerge( Link Here 
100941
    }
108010
    }
100942
  }
108011
  }
100943
108012
100944
  *p++ = '\0';
108013
  *p++ = POS_END;
100945
  *pp = p;
108014
  *pp = p;
100946
  *pp1 = p1 + 1;
108015
  *pp1 = p1 + 1;
100947
  *pp2 = p2 + 1;
108016
  *pp2 = p2 + 1;
 Lines 100964-100974   static int fts3PoslistPhraseMerge( Link Here 
100964
  int iCol1 = 0;
108033
  int iCol1 = 0;
100965
  int iCol2 = 0;
108034
  int iCol2 = 0;
100966
  assert( *p1!=0 && *p2!=0 );
108035
  assert( *p1!=0 && *p2!=0 );
100967
  if( *p1==0x01 ){ 
108036
  if( *p1==POS_COLUMN ){ 
100968
    p1++;
108037
    p1++;
100969
    p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
108038
    p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
100970
  }
108039
  }
100971
  if( *p2==0x01 ){ 
108040
  if( *p2==POS_COLUMN ){ 
100972
    p2++;
108041
    p2++;
100973
    p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
108042
    p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
100974
  }
108043
  }
 Lines 100981-100991   static int fts3PoslistPhraseMerge( Link Here 
100981
      sqlite3_int64 iPos2 = 0;
108050
      sqlite3_int64 iPos2 = 0;
100982
108051
100983
      if( pp && iCol1 ){
108052
      if( pp && iCol1 ){
100984
        *p++ = 0x01;
108053
        *p++ = POS_COLUMN;
100985
        p += sqlite3Fts3PutVarint(p, iCol1);
108054
        p += sqlite3Fts3PutVarint(p, iCol1);
100986
      }
108055
      }
100987
108056
100988
      assert( *p1!=0x00 && *p2!=0x00 && *p1!=0x01 && *p2!=0x01 );
108057
      assert( *p1!=POS_END && *p1!=POS_COLUMN );
108058
      assert( *p2!=POS_END && *p2!=POS_COLUMN );
100989
      fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
108059
      fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
100990
      fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
108060
      fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
100991
108061
 Lines 101237-101242   static int fts3DoclistMerge( Link Here 
101237
    default: assert( mergetype==MERGE_POS_NEAR || mergetype==MERGE_NEAR ); {
108307
    default: assert( mergetype==MERGE_POS_NEAR || mergetype==MERGE_NEAR ); {
101238
      char *aTmp = 0;
108308
      char *aTmp = 0;
101239
      char **ppPos = 0;
108309
      char **ppPos = 0;
108310
101240
      if( mergetype==MERGE_POS_NEAR ){
108311
      if( mergetype==MERGE_POS_NEAR ){
101241
        ppPos = &p;
108312
        ppPos = &p;
101242
        aTmp = sqlite3_malloc(2*(n1+n2+1));
108313
        aTmp = sqlite3_malloc(2*(n1+n2+1));
 Lines 101282-101290   static int fts3DoclistMerge( Link Here 
101282
typedef struct TermSelect TermSelect;
108353
typedef struct TermSelect TermSelect;
101283
struct TermSelect {
108354
struct TermSelect {
101284
  int isReqPos;
108355
  int isReqPos;
101285
  char *aOutput;                  /* Malloc'd output buffer */
108356
  char *aaOutput[16];             /* Malloc'd output buffer */
101286
  int nOutput;                    /* Size of output in bytes */
108357
  int anOutput[16];               /* Size of output in bytes */
101287
};
108358
};
108359
108360
/*
108361
** Merge all doclists in the TermSelect.aaOutput[] array into a single
108362
** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
108363
** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
108364
**
108365
** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
108366
** the responsibility of the caller to free any doclists left in the
108367
** TermSelect.aaOutput[] array.
108368
*/
108369
static int fts3TermSelectMerge(TermSelect *pTS){
108370
  int mergetype = (pTS->isReqPos ? MERGE_POS_OR : MERGE_OR);
108371
  char *aOut = 0;
108372
  int nOut = 0;
108373
  int i;
108374
108375
  /* Loop through the doclists in the aaOutput[] array. Merge them all
108376
  ** into a single doclist.
108377
  */
108378
  for(i=0; i<SizeofArray(pTS->aaOutput); i++){
108379
    if( pTS->aaOutput[i] ){
108380
      if( !aOut ){
108381
        aOut = pTS->aaOutput[i];
108382
        nOut = pTS->anOutput[i];
108383
        pTS->aaOutput[0] = 0;
108384
      }else{
108385
        int nNew = nOut + pTS->anOutput[i];
108386
        char *aNew = sqlite3_malloc(nNew);
108387
        if( !aNew ){
108388
          sqlite3_free(aOut);
108389
          return SQLITE_NOMEM;
108390
        }
108391
        fts3DoclistMerge(mergetype, 0, 0,
108392
            aNew, &nNew, pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut
108393
        );
108394
        sqlite3_free(pTS->aaOutput[i]);
108395
        sqlite3_free(aOut);
108396
        pTS->aaOutput[i] = 0;
108397
        aOut = aNew;
108398
        nOut = nNew;
108399
      }
108400
    }
108401
  }
108402
108403
  pTS->aaOutput[0] = aOut;
108404
  pTS->anOutput[0] = nOut;
108405
  return SQLITE_OK;
108406
}
101288
108407
101289
/*
108408
/*
101290
** This function is used as the sqlite3Fts3SegReaderIterate() callback when
108409
** This function is used as the sqlite3Fts3SegReaderIterate() callback when
 Lines 101300-101337   static int fts3TermSelectCb( Link Here 
101300
  int nDoclist
108419
  int nDoclist
101301
){
108420
){
101302
  TermSelect *pTS = (TermSelect *)pContext;
108421
  TermSelect *pTS = (TermSelect *)pContext;
101303
  int nNew = pTS->nOutput + nDoclist;
101304
  char *aNew = sqlite3_malloc(nNew);
101305
108422
101306
  UNUSED_PARAMETER(p);
108423
  UNUSED_PARAMETER(p);
101307
  UNUSED_PARAMETER(zTerm);
108424
  UNUSED_PARAMETER(zTerm);
101308
  UNUSED_PARAMETER(nTerm);
108425
  UNUSED_PARAMETER(nTerm);
101309
108426
101310
  if( !aNew ){
108427
  if( pTS->aaOutput[0]==0 ){
101311
    return SQLITE_NOMEM;
101312
  }
101313
101314
  if( pTS->nOutput==0 ){
101315
    /* If this is the first term selected, copy the doclist to the output
108428
    /* If this is the first term selected, copy the doclist to the output
101316
    ** buffer using memcpy(). TODO: Add a way to transfer control of the
108429
    ** buffer using memcpy(). TODO: Add a way to transfer control of the
101317
    ** aDoclist buffer from the caller so as to avoid the memcpy().
108430
    ** aDoclist buffer from the caller so as to avoid the memcpy().
101318
    */
108431
    */
101319
    memcpy(aNew, aDoclist, nDoclist);
108432
    pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
101320
  }else{
108433
    pTS->anOutput[0] = nDoclist;
101321
    /* The output buffer is not empty. Merge doclist aDoclist with the
108434
    if( pTS->aaOutput[0] ){
101322
    ** existing output. This can only happen with prefix-searches (as
108435
      memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
101323
    ** searches for exact terms return exactly one doclist).
108436
    }else{
101324
    */
108437
      return SQLITE_NOMEM;
108438
    }
108439
  }else{
101325
    int mergetype = (pTS->isReqPos ? MERGE_POS_OR : MERGE_OR);
108440
    int mergetype = (pTS->isReqPos ? MERGE_POS_OR : MERGE_OR);
101326
    fts3DoclistMerge(mergetype, 0, 0,
108441
    char *aMerge = aDoclist;
101327
        aNew, &nNew, pTS->aOutput, pTS->nOutput, aDoclist, nDoclist
108442
    int nMerge = nDoclist;
101328
    );
108443
    int iOut;
101329
  }
108444
101330
108445
    for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
101331
  sqlite3_free(pTS->aOutput);
108446
      char *aNew;
101332
  pTS->aOutput = aNew;
108447
      int nNew;
101333
  pTS->nOutput = nNew;
108448
      if( pTS->aaOutput[iOut]==0 ){
101334
108449
        assert( iOut>0 );
108450
        pTS->aaOutput[iOut] = aMerge;
108451
        pTS->anOutput[iOut] = nMerge;
108452
        break;
108453
      }
108454
108455
      nNew = nMerge + pTS->anOutput[iOut];
108456
      aNew = sqlite3_malloc(nNew);
108457
      if( !aNew ){
108458
        if( aMerge!=aDoclist ){
108459
          sqlite3_free(aMerge);
108460
        }
108461
        return SQLITE_NOMEM;
108462
      }
108463
      fts3DoclistMerge(mergetype, 0, 0,
108464
          aNew, &nNew, pTS->aaOutput[iOut], pTS->anOutput[iOut], aMerge, nMerge
108465
      );
108466
108467
      if( iOut>0 ) sqlite3_free(aMerge);
108468
      sqlite3_free(pTS->aaOutput[iOut]);
108469
      pTS->aaOutput[iOut] = 0;
108470
108471
      aMerge = aNew;
108472
      nMerge = nNew;
108473
      if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
108474
        pTS->aaOutput[iOut] = aMerge;
108475
        pTS->anOutput[iOut] = nMerge;
108476
      }
108477
    }
108478
  }
101335
  return SQLITE_OK;
108479
  return SQLITE_OK;
101336
}
108480
}
101337
108481
 Lines 101341-101349   static int fts3TermSelectCb( Link Here 
101341
**
108485
**
101342
** The returned doclist may be in one of two formats, depending on the 
108486
** The returned doclist may be in one of two formats, depending on the 
101343
** value of parameter isReqPos. If isReqPos is zero, then the doclist is
108487
** value of parameter isReqPos. If isReqPos is zero, then the doclist is
101344
** a sorted list of delta-compressed docids. If isReqPos is non-zero, 
108488
** a sorted list of delta-compressed docids (a bare doclist). If isReqPos
101345
** then the returned list is in the same format as is stored in the
108489
** is non-zero, then the returned list is in the same format as is stored 
101346
** database without the found length specifier at the start of on-disk
108490
** in the database without the found length specifier at the start of on-disk
101347
** doclists.
108491
** doclists.
101348
*/
108492
*/
101349
static int fts3TermSelect(
108493
static int fts3TermSelect(
 Lines 101455-101466   static int fts3TermSelect( Link Here 
101455
  rc = sqlite3Fts3SegReaderIterate(p, apSegment, nSegment, &filter,
108599
  rc = sqlite3Fts3SegReaderIterate(p, apSegment, nSegment, &filter,
101456
      fts3TermSelectCb, (void *)&tsc
108600
      fts3TermSelectCb, (void *)&tsc
101457
  );
108601
  );
101458
101459
  if( rc==SQLITE_OK ){
108602
  if( rc==SQLITE_OK ){
101460
    *ppOut = tsc.aOutput;
108603
    rc = fts3TermSelectMerge(&tsc);
101461
    *pnOut = tsc.nOutput;
108604
  }
101462
  }else{
108605
101463
    sqlite3_free(tsc.aOutput);
108606
  if( rc==SQLITE_OK ){
108607
    *ppOut = tsc.aaOutput[0];
108608
    *pnOut = tsc.anOutput[0];
108609
  }else{
108610
    for(i=0; i<SizeofArray(tsc.aaOutput); i++){
108611
      sqlite3_free(tsc.aaOutput[i]);
108612
    }
101464
  }
108613
  }
101465
108614
101466
finished:
108615
finished:
 Lines 101603-101609   SQLITE_PRIVATE int sqlite3Fts3ExprNearTr Link Here 
101603
108752
101604
/*
108753
/*
101605
** Evaluate the full-text expression pExpr against fts3 table pTab. Store
108754
** Evaluate the full-text expression pExpr against fts3 table pTab. Store
101606
** the resulting doclist in *paOut and *pnOut.
108755
** the resulting doclist in *paOut and *pnOut.  This routine mallocs for
108756
** the space needed to store the output.  The caller is responsible for
108757
** freeing the space when it has finished.
101607
*/
108758
*/
101608
static int evalFts3Expr(
108759
static int evalFts3Expr(
101609
  Fts3Table *p,                   /* Virtual table handle */
108760
  Fts3Table *p,                   /* Virtual table handle */
 Lines 102234-102240   static void hashDestroy(void *p){ Link Here 
102234
** used to retrieve the respective implementations.
109385
** used to retrieve the respective implementations.
102235
**
109386
**
102236
** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
109387
** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
102237
** to by the argument to point a the "simple" tokenizer implementation.
109388
** to by the argument to point to the "simple" tokenizer implementation.
102238
** Function ...PorterTokenizerModule() sets *pModule to point to the
109389
** Function ...PorterTokenizerModule() sets *pModule to point to the
102239
** porter tokenizer/stemmer implementation.
109390
** porter tokenizer/stemmer implementation.
102240
*/
109391
*/
 Lines 102436-102442   struct ParseContext { Link Here 
102436
** negative values).
109587
** negative values).
102437
*/
109588
*/
102438
static int fts3isspace(char c){
109589
static int fts3isspace(char c){
102439
  return (c&0x80)==0 ? isspace(c) : 0;
109590
  return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
102440
}
109591
}
102441
109592
102442
/*
109593
/*
 Lines 104823-104828   typedef struct simple_tokenizer_cursor { Link Here 
104823
static int simpleDelim(simple_tokenizer *t, unsigned char c){
111974
static int simpleDelim(simple_tokenizer *t, unsigned char c){
104824
  return c<0x80 && t->delim[c];
111975
  return c<0x80 && t->delim[c];
104825
}
111976
}
111977
static int fts3_isalnum(int x){
111978
  return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
111979
}
104826
111980
104827
/*
111981
/*
104828
** Create a new tokenizer instance.
111982
** Create a new tokenizer instance.
 Lines 104857-104863   static int simpleCreate( Link Here 
104857
    /* Mark non-alphanumeric ASCII characters as delimiters */
112011
    /* Mark non-alphanumeric ASCII characters as delimiters */
104858
    int i;
112012
    int i;
104859
    for(i=1; i<0x80; i++){
112013
    for(i=1; i<0x80; i++){
104860
      t->delim[i] = !isalnum(i) ? -1 : 0;
112014
      t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
104861
    }
112015
    }
104862
  }
112016
  }
104863
112017
 Lines 104963-104969   static int simpleNext( Link Here 
104963
        ** case-insensitivity.
112117
        ** case-insensitivity.
104964
        */
112118
        */
104965
        unsigned char ch = p[iStartOffset+i];
112119
        unsigned char ch = p[iStartOffset+i];
104966
        c->pToken[i] = (char)(ch<0x80 ? tolower(ch) : ch);
112120
        c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
104967
      }
112121
      }
104968
      *ppToken = c->pToken;
112122
      *ppToken = c->pToken;
104969
      *pnBytes = n;
112123
      *pnBytes = n;
 Lines 108163-108169   static int fts3StringAppend( Link Here 
108163
** is no way for fts3BestSnippet() to know whether or not the document 
115317
** is no way for fts3BestSnippet() to know whether or not the document 
108164
** actually contains terms that follow the final highlighted term. 
115318
** actually contains terms that follow the final highlighted term. 
108165
*/
115319
*/
108166
int fts3SnippetShift(
115320
static int fts3SnippetShift(
108167
  Fts3Table *pTab,                /* FTS3 table snippet comes from */
115321
  Fts3Table *pTab,                /* FTS3 table snippet comes from */
108168
  int nSnippet,                   /* Number of tokens desired for snippet */
115322
  int nSnippet,                   /* Number of tokens desired for snippet */
108169
  const char *zDoc,               /* Document text to extract snippet from */
115323
  const char *zDoc,               /* Document text to extract snippet from */
 Lines 109869-109879   static int rtreeFilter( Link Here 
109869
**   idxNum     idxStr        Strategy
117023
**   idxNum     idxStr        Strategy
109870
**   ------------------------------------------------
117024
**   ------------------------------------------------
109871
**     1        Unused        Direct lookup by rowid.
117025
**     1        Unused        Direct lookup by rowid.
109872
**     2        See below     R-tree query.
117026
**     2        See below     R-tree query or full-table scan.
109873
**     3        Unused        Full table scan.
109874
**   ------------------------------------------------
117027
**   ------------------------------------------------
109875
**
117028
**
109876
** If strategy 1 or 3 is used, then idxStr is not meaningful. If strategy
117029
** If strategy 1 is used, then idxStr is not meaningful. If strategy
109877
** 2 is used, idxStr is formatted to contain 2 bytes for each 
117030
** 2 is used, idxStr is formatted to contain 2 bytes for each 
109878
** constraint used. The first two bytes of idxStr correspond to 
117031
** constraint used. The first two bytes of idxStr correspond to 
109879
** the constraint in sqlite3_index_info.aConstraintUsage[] with
117032
** the constraint in sqlite3_index_info.aConstraintUsage[] with
 Lines 111280-111285   static int rtreeUpdate( Link Here 
111280
      }
118433
      }
111281
      rc = sqlite3_reset(pRtree->pReadRowid);
118434
      rc = sqlite3_reset(pRtree->pReadRowid);
111282
    }
118435
    }
118436
    *pRowid = cell.iRowid;
111283
118437
111284
    if( rc==SQLITE_OK ){
118438
    if( rc==SQLITE_OK ){
111285
      rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
118439
      rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
(-)a/db/sqlite3/src/sqlite3.h (-100 / +329 lines)
Line     Link Here 
 Lines 97-103   extern "C" { Link Here 
97
**
97
**
98
** Since version 3.6.18, SQLite source code has been stored in the
98
** Since version 3.6.18, SQLite source code has been stored in the
99
** <a href="http://www.fossil-scm.org/">Fossil configuration management
99
** <a href="http://www.fossil-scm.org/">Fossil configuration management
100
** system</a>.  ^The SQLITE_SOURCE_ID macro evalutes to
100
** system</a>.  ^The SQLITE_SOURCE_ID macro evaluates to
101
** a string which identifies a particular check-in of SQLite
101
** a string which identifies a particular check-in of SQLite
102
** within its configuration management system.  ^The SQLITE_SOURCE_ID
102
** within its configuration management system.  ^The SQLITE_SOURCE_ID
103
** string contains the date and time of the check-in (UTC) and an SHA1
103
** string contains the date and time of the check-in (UTC) and an SHA1
 Lines 107-115   extern "C" { Link Here 
107
** [sqlite3_libversion_number()], [sqlite3_sourceid()],
107
** [sqlite3_libversion_number()], [sqlite3_sourceid()],
108
** [sqlite_version()] and [sqlite_source_id()].
108
** [sqlite_version()] and [sqlite_source_id()].
109
*/
109
*/
110
#define SQLITE_VERSION        "3.6.23.1"
110
#define SQLITE_VERSION        "3.7.1"
111
#define SQLITE_VERSION_NUMBER 3006023
111
#define SQLITE_VERSION_NUMBER 3007001
112
#define SQLITE_SOURCE_ID      "2010-03-26 22:28:06 b078b588d617e07886ad156e9f54ade6d823568e"
112
#define SQLITE_SOURCE_ID      "2010-08-19 15:12:55 b03091fc3592896fcf1ec563ae9682a8e0a05baa"
113
113
114
/*
114
/*
115
** CAPI3REF: Run-Time Library Version Numbers
115
** CAPI3REF: Run-Time Library Version Numbers
 Lines 146-152   SQLITE_API const char *sqlite3_libversio Link Here 
146
SQLITE_API const char *sqlite3_sourceid(void);
146
SQLITE_API const char *sqlite3_sourceid(void);
147
SQLITE_API int sqlite3_libversion_number(void);
147
SQLITE_API int sqlite3_libversion_number(void);
148
148
149
#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
150
/*
149
/*
151
** CAPI3REF: Run-Time Library Compilation Options Diagnostics
150
** CAPI3REF: Run-Time Library Compilation Options Diagnostics
152
**
151
**
 Lines 155-161   SQLITE_API int sqlite3_libversion_number Link Here 
155
** compile time.  ^The SQLITE_ prefix may be omitted from the 
154
** compile time.  ^The SQLITE_ prefix may be omitted from the 
156
** option name passed to sqlite3_compileoption_used().  
155
** option name passed to sqlite3_compileoption_used().  
157
**
156
**
158
** ^The sqlite3_compileoption_get() function allows interating
157
** ^The sqlite3_compileoption_get() function allows iterating
159
** over the list of options that were defined at compile time by
158
** over the list of options that were defined at compile time by
160
** returning the N-th compile time option string.  ^If N is out of range,
159
** returning the N-th compile time option string.  ^If N is out of range,
161
** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_ 
160
** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_ 
 Lines 163-177   SQLITE_API int sqlite3_libversion_number Link Here 
163
** sqlite3_compileoption_get().
162
** sqlite3_compileoption_get().
164
**
163
**
165
** ^Support for the diagnostic functions sqlite3_compileoption_used()
164
** ^Support for the diagnostic functions sqlite3_compileoption_used()
166
** and sqlite3_compileoption_get() may be omitted by specifing the 
165
** and sqlite3_compileoption_get() may be omitted by specifying the 
167
** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
166
** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
168
**
167
**
169
** See also: SQL functions [sqlite_compileoption_used()] and
168
** See also: SQL functions [sqlite_compileoption_used()] and
170
** [sqlite_compileoption_get()] and the [compile_options pragma].
169
** [sqlite_compileoption_get()] and the [compile_options pragma].
171
*/
170
*/
171
#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
172
SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
172
SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
173
SQLITE_API const char *sqlite3_compileoption_get(int N);
173
SQLITE_API const char *sqlite3_compileoption_get(int N);
174
#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
174
#endif
175
175
176
/*
176
/*
177
** CAPI3REF: Test To See If The Library Is Threadsafe
177
** CAPI3REF: Test To See If The Library Is Threadsafe
 Lines 268-274   typedef sqlite_uint64 sqlite3_uint64; Link Here 
268
**
268
**
269
** ^The sqlite3_close() routine is the destructor for the [sqlite3] object.
269
** ^The sqlite3_close() routine is the destructor for the [sqlite3] object.
270
** ^Calls to sqlite3_close() return SQLITE_OK if the [sqlite3] object is
270
** ^Calls to sqlite3_close() return SQLITE_OK if the [sqlite3] object is
271
** successfullly destroyed and all associated resources are deallocated.
271
** successfully destroyed and all associated resources are deallocated.
272
**
272
**
273
** Applications must [sqlite3_finalize | finalize] all [prepared statements]
273
** Applications must [sqlite3_finalize | finalize] all [prepared statements]
274
** and [sqlite3_blob_close | close] all [BLOB handles] associated with
274
** and [sqlite3_blob_close | close] all [BLOB handles] associated with
 Lines 393-399   SQLITE_API int sqlite3_exec( Link Here 
393
#define SQLITE_NOTFOUND    12   /* NOT USED. Table or record not found */
393
#define SQLITE_NOTFOUND    12   /* NOT USED. Table or record not found */
394
#define SQLITE_FULL        13   /* Insertion failed because database is full */
394
#define SQLITE_FULL        13   /* Insertion failed because database is full */
395
#define SQLITE_CANTOPEN    14   /* Unable to open the database file */
395
#define SQLITE_CANTOPEN    14   /* Unable to open the database file */
396
#define SQLITE_PROTOCOL    15   /* NOT USED. Database lock protocol error */
396
#define SQLITE_PROTOCOL    15   /* Database lock protocol error */
397
#define SQLITE_EMPTY       16   /* Database is empty */
397
#define SQLITE_EMPTY       16   /* Database is empty */
398
#define SQLITE_SCHEMA      17   /* The database schema changed */
398
#define SQLITE_SCHEMA      17   /* The database schema changed */
399
#define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
399
#define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
 Lines 449-455   SQLITE_API int sqlite3_exec( Link Here 
449
#define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
449
#define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
450
#define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
450
#define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
451
#define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
451
#define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
452
#define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED | (1<<8) )
452
#define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))
453
#define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))
454
#define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))
455
#define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))
456
#define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))
457
#define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
453
458
454
/*
459
/*
455
** CAPI3REF: Flags For File Open Operations
460
** CAPI3REF: Flags For File Open Operations
 Lines 476-486   SQLITE_API int sqlite3_exec( Link Here 
476
#define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
481
#define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
477
#define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
482
#define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
478
#define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
483
#define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
484
#define SQLITE_OPEN_WAL              0x00080000  /* VFS only */
479
485
480
/*
486
/*
481
** CAPI3REF: Device Characteristics
487
** CAPI3REF: Device Characteristics
482
**
488
**
483
** The xDeviceCapabilities method of the [sqlite3_io_methods]
489
** The xDeviceCharacteristics method of the [sqlite3_io_methods]
484
** object returns an integer which is a vector of the these
490
** object returns an integer which is a vector of the these
485
** bit values expressing I/O characteristics of the mass storage
491
** bit values expressing I/O characteristics of the mass storage
486
** device that holds the file that the [sqlite3_io_methods]
492
** device that holds the file that the [sqlite3_io_methods]
 Lines 497-513   SQLITE_API int sqlite3_exec( Link Here 
497
** information is written to disk in the same order as calls
503
** information is written to disk in the same order as calls
498
** to xWrite().
504
** to xWrite().
499
*/
505
*/
500
#define SQLITE_IOCAP_ATOMIC          0x00000001
506
#define SQLITE_IOCAP_ATOMIC                 0x00000001
501
#define SQLITE_IOCAP_ATOMIC512       0x00000002
507
#define SQLITE_IOCAP_ATOMIC512              0x00000002
502
#define SQLITE_IOCAP_ATOMIC1K        0x00000004
508
#define SQLITE_IOCAP_ATOMIC1K               0x00000004
503
#define SQLITE_IOCAP_ATOMIC2K        0x00000008
509
#define SQLITE_IOCAP_ATOMIC2K               0x00000008
504
#define SQLITE_IOCAP_ATOMIC4K        0x00000010
510
#define SQLITE_IOCAP_ATOMIC4K               0x00000010
505
#define SQLITE_IOCAP_ATOMIC8K        0x00000020
511
#define SQLITE_IOCAP_ATOMIC8K               0x00000020
506
#define SQLITE_IOCAP_ATOMIC16K       0x00000040
512
#define SQLITE_IOCAP_ATOMIC16K              0x00000040
507
#define SQLITE_IOCAP_ATOMIC32K       0x00000080
513
#define SQLITE_IOCAP_ATOMIC32K              0x00000080
508
#define SQLITE_IOCAP_ATOMIC64K       0x00000100
514
#define SQLITE_IOCAP_ATOMIC64K              0x00000100
509
#define SQLITE_IOCAP_SAFE_APPEND     0x00000200
515
#define SQLITE_IOCAP_SAFE_APPEND            0x00000200
510
#define SQLITE_IOCAP_SEQUENTIAL      0x00000400
516
#define SQLITE_IOCAP_SEQUENTIAL             0x00000400
517
#define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800
511
518
512
/*
519
/*
513
** CAPI3REF: File Locking Levels
520
** CAPI3REF: File Locking Levels
 Lines 658-663   struct sqlite3_io_methods { Link Here 
658
  int (*xFileControl)(sqlite3_file*, int op, void *pArg);
665
  int (*xFileControl)(sqlite3_file*, int op, void *pArg);
659
  int (*xSectorSize)(sqlite3_file*);
666
  int (*xSectorSize)(sqlite3_file*);
660
  int (*xDeviceCharacteristics)(sqlite3_file*);
667
  int (*xDeviceCharacteristics)(sqlite3_file*);
668
  /* Methods above are valid for version 1 */
669
  int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
670
  int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
671
  void (*xShmBarrier)(sqlite3_file*);
672
  int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
673
  /* Methods above are valid for version 2 */
661
  /* Additional methods may be added in future releases */
674
  /* Additional methods may be added in future releases */
662
};
675
};
663
676
 Lines 675-685   struct sqlite3_io_methods { Link Here 
675
** into an integer that the pArg argument points to. This capability
688
** into an integer that the pArg argument points to. This capability
676
** is used during testing and only needs to be supported when SQLITE_TEST
689
** is used during testing and only needs to be supported when SQLITE_TEST
677
** is defined.
690
** is defined.
691
**
692
** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
693
** layer a hint of how large the database file will grow to be during the
694
** current transaction.  This hint is not guaranteed to be accurate but it
695
** is often close.  The underlying VFS might choose to preallocate database
696
** file space based on this hint in order to help writes to the database
697
** file run faster.
698
**
699
** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
700
** extends and truncates the database file in chunks of a size specified
701
** by the user. The fourth argument to [sqlite3_file_control()] should 
702
** point to an integer (type int) containing the new chunk-size to use
703
** for the nominated database. Allocating database file space in large
704
** chunks (say 1MB at a time), may reduce file-system fragmentation and
705
** improve performance on some systems.
678
*/
706
*/
679
#define SQLITE_FCNTL_LOCKSTATE        1
707
#define SQLITE_FCNTL_LOCKSTATE        1
680
#define SQLITE_GET_LOCKPROXYFILE      2
708
#define SQLITE_GET_LOCKPROXYFILE      2
681
#define SQLITE_SET_LOCKPROXYFILE      3
709
#define SQLITE_SET_LOCKPROXYFILE      3
682
#define SQLITE_LAST_ERRNO             4
710
#define SQLITE_LAST_ERRNO             4
711
#define SQLITE_FCNTL_SIZE_HINT        5
712
#define SQLITE_FCNTL_CHUNK_SIZE       6
683
713
684
/*
714
/*
685
** CAPI3REF: Mutex Handle
715
** CAPI3REF: Mutex Handle
 Lines 811-830   typedef struct sqlite3_mutex sqlite3_mut Link Here 
811
** handled as a fatal error by SQLite, vfs implementations should endeavor
841
** handled as a fatal error by SQLite, vfs implementations should endeavor
812
** to prevent this by setting mxPathname to a sufficiently large value.
842
** to prevent this by setting mxPathname to a sufficiently large value.
813
**
843
**
814
** The xRandomness(), xSleep(), and xCurrentTime() interfaces
844
** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
815
** are not strictly a part of the filesystem, but they are
845
** interfaces are not strictly a part of the filesystem, but they are
816
** included in the VFS structure for completeness.
846
** included in the VFS structure for completeness.
817
** The xRandomness() function attempts to return nBytes bytes
847
** The xRandomness() function attempts to return nBytes bytes
818
** of good-quality randomness into zOut.  The return value is
848
** of good-quality randomness into zOut.  The return value is
819
** the actual number of bytes of randomness obtained.
849
** the actual number of bytes of randomness obtained.
820
** The xSleep() method causes the calling thread to sleep for at
850
** The xSleep() method causes the calling thread to sleep for at
821
** least the number of microseconds given.  The xCurrentTime()
851
** least the number of microseconds given.  The xCurrentTime()
822
** method returns a Julian Day Number for the current date and time.
852
** method returns a Julian Day Number for the current date and time as
823
**
853
** a floating point value.
854
** The xCurrentTimeInt64() method returns, as an integer, the Julian
855
** Day Number multipled by 86400000 (the number of milliseconds in 
856
** a 24-hour day).  
857
** ^SQLite will use the xCurrentTimeInt64() method to get the current
858
** date and time if that method is available (if iVersion is 2 or 
859
** greater and the function pointer is not NULL) and will fall back
860
** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
824
*/
861
*/
825
typedef struct sqlite3_vfs sqlite3_vfs;
862
typedef struct sqlite3_vfs sqlite3_vfs;
826
struct sqlite3_vfs {
863
struct sqlite3_vfs {
827
  int iVersion;            /* Structure version number */
864
  int iVersion;            /* Structure version number (currently 2) */
828
  int szOsFile;            /* Size of subclassed sqlite3_file */
865
  int szOsFile;            /* Size of subclassed sqlite3_file */
829
  int mxPathname;          /* Maximum file pathname length */
866
  int mxPathname;          /* Maximum file pathname length */
830
  sqlite3_vfs *pNext;      /* Next registered VFS */
867
  sqlite3_vfs *pNext;      /* Next registered VFS */
 Lines 843-850   struct sqlite3_vfs { Link Here 
843
  int (*xSleep)(sqlite3_vfs*, int microseconds);
880
  int (*xSleep)(sqlite3_vfs*, int microseconds);
844
  int (*xCurrentTime)(sqlite3_vfs*, double*);
881
  int (*xCurrentTime)(sqlite3_vfs*, double*);
845
  int (*xGetLastError)(sqlite3_vfs*, int, char *);
882
  int (*xGetLastError)(sqlite3_vfs*, int, char *);
846
  /* New fields may be appended in figure versions.  The iVersion
883
  /*
847
  ** value will increment whenever this happens. */
884
  ** The methods above are in version 1 of the sqlite_vfs object
885
  ** definition.  Those that follow are added in version 2 or later
886
  */
887
  int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
888
  /*
889
  ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
890
  ** New fields may be appended in figure versions.  The iVersion
891
  ** value will increment whenever this happens. 
892
  */
848
};
893
};
849
894
850
/*
895
/*
 Lines 856-868   struct sqlite3_vfs { Link Here 
856
** With SQLITE_ACCESS_EXISTS, the xAccess method
901
** With SQLITE_ACCESS_EXISTS, the xAccess method
857
** simply checks whether the file exists.
902
** simply checks whether the file exists.
858
** With SQLITE_ACCESS_READWRITE, the xAccess method
903
** With SQLITE_ACCESS_READWRITE, the xAccess method
859
** checks whether the file is both readable and writable.
904
** checks whether the named directory is both readable and writable
905
** (in other words, if files can be added, removed, and renamed within
906
** the directory).
907
** The SQLITE_ACCESS_READWRITE constant is currently used only by the
908
** [temp_store_directory pragma], though this could change in a future
909
** release of SQLite.
860
** With SQLITE_ACCESS_READ, the xAccess method
910
** With SQLITE_ACCESS_READ, the xAccess method
861
** checks whether the file is readable.
911
** checks whether the file is readable.  The SQLITE_ACCESS_READ constant is
912
** currently unused, though it might be used in a future release of
913
** SQLite.
862
*/
914
*/
863
#define SQLITE_ACCESS_EXISTS    0
915
#define SQLITE_ACCESS_EXISTS    0
864
#define SQLITE_ACCESS_READWRITE 1
916
#define SQLITE_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */
865
#define SQLITE_ACCESS_READ      2
917
#define SQLITE_ACCESS_READ      2   /* Unused */
918
919
/*
920
** CAPI3REF: Flags for the xShmLock VFS method
921
**
922
** These integer constants define the various locking operations
923
** allowed by the xShmLock method of [sqlite3_io_methods].  The
924
** following are the only legal combinations of flags to the
925
** xShmLock method:
926
**
927
** <ul>
928
** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
929
** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
930
** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
931
** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
932
** </ul>
933
**
934
** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
935
** was given no the corresponding lock.  
936
**
937
** The xShmLock method can transition between unlocked and SHARED or
938
** between unlocked and EXCLUSIVE.  It cannot transition between SHARED
939
** and EXCLUSIVE.
940
*/
941
#define SQLITE_SHM_UNLOCK       1
942
#define SQLITE_SHM_LOCK         2
943
#define SQLITE_SHM_SHARED       4
944
#define SQLITE_SHM_EXCLUSIVE    8
945
946
/*
947
** CAPI3REF: Maximum xShmLock index
948
**
949
** The xShmLock method on [sqlite3_io_methods] may use values
950
** between 0 and this upper bound as its "offset" argument.
951
** The SQLite core will never attempt to acquire or release a
952
** lock outside of this range
953
*/
954
#define SQLITE_SHM_NLOCK        8
955
866
956
867
/*
957
/*
868
** CAPI3REF: Initialize The SQLite Library
958
** CAPI3REF: Initialize The SQLite Library
 Lines 973-983   SQLITE_API int sqlite3_os_end(void); Link Here 
973
** ^If the option is unknown or SQLite is unable to set the option
1063
** ^If the option is unknown or SQLite is unable to set the option
974
** then this routine returns a non-zero [error code].
1064
** then this routine returns a non-zero [error code].
975
*/
1065
*/
976
SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_config(int, ...);
1066
SQLITE_API int sqlite3_config(int, ...);
977
1067
978
/*
1068
/*
979
** CAPI3REF: Configure database connections
1069
** CAPI3REF: Configure database connections
980
** EXPERIMENTAL
981
**
1070
**
982
** The sqlite3_db_config() interface is used to make configuration
1071
** The sqlite3_db_config() interface is used to make configuration
983
** changes to a [database connection].  The interface is similar to
1072
** changes to a [database connection].  The interface is similar to
 Lines 997-1007   SQLITE_API SQLITE_EXPERIMENTAL int sqlit Link Here 
997
** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1086
** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
998
** the call is considered successful.
1087
** the call is considered successful.
999
*/
1088
*/
1000
SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_db_config(sqlite3*, int op, ...);
1089
SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
1001
1090
1002
/*
1091
/*
1003
** CAPI3REF: Memory Allocation Routines
1092
** CAPI3REF: Memory Allocation Routines
1004
** EXPERIMENTAL
1005
**
1093
**
1006
** An instance of this object defines the interface between SQLite
1094
** An instance of this object defines the interface between SQLite
1007
** and low-level memory allocation routines.
1095
** and low-level memory allocation routines.
 Lines 1083-1089   struct sqlite3_mem_methods { Link Here 
1083
1171
1084
/*
1172
/*
1085
** CAPI3REF: Configuration Options
1173
** CAPI3REF: Configuration Options
1086
** EXPERIMENTAL
1087
**
1174
**
1088
** These constants are the available integer configuration options that
1175
** These constants are the available integer configuration options that
1089
** can be passed as the first argument to the [sqlite3_config()] interface.
1176
** can be passed as the first argument to the [sqlite3_config()] interface.
 Lines 1269-1274   struct sqlite3_mem_methods { Link Here 
1269
** [sqlite3_pcache_methods] object.  SQLite copies of the current
1356
** [sqlite3_pcache_methods] object.  SQLite copies of the current
1270
** page cache implementation into that object.)^ </dd>
1357
** page cache implementation into that object.)^ </dd>
1271
**
1358
**
1359
** <dt>SQLITE_CONFIG_LOG</dt>
1360
** <dd> ^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
1361
** function with a call signature of void(*)(void*,int,const char*), 
1362
** and a pointer to void. ^If the function pointer is not NULL, it is
1363
** invoked by [sqlite3_log()] to process each logging event.  ^If the
1364
** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
1365
** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
1366
** passed through as the first parameter to the application-defined logger
1367
** function whenever that function is invoked.  ^The second parameter to
1368
** the logger function is a copy of the first parameter to the corresponding
1369
** [sqlite3_log()] call and is intended to be a [result code] or an
1370
** [extended result code].  ^The third parameter passed to the logger is
1371
** log message after formatting via [sqlite3_snprintf()].
1372
** The SQLite logging interface is not reentrant; the logger function
1373
** supplied by the application must not invoke any SQLite interface.
1374
** In a multi-threaded application, the application-defined logger
1375
** function must be threadsafe. </dd>
1376
**
1272
** </dl>
1377
** </dl>
1273
*/
1378
*/
1274
#define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
1379
#define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
 Lines 1289-1296   struct sqlite3_mem_methods { Link Here 
1289
#define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
1394
#define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
1290
1395
1291
/*
1396
/*
1292
** CAPI3REF: Configuration Options
1397
** CAPI3REF: Database Connection Configuration Options
1293
** EXPERIMENTAL
1294
**
1398
**
1295
** These constants are the available integer configuration options that
1399
** These constants are the available integer configuration options that
1296
** can be passed as the second argument to the [sqlite3_db_config()] interface.
1400
** can be passed as the second argument to the [sqlite3_db_config()] interface.
 Lines 2066-2072   SQLITE_API int sqlite3_set_authorizer( Link Here 
2066
2170
2067
/*
2171
/*
2068
** CAPI3REF: Tracing And Profiling Functions
2172
** CAPI3REF: Tracing And Profiling Functions
2069
** EXPERIMENTAL
2070
**
2173
**
2071
** These routines register callback functions that can be used for
2174
** These routines register callback functions that can be used for
2072
** tracing and profiling the execution of SQL statements.
2175
** tracing and profiling the execution of SQL statements.
 Lines 2082-2090   SQLITE_API int sqlite3_set_authorizer( Link Here 
2082
** ^The callback function registered by sqlite3_profile() is invoked
2185
** ^The callback function registered by sqlite3_profile() is invoked
2083
** as each SQL statement finishes.  ^The profile callback contains
2186
** as each SQL statement finishes.  ^The profile callback contains
2084
** the original statement text and an estimate of wall-clock time
2187
** the original statement text and an estimate of wall-clock time
2085
** of how long that statement took to run.
2188
** of how long that statement took to run.  ^The profile callback
2189
** time is in units of nanoseconds, however the current implementation
2190
** is only capable of millisecond resolution so the six least significant
2191
** digits in the time are meaningless.  Future versions of SQLite
2192
** might provide greater resolution on the profiler callback.  The
2193
** sqlite3_profile() function is considered experimental and is
2194
** subject to change in future versions of SQLite.
2086
*/
2195
*/
2087
SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
2196
SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
2088
SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
2197
SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
2089
   void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
2198
   void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
2090
2199
 Lines 2563-2569   typedef struct sqlite3_context sqlite3_c Link Here 
2563
** </ul>
2672
** </ul>
2564
**
2673
**
2565
** In the templates above, NNN represents an integer literal,
2674
** In the templates above, NNN represents an integer literal,
2566
** and VVV represents an alphanumeric identifer.)^  ^The values of these
2675
** and VVV represents an alphanumeric identifier.)^  ^The values of these
2567
** parameters (also called "host parameter names" or "SQL parameters")
2676
** parameters (also called "host parameter names" or "SQL parameters")
2568
** can be set using the sqlite3_bind_*() routines defined here.
2677
** can be set using the sqlite3_bind_*() routines defined here.
2569
**
2678
**
 Lines 2877-2882   SQLITE_API const void *sqlite3_column_de Link Here 
2877
** be the case that the same database connection is being used by two or
2986
** be the case that the same database connection is being used by two or
2878
** more threads at the same moment in time.
2987
** more threads at the same moment in time.
2879
**
2988
**
2989
** For all versions of SQLite up to and including 3.6.23.1, it was required
2990
** after sqlite3_step() returned anything other than [SQLITE_ROW] that
2991
** [sqlite3_reset()] be called before any subsequent invocation of
2992
** sqlite3_step().  Failure to invoke [sqlite3_reset()] in this way would
2993
** result in an [SQLITE_MISUSE] return from sqlite3_step().  But after
2994
** version 3.6.23.1, sqlite3_step() began calling [sqlite3_reset()] 
2995
** automatically in this circumstance rather than returning [SQLITE_MISUSE].  
2996
**
2880
** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
2997
** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
2881
** API always returns a generic error code, [SQLITE_ERROR], following any
2998
** API always returns a generic error code, [SQLITE_ERROR], following any
2882
** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
2999
** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
 Lines 3334-3340   SQLITE_API int sqlite3_value_numeric_typ Link Here 
3334
/*
3451
/*
3335
** CAPI3REF: Obtain Aggregate Function Context
3452
** CAPI3REF: Obtain Aggregate Function Context
3336
**
3453
**
3337
** Implementions of aggregate SQL functions use this
3454
** Implementations of aggregate SQL functions use this
3338
** routine to allocate memory for storing their state.
3455
** routine to allocate memory for storing their state.
3339
**
3456
**
3340
** ^The first time the sqlite3_aggregate_context(C,N) routine is called 
3457
** ^The first time the sqlite3_aggregate_context(C,N) routine is called 
 Lines 3606-3612   SQLITE_API void sqlite3_result_zeroblob( Link Here 
3606
**
3723
**
3607
** A pointer to the user supplied routine must be passed as the fifth
3724
** A pointer to the user supplied routine must be passed as the fifth
3608
** argument.  ^If it is NULL, this is the same as deleting the collation
3725
** argument.  ^If it is NULL, this is the same as deleting the collation
3609
** sequence (so that SQLite cannot call it anymore).
3726
** sequence (so that SQLite cannot call it any more).
3610
** ^Each time the application supplied function is invoked, it is passed
3727
** ^Each time the application supplied function is invoked, it is passed
3611
** as its first parameter a copy of the void* passed as the fourth argument
3728
** as its first parameter a copy of the void* passed as the fourth argument
3612
** to sqlite3_create_collation() or sqlite3_create_collation16().
3729
** to sqlite3_create_collation() or sqlite3_create_collation16().
 Lines 3689-3695   SQLITE_API int sqlite3_collation_needed1 Link Here 
3689
  void(*)(void*,sqlite3*,int eTextRep,const void*)
3806
  void(*)(void*,sqlite3*,int eTextRep,const void*)
3690
);
3807
);
3691
3808
3692
#if SQLITE_HAS_CODEC
3809
#ifdef SQLITE_HAS_CODEC
3693
/*
3810
/*
3694
** Specify the key for an encrypted database.  This routine should be
3811
** Specify the key for an encrypted database.  This routine should be
3695
** called right after sqlite3_open().
3812
** called right after sqlite3_open().
 Lines 3872-3879   SQLITE_API sqlite3_stmt *sqlite3_next_st Link Here 
3872
** an error or constraint causes an implicit rollback to occur.
3989
** an error or constraint causes an implicit rollback to occur.
3873
** ^The rollback callback is not invoked if a transaction is
3990
** ^The rollback callback is not invoked if a transaction is
3874
** automatically rolled back because the database connection is closed.
3991
** automatically rolled back because the database connection is closed.
3875
** ^The rollback callback is not invoked if a transaction is
3876
** rolled back because a commit callback returned non-zero.
3877
**
3992
**
3878
** See also the [sqlite3_update_hook()] interface.
3993
** See also the [sqlite3_update_hook()] interface.
3879
*/
3994
*/
 Lines 4159-4166   SQLITE_API int sqlite3_auto_extension(vo Link Here 
4159
SQLITE_API void sqlite3_reset_auto_extension(void);
4274
SQLITE_API void sqlite3_reset_auto_extension(void);
4160
4275
4161
/*
4276
/*
4162
****** EXPERIMENTAL - subject to change without notice **************
4163
**
4164
** The interface to the virtual-table mechanism is currently considered
4277
** The interface to the virtual-table mechanism is currently considered
4165
** to be experimental.  The interface might change in incompatible ways.
4278
** to be experimental.  The interface might change in incompatible ways.
4166
** If this is a problem for you, do not use the interface at this time.
4279
** If this is a problem for you, do not use the interface at this time.
 Lines 4180-4186   typedef struct sqlite3_module sqlite3_mo Link Here 
4180
/*
4293
/*
4181
** CAPI3REF: Virtual Table Object
4294
** CAPI3REF: Virtual Table Object
4182
** KEYWORDS: sqlite3_module {virtual table module}
4295
** KEYWORDS: sqlite3_module {virtual table module}
4183
** EXPERIMENTAL
4184
**
4296
**
4185
** This structure, sometimes called a a "virtual table module", 
4297
** This structure, sometimes called a a "virtual table module", 
4186
** defines the implementation of a [virtual tables].  
4298
** defines the implementation of a [virtual tables].  
 Lines 4227-4235   struct sqlite3_module { Link Here 
4227
/*
4339
/*
4228
** CAPI3REF: Virtual Table Indexing Information
4340
** CAPI3REF: Virtual Table Indexing Information
4229
** KEYWORDS: sqlite3_index_info
4341
** KEYWORDS: sqlite3_index_info
4230
** EXPERIMENTAL
4342
**
4231
**
4343
** The sqlite3_index_info structure and its substructures is used as part
4232
** The sqlite3_index_info structure and its substructures is used to
4344
** of the [virtual table] interface to
4233
** pass information into and receive the reply from the [xBestIndex]
4345
** pass information into and receive the reply from the [xBestIndex]
4234
** method of a [virtual table module].  The fields under **Inputs** are the
4346
** method of a [virtual table module].  The fields under **Inputs** are the
4235
** inputs to xBestIndex and are read-only.  xBestIndex inserts its
4347
** inputs to xBestIndex and are read-only.  xBestIndex inserts its
 Lines 4237-4246   struct sqlite3_module { Link Here 
4237
**
4349
**
4238
** ^(The aConstraint[] array records WHERE clause constraints of the form:
4350
** ^(The aConstraint[] array records WHERE clause constraints of the form:
4239
**
4351
**
4240
** <pre>column OP expr</pre>
4352
** <blockquote>column OP expr</blockquote>
4241
**
4353
**
4242
** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
4354
** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
4243
** stored in aConstraint[].op.)^  ^(The index of the column is stored in
4355
** stored in aConstraint[].op using one of the
4356
** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
4357
** ^(The index of the column is stored in
4244
** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
4358
** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
4245
** expr on the right-hand side can be evaluated (and thus the constraint
4359
** expr on the right-hand side can be evaluated (and thus the constraint
4246
** is usable) and false if it cannot.)^
4360
** is usable) and false if it cannot.)^
 Lines 4300-4305   struct sqlite3_index_info { Link Here 
4300
  int orderByConsumed;       /* True if output is already ordered */
4414
  int orderByConsumed;       /* True if output is already ordered */
4301
  double estimatedCost;      /* Estimated cost of using this index */
4415
  double estimatedCost;      /* Estimated cost of using this index */
4302
};
4416
};
4417
4418
/*
4419
** CAPI3REF: Virtual Table Constraint Operator Codes
4420
**
4421
** These macros defined the allowed values for the
4422
** [sqlite3_index_info].aConstraint[].op field.  Each value represents
4423
** an operator that is part of a constraint term in the wHERE clause of
4424
** a query that uses a [virtual table].
4425
*/
4303
#define SQLITE_INDEX_CONSTRAINT_EQ    2
4426
#define SQLITE_INDEX_CONSTRAINT_EQ    2
4304
#define SQLITE_INDEX_CONSTRAINT_GT    4
4427
#define SQLITE_INDEX_CONSTRAINT_GT    4
4305
#define SQLITE_INDEX_CONSTRAINT_LE    8
4428
#define SQLITE_INDEX_CONSTRAINT_LE    8
 Lines 4309-4315   struct sqlite3_index_info { Link Here 
4309
4432
4310
/*
4433
/*
4311
** CAPI3REF: Register A Virtual Table Implementation
4434
** CAPI3REF: Register A Virtual Table Implementation
4312
** EXPERIMENTAL
4313
**
4435
**
4314
** ^These routines are used to register a new [virtual table module] name.
4436
** ^These routines are used to register a new [virtual table module] name.
4315
** ^Module names must be registered before
4437
** ^Module names must be registered before
 Lines 4331-4343   struct sqlite3_index_info { Link Here 
4331
** interface is equivalent to sqlite3_create_module_v2() with a NULL
4453
** interface is equivalent to sqlite3_create_module_v2() with a NULL
4332
** destructor.
4454
** destructor.
4333
*/
4455
*/
4334
SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_create_module(
4456
SQLITE_API int sqlite3_create_module(
4335
  sqlite3 *db,               /* SQLite connection to register module with */
4457
  sqlite3 *db,               /* SQLite connection to register module with */
4336
  const char *zName,         /* Name of the module */
4458
  const char *zName,         /* Name of the module */
4337
  const sqlite3_module *p,   /* Methods for the module */
4459
  const sqlite3_module *p,   /* Methods for the module */
4338
  void *pClientData          /* Client data for xCreate/xConnect */
4460
  void *pClientData          /* Client data for xCreate/xConnect */
4339
);
4461
);
4340
SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_create_module_v2(
4462
SQLITE_API int sqlite3_create_module_v2(
4341
  sqlite3 *db,               /* SQLite connection to register module with */
4463
  sqlite3 *db,               /* SQLite connection to register module with */
4342
  const char *zName,         /* Name of the module */
4464
  const char *zName,         /* Name of the module */
4343
  const sqlite3_module *p,   /* Methods for the module */
4465
  const sqlite3_module *p,   /* Methods for the module */
 Lines 4348-4354   SQLITE_API SQLITE_EXPERIMENTAL int sqlit Link Here 
4348
/*
4470
/*
4349
** CAPI3REF: Virtual Table Instance Object
4471
** CAPI3REF: Virtual Table Instance Object
4350
** KEYWORDS: sqlite3_vtab
4472
** KEYWORDS: sqlite3_vtab
4351
** EXPERIMENTAL
4352
**
4473
**
4353
** Every [virtual table module] implementation uses a subclass
4474
** Every [virtual table module] implementation uses a subclass
4354
** of this object to describe a particular instance
4475
** of this object to describe a particular instance
 Lines 4374-4380   struct sqlite3_vtab { Link Here 
4374
/*
4495
/*
4375
** CAPI3REF: Virtual Table Cursor Object
4496
** CAPI3REF: Virtual Table Cursor Object
4376
** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
4497
** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
4377
** EXPERIMENTAL
4378
**
4498
**
4379
** Every [virtual table module] implementation uses a subclass of the
4499
** Every [virtual table module] implementation uses a subclass of the
4380
** following structure to describe cursors that point into the
4500
** following structure to describe cursors that point into the
 Lines 4396-4413   struct sqlite3_vtab_cursor { Link Here 
4396
4516
4397
/*
4517
/*
4398
** CAPI3REF: Declare The Schema Of A Virtual Table
4518
** CAPI3REF: Declare The Schema Of A Virtual Table
4399
** EXPERIMENTAL
4400
**
4519
**
4401
** ^The [xCreate] and [xConnect] methods of a
4520
** ^The [xCreate] and [xConnect] methods of a
4402
** [virtual table module] call this interface
4521
** [virtual table module] call this interface
4403
** to declare the format (the names and datatypes of the columns) of
4522
** to declare the format (the names and datatypes of the columns) of
4404
** the virtual tables they implement.
4523
** the virtual tables they implement.
4405
*/
4524
*/
4406
SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
4525
SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
4407
4526
4408
/*
4527
/*
4409
** CAPI3REF: Overload A Function For A Virtual Table
4528
** CAPI3REF: Overload A Function For A Virtual Table
4410
** EXPERIMENTAL
4411
**
4529
**
4412
** ^(Virtual tables can provide alternative implementations of functions
4530
** ^(Virtual tables can provide alternative implementations of functions
4413
** using the [xFindFunction] method of the [virtual table module].  
4531
** using the [xFindFunction] method of the [virtual table module].  
 Lines 4422-4428   SQLITE_API SQLITE_EXPERIMENTAL int sqlit Link Here 
4422
** purpose is to be a placeholder function that can be overloaded
4540
** purpose is to be a placeholder function that can be overloaded
4423
** by a [virtual table].
4541
** by a [virtual table].
4424
*/
4542
*/
4425
SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
4543
SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
4426
4544
4427
/*
4545
/*
4428
** The interface to the virtual-table mechanism defined above (back up
4546
** The interface to the virtual-table mechanism defined above (back up
 Lines 4432-4439   SQLITE_API SQLITE_EXPERIMENTAL int sqlit Link Here 
4432
**
4550
**
4433
** When the virtual-table mechanism stabilizes, we will declare the
4551
** When the virtual-table mechanism stabilizes, we will declare the
4434
** interface fixed, support it indefinitely, and remove this comment.
4552
** interface fixed, support it indefinitely, and remove this comment.
4435
**
4436
****** EXPERIMENTAL - subject to change without notice **************
4437
*/
4553
*/
4438
4554
4439
/*
4555
/*
 Lines 4776-4782   SQLITE_API void sqlite3_mutex_leave(sqli Link Here 
4776
4892
4777
/*
4893
/*
4778
** CAPI3REF: Mutex Methods Object
4894
** CAPI3REF: Mutex Methods Object
4779
** EXPERIMENTAL
4780
**
4895
**
4781
** An instance of this structure defines the low-level routines
4896
** An instance of this structure defines the low-level routines
4782
** used to allocate and use mutexes.
4897
** used to allocate and use mutexes.
 Lines 4826-4832   SQLITE_API void sqlite3_mutex_leave(sqli Link Here 
4826
** it is passed a NULL pointer).
4941
** it is passed a NULL pointer).
4827
**
4942
**
4828
** The xMutexInit() method must be threadsafe.  ^It must be harmless to
4943
** The xMutexInit() method must be threadsafe.  ^It must be harmless to
4829
** invoke xMutexInit() mutiple times within the same process and without
4944
** invoke xMutexInit() multiple times within the same process and without
4830
** intervening calls to xMutexEnd().  Second and subsequent calls to
4945
** intervening calls to xMutexEnd().  Second and subsequent calls to
4831
** xMutexInit() must be no-ops.
4946
** xMutexInit() must be no-ops.
4832
**
4947
**
 Lines 4989-5002   SQLITE_API int sqlite3_test_control(int Link Here 
4989
#define SQLITE_TESTCTRL_RESERVE                 14
5104
#define SQLITE_TESTCTRL_RESERVE                 14
4990
#define SQLITE_TESTCTRL_OPTIMIZATIONS           15
5105
#define SQLITE_TESTCTRL_OPTIMIZATIONS           15
4991
#define SQLITE_TESTCTRL_ISKEYWORD               16
5106
#define SQLITE_TESTCTRL_ISKEYWORD               16
4992
#define SQLITE_TESTCTRL_LAST                    16
5107
#define SQLITE_TESTCTRL_PGHDRSZ                 17
5108
#define SQLITE_TESTCTRL_LAST                    17
4993
5109
4994
/*
5110
/*
4995
** CAPI3REF: SQLite Runtime Status
5111
** CAPI3REF: SQLite Runtime Status
4996
** EXPERIMENTAL
4997
**
5112
**
4998
** ^This interface is used to retrieve runtime status information
5113
** ^This interface is used to retrieve runtime status information
4999
** about the preformance of SQLite, and optionally to reset various
5114
** about the performance of SQLite, and optionally to reset various
5000
** highwater marks.  ^The first argument is an integer code for
5115
** highwater marks.  ^The first argument is an integer code for
5001
** the specific parameter to measure.  ^(Recognized integer codes
5116
** the specific parameter to measure.  ^(Recognized integer codes
5002
** are of the form [SQLITE_STATUS_MEMORY_USED | SQLITE_STATUS_...].)^
5117
** are of the form [SQLITE_STATUS_MEMORY_USED | SQLITE_STATUS_...].)^
 Lines 5021-5032   SQLITE_API int sqlite3_test_control(int Link Here 
5021
**
5136
**
5022
** See also: [sqlite3_db_status()]
5137
** See also: [sqlite3_db_status()]
5023
*/
5138
*/
5024
SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
5139
SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
5025
5140
5026
5141
5027
/*
5142
/*
5028
** CAPI3REF: Status Parameters
5143
** CAPI3REF: Status Parameters
5029
** EXPERIMENTAL
5030
**
5144
**
5031
** These integer constants designate various run-time status parameters
5145
** These integer constants designate various run-time status parameters
5032
** that can be returned by [sqlite3_status()].
5146
** that can be returned by [sqlite3_status()].
 Lines 5049-5054   SQLITE_API SQLITE_EXPERIMENTAL int sqlit Link Here 
5049
** *pHighwater parameter to [sqlite3_status()] is of interest.  
5163
** *pHighwater parameter to [sqlite3_status()] is of interest.  
5050
** The value written into the *pCurrent parameter is undefined.</dd>)^
5164
** The value written into the *pCurrent parameter is undefined.</dd>)^
5051
**
5165
**
5166
** ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
5167
** <dd>This parameter records the number of separate memory allocations.</dd>)^
5168
**
5052
** ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
5169
** ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
5053
** <dd>This parameter returns the number of pages used out of the
5170
** <dd>This parameter returns the number of pages used out of the
5054
** [pagecache memory allocator] that was configured using 
5171
** [pagecache memory allocator] that was configured using 
 Lines 5110-5126   SQLITE_API SQLITE_EXPERIMENTAL int sqlit Link Here 
5110
#define SQLITE_STATUS_PARSER_STACK         6
5227
#define SQLITE_STATUS_PARSER_STACK         6
5111
#define SQLITE_STATUS_PAGECACHE_SIZE       7
5228
#define SQLITE_STATUS_PAGECACHE_SIZE       7
5112
#define SQLITE_STATUS_SCRATCH_SIZE         8
5229
#define SQLITE_STATUS_SCRATCH_SIZE         8
5230
#define SQLITE_STATUS_MALLOC_COUNT         9
5113
5231
5114
/*
5232
/*
5115
** CAPI3REF: Database Connection Status
5233
** CAPI3REF: Database Connection Status
5116
** EXPERIMENTAL
5117
**
5234
**
5118
** ^This interface is used to retrieve runtime status information 
5235
** ^This interface is used to retrieve runtime status information 
5119
** about a single [database connection].  ^The first argument is the
5236
** about a single [database connection].  ^The first argument is the
5120
** database connection object to be interrogated.  ^The second argument
5237
** database connection object to be interrogated.  ^The second argument
5121
** is the parameter to interrogate.  ^Currently, the only allowed value
5238
** is an integer constant, taken from the set of
5122
** for the second parameter is [SQLITE_DBSTATUS_LOOKASIDE_USED].
5239
** [SQLITE_DBSTATUS_LOOKASIDE_USED | SQLITE_DBSTATUS_*] macros, that
5123
** Additional options will likely appear in future releases of SQLite.
5240
** determines the parameter to interrogate.  The set of 
5241
** [SQLITE_DBSTATUS_LOOKASIDE_USED | SQLITE_DBSTATUS_*] macros is likely
5242
** to grow in future releases of SQLite.
5124
**
5243
**
5125
** ^The current value of the requested parameter is written into *pCur
5244
** ^The current value of the requested parameter is written into *pCur
5126
** and the highest instantaneous value is written into *pHiwtr.  ^If
5245
** and the highest instantaneous value is written into *pHiwtr.  ^If
 Lines 5129-5139   SQLITE_API SQLITE_EXPERIMENTAL int sqlit Link Here 
5129
**
5248
**
5130
** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
5249
** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
5131
*/
5250
*/
5132
SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
5251
SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
5133
5252
5134
/*
5253
/*
5135
** CAPI3REF: Status Parameters for database connections
5254
** CAPI3REF: Status Parameters for database connections
5136
** EXPERIMENTAL
5137
**
5255
**
5138
** These constants are the available integer "verbs" that can be passed as
5256
** These constants are the available integer "verbs" that can be passed as
5139
** the second argument to the [sqlite3_db_status()] interface.
5257
** the second argument to the [sqlite3_db_status()] interface.
 Lines 5148-5161   SQLITE_API SQLITE_EXPERIMENTAL int sqlit Link Here 
5148
** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
5266
** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
5149
** <dd>This parameter returns the number of lookaside memory slots currently
5267
** <dd>This parameter returns the number of lookaside memory slots currently
5150
** checked out.</dd>)^
5268
** checked out.</dd>)^
5269
**
5270
** ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
5271
** <dd>This parameter returns the approximate number of of bytes of heap
5272
** memory used by all pager caches associated with the database connection.)^
5273
** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
5274
**
5275
** ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
5276
** <dd>This parameter returns the approximate number of of bytes of heap
5277
** memory used to store the schema for all databases associated
5278
** with the connection - main, temp, and any [ATTACH]-ed databases.)^ 
5279
** ^The full amount of memory used by the schemas is reported, even if the
5280
** schema memory is shared with other database connections due to
5281
** [shared cache mode] being enabled.
5282
** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
5283
**
5284
** ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
5285
** <dd>This parameter returns the approximate number of of bytes of heap
5286
** and lookaside memory used by all prepared statements associated with
5287
** the database connection.)^
5288
** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
5289
** </dd>
5151
** </dl>
5290
** </dl>
5152
*/
5291
*/
5153
#define SQLITE_DBSTATUS_LOOKASIDE_USED     0
5292
#define SQLITE_DBSTATUS_LOOKASIDE_USED     0
5293
#define SQLITE_DBSTATUS_CACHE_USED         1
5294
#define SQLITE_DBSTATUS_SCHEMA_USED        2
5295
#define SQLITE_DBSTATUS_STMT_USED          3
5296
#define SQLITE_DBSTATUS_MAX                3   /* Largest defined DBSTATUS */
5154
5297
5155
5298
5156
/*
5299
/*
5157
** CAPI3REF: Prepared Statement Status
5300
** CAPI3REF: Prepared Statement Status
5158
** EXPERIMENTAL
5159
**
5301
**
5160
** ^(Each prepared statement maintains various
5302
** ^(Each prepared statement maintains various
5161
** [SQLITE_STMTSTATUS_SORT | counters] that measure the number
5303
** [SQLITE_STMTSTATUS_SORT | counters] that measure the number
 Lines 5177-5187   SQLITE_API SQLITE_EXPERIMENTAL int sqlit Link Here 
5177
**
5319
**
5178
** See also: [sqlite3_status()] and [sqlite3_db_status()].
5320
** See also: [sqlite3_status()] and [sqlite3_db_status()].
5179
*/
5321
*/
5180
SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
5322
SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
5181
5323
5182
/*
5324
/*
5183
** CAPI3REF: Status Parameters for prepared statements
5325
** CAPI3REF: Status Parameters for prepared statements
5184
** EXPERIMENTAL
5185
**
5326
**
5186
** These preprocessor macros define integer codes that name counter
5327
** These preprocessor macros define integer codes that name counter
5187
** values associated with the [sqlite3_stmt_status()] interface.
5328
** values associated with the [sqlite3_stmt_status()] interface.
 Lines 5199-5212   SQLITE_API SQLITE_EXPERIMENTAL int sqlit Link Here 
5199
** A non-zero value in this counter may indicate an opportunity to
5340
** A non-zero value in this counter may indicate an opportunity to
5200
** improvement performance through careful use of indices.</dd>
5341
** improvement performance through careful use of indices.</dd>
5201
**
5342
**
5343
** <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
5344
** <dd>^This is the number of rows inserted into transient indices that
5345
** were created automatically in order to help joins run faster.
5346
** A non-zero value in this counter may indicate an opportunity to
5347
** improvement performance by adding permanent indices that do not
5348
** need to be reinitialized each time the statement is run.</dd>
5349
**
5202
** </dl>
5350
** </dl>
5203
*/
5351
*/
5204
#define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
5352
#define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
5205
#define SQLITE_STMTSTATUS_SORT              2
5353
#define SQLITE_STMTSTATUS_SORT              2
5354
#define SQLITE_STMTSTATUS_AUTOINDEX         3
5206
5355
5207
/*
5356
/*
5208
** CAPI3REF: Custom Page Cache Object
5357
** CAPI3REF: Custom Page Cache Object
5209
** EXPERIMENTAL
5210
**
5358
**
5211
** The sqlite3_pcache type is opaque.  It is implemented by
5359
** The sqlite3_pcache type is opaque.  It is implemented by
5212
** the pluggable module.  The SQLite core has no knowledge of
5360
** the pluggable module.  The SQLite core has no knowledge of
 Lines 5221-5227   typedef struct sqlite3_pcache sqlite3_pc Link Here 
5221
/*
5369
/*
5222
** CAPI3REF: Application Defined Page Cache.
5370
** CAPI3REF: Application Defined Page Cache.
5223
** KEYWORDS: {page cache}
5371
** KEYWORDS: {page cache}
5224
** EXPERIMENTAL
5225
**
5372
**
5226
** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE], ...) interface can
5373
** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE], ...) interface can
5227
** register an alternative page cache implementation by passing in an 
5374
** register an alternative page cache implementation by passing in an 
 Lines 5363-5369   struct sqlite3_pcache_methods { Link Here 
5363
5510
5364
/*
5511
/*
5365
** CAPI3REF: Online Backup Object
5512
** CAPI3REF: Online Backup Object
5366
** EXPERIMENTAL
5367
**
5513
**
5368
** The sqlite3_backup object records state information about an ongoing
5514
** The sqlite3_backup object records state information about an ongoing
5369
** online backup operation.  ^The sqlite3_backup object is created by
5515
** online backup operation.  ^The sqlite3_backup object is created by
 Lines 5376-5382   typedef struct sqlite3_backup sqlite3_ba Link Here 
5376
5522
5377
/*
5523
/*
5378
** CAPI3REF: Online Backup API.
5524
** CAPI3REF: Online Backup API.
5379
** EXPERIMENTAL
5380
**
5525
**
5381
** The backup API copies the content of one database into another.
5526
** The backup API copies the content of one database into another.
5382
** It is useful either for creating backups of databases or
5527
** It is useful either for creating backups of databases or
 Lines 5445-5454   typedef struct sqlite3_backup sqlite3_ba Link Here 
5445
** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
5590
** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
5446
** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
5591
** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
5447
**
5592
**
5448
** ^The sqlite3_backup_step() might return [SQLITE_READONLY] if the destination
5593
** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
5449
** database was opened read-only or if
5594
** <ol>
5450
** the destination is an in-memory database with a different page size
5595
** <li> the destination database was opened read-only, or
5451
** from the source database.
5596
** <li> the destination database is using write-ahead-log journaling
5597
** and the destination and source page sizes differ, or
5598
** <li> The destination database is an in-memory database and the
5599
** destination and source page sizes differ.
5600
** </ol>)^
5452
**
5601
**
5453
** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
5602
** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
5454
** the [sqlite3_busy_handler | busy-handler function]
5603
** the [sqlite3_busy_handler | busy-handler function]
 Lines 5510-5516   typedef struct sqlite3_backup sqlite3_ba Link Here 
5510
**
5659
**
5511
** ^Each call to sqlite3_backup_step() sets two values inside
5660
** ^Each call to sqlite3_backup_step() sets two values inside
5512
** the [sqlite3_backup] object: the number of pages still to be backed
5661
** the [sqlite3_backup] object: the number of pages still to be backed
5513
** up and the total number of pages in the source databae file.
5662
** up and the total number of pages in the source database file.
5514
** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
5663
** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
5515
** retrieve these two values, respectively.
5664
** retrieve these two values, respectively.
5516
**
5665
**
 Lines 5564-5570   SQLITE_API int sqlite3_backup_pagecount( Link Here 
5564
5713
5565
/*
5714
/*
5566
** CAPI3REF: Unlock Notification
5715
** CAPI3REF: Unlock Notification
5567
** EXPERIMENTAL
5568
**
5716
**
5569
** ^When running in shared-cache mode, a database operation may fail with
5717
** ^When running in shared-cache mode, a database operation may fail with
5570
** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
5718
** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
 Lines 5607-5613   SQLITE_API int sqlite3_backup_pagecount( Link Here 
5607
** blocked connection already has a registered unlock-notify callback,
5755
** blocked connection already has a registered unlock-notify callback,
5608
** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
5756
** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
5609
** called with a NULL pointer as its second argument, then any existing
5757
** called with a NULL pointer as its second argument, then any existing
5610
** unlock-notify callback is cancelled. ^The blocked connections 
5758
** unlock-notify callback is canceled. ^The blocked connections 
5611
** unlock-notify callback may also be canceled by closing the blocked
5759
** unlock-notify callback may also be canceled by closing the blocked
5612
** connection using [sqlite3_close()].
5760
** connection using [sqlite3_close()].
5613
**
5761
**
 Lines 5686-5708   SQLITE_API int sqlite3_unlock_notify( Link Here 
5686
5834
5687
/*
5835
/*
5688
** CAPI3REF: String Comparison
5836
** CAPI3REF: String Comparison
5689
** EXPERIMENTAL
5690
**
5837
**
5691
** ^The [sqlite3_strnicmp()] API allows applications and extensions to
5838
** ^The [sqlite3_strnicmp()] API allows applications and extensions to
5692
** compare the contents of two buffers containing UTF-8 strings in a
5839
** compare the contents of two buffers containing UTF-8 strings in a
5693
** case-indendent fashion, using the same definition of case independence 
5840
** case-independent fashion, using the same definition of case independence 
5694
** that SQLite uses internally when comparing identifiers.
5841
** that SQLite uses internally when comparing identifiers.
5695
*/
5842
*/
5696
SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
5843
SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
5697
5844
5698
/*
5845
/*
5699
** CAPI3REF: Error Logging Interface
5846
** CAPI3REF: Error Logging Interface
5700
** EXPERIMENTAL
5701
**
5847
**
5702
** ^The [sqlite3_log()] interface writes a message into the error log
5848
** ^The [sqlite3_log()] interface writes a message into the error log
5703
** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
5849
** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
5704
** ^If logging is enabled, the zFormat string and subsequent arguments are
5850
** ^If logging is enabled, the zFormat string and subsequent arguments are
5705
** passed through to [sqlite3_vmprintf()] to generate the final output string.
5851
** used with [sqlite3_snprintf()] to generate the final output string.
5706
**
5852
**
5707
** The sqlite3_log() interface is intended for use by extensions such as
5853
** The sqlite3_log() interface is intended for use by extensions such as
5708
** virtual tables, collating functions, and SQL functions.  While there is
5854
** virtual tables, collating functions, and SQL functions.  While there is
 Lines 5720-5725   SQLITE_API int sqlite3_strnicmp(const ch Link Here 
5720
SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
5866
SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
5721
5867
5722
/*
5868
/*
5869
** CAPI3REF: Write-Ahead Log Commit Hook
5870
**
5871
** ^The [sqlite3_wal_hook()] function is used to register a callback that
5872
** will be invoked each time a database connection commits data to a
5873
** [write-ahead log] (i.e. whenever a transaction is committed in
5874
** [journal_mode | journal_mode=WAL mode]). 
5875
**
5876
** ^The callback is invoked by SQLite after the commit has taken place and 
5877
** the associated write-lock on the database released, so the implementation 
5878
** may read, write or [checkpoint] the database as required.
5879
**
5880
** ^The first parameter passed to the callback function when it is invoked
5881
** is a copy of the third parameter passed to sqlite3_wal_hook() when
5882
** registering the callback. ^The second is a copy of the database handle.
5883
** ^The third parameter is the name of the database that was written to -
5884
** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
5885
** is the number of pages currently in the write-ahead log file,
5886
** including those that were just committed.
5887
**
5888
** The callback function should normally return [SQLITE_OK].  ^If an error
5889
** code is returned, that error will propagate back up through the
5890
** SQLite code base to cause the statement that provoked the callback
5891
** to report an error, though the commit will have still occurred. If the
5892
** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
5893
** that does not correspond to any valid SQLite error code, the results
5894
** are undefined.
5895
**
5896
** A single database handle may have at most a single write-ahead log callback 
5897
** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
5898
** previously registered write-ahead log callback. ^Note that the
5899
** [sqlite3_wal_autocheckpoint()] interface and the
5900
** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
5901
** those overwrite any prior [sqlite3_wal_hook()] settings.
5902
*/
5903
SQLITE_API void *sqlite3_wal_hook(
5904
  sqlite3*, 
5905
  int(*)(void *,sqlite3*,const char*,int),
5906
  void*
5907
);
5908
5909
/*
5910
** CAPI3REF: Configure an auto-checkpoint
5911
**
5912
** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
5913
** [sqlite3_wal_hook()] that causes any database on [database connection] D
5914
** to automatically [checkpoint]
5915
** after committing a transaction if there are N or
5916
** more frames in the [write-ahead log] file.  ^Passing zero or 
5917
** a negative value as the nFrame parameter disables automatic
5918
** checkpoints entirely.
5919
**
5920
** ^The callback registered by this function replaces any existing callback
5921
** registered using [sqlite3_wal_hook()].  ^Likewise, registering a callback
5922
** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
5923
** configured by this function.
5924
**
5925
** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
5926
** from SQL.
5927
**
5928
** ^Every new [database connection] defaults to having the auto-checkpoint
5929
** enabled with a threshold of 1000 pages.  The use of this interface
5930
** is only necessary if the default setting is found to be suboptimal
5931
** for a particular application.
5932
*/
5933
SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
5934
5935
/*
5936
** CAPI3REF: Checkpoint a database
5937
**
5938
** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X
5939
** on [database connection] D to be [checkpointed].  ^If X is NULL or an
5940
** empty string, then a checkpoint is run on all databases of
5941
** connection D.  ^If the database connection D is not in
5942
** [WAL | write-ahead log mode] then this interface is a harmless no-op.
5943
**
5944
** ^The [wal_checkpoint pragma] can be used to invoke this interface
5945
** from SQL.  ^The [sqlite3_wal_autocheckpoint()] interface and the
5946
** [wal_autocheckpoint pragma] can be used to cause this interface to be
5947
** run whenever the WAL reaches a certain size threshold.
5948
*/
5949
SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
5950
5951
/*
5723
** Undo the hack that converts floating point types to integer for
5952
** Undo the hack that converts floating point types to integer for
5724
** builds on processors without floating point support.
5953
** builds on processors without floating point support.
5725
*/
5954
*/

Return to bug 581606