diff --git a/Makefile b/Makefile index 68ed0964..59c72506 100644 --- a/Makefile +++ b/Makefile @@ -136,6 +136,7 @@ include third_party/third_party.mk include libc/testlib/testlib.mk include tool/viz/lib/vizlib.mk include third_party/lua/lua.mk +include third_party/sqlite3/sqlite3.mk include third_party/quickjs/quickjs.mk include third_party/lz4cli/lz4cli.mk include tool/build/lib/buildlib.mk diff --git a/third_party/sqlite3/alter.c b/third_party/sqlite3/alter.c index 175f8981..be29d9f5 100644 --- a/third_party/sqlite3/alter.c +++ b/third_party/sqlite3/alter.c @@ -12,7 +12,8 @@ ** This file contains C code routines that used to generate VDBE code ** that implements the ALTER TABLE command. */ -#include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" +/* clang-format off */ /* ** The code in this file only exists if we are not omitting the diff --git a/third_party/sqlite3/analyze.c b/third_party/sqlite3/analyze.c index dc77220a..d579e89c 100644 --- a/third_party/sqlite3/analyze.c +++ b/third_party/sqlite3/analyze.c @@ -30,7 +30,7 @@ ** created and used by SQLite versions 3.7.9 through 3.29.0 when ** SQLITE_ENABLE_STAT3 defined. The functionality of sqlite_stat3 ** is a superset of sqlite_stat2 and is also now deprecated. The -** sqlite_stat4 is an enhanced version of sqlite_stat3 and is only +** sqlite_stat4 is an enhanced version of sqlite_stat3 and is only ** available when compiled with SQLITE_ENABLE_STAT4 and in SQLite ** versions 3.8.1 and later. STAT4 is the only variant that is still ** supported. @@ -49,7 +49,7 @@ ** integer is the average number of rows in the index that have the same ** value in the first column of the index. The third integer is the average ** number of rows in the index that have the same value for the first two -** columns. The N-th integer (for N>1) is the average number of rows in +** columns. The N-th integer (for N>1) is the average number of rows in ** the index which have the same value for the first N-1 columns. For ** a K-column index, there will be K+1 integers in the stat column. If ** the index is unique, then the last integer will be 1. @@ -59,7 +59,7 @@ ** must be separated from the last integer by a single space. If the ** "unordered" keyword is present, then the query planner assumes that ** the index is unordered and will not use the index for a range query. -** +** ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat ** column contains a single integer which is the (estimated) number of ** rows in the table identified by sqlite_stat1.tbl. @@ -117,9 +117,9 @@ ** number of entries that are strictly less than the sample. The first ** integer in nLt contains the number of entries in the index where the ** left-most column is less than the left-most column of the sample. -** The K-th integer in the nLt entry is the number of index entries +** The K-th integer in the nLt entry is the number of index entries ** where the first K columns are less than the first K columns of the -** sample. The nDLt column is like nLt except that it contains the +** sample. The nDLt column is like nLt except that it contains the ** number of distinct entries in the index that are less than the ** sample. ** @@ -140,7 +140,8 @@ ** integer in the equivalent columns in sqlite_stat4. */ #ifndef SQLITE_OMIT_ANALYZE -#include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" +/* clang-format off */ #if defined(SQLITE_ENABLE_STAT4) # define IsStat4 1 diff --git a/third_party/sqlite3/attach.c b/third_party/sqlite3/attach.c index 8eb4486e..4bae45fe 100644 --- a/third_party/sqlite3/attach.c +++ b/third_party/sqlite3/attach.c @@ -11,7 +11,8 @@ ************************************************************************* ** This file contains code used to implement the ATTACH and DETACH commands. */ -#include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" +/* clang-format off */ #ifndef SQLITE_OMIT_ATTACH /* diff --git a/third_party/sqlite3/auth.c b/third_party/sqlite3/auth.c index 33420f58..ce65bb7a 100644 --- a/third_party/sqlite3/auth.c +++ b/third_party/sqlite3/auth.c @@ -14,7 +14,8 @@ ** systems that do not need this facility may omit it by recompiling ** the library with -DSQLITE_OMIT_AUTHORIZATION=1 */ -#include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" +/* clang-format off */ /* ** All of the code in this file may be omitted by defining a single diff --git a/third_party/sqlite3/backup.c b/third_party/sqlite3/backup.c index 2b286de6..860841de 100644 --- a/third_party/sqlite3/backup.c +++ b/third_party/sqlite3/backup.c @@ -9,11 +9,12 @@ ** May you share freely, never taking more than you give. ** ************************************************************************* -** This file contains the implementation of the sqlite3_backup_XXX() +** This file contains the implementation of the sqlite3_backup_XXX() ** API functions and the related features. */ -#include "sqliteInt.h" -#include "btreeInt.h" +#include "third_party/sqlite3/btreeInt.h" +#include "third_party/sqlite3/sqliteInt.h" +/* clang-format off */ /* ** Structure allocated for each backup operation. diff --git a/third_party/sqlite3/bitvec.c b/third_party/sqlite3/bitvec.c index bd4a0942..14cba75c 100644 --- a/third_party/sqlite3/bitvec.c +++ b/third_party/sqlite3/bitvec.c @@ -17,8 +17,8 @@ ** property. Usually only a few pages are meet either condition. ** So the bitmap is usually sparse and has low cardinality. ** But sometimes (for example when during a DROP of a large table) most -** or all of the pages in a database can get journalled. In those cases, -** the bitmap becomes dense with high cardinality. The algorithm needs +** or all of the pages in a database can get journalled. In those cases, +** the bitmap becomes dense with high cardinality. The algorithm needs ** to handle both cases well. ** ** The size of the bitmap is fixed when the object is created. @@ -34,7 +34,8 @@ ** start of a transaction, and is thus usually less than a few thousand, ** but can be as large as 2 billion for a really big database. */ -#include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" +/* clang-format off */ /* Size of the Bitvec structure in bytes. */ #define BITVEC_SZ 512 diff --git a/third_party/sqlite3/btmutex.c b/third_party/sqlite3/btmutex.c index 275a93ff..9a21e6e8 100644 --- a/third_party/sqlite3/btmutex.c +++ b/third_party/sqlite3/btmutex.c @@ -15,7 +15,9 @@ ** big and we want to break it down some. This packaged seemed like ** a good breakout. */ -#include "btreeInt.h" +#include "third_party/sqlite3/btreeInt.h" + +/* clang-format off */ #ifndef SQLITE_OMIT_SHARED_CACHE #if SQLITE_THREADSAFE diff --git a/third_party/sqlite3/btree.c b/third_party/sqlite3/btree.c index 1623e017..ec56027d 100644 --- a/third_party/sqlite3/btree.c +++ b/third_party/sqlite3/btree.c @@ -13,7 +13,9 @@ ** See the header comment on "btreeInt.h" for additional information. ** Including a description of file format and an overview of operation. */ -#include "btreeInt.h" +#include "third_party/sqlite3/btreeInt.h" + +/* clang-format off */ /* ** The header string that appears at the beginning of every diff --git a/third_party/sqlite3/btree.h b/third_party/sqlite3/btree.h index b7afecc4..9c77efd0 100644 --- a/third_party/sqlite3/btree.h +++ b/third_party/sqlite3/btree.h @@ -1,20 +1,6 @@ -/* -** 2001 September 15 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** This header file defines the interface that the sqlite B-Tree file -** subsystem. See comments in the source code for a detailed description -** of what each interface routine does. -*/ #ifndef SQLITE_BTREE_H #define SQLITE_BTREE_H +/* clang-format off */ /* TODO: This definition is just included so other modules compile. It ** needs to be revisited. @@ -359,7 +345,7 @@ void sqlite3BtreeCursorList(Btree*); #endif #ifndef SQLITE_OMIT_WAL - int sqlite3BtreeCheckpoint(Btree*, int, int *, int *); + /* int sqlite3BtreeCheckpoint(Btree*, int, int *, int *); */ #endif int sqlite3BtreeTransferRow(BtCursor*, BtCursor*, i64); diff --git a/third_party/sqlite3/btreeInt.h b/third_party/sqlite3/btreeInt.h index 37c07fe9..fc3ebf06 100644 --- a/third_party/sqlite3/btreeInt.h +++ b/third_party/sqlite3/btreeInt.h @@ -29,16 +29,16 @@ ** on Ptr(N) and its subpages have values greater than Key(N-1). And ** so forth. ** -** Finding a particular key requires reading O(log(M)) pages from the +** Finding a particular key requires reading O(log(M)) pages from the ** disk where M is the number of entries in the tree. ** -** In this implementation, a single file can hold one or more separate +** In this implementation, a single file can hold one or more separate ** BTrees. Each BTree is identified by the index of its root page. The ** key and data for any entry are combined to form the "payload". A ** fixed amount of payload can be carried directly on the database ** page. If the payload is larger than the preset amount then surplus ** bytes are stored on overflow pages. The payload for an entry -** and the preceding pointer are combined to form a "Cell". Each +** and the preceding pointer are combined to form a "Cell". Each ** page has a small header which contains the Ptr(N) pointer and other ** information such as the size of key and data. ** @@ -168,7 +168,7 @@ ** contiguous or in order, but cell pointers are contiguous and in order. ** ** Cell content makes use of variable length integers. A variable -** length integer is 1 to 9 bytes where the lower 7 bits of each +** length integer is 1 to 9 bytes where the lower 7 bits of each ** byte are used. The integer consists of all bytes that have bit 8 set and ** the first byte with bit 8 clear. The most significant byte of the integer ** appears first. A variable-length integer may not be more than 9 bytes long. @@ -213,8 +213,9 @@ ** 4 Number of leaf pointers on this page ** * zero or more pages numbers of leaves */ -#include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" +/* clang-format off */ /* The following value is the maximum cell size assuming a maximum page ** size give above. diff --git a/third_party/sqlite3/build.c b/third_party/sqlite3/build.c index b6faf080..e0e5908f 100644 --- a/third_party/sqlite3/build.c +++ b/third_party/sqlite3/build.c @@ -22,7 +22,9 @@ ** COMMIT ** ROLLBACK */ -#include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" + +/* clang-format off */ #ifndef SQLITE_OMIT_SHARED_CACHE /* diff --git a/third_party/sqlite3/callback.c b/third_party/sqlite3/callback.c index 421cef28..dc659886 100644 --- a/third_party/sqlite3/callback.c +++ b/third_party/sqlite3/callback.c @@ -1,5 +1,5 @@ /* -** 2005 May 23 +** 2005 May 23 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: @@ -13,8 +13,9 @@ ** This file contains functions used to access the internal hash tables ** of user defined functions and collation sequences. */ +#include "third_party/sqlite3/sqliteInt.h" -#include "sqliteInt.h" +/* clang-format off */ /* ** Invoke the 'collation needed' callback to request a collation sequence diff --git a/third_party/sqlite3/complete.c b/third_party/sqlite3/complete.c index bb2c0309..12f0973a 100644 --- a/third_party/sqlite3/complete.c +++ b/third_party/sqlite3/complete.c @@ -16,7 +16,10 @@ ** separating it out, the code will be automatically omitted from ** static links that do not use it. */ -#include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" + +/* clang-format off */ + #ifndef SQLITE_OMIT_COMPLETE /* diff --git a/third_party/sqlite3/ctime.c b/third_party/sqlite3/ctime.c index 7982f23a..2ea9bd3c 100644 --- a/third_party/sqlite3/ctime.c +++ b/third_party/sqlite3/ctime.c @@ -13,6 +13,7 @@ ** This file implements routines used to report what compile-time options ** SQLite was built with. */ +/* clang-format off */ #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS /* IMP: R-16824-07538 */ @@ -21,7 +22,7 @@ ** autoconf-based build */ #if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H) -#include "config.h" +#include "third_party/sqlite3/config.h" #define SQLITECONFIG_H 1 #endif diff --git a/third_party/sqlite3/date.c b/third_party/sqlite3/date.c index f88f544e..c6e543ad 100644 --- a/third_party/sqlite3/date.c +++ b/third_party/sqlite3/date.c @@ -10,7 +10,7 @@ ** ************************************************************************* ** This file contains the C functions that implement date and time -** functions for SQLite. +** functions for SQLite. ** ** There is only one exported symbol in this file - the function ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file. @@ -19,7 +19,7 @@ ** SQLite processes all times and dates as julian day numbers. The ** dates and times are stored as the number of days since noon ** in Greenwich on November 24, 4714 B.C. according to the Gregorian -** calendar system. +** calendar system. ** ** 1970-01-01 00:00:00 is JD 2440587.5 ** 2000-01-01 00:00:00 is JD 2451544.5 @@ -43,10 +43,14 @@ ** Willmann-Bell, Inc ** Richmond, Virginia (USA) */ -#include "sqliteInt.h" -#include -#include -#include +#include "libc/assert.h" +#include "libc/calls/weirdtypes.h" +#include "libc/mem/mem.h" +#include "libc/time/struct/tm.h" +#include "libc/time/time.h" +#include "third_party/sqlite3/sqliteInt.h" + +/* clang-format off */ #ifndef SQLITE_OMIT_DATETIME_FUNCS diff --git a/third_party/sqlite3/dbpage.c b/third_party/sqlite3/dbpage.c index c4f0b539..9800a13b 100644 --- a/third_party/sqlite3/dbpage.c +++ b/third_party/sqlite3/dbpage.c @@ -13,7 +13,7 @@ ** This file contains an implementation of the "sqlite_dbpage" virtual table. ** ** The sqlite_dbpage virtual table is used to read or write whole raw -** pages of the database file. The pager interface is used so that +** pages of the database file. The pager interface is used so that ** uncommitted changes and changes recorded in the WAL file are correctly ** retrieved. ** @@ -30,10 +30,12 @@ ** value must be a BLOB which is the correct page size, otherwise the ** update fails. Rows may not be deleted or inserted. */ +#include "third_party/sqlite3/sqliteInt.h" /* Requires access to internal data structures */ -#include "sqliteInt.h" /* Requires access to internal data structures */ -#if (defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST)) \ - && !defined(SQLITE_OMIT_VIRTUALTABLE) +/* clang-format off */ + +#if (defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST)) && \ + !defined(SQLITE_OMIT_VIRTUALTABLE) typedef struct DbpageTable DbpageTable; typedef struct DbpageCursor DbpageCursor; diff --git a/third_party/sqlite3/dbstat.c b/third_party/sqlite3/dbstat.c index 78173c39..a2982221 100644 --- a/third_party/sqlite3/dbstat.c +++ b/third_party/sqlite3/dbstat.c @@ -20,10 +20,12 @@ ** Additional information is available on the "dbstat.html" page of the ** official SQLite documentation. */ +#include "third_party/sqlite3/sqliteInt.h" /* Requires access to internal data structures */ -#include "sqliteInt.h" /* Requires access to internal data structures */ -#if (defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)) \ - && !defined(SQLITE_OMIT_VIRTUALTABLE) +/* clang-format off */ + +#if (defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)) && \ + !defined(SQLITE_OMIT_VIRTUALTABLE) /* ** Page paths: diff --git a/third_party/sqlite3/delete.c b/third_party/sqlite3/delete.c index 0c9c7bc8..7b8c7d60 100644 --- a/third_party/sqlite3/delete.c +++ b/third_party/sqlite3/delete.c @@ -12,7 +12,9 @@ ** This file contains C code routines that are called by the parser ** in order to generate code for DELETE FROM statements. */ -#include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" + +/* clang-format off */ /* ** While a SrcList can in general represent multiple tables and subqueries diff --git a/third_party/sqlite3/expr.c b/third_party/sqlite3/expr.c index 6a58616d..235a427d 100644 --- a/third_party/sqlite3/expr.c +++ b/third_party/sqlite3/expr.c @@ -12,7 +12,9 @@ ** This file contains routines used for analyzing expressions and ** for generating VDBE code that evaluates expressions in SQLite. */ -#include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" + +/* clang-format off */ /* Forward declarations */ static void exprCodeBetween(Parse*,Expr*,int,void(*)(Parse*,Expr*,int,int),int); diff --git a/third_party/sqlite3/fault.c b/third_party/sqlite3/fault.c index 5b41b603..104a0979 100644 --- a/third_party/sqlite3/fault.c +++ b/third_party/sqlite3/fault.c @@ -10,21 +10,22 @@ ** ************************************************************************* ** -** This file contains code to support the concept of "benign" +** This file contains code to support the concept of "benign" ** malloc failures (when the xMalloc() or xRealloc() method of the ** sqlite3_mem_methods structure fails to allocate a block of memory -** and returns 0). +** and returns 0). ** ** Most malloc failures are non-benign. After they occur, SQLite ** abandons the current operation and returns an error code (usually ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily -** fatal. For example, if a malloc fails while resizing a hash table, this -** is completely recoverable simply by not carrying out the resize. The -** hash table will continue to function normally. So a malloc failure +** fatal. For example, if a malloc fails while resizing a hash table, this +** is completely recoverable simply by not carrying out the resize. The +** hash table will continue to function normally. So a malloc failure ** during a hash table resize is a benign fault. */ +#include "third_party/sqlite3/sqliteInt.h" -#include "sqliteInt.h" +/* clang-format off */ #ifndef SQLITE_UNTESTABLE diff --git a/third_party/sqlite3/fkey.c b/third_party/sqlite3/fkey.c index 9f622f40..fdb52a91 100644 --- a/third_party/sqlite3/fkey.c +++ b/third_party/sqlite3/fkey.c @@ -11,7 +11,9 @@ ** This file contains code used by the compiler to add foreign key ** support to compiled SQL statements. */ -#include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" + +/* clang-format off */ #ifndef SQLITE_OMIT_FOREIGN_KEY #ifndef SQLITE_OMIT_TRIGGER diff --git a/third_party/sqlite3/fts1.c b/third_party/sqlite3/fts1.c index 77fa9e23..6a24348d 100644 --- a/third_party/sqlite3/fts1.c +++ b/third_party/sqlite3/fts1.c @@ -3,6 +3,9 @@ ** fts3 (or higher). If you believe that your use of fts1 is safe, ** add -DSQLITE_ENABLE_BROKEN_FTS1=1 to your CFLAGS. */ + +/* clang-format off */ + #if (!defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS1)) \ && !defined(SQLITE_ENABLE_BROKEN_FTS1) #error fts1 has a design flaw and has been deprecated. diff --git a/third_party/sqlite3/fts1_hash.c b/third_party/sqlite3/fts1_hash.c index 463a52b6..00e76260 100644 --- a/third_party/sqlite3/fts1_hash.c +++ b/third_party/sqlite3/fts1_hash.c @@ -13,9 +13,8 @@ ** We've modified it slightly to serve as a standalone hash table ** implementation for the full-text indexing module. */ -#include -#include -#include + +/* clang-format off */ /* ** The code in this file is only compiled if: @@ -29,7 +28,7 @@ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS1) -#include "fts1_hash.h" +#include "third_party/sqlite3/fts1_hash.h" static void *malloc_and_zero(int n){ void *p = malloc(n); diff --git a/third_party/sqlite3/fts1_hash.h b/third_party/sqlite3/fts1_hash.h index 90011529..e06d7721 100644 --- a/third_party/sqlite3/fts1_hash.h +++ b/third_party/sqlite3/fts1_hash.h @@ -17,6 +17,8 @@ #ifndef _FTS1_HASH_H_ #define _FTS1_HASH_H_ +/* clang-format off */ + /* Forward declarations of structures. */ typedef struct fts1Hash fts1Hash; typedef struct fts1HashElem fts1HashElem; diff --git a/third_party/sqlite3/fts1_porter.c b/third_party/sqlite3/fts1_porter.c index 1d262366..620f24d0 100644 --- a/third_party/sqlite3/fts1_porter.c +++ b/third_party/sqlite3/fts1_porter.c @@ -12,7 +12,6 @@ ** Implementation of the full-text-search tokenizer that implements ** a Porter stemmer. */ - /* ** The code in this file is only compiled if: ** @@ -24,6 +23,7 @@ */ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS1) +/* clang-format off */ #include #include diff --git a/third_party/sqlite3/fts1_tokenizer.h b/third_party/sqlite3/fts1_tokenizer.h index a48cb745..dda8d655 100644 --- a/third_party/sqlite3/fts1_tokenizer.h +++ b/third_party/sqlite3/fts1_tokenizer.h @@ -20,6 +20,8 @@ #ifndef _FTS1_TOKENIZER_H_ #define _FTS1_TOKENIZER_H_ +/* clang-format off */ + /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time. ** If tokenizers are to be allowed to call sqlite3_*() functions, then ** we will need a way to register the API consistently. diff --git a/third_party/sqlite3/fts1_tokenizer1.c b/third_party/sqlite3/fts1_tokenizer1.c index f58fba8f..5cac2a3f 100644 --- a/third_party/sqlite3/fts1_tokenizer1.c +++ b/third_party/sqlite3/fts1_tokenizer1.c @@ -4,7 +4,6 @@ ************************************************************************* ** Implementation of the "simple" full-text-search tokenizer. */ - /* ** The code in this file is only compiled if: ** @@ -16,6 +15,7 @@ */ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS1) +/* clang-format off */ #include #include diff --git a/third_party/sqlite3/fts2.c b/third_party/sqlite3/fts2.c index 0405fb7b..40b1d348 100644 --- a/third_party/sqlite3/fts2.c +++ b/third_party/sqlite3/fts2.c @@ -3,6 +3,7 @@ ** fts3 (or higher). If you believe that your use of fts2 is safe, ** add -DSQLITE_ENABLE_BROKEN_FTS2=1 to your CFLAGS. */ +/* clang-format off */ #if (!defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS2)) \ && !defined(SQLITE_ENABLE_BROKEN_FTS2) #error fts2 has a design flaw and has been deprecated. diff --git a/third_party/sqlite3/fts2_hash.c b/third_party/sqlite3/fts2_hash.c index 3596dcf0..5dd41db7 100644 --- a/third_party/sqlite3/fts2_hash.c +++ b/third_party/sqlite3/fts2_hash.c @@ -13,7 +13,6 @@ ** We've modified it slightly to serve as a standalone hash table ** implementation for the full-text indexing module. */ - /* ** The code in this file is only compiled if: ** @@ -23,6 +22,7 @@ ** * The FTS2 module is being built into the core of ** SQLite (in which case SQLITE_ENABLE_FTS2 is defined). */ +/* clang-format off */ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS2) #include diff --git a/third_party/sqlite3/fts2_hash.h b/third_party/sqlite3/fts2_hash.h index 02936f18..86c6c0da 100644 --- a/third_party/sqlite3/fts2_hash.h +++ b/third_party/sqlite3/fts2_hash.h @@ -17,6 +17,8 @@ #ifndef _FTS2_HASH_H_ #define _FTS2_HASH_H_ +/* clang-format off */ + /* Forward declarations of structures. */ typedef struct fts2Hash fts2Hash; typedef struct fts2HashElem fts2HashElem; diff --git a/third_party/sqlite3/fts2_icu.c b/third_party/sqlite3/fts2_icu.c index 2670301f..170b285f 100644 --- a/third_party/sqlite3/fts2_icu.c +++ b/third_party/sqlite3/fts2_icu.c @@ -10,13 +10,14 @@ ** ************************************************************************* ** This file implements a tokenizer for fts2 based on the ICU library. -** +** ** $Id: fts2_icu.c,v 1.3 2008/12/18 05:30:26 danielk1977 Exp $ */ - #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS2) #ifdef SQLITE_ENABLE_ICU +/* clang-format off */ + #include #include #include "fts2_tokenizer.h" diff --git a/third_party/sqlite3/fts2_porter.c b/third_party/sqlite3/fts2_porter.c index 881baf71..29a9c32f 100644 --- a/third_party/sqlite3/fts2_porter.c +++ b/third_party/sqlite3/fts2_porter.c @@ -12,7 +12,6 @@ ** Implementation of the full-text-search tokenizer that implements ** a Porter stemmer. */ - /* ** The code in this file is only compiled if: ** @@ -24,6 +23,7 @@ */ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS2) +/* clang-format off */ #include #include diff --git a/third_party/sqlite3/fts2_tokenizer.c b/third_party/sqlite3/fts2_tokenizer.c index dda33a72..8c9aa8ab 100644 --- a/third_party/sqlite3/fts2_tokenizer.c +++ b/third_party/sqlite3/fts2_tokenizer.c @@ -13,7 +13,6 @@ ** This is part of an SQLite module implementing full-text search. ** This particular file implements the generic tokenizer interface. */ - /* ** The code in this file is only compiled if: ** @@ -25,6 +24,7 @@ */ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS2) +/* clang-format off */ #include "sqlite3.h" #include "sqlite3ext.h" diff --git a/third_party/sqlite3/fts2_tokenizer.h b/third_party/sqlite3/fts2_tokenizer.h index 8db2048d..126f6b32 100644 --- a/third_party/sqlite3/fts2_tokenizer.h +++ b/third_party/sqlite3/fts2_tokenizer.h @@ -20,6 +20,8 @@ #ifndef _FTS2_TOKENIZER_H_ #define _FTS2_TOKENIZER_H_ +/* clang-format off */ + /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time. ** If tokenizers are to be allowed to call sqlite3_*() functions, then ** we will need a way to register the API consistently. diff --git a/third_party/sqlite3/fts2_tokenizer1.c b/third_party/sqlite3/fts2_tokenizer1.c index fe4f9eb4..bb326111 100644 --- a/third_party/sqlite3/fts2_tokenizer1.c +++ b/third_party/sqlite3/fts2_tokenizer1.c @@ -12,7 +12,6 @@ ** ** Implementation of the "simple" full-text-search tokenizer. */ - /* ** The code in this file is only compiled if: ** @@ -24,6 +23,7 @@ */ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS2) +/* clang-format off */ #include #include diff --git a/third_party/sqlite3/fts3.c b/third_party/sqlite3/fts3.c index 50fa88db..cedd5ca5 100644 --- a/third_party/sqlite3/fts3.c +++ b/third_party/sqlite3/fts3.c @@ -61,7 +61,7 @@ ** A doclist (document list) holds a docid-sorted list of hits for a ** given term. Doclists hold docids and associated token positions. ** A docid is the unique integer identifier for a single document. -** A position is the index of a word within the document. The first +** A position is the index of a word within the document. The first ** word of the document has a position of 0. ** ** FTS3 used to optionally store character offsets using a compile-time @@ -86,7 +86,7 @@ ** ** Here, array { X } means zero or more occurrences of X, adjacent in ** memory. A "position" is an index of a token in the token stream -** generated by the tokenizer. Note that POS_END and POS_COLUMN occur +** generated by the tokenizer. Note that POS_END and POS_COLUMN occur ** in the same logical place as the position element, and act as sentinals ** ending a position list array. POS_END is 0. POS_COLUMN is 1. ** The positions numbers are not stored literally but rather as two more @@ -110,7 +110,7 @@ ** a document record consists of a docid followed by a position-list and ** a doclist consists of one or more document records. ** -** A bare doclist omits the position information, becoming an +** A bare doclist omits the position information, becoming an ** array of varint-encoded docids. ** **** Segment leaf nodes **** @@ -287,25 +287,23 @@ ** query logic likewise merges doclists so that newer data knocks out ** older data. */ +/* clang-format off */ -#include "fts3Int.h" +#include "third_party/sqlite3/fts3Int.h" #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE) # define SQLITE_CORE 1 #endif -#include -#include -#include -#include -#include -#include - -#include "fts3.h" -#ifndef SQLITE_CORE -# include "sqlite3ext.h" - SQLITE_EXTENSION_INIT1 +#include "libc/assert.h" +#include "libc/mem/mem.h" +#include "libc/stdio/stdio.h" +#include "libc/str/str.h" +#include "third_party/sqlite3/fts3.h" +#ifndef SQLITE_CORE +#include "third_party/sqlite3/sqlite3ext.h" +SQLITE_EXTENSION_INIT1 #endif static int fts3EvalNext(Fts3Cursor *pCsr); diff --git a/third_party/sqlite3/fts3.h b/third_party/sqlite3/fts3.h index c1aa8caf..10283cff 100644 --- a/third_party/sqlite3/fts3.h +++ b/third_party/sqlite3/fts3.h @@ -13,7 +13,7 @@ ** This header file is used by programs that want to link against the ** FTS3 library. All it does is declare the sqlite3Fts3Init() interface. */ -#include "sqlite3.h" +#include "third_party/sqlite3/sqlite3.h" #ifdef __cplusplus extern "C" { diff --git a/third_party/sqlite3/fts3Int.h b/third_party/sqlite3/fts3Int.h index b3e0ec85..0d2a7717 100644 --- a/third_party/sqlite3/fts3Int.h +++ b/third_party/sqlite3/fts3Int.h @@ -13,6 +13,7 @@ */ #ifndef _FTSINT_H #define _FTSINT_H +/* clang-format off */ #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) # define NDEBUG 1 @@ -37,13 +38,13 @@ /* If not building as part of the core, include sqlite3ext.h. */ #ifndef SQLITE_CORE -# include "sqlite3ext.h" +#include "third_party/sqlite3/sqlite3ext.h" SQLITE_EXTENSION_INIT3 #endif -#include "sqlite3.h" -#include "fts3_tokenizer.h" -#include "fts3_hash.h" +#include "third_party/sqlite3/fts3_hash.h" +#include "third_party/sqlite3/fts3_tokenizer.h" +#include "third_party/sqlite3/sqlite3.h" /* ** This constant determines the maximum depth of an FTS expression tree diff --git a/third_party/sqlite3/fts3_aux.c b/third_party/sqlite3/fts3_aux.c index 08edc00f..b9240c0d 100644 --- a/third_party/sqlite3/fts3_aux.c +++ b/third_party/sqlite3/fts3_aux.c @@ -11,11 +11,12 @@ ****************************************************************************** ** */ -#include "fts3Int.h" +/* clang-format off */ +#include "third_party/sqlite3/fts3Int.h" #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) -#include -#include +#include "libc/assert.h" +#include "libc/str/str.h" typedef struct Fts3auxTable Fts3auxTable; typedef struct Fts3auxCursor Fts3auxCursor; diff --git a/third_party/sqlite3/fts3_expr.c b/third_party/sqlite3/fts3_expr.c index 7a69a935..44ae012f 100644 --- a/third_party/sqlite3/fts3_expr.c +++ b/third_party/sqlite3/fts3_expr.c @@ -11,12 +11,13 @@ ****************************************************************************** ** ** This module contains code that implements a parser for fts3 query strings -** (the right-hand argument to the MATCH operator). Because the supported +** (the right-hand argument to the MATCH operator). Because the supported ** syntax is relatively simple, the whole tokenizer/parser system is -** hand-coded. +** hand-coded. */ -#include "fts3Int.h" +#include "third_party/sqlite3/fts3Int.h" #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) +/* clang-format off */ /* ** By default, this module parses the legacy syntax that has been @@ -78,8 +79,8 @@ int sqlite3_fts3_enable_parentheses = 0; */ #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10 -#include -#include +#include "libc/assert.h" +#include "libc/str/str.h" /* ** isNot: @@ -1107,7 +1108,7 @@ void sqlite3Fts3ExprFree(Fts3Expr *pDel){ #ifdef SQLITE_TEST -#include +#include "libc/stdio/stdio.h" /* ** Return a pointer to a buffer containing a text representation of the diff --git a/third_party/sqlite3/fts3_hash.c b/third_party/sqlite3/fts3_hash.c index 63e55b3d..46c2a2df 100644 --- a/third_party/sqlite3/fts3_hash.c +++ b/third_party/sqlite3/fts3_hash.c @@ -13,6 +13,7 @@ ** We've modified it slightly to serve as a standalone hash table ** implementation for the full-text indexing module. */ +/* clang-format off */ /* ** The code in this file is only compiled if: @@ -23,14 +24,13 @@ ** * The FTS3 module is being built into the core of ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined). */ -#include "fts3Int.h" +#include "third_party/sqlite3/fts3Int.h" #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) -#include -#include -#include - -#include "fts3_hash.h" +#include "libc/assert.h" +#include "libc/mem/mem.h" +#include "libc/str/str.h" +#include "third_party/sqlite3/fts3_hash.h" /* ** Malloc and Free functions diff --git a/third_party/sqlite3/fts3_hash.h b/third_party/sqlite3/fts3_hash.h index dc3fcf83..447d19fe 100644 --- a/third_party/sqlite3/fts3_hash.h +++ b/third_party/sqlite3/fts3_hash.h @@ -16,6 +16,7 @@ */ #ifndef _FTS3_HASH_H_ #define _FTS3_HASH_H_ +/* clang-format off */ /* Forward declarations of structures. */ typedef struct Fts3Hash Fts3Hash; diff --git a/third_party/sqlite3/fts3_icu.c b/third_party/sqlite3/fts3_icu.c index 0848a5aa..2bb31efd 100644 --- a/third_party/sqlite3/fts3_icu.c +++ b/third_party/sqlite3/fts3_icu.c @@ -11,18 +11,15 @@ ************************************************************************* ** This file implements a tokenizer for fts3 based on the ICU library. */ -#include "fts3Int.h" +#include "third_party/sqlite3/fts3Int.h" #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) #ifdef SQLITE_ENABLE_ICU +/* clang-format off */ -#include -#include -#include "fts3_tokenizer.h" - -#include -#include -#include -#include +#include "libc/assert.h" +#include "libc/str/str.h" +#include "libc/unicode/unicode.h" +#include "third_party/sqlite3/fts3_tokenizer.h" typedef struct IcuTokenizer IcuTokenizer; typedef struct IcuCursor IcuCursor; diff --git a/third_party/sqlite3/fts3_porter.c b/third_party/sqlite3/fts3_porter.c index 8fb4c25d..b1713f99 100644 --- a/third_party/sqlite3/fts3_porter.c +++ b/third_party/sqlite3/fts3_porter.c @@ -12,6 +12,7 @@ ** Implementation of the full-text-search tokenizer that implements ** a Porter stemmer. */ +/* clang-format off */ /* ** The code in this file is only compiled if: @@ -22,15 +23,14 @@ ** * The FTS3 module is being built into the core of ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined). */ -#include "fts3Int.h" +#include "third_party/sqlite3/fts3Int.h" #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) -#include -#include -#include -#include - -#include "fts3_tokenizer.h" +#include "libc/assert.h" +#include "libc/mem/mem.h" +#include "libc/stdio/stdio.h" +#include "libc/str/str.h" +#include "third_party/sqlite3/fts3_tokenizer.h" /* ** Class derived from sqlite3_tokenizer diff --git a/third_party/sqlite3/fts3_snippet.c b/third_party/sqlite3/fts3_snippet.c index ebc771fd..0931ea59 100644 --- a/third_party/sqlite3/fts3_snippet.c +++ b/third_party/sqlite3/fts3_snippet.c @@ -10,12 +10,13 @@ ** ****************************************************************************** */ +/* clang-format off */ -#include "fts3Int.h" +#include "third_party/sqlite3/fts3Int.h" #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) -#include -#include +#include "libc/assert.h" +#include "libc/str/str.h" /* ** Characters that may appear in the second argument to matchinfo(). diff --git a/third_party/sqlite3/fts3_tokenize_vtab.c b/third_party/sqlite3/fts3_tokenize_vtab.c index 8bd22230..1abcac61 100644 --- a/third_party/sqlite3/fts3_tokenize_vtab.c +++ b/third_party/sqlite3/fts3_tokenize_vtab.c @@ -25,8 +25,8 @@ ** ** input = ** -** The virtual table module tokenizes this , using the FTS3 -** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE +** The virtual table module tokenizes this , using the FTS3 +** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE ** statement and returns one row for each token in the result. With ** fields set as follows: ** @@ -38,11 +38,12 @@ ** pos: Token offset of token within input. ** */ -#include "fts3Int.h" +#include "third_party/sqlite3/fts3Int.h" #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) +/* clang-format off */ -#include -#include +#include "libc/assert.h" +#include "libc/str/str.h" typedef struct Fts3tokTable Fts3tokTable; typedef struct Fts3tokCursor Fts3tokCursor; diff --git a/third_party/sqlite3/fts3_tokenizer.c b/third_party/sqlite3/fts3_tokenizer.c index eab3f513..97b50a3f 100644 --- a/third_party/sqlite3/fts3_tokenizer.c +++ b/third_party/sqlite3/fts3_tokenizer.c @@ -13,6 +13,7 @@ ** This is part of an SQLite module implementing full-text search. ** This particular file implements the generic tokenizer interface. */ +/* clang-format off */ /* ** The code in this file is only compiled if: @@ -23,11 +24,11 @@ ** * The FTS3 module is being built into the core of ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined). */ -#include "fts3Int.h" +#include "third_party/sqlite3/fts3Int.h" #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) -#include -#include +#include "libc/assert.h" +#include "libc/str/str.h" /* ** Return true if the two-argument version of fts3_tokenizer() @@ -227,11 +228,11 @@ int sqlite3Fts3InitTokenizer( #ifdef SQLITE_TEST #if defined(INCLUDE_SQLITE_TCL_H) -# include "sqlite_tcl.h" +#include "third_party/sqlite3/sqlite_tcl.h" #else -# include "tcl.h" +#include "third_party/sqlite3/tcl.h" #endif -#include +#include "libc/str/str.h" /* ** Implementation of a special SQL scalar function for testing tokenizers diff --git a/third_party/sqlite3/fts3_tokenizer.h b/third_party/sqlite3/fts3_tokenizer.h index 4a40b2b3..725f3aa3 100644 --- a/third_party/sqlite3/fts3_tokenizer.h +++ b/third_party/sqlite3/fts3_tokenizer.h @@ -19,12 +19,13 @@ */ #ifndef _FTS3_TOKENIZER_H_ #define _FTS3_TOKENIZER_H_ +/* clang-format off */ /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time. ** If tokenizers are to be allowed to call sqlite3_*() functions, then ** we will need a way to register the API consistently. */ -#include "sqlite3.h" +#include "third_party/sqlite3/sqlite3.h" /* ** Structures used by the tokenizer interface. When a new tokenizer diff --git a/third_party/sqlite3/fts3_tokenizer1.c b/third_party/sqlite3/fts3_tokenizer1.c index deea06d9..fe06ba77 100644 --- a/third_party/sqlite3/fts3_tokenizer1.c +++ b/third_party/sqlite3/fts3_tokenizer1.c @@ -12,6 +12,7 @@ ** ** Implementation of the "simple" full-text-search tokenizer. */ +/* clang-format off */ /* ** The code in this file is only compiled if: @@ -22,15 +23,14 @@ ** * The FTS3 module is being built into the core of ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined). */ -#include "fts3Int.h" +#include "third_party/sqlite3/fts3Int.h" #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) -#include -#include -#include -#include - -#include "fts3_tokenizer.h" +#include "libc/assert.h" +#include "libc/mem/mem.h" +#include "libc/stdio/stdio.h" +#include "libc/str/str.h" +#include "third_party/sqlite3/fts3_tokenizer.h" typedef struct simple_tokenizer { sqlite3_tokenizer base; diff --git a/third_party/sqlite3/fts3_unicode.c b/third_party/sqlite3/fts3_unicode.c index 2fd4b39f..4d422f8b 100644 --- a/third_party/sqlite3/fts3_unicode.c +++ b/third_party/sqlite3/fts3_unicode.c @@ -12,18 +12,18 @@ ** ** Implementation of the "unicode" full-text-search tokenizer. */ +/* clang-format off */ #ifndef SQLITE_DISABLE_FTS3_UNICODE -#include "fts3Int.h" +#include "third_party/sqlite3/fts3Int.h" #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) -#include -#include -#include -#include - -#include "fts3_tokenizer.h" +#include "libc/assert.h" +#include "libc/mem/mem.h" +#include "libc/stdio/stdio.h" +#include "libc/str/str.h" +#include "third_party/sqlite3/fts3_tokenizer.h" /* ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied diff --git a/third_party/sqlite3/fts3_unicode2.c b/third_party/sqlite3/fts3_unicode2.c index c5101624..652c334f 100644 --- a/third_party/sqlite3/fts3_unicode2.c +++ b/third_party/sqlite3/fts3_unicode2.c @@ -10,6 +10,7 @@ ** ****************************************************************************** */ +/* clang-format off */ /* ** DO NOT EDIT THIS MACHINE GENERATED FILE. @@ -18,7 +19,7 @@ #ifndef SQLITE_DISABLE_FTS3_UNICODE #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) -#include +#include "libc/assert.h" /* ** Return true if the argument corresponds to a unicode codepoint diff --git a/third_party/sqlite3/fts3_write.c b/third_party/sqlite3/fts3_write.c index bc42fc3d..cd9f6fd0 100644 --- a/third_party/sqlite3/fts3_write.c +++ b/third_party/sqlite3/fts3_write.c @@ -13,17 +13,19 @@ ** This file is part of the SQLite FTS3 extension module. Specifically, ** this file contains code to insert, update and delete rows from FTS3 ** tables. It also contains code to merge FTS3 b-tree segments. Some -** of the sub-routines used to merge segments are also used by the query +** of the sub-routines used to merge segments are also used by the query ** code in fts3.c. */ +/* clang-format off */ -#include "fts3Int.h" +#include "third_party/sqlite3/fts3Int.h" #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) -#include -#include -#include -#include +#include "libc/alg/alg.h" +#include "libc/assert.h" +#include "libc/mem/mem.h" +#include "libc/stdio/stdio.h" +#include "libc/str/str.h" #define FTS_MAX_APPENDABLE_HEIGHT 16 diff --git a/third_party/sqlite3/fts5.c b/third_party/sqlite3/fts5.c index 7fe2fec4..3020f834 100644 --- a/third_party/sqlite3/fts5.c +++ b/third_party/sqlite3/fts5.c @@ -1,4 +1,5 @@ +/* clang-format off */ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5) @@ -33,7 +34,7 @@ #ifndef _FTS5_H #define _FTS5_H -#include "sqlite3.h" +#include "third_party/sqlite3/sqlite3.h" #ifdef __cplusplus extern "C" { @@ -603,12 +604,12 @@ struct fts5_api { #ifndef _FTS5INT_H #define _FTS5INT_H -/* #include "fts5.h" */ -#include "sqlite3ext.h" +/* #include "third_party/sqlite3/fts5.h" */ +#include "third_party/sqlite3/sqlite3ext.h" SQLITE_EXTENSION_INIT1 -#include -#include +#include "libc/assert.h" +#include "libc/str/str.h" #ifndef SQLITE_AMALGAMATION @@ -1477,8 +1478,8 @@ static void sqlite3Fts5UnicodeAscii(u8*, u8*); /************ Begin %include sections from the grammar ************************/ #line 47 "fts5parse.y" -/* #include "fts5Int.h" */ -/* #include "fts5parse.h" */ +/* #include "third_party/sqlite3/fts5Int.h" */ +/* #include "third_party/sqlite3/fts5parse.h" */ /* ** Disable all error recovery processing in the parser push-down @@ -1806,8 +1807,8 @@ struct fts5yyParser { typedef struct fts5yyParser fts5yyParser; #ifndef NDEBUG -#include -#include +#include "libc/assert.h" +#include "libc/stdio/stdio.h" static FILE *fts5yyTraceFILE = 0; static char *fts5yyTracePrompt = 0; #endif /* NDEBUG */ @@ -3012,9 +3013,8 @@ static int sqlite3Fts5ParserFallback(int iToken){ ****************************************************************************** */ - -/* #include "fts5Int.h" */ -#include /* amalgamator: keep */ +/* #include "third_party/sqlite3/fts5Int.h" */ +#include "libc/math.h" /* amalgamator: keep */ /* ** Object used to iterate through all "coalesced phrase instances" in @@ -3728,9 +3728,7 @@ static int sqlite3Fts5AuxInit(fts5_api *pApi){ ****************************************************************************** */ - - -/* #include "fts5Int.h" */ +/* #include "third_party/sqlite3/fts5Int.h" */ static int sqlite3Fts5BufferSize(int *pRc, Fts5Buffer *pBuf, u32 nByte){ if( (u32)pBuf->nSpace -static void sqlite3Fts5ParserTrace(FILE*, char*); +#include "libc/stdio/stdio.h" +static void sqlite3Fts5ParserTrace(FILE *, char *); #endif -static int sqlite3Fts5ParserFallback(int); +// static int sqlite3Fts5ParserFallback(int); struct Fts5Expr { @@ -8152,9 +8147,7 @@ static int sqlite3Fts5ExprPhraseCollist( ** */ - - -/* #include "fts5Int.h" */ +/* #include "third_party/sqlite3/fts5Int.h" */ typedef struct Fts5HashEntry Fts5HashEntry; @@ -8718,8 +8711,7 @@ static void sqlite3Fts5HashScanEntry( ** the interface defined in fts5Int.h. */ - -/* #include "fts5Int.h" */ +/* #include "third_party/sqlite3/fts5Int.h" */ /* ** Overview: @@ -15426,8 +15418,7 @@ static int sqlite3Fts5IndexReset(Fts5Index *p){ ** This is an SQLite module implementing full-text search. */ - -/* #include "fts5Int.h" */ +/* #include "third_party/sqlite3/fts5Int.h" */ /* ** This variable is set to false when running tests for which the on disk @@ -18348,9 +18339,7 @@ int sqlite3Fts5Init(sqlite3 *db){ ** */ - - -/* #include "fts5Int.h" */ +/* #include "third_party/sqlite3/fts5Int.h" */ struct Fts5Storage { Fts5Config *pConfig; @@ -19510,8 +19499,7 @@ static int sqlite3Fts5StorageConfigValue( ****************************************************************************** */ - -/* #include "fts5Int.h" */ +/* #include "third_party/sqlite3/fts5Int.h" */ /************************************************************************** ** Start of ascii tokenizer implementation. @@ -20931,8 +20919,7 @@ static int sqlite3Fts5TokenizerInit(fts5_api *pApi){ ** DO NOT EDIT THIS MACHINE GENERATED FILE. */ - -#include +#include "libc/assert.h" @@ -21709,8 +21696,7 @@ static void sqlite3Fts5UnicodeAscii(u8 *aArray, u8 *aAscii){ ** Routines for varint serialization and deserialization. */ - -/* #include "fts5Int.h" */ +/* #include "third_party/sqlite3/fts5Int.h" */ /* ** This is a copy of the sqlite3GetVarint32() routine from the SQLite core. @@ -22078,8 +22064,7 @@ static int sqlite3Fts5GetVarintLen(u32 iVal){ ** One row for each term instance in the database. */ - -/* #include "fts5Int.h" */ +/* #include "third_party/sqlite3/fts5Int.h" */ typedef struct Fts5VocabTable Fts5VocabTable; diff --git a/third_party/sqlite3/fts5.h b/third_party/sqlite3/fts5.h index 081e534f..5aa56821 100644 --- a/third_party/sqlite3/fts5.h +++ b/third_party/sqlite3/fts5.h @@ -10,18 +10,19 @@ ** ****************************************************************************** ** -** Interfaces to extend FTS5. Using the interfaces defined in this file, +** Interfaces to extend FTS5. Using the interfaces defined in this file, ** FTS5 may be extended with: ** ** * custom tokenizers, and ** * custom auxiliary functions. */ +/* clang-format off */ #ifndef _FTS5_H #define _FTS5_H -#include "sqlite3.h" +#include "third_party/sqlite3/sqlite3.h" #ifdef __cplusplus extern "C" { diff --git a/third_party/sqlite3/func.c b/third_party/sqlite3/func.c index aedbda6f..dc2c4359 100644 --- a/third_party/sqlite3/func.c +++ b/third_party/sqlite3/func.c @@ -13,13 +13,14 @@ ** functions of SQLite. (Some function, and in particular the date and ** time functions, are implemented separately.) */ -#include "sqliteInt.h" -#include -#include +#include "libc/assert.h" +#include "libc/mem/mem.h" +#include "third_party/sqlite3/sqliteInt.h" #ifndef SQLITE_OMIT_FLOATING_POINT -#include +#include "libc/math.h" #endif -#include "vdbeInt.h" +#include "third_party/sqlite3/vdbeInt.h" +/* clang-format off */ /* ** Return the collating function associated with a function. diff --git a/third_party/sqlite3/geopoly.c b/third_party/sqlite3/geopoly.c index b1cff38e..83533ada 100644 --- a/third_party/sqlite3/geopoly.c +++ b/third_party/sqlite3/geopoly.c @@ -16,7 +16,12 @@ ** This file is #include-ed onto the end of "rtree.c" so that it has ** access to all of the R-Tree internals. */ -#include +#include "libc/fmt/conv.h" +#include "libc/mem/mem.h" +#include "third_party/gdtoa/gdtoa.h" +#include "third_party/sqlite3/rtree.h" +#include "third_party/sqlite3/sqlite3.h" +/* clang-format off */ /* Enable -DGEOPOLY_ENABLE_DEBUG for debugging facilities */ #ifdef GEOPOLY_ENABLE_DEBUG @@ -38,11 +43,11 @@ # define safe_isalnum(x) sqlite3Isalnum(x) # define safe_isxdigit(x) sqlite3Isxdigit(x) #else - /* Use the standard library for separate compilation */ -#include /* amalgamator: keep */ -# define safe_isdigit(x) isdigit((unsigned char)(x)) -# define safe_isalnum(x) isalnum((unsigned char)(x)) -# define safe_isxdigit(x) isxdigit((unsigned char)(x)) +/* Use the standard library for separate compilation */ +#include "libc/str/str.h" /* amalgamator: keep */ +#define safe_isdigit(x) isdigit((unsigned char)(x)) +#define safe_isalnum(x) isalnum((unsigned char)(x)) +#define safe_isxdigit(x) isxdigit((unsigned char)(x)) #endif /* diff --git a/third_party/sqlite3/global.c b/third_party/sqlite3/global.c index b5239ad8..bf96ced8 100644 --- a/third_party/sqlite3/global.c +++ b/third_party/sqlite3/global.c @@ -12,7 +12,8 @@ ** ** This file contains definitions of global variables and constants. */ -#include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" +/* clang-format off */ /* An array to map all upper-case characters into their corresponding ** lower-case character. @@ -306,7 +307,7 @@ int sqlite3PendingByte = 0x40000000; u32 sqlite3SelectTrace = 0; u32 sqlite3WhereTrace = 0; -#include "opcodes.h" +#include "third_party/sqlite3/opcodes.h" /* ** Properties of opcodes. The OPFLG_INITIALIZER macro is ** created by mkopcodeh.awk during compilation. Data is obtained diff --git a/third_party/sqlite3/hash.c b/third_party/sqlite3/hash.c index 96f41361..773f76da 100644 --- a/third_party/sqlite3/hash.c +++ b/third_party/sqlite3/hash.c @@ -12,8 +12,9 @@ ** This is the implementation of generic hash-tables ** used in SQLite. */ -#include "sqliteInt.h" -#include +#include "libc/assert.h" +#include "third_party/sqlite3/sqliteInt.h" +/* clang-format off */ /* Turn bulk memory into a hash table object by initializing the ** fields of the Hash structure. diff --git a/third_party/sqlite3/hash.h b/third_party/sqlite3/hash.h index 951cc06c..e3ebd15a 100644 --- a/third_party/sqlite3/hash.h +++ b/third_party/sqlite3/hash.h @@ -14,6 +14,7 @@ */ #ifndef SQLITE_HASH_H #define SQLITE_HASH_H +/* clang-format off */ /* Forward declarations of structures. */ typedef struct Hash Hash; diff --git a/third_party/sqlite3/hwtime.h b/third_party/sqlite3/hwtime.h index 037c55a9..1c315733 100644 --- a/third_party/sqlite3/hwtime.h +++ b/third_party/sqlite3/hwtime.h @@ -15,6 +15,7 @@ */ #ifndef SQLITE_HWTIME_H #define SQLITE_HWTIME_H +/* clang-format off */ /* ** The following routine only works on pentium-class (or newer) processors. diff --git a/third_party/sqlite3/icu.c b/third_party/sqlite3/icu.c index 92d7c543..ced08d6b 100644 --- a/third_party/sqlite3/icu.c +++ b/third_party/sqlite3/icu.c @@ -11,9 +11,9 @@ ************************************************************************* ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $ ** -** This file implements an integration between the ICU library -** ("International Components for Unicode", an open-source library -** for handling unicode data) and SQLite. The integration uses +** This file implements an integration between the ICU library +** ("International Components for Unicode", an open-source library +** for handling unicode data) and SQLite. The integration uses ** ICU to provide the following to SQLite: ** ** * An implementation of the SQL regexp() function (and hence REGEXP @@ -24,27 +24,23 @@ ** ** * Integration of ICU and SQLite collation sequences. ** -** * An implementation of the LIKE operator that uses ICU to +** * An implementation of the LIKE operator that uses ICU to ** provide case-independent matching. */ +/* clang-format off */ -#if !defined(SQLITE_CORE) \ - || defined(SQLITE_ENABLE_ICU) \ - || defined(SQLITE_ENABLE_ICU_COLLATIONS) +#if 0 && !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU) || \ + defined(SQLITE_ENABLE_ICU_COLLATIONS) /* Include ICU headers */ -#include -#include -#include -#include - -#include +#include "libc/assert.h" +#include "libc/unicode/unicode.h" #ifndef SQLITE_CORE - #include "sqlite3ext.h" - SQLITE_EXTENSION_INIT1 +#include "third_party/sqlite3/sqlite3ext.h" +SQLITE_EXTENSION_INIT1 #else - #include "sqlite3.h" +#include "third_party/sqlite3/sqlite3.h" #endif /* diff --git a/third_party/sqlite3/insert.c b/third_party/sqlite3/insert.c index 89b66baf..7a5824e5 100644 --- a/third_party/sqlite3/insert.c +++ b/third_party/sqlite3/insert.c @@ -12,7 +12,8 @@ ** This file contains C code routines that are called by the parser ** to handle INSERT statements in SQLite. */ -#include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" +/* clang-format off */ /* ** Generate code that will diff --git a/third_party/sqlite3/json1.c b/third_party/sqlite3/json1.c index 77641064..17183d78 100644 --- a/third_party/sqlite3/json1.c +++ b/third_party/sqlite3/json1.c @@ -23,13 +23,14 @@ */ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) #if !defined(SQLITEINT_H) -#include "sqlite3ext.h" +#include "third_party/sqlite3/sqlite3ext.h" #endif SQLITE_EXTENSION_INIT1 -#include -#include -#include -#include +#include "libc/assert.h" +#include "libc/mem/mem.h" +#include "libc/str/str.h" +#include "third_party/gdtoa/gdtoa.h" +/* clang-format off */ /* Mark a function parameter as unused, to suppress nuisance compiler ** warnings. */ @@ -57,11 +58,11 @@ SQLITE_EXTENSION_INIT1 # define safe_isalnum(x) sqlite3Isalnum(x) # define safe_isxdigit(x) sqlite3Isxdigit(x) #else - /* Use the standard library for separate compilation */ -#include /* amalgamator: keep */ -# define safe_isdigit(x) isdigit((unsigned char)(x)) -# define safe_isalnum(x) isalnum((unsigned char)(x)) -# define safe_isxdigit(x) isxdigit((unsigned char)(x)) +/* Use the standard library for separate compilation */ +#include "libc/str/str.h" /* amalgamator: keep */ +#define safe_isdigit(x) isdigit((unsigned char)(x)) +#define safe_isalnum(x) isalnum((unsigned char)(x)) +#define safe_isxdigit(x) isxdigit((unsigned char)(x)) #endif /* @@ -717,9 +718,9 @@ static int jsonParseAddNode(JsonParse*,u32,u32,const char*); ** inlined. */ #if defined(__GNUC__) -# define JSON_NOINLINE __attribute__((noinline)) -#elif defined(_MSC_VER) && _MSC_VER>=1310 -# define JSON_NOINLINE __declspec(noinline) +#define JSON_NOINLINE __attribute__((__noinline__)) +#elif defined(_MSC_VER) && _MSC_VER >= 1310 +#define JSON_NOINLINE __declspec(noinline) #else # define JSON_NOINLINE #endif diff --git a/third_party/sqlite3/legacy.c b/third_party/sqlite3/legacy.c index 867587e5..430ff117 100644 --- a/third_party/sqlite3/legacy.c +++ b/third_party/sqlite3/legacy.c @@ -14,8 +14,9 @@ ** other files are for internal use by SQLite and should not be ** accessed by users of the library. */ +/* clang-format off */ -#include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" /* ** Execute SQL code. Return one of the SQLITE_ success/failure diff --git a/third_party/sqlite3/loadext.c b/third_party/sqlite3/loadext.c index 60cffdae..c7a1829f 100644 --- a/third_party/sqlite3/loadext.c +++ b/third_party/sqlite3/loadext.c @@ -12,12 +12,13 @@ ** This file contains code used to dynamically load extensions into ** the SQLite library. */ +/* clang-format off */ #ifndef SQLITE_CORE #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */ #endif -#include "sqlite3ext.h" -#include "sqliteInt.h" +#include "third_party/sqlite3/sqlite3ext.h" +#include "third_party/sqlite3/sqliteInt.h" #ifndef SQLITE_OMIT_LOAD_EXTENSION /* diff --git a/third_party/sqlite3/main.c b/third_party/sqlite3/main.c index 328cb823..9c78646b 100644 --- a/third_party/sqlite3/main.c +++ b/third_party/sqlite3/main.c @@ -14,16 +14,17 @@ ** other files are for internal use by SQLite and should not be ** accessed by users of the library. */ -#include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" +/* clang-format off */ #ifdef SQLITE_ENABLE_FTS3 -# include "fts3.h" +#include "third_party/sqlite3/fts3.h" #endif #ifdef SQLITE_ENABLE_RTREE -# include "rtree.h" +#include "third_party/sqlite3/rtree.h" #endif #if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS) -# include "sqliteicu.h" +#include "third_party/sqlite3/sqliteicu.h" #endif /* diff --git a/third_party/sqlite3/malloc.c b/third_party/sqlite3/malloc.c index a0f7a739..76ec456c 100644 --- a/third_party/sqlite3/malloc.c +++ b/third_party/sqlite3/malloc.c @@ -12,8 +12,9 @@ ** ** Memory allocation functions used throughout sqlite. */ -#include "sqliteInt.h" -#include +/* clang-format off */ + +#include "third_party/sqlite3/sqliteInt.h" /* ** Attempt to release up to n bytes of non-essential memory currently diff --git a/third_party/sqlite3/mem0.c b/third_party/sqlite3/mem0.c index 0d0b6667..4f2b7315 100644 --- a/third_party/sqlite3/mem0.c +++ b/third_party/sqlite3/mem0.c @@ -16,7 +16,8 @@ ** are merely placeholders. Real drivers must be substituted using ** sqlite3_config() before SQLite will operate. */ -#include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" +/* clang-format off */ /* ** This version of the memory allocator is the default. It is diff --git a/third_party/sqlite3/mem1.c b/third_party/sqlite3/mem1.c index 512ab374..a988240e 100644 --- a/third_party/sqlite3/mem1.c +++ b/third_party/sqlite3/mem1.c @@ -41,7 +41,8 @@ ** be necessary when compiling for Delphi, ** for example. */ -#include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" +/* clang-format off */ /* ** This version of the memory allocator is the default. It is @@ -103,16 +104,16 @@ static malloc_zone_t* _sqliteZone_; ** the macro SQLITE_MALLOCSIZE to the desired function name. */ #if defined(SQLITE_USE_MALLOC_H) -# include -# if defined(SQLITE_USE_MALLOC_USABLE_SIZE) -# if !defined(SQLITE_MALLOCSIZE) -# define SQLITE_MALLOCSIZE(x) malloc_usable_size(x) -# endif -# elif defined(SQLITE_USE_MSIZE) -# if !defined(SQLITE_MALLOCSIZE) -# define SQLITE_MALLOCSIZE _msize -# endif -# endif +#include "libc/mem/mem.h" +#if defined(SQLITE_USE_MALLOC_USABLE_SIZE) +#if !defined(SQLITE_MALLOCSIZE) +#define SQLITE_MALLOCSIZE(x) malloc_usable_size(x) +#endif +#elif defined(SQLITE_USE_MSIZE) +#if !defined(SQLITE_MALLOCSIZE) +#define SQLITE_MALLOCSIZE _msize +#endif +#endif #endif /* defined(SQLITE_USE_MALLOC_H) */ #endif /* __APPLE__ or not __APPLE__ */ diff --git a/third_party/sqlite3/mem2.c b/third_party/sqlite3/mem2.c index ac031508..9fdbdfc3 100644 --- a/third_party/sqlite3/mem2.c +++ b/third_party/sqlite3/mem2.c @@ -19,7 +19,8 @@ ** This file contains implementations of the low-level memory allocation ** routines specified in the sqlite3_mem_methods object. */ -#include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" +/* clang-format off */ /* ** This version of the memory allocator is used only if the @@ -37,7 +38,7 @@ # define backtrace(A,B) 1 # define backtrace_symbols_fd(A,B,C) #endif -#include +#include "libc/stdio/stdio.h" /* ** Each memory allocation looks like this: diff --git a/third_party/sqlite3/mem3.c b/third_party/sqlite3/mem3.c index 16463d6a..770d024f 100644 --- a/third_party/sqlite3/mem3.c +++ b/third_party/sqlite3/mem3.c @@ -10,12 +10,12 @@ ** ************************************************************************* ** This file contains the C functions that implement a memory -** allocation subsystem for use by SQLite. +** allocation subsystem for use by SQLite. ** ** This version of the memory allocation subsystem omits all ** use of malloc(). The SQLite user supplies a block of memory ** before calling sqlite3_initialize() from which allocations -** are made and returned by the xMalloc() and xRealloc() +** are made and returned by the xMalloc() and xRealloc() ** implementations. Once sqlite3_initialize() has been called, ** the amount of memory available to SQLite is fixed and cannot ** be changed. @@ -23,7 +23,8 @@ ** This version of the memory allocation subsystem is included ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined. */ -#include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" +/* clang-format off */ /* ** This version of the memory allocator is only built into the library diff --git a/third_party/sqlite3/mem5.c b/third_party/sqlite3/mem5.c index c194a6b7..77f2d82e 100644 --- a/third_party/sqlite3/mem5.c +++ b/third_party/sqlite3/mem5.c @@ -10,12 +10,12 @@ ** ************************************************************************* ** This file contains the C functions that implement a memory -** allocation subsystem for use by SQLite. +** allocation subsystem for use by SQLite. ** ** This version of the memory allocation subsystem omits all ** use of malloc(). The application gives SQLite a block of memory ** before calling sqlite3_initialize() from which allocations -** are made and returned by the xMalloc() and xRealloc() +** are made and returned by the xMalloc() and xRealloc() ** implementations. Once sqlite3_initialize() has been called, ** the amount of memory available to SQLite is fixed and cannot ** be changed. @@ -35,12 +35,12 @@ ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions ** Concerning Dynamic Storage Allocation". Journal of the Association for ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499. -** +** ** Let n be the size of the largest allocation divided by the minimum ** allocation size (after rounding all sizes up to a power of 2.) Let M ** be the maximum amount of memory ever outstanding at one time. Let ** N be the total amount of memory available for allocation. Robson -** proved that this memory allocator will never breakdown due to +** proved that this memory allocator will never breakdown due to ** fragmentation as long as the following constraint holds: ** ** N >= M*(1 + log2(n)/2) - n + 1 @@ -48,7 +48,8 @@ ** The sqlite3_status() logic tracks the maximum values of n and M so ** that an application can, at any time, verify this constraint. */ -#include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" +/* clang-format off */ /* ** This version of the memory allocator is used only when diff --git a/third_party/sqlite3/memdb.c b/third_party/sqlite3/memdb.c index a48980aa..7cabb03b 100644 --- a/third_party/sqlite3/memdb.c +++ b/third_party/sqlite3/memdb.c @@ -16,8 +16,9 @@ ** This file also implements interface sqlite3_serialize() and ** sqlite3_deserialize(). */ -#include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" #ifdef SQLITE_ENABLE_DESERIALIZE +/* clang-format off */ /* ** Forward declaration of objects used by this utility diff --git a/third_party/sqlite3/memjournal.c b/third_party/sqlite3/memjournal.c index 660a8426..fac90946 100644 --- a/third_party/sqlite3/memjournal.c +++ b/third_party/sqlite3/memjournal.c @@ -23,7 +23,8 @@ ** in the common case, they are usually small and no file I/O needs to ** occur. */ -#include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" +/* clang-format off */ /* Forward references to internal structures */ typedef struct MemJournal MemJournal; diff --git a/third_party/sqlite3/msvc.h b/third_party/sqlite3/msvc.h index f1742273..72232846 100644 --- a/third_party/sqlite3/msvc.h +++ b/third_party/sqlite3/msvc.h @@ -14,6 +14,7 @@ */ #ifndef SQLITE_MSVC_H #define SQLITE_MSVC_H +/* clang-format off */ #if defined(_MSC_VER) #pragma warning(disable : 4054) diff --git a/third_party/sqlite3/mutex.c b/third_party/sqlite3/mutex.c index 13a9fca1..6b130212 100644 --- a/third_party/sqlite3/mutex.c +++ b/third_party/sqlite3/mutex.c @@ -13,7 +13,8 @@ ** ** This file contains code that is common across all mutex implementations. */ -#include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" +/* clang-format off */ #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT) /* diff --git a/third_party/sqlite3/mutex.h b/third_party/sqlite3/mutex.h index a6806a25..22ff0fea 100644 --- a/third_party/sqlite3/mutex.h +++ b/third_party/sqlite3/mutex.h @@ -19,6 +19,7 @@ ** Source files should #include the sqliteInt.h file and let that file ** include this one indirectly. */ +/* clang-format off */ /* diff --git a/third_party/sqlite3/mutex_noop.c b/third_party/sqlite3/mutex_noop.c index ecc84b4a..0d6a5490 100644 --- a/third_party/sqlite3/mutex_noop.c +++ b/third_party/sqlite3/mutex_noop.c @@ -25,7 +25,8 @@ ** that does error checking on mutexes to make sure they are being ** called correctly. */ -#include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" +/* clang-format off */ #ifndef SQLITE_MUTEX_OMIT diff --git a/third_party/sqlite3/mutex_unix.c b/third_party/sqlite3/mutex_unix.c index 2afaddec..3eb82feb 100644 --- a/third_party/sqlite3/mutex_unix.c +++ b/third_party/sqlite3/mutex_unix.c @@ -11,7 +11,8 @@ ************************************************************************* ** This file contains the C functions that implement mutexes for pthreads */ -#include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" +/* clang-format off */ /* ** The code in this file is only used if we are compiling threadsafe diff --git a/third_party/sqlite3/mutex_w32.c b/third_party/sqlite3/mutex_w32.c index 09deda40..54e65408 100644 --- a/third_party/sqlite3/mutex_w32.c +++ b/third_party/sqlite3/mutex_w32.c @@ -11,18 +11,19 @@ ************************************************************************* ** This file contains the C functions that implement mutexes for Win32. */ -#include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" +/* clang-format off */ #if SQLITE_OS_WIN /* ** Include code that is common to all os_*.c files */ -#include "os_common.h" +#include "third_party/sqlite3/os_common.h" /* ** Include the header file for the Windows VFS. */ -#include "os_win.h" +#include "third_party/sqlite3/os_win.h" #endif /* diff --git a/third_party/sqlite3/notify.c b/third_party/sqlite3/notify.c index 4960ab76..9e79c7a9 100644 --- a/third_party/sqlite3/notify.c +++ b/third_party/sqlite3/notify.c @@ -13,8 +13,9 @@ ** This file contains the implementation of the sqlite3_unlock_notify() ** API method and its associated functionality. */ -#include "sqliteInt.h" -#include "btreeInt.h" +#include "third_party/sqlite3/btreeInt.h" +#include "third_party/sqlite3/sqliteInt.h" +/* clang-format off */ /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */ #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY diff --git a/third_party/sqlite3/opcodes.c b/third_party/sqlite3/opcodes.c index f3775a63..a8282b1f 100644 --- a/third_party/sqlite3/opcodes.c +++ b/third_party/sqlite3/opcodes.c @@ -1,3 +1,4 @@ +/* clang-format off */ /* Automatically generated. Do not edit */ /* See the tool/mkopcodec.tcl script for details. */ #if !defined(SQLITE_OMIT_EXPLAIN) \ diff --git a/third_party/sqlite3/opcodes.h b/third_party/sqlite3/opcodes.h index b90eff05..e808c978 100644 --- a/third_party/sqlite3/opcodes.h +++ b/third_party/sqlite3/opcodes.h @@ -1,111 +1,116 @@ /* Automatically generated. Do not edit */ /* See the tool/mkopcodeh.tcl script for details */ -#define OP_Savepoint 0 -#define OP_AutoCommit 1 -#define OP_Transaction 2 -#define OP_SorterNext 3 /* jump */ -#define OP_Prev 4 /* jump */ -#define OP_Next 5 /* jump */ -#define OP_Checkpoint 6 -#define OP_JournalMode 7 -#define OP_Vacuum 8 -#define OP_VFilter 9 /* jump, synopsis: iplan=r[P3] zplan='P4' */ -#define OP_VUpdate 10 /* synopsis: data=r[P3@P2] */ -#define OP_Goto 11 /* jump */ -#define OP_Gosub 12 /* jump */ -#define OP_InitCoroutine 13 /* jump */ -#define OP_Yield 14 /* jump */ -#define OP_MustBeInt 15 /* jump */ -#define OP_Jump 16 /* jump */ -#define OP_Once 17 /* jump */ -#define OP_If 18 /* jump */ -#define OP_Not 19 /* same as TK_NOT, synopsis: r[P2]= !r[P1] */ -#define OP_IfNot 20 /* jump */ -#define OP_IfNullRow 21 /* jump, synopsis: if P1.nullRow then r[P3]=NULL, goto P2 */ -#define OP_SeekLT 22 /* jump, synopsis: key=r[P3@P4] */ -#define OP_SeekLE 23 /* jump, synopsis: key=r[P3@P4] */ -#define OP_SeekGE 24 /* jump, synopsis: key=r[P3@P4] */ -#define OP_SeekGT 25 /* jump, synopsis: key=r[P3@P4] */ -#define OP_IfNotOpen 26 /* jump, synopsis: if( !csr[P1] ) goto P2 */ -#define OP_IfNoHope 27 /* jump, synopsis: key=r[P3@P4] */ -#define OP_NoConflict 28 /* jump, synopsis: key=r[P3@P4] */ -#define OP_NotFound 29 /* jump, synopsis: key=r[P3@P4] */ -#define OP_Found 30 /* jump, synopsis: key=r[P3@P4] */ -#define OP_SeekRowid 31 /* jump, synopsis: intkey=r[P3] */ -#define OP_NotExists 32 /* jump, synopsis: intkey=r[P3] */ -#define OP_Last 33 /* jump */ -#define OP_IfSmaller 34 /* jump */ -#define OP_SorterSort 35 /* jump */ -#define OP_Sort 36 /* jump */ -#define OP_Rewind 37 /* jump */ -#define OP_IdxLE 38 /* jump, synopsis: key=r[P3@P4] */ -#define OP_IdxGT 39 /* jump, synopsis: key=r[P3@P4] */ -#define OP_IdxLT 40 /* jump, synopsis: key=r[P3@P4] */ -#define OP_IdxGE 41 /* jump, synopsis: key=r[P3@P4] */ -#define OP_RowSetRead 42 /* jump, synopsis: r[P3]=rowset(P1) */ -#define OP_Or 43 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */ -#define OP_And 44 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */ -#define OP_RowSetTest 45 /* jump, synopsis: if r[P3] in rowset(P1) goto P2 */ -#define OP_Program 46 /* jump */ -#define OP_FkIfZero 47 /* jump, synopsis: if fkctr[P1]==0 goto P2 */ -#define OP_IfPos 48 /* jump, synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */ -#define OP_IfNotZero 49 /* jump, synopsis: if r[P1]!=0 then r[P1]--, goto P2 */ -#define OP_IsNull 50 /* jump, same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */ -#define OP_NotNull 51 /* jump, same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */ -#define OP_Ne 52 /* jump, same as TK_NE, synopsis: IF r[P3]!=r[P1] */ -#define OP_Eq 53 /* jump, same as TK_EQ, synopsis: IF r[P3]==r[P1] */ -#define OP_Gt 54 /* jump, same as TK_GT, synopsis: IF r[P3]>r[P1] */ -#define OP_Le 55 /* jump, same as TK_LE, synopsis: IF r[P3]<=r[P1] */ -#define OP_Lt 56 /* jump, same as TK_LT, synopsis: IF r[P3]=r[P1] */ -#define OP_ElseNotEq 58 /* jump, same as TK_ESCAPE */ -#define OP_DecrJumpZero 59 /* jump, synopsis: if (--r[P1])==0 goto P2 */ -#define OP_IncrVacuum 60 /* jump */ -#define OP_VNext 61 /* jump */ -#define OP_Init 62 /* jump, synopsis: Start at P2 */ -#define OP_PureFunc 63 /* synopsis: r[P3]=func(r[P2@NP]) */ -#define OP_Function 64 /* synopsis: r[P3]=func(r[P2@NP]) */ -#define OP_Return 65 -#define OP_EndCoroutine 66 -#define OP_HaltIfNull 67 /* synopsis: if r[P3]=null halt */ -#define OP_Halt 68 -#define OP_Integer 69 /* synopsis: r[P2]=P1 */ -#define OP_Int64 70 /* synopsis: r[P2]=P4 */ -#define OP_String 71 /* synopsis: r[P2]='P4' (len=P1) */ -#define OP_Null 72 /* synopsis: r[P2..P3]=NULL */ -#define OP_SoftNull 73 /* synopsis: r[P1]=NULL */ -#define OP_Blob 74 /* synopsis: r[P2]=P4 (len=P1) */ -#define OP_Variable 75 /* synopsis: r[P2]=parameter(P1,P4) */ -#define OP_Move 76 /* synopsis: r[P2@P3]=r[P1@P3] */ -#define OP_Copy 77 /* synopsis: r[P2@P3+1]=r[P1@P3+1] */ -#define OP_SCopy 78 /* synopsis: r[P2]=r[P1] */ -#define OP_IntCopy 79 /* synopsis: r[P2]=r[P1] */ -#define OP_ChngCntRow 80 /* synopsis: output=r[P1] */ -#define OP_ResultRow 81 /* synopsis: output=r[P1@P2] */ -#define OP_CollSeq 82 -#define OP_AddImm 83 /* synopsis: r[P1]=r[P1]+P2 */ -#define OP_RealAffinity 84 -#define OP_Cast 85 /* synopsis: affinity(r[P1]) */ -#define OP_Permutation 86 -#define OP_Compare 87 /* synopsis: r[P1@P3] <-> r[P2@P3] */ -#define OP_IsTrue 88 /* synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4 */ -#define OP_Offset 89 /* synopsis: r[P3] = sqlite_offset(P1) */ -#define OP_Column 90 /* synopsis: r[P3]=PX */ -#define OP_Affinity 91 /* synopsis: affinity(r[P1@P2]) */ -#define OP_MakeRecord 92 /* synopsis: r[P3]=mkrec(r[P1@P2]) */ -#define OP_Count 93 /* synopsis: r[P2]=count() */ -#define OP_ReadCookie 94 -#define OP_SetCookie 95 -#define OP_ReopenIdx 96 /* synopsis: root=P2 iDb=P3 */ -#define OP_OpenRead 97 /* synopsis: root=P2 iDb=P3 */ -#define OP_OpenWrite 98 /* synopsis: root=P2 iDb=P3 */ -#define OP_OpenDup 99 +#define OP_Savepoint 0 +#define OP_AutoCommit 1 +#define OP_Transaction 2 +#define OP_SorterNext 3 /* jump */ +#define OP_Prev 4 /* jump */ +#define OP_Next 5 /* jump */ +#define OP_Checkpoint 6 +#define OP_JournalMode 7 +#define OP_Vacuum 8 +#define OP_VFilter 9 /* jump, synopsis: iplan=r[P3] zplan='P4' */ +#define OP_VUpdate 10 /* synopsis: data=r[P3@P2] */ +#define OP_Goto 11 /* jump */ +#define OP_Gosub 12 /* jump */ +#define OP_InitCoroutine 13 /* jump */ +#define OP_Yield 14 /* jump */ +#define OP_MustBeInt 15 /* jump */ +#define OP_Jump 16 /* jump */ +#define OP_Once 17 /* jump */ +#define OP_If 18 /* jump */ +#define OP_Not 19 /* same as TK_NOT, synopsis: r[P2]= !r[P1] */ +#define OP_IfNot 20 /* jump */ +#define OP_IfNullRow \ + 21 /* jump, synopsis: if P1.nullRow then r[P3]=NULL, goto P2 */ +#define OP_SeekLT 22 /* jump, synopsis: key=r[P3@P4] */ +#define OP_SeekLE 23 /* jump, synopsis: key=r[P3@P4] */ +#define OP_SeekGE 24 /* jump, synopsis: key=r[P3@P4] */ +#define OP_SeekGT 25 /* jump, synopsis: key=r[P3@P4] */ +#define OP_IfNotOpen 26 /* jump, synopsis: if( !csr[P1] ) goto P2 */ +#define OP_IfNoHope 27 /* jump, synopsis: key=r[P3@P4] */ +#define OP_NoConflict 28 /* jump, synopsis: key=r[P3@P4] */ +#define OP_NotFound 29 /* jump, synopsis: key=r[P3@P4] */ +#define OP_Found 30 /* jump, synopsis: key=r[P3@P4] */ +#define OP_SeekRowid 31 /* jump, synopsis: intkey=r[P3] */ +#define OP_NotExists 32 /* jump, synopsis: intkey=r[P3] */ +#define OP_Last 33 /* jump */ +#define OP_IfSmaller 34 /* jump */ +#define OP_SorterSort 35 /* jump */ +#define OP_Sort 36 /* jump */ +#define OP_Rewind 37 /* jump */ +#define OP_IdxLE 38 /* jump, synopsis: key=r[P3@P4] */ +#define OP_IdxGT 39 /* jump, synopsis: key=r[P3@P4] */ +#define OP_IdxLT 40 /* jump, synopsis: key=r[P3@P4] */ +#define OP_IdxGE 41 /* jump, synopsis: key=r[P3@P4] */ +#define OP_RowSetRead 42 /* jump, synopsis: r[P3]=rowset(P1) */ +#define OP_Or 43 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */ +#define OP_And 44 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */ +#define OP_RowSetTest 45 /* jump, synopsis: if r[P3] in rowset(P1) goto P2 */ +#define OP_Program 46 /* jump */ +#define OP_FkIfZero 47 /* jump, synopsis: if fkctr[P1]==0 goto P2 */ +#define OP_IfPos 48 /* jump, synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */ +#define OP_IfNotZero 49 /* jump, synopsis: if r[P1]!=0 then r[P1]--, goto P2 \ + */ +#define OP_IsNull \ + 50 /* jump, same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */ +#define OP_NotNull \ + 51 /* jump, same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */ +#define OP_Ne 52 /* jump, same as TK_NE, synopsis: IF r[P3]!=r[P1] */ +#define OP_Eq 53 /* jump, same as TK_EQ, synopsis: IF r[P3]==r[P1] */ +#define OP_Gt 54 /* jump, same as TK_GT, synopsis: IF r[P3]>r[P1] */ +#define OP_Le 55 /* jump, same as TK_LE, synopsis: IF r[P3]<=r[P1] */ +#define OP_Lt 56 /* jump, same as TK_LT, synopsis: IF r[P3]=r[P1] */ +#define OP_ElseNotEq 58 /* jump, same as TK_ESCAPE */ +#define OP_DecrJumpZero 59 /* jump, synopsis: if (--r[P1])==0 goto P2 */ +#define OP_IncrVacuum 60 /* jump */ +#define OP_VNext 61 /* jump */ +#define OP_Init 62 /* jump, synopsis: Start at P2 */ +#define OP_PureFunc 63 /* synopsis: r[P3]=func(r[P2@NP]) */ +#define OP_Function 64 /* synopsis: r[P3]=func(r[P2@NP]) */ +#define OP_Return 65 +#define OP_EndCoroutine 66 +#define OP_HaltIfNull 67 /* synopsis: if r[P3]=null halt */ +#define OP_Halt 68 +#define OP_Integer 69 /* synopsis: r[P2]=P1 */ +#define OP_Int64 70 /* synopsis: r[P2]=P4 */ +#define OP_String 71 /* synopsis: r[P2]='P4' (len=P1) */ +#define OP_Null 72 /* synopsis: r[P2..P3]=NULL */ +#define OP_SoftNull 73 /* synopsis: r[P1]=NULL */ +#define OP_Blob 74 /* synopsis: r[P2]=P4 (len=P1) */ +#define OP_Variable 75 /* synopsis: r[P2]=parameter(P1,P4) */ +#define OP_Move 76 /* synopsis: r[P2@P3]=r[P1@P3] */ +#define OP_Copy 77 /* synopsis: r[P2@P3+1]=r[P1@P3+1] */ +#define OP_SCopy 78 /* synopsis: r[P2]=r[P1] */ +#define OP_IntCopy 79 /* synopsis: r[P2]=r[P1] */ +#define OP_ChngCntRow 80 /* synopsis: output=r[P1] */ +#define OP_ResultRow 81 /* synopsis: output=r[P1@P2] */ +#define OP_CollSeq 82 +#define OP_AddImm 83 /* synopsis: r[P1]=r[P1]+P2 */ +#define OP_RealAffinity 84 +#define OP_Cast 85 /* synopsis: affinity(r[P1]) */ +#define OP_Permutation 86 +#define OP_Compare 87 /* synopsis: r[P1@P3] <-> r[P2@P3] */ +#define OP_IsTrue 88 /* synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4 */ +#define OP_Offset 89 /* synopsis: r[P3] = sqlite_offset(P1) */ +#define OP_Column 90 /* synopsis: r[P3]=PX */ +#define OP_Affinity 91 /* synopsis: affinity(r[P1@P2]) */ +#define OP_MakeRecord 92 /* synopsis: r[P3]=mkrec(r[P1@P2]) */ +#define OP_Count 93 /* synopsis: r[P2]=count() */ +#define OP_ReadCookie 94 +#define OP_SetCookie 95 +#define OP_ReopenIdx 96 /* synopsis: root=P2 iDb=P3 */ +#define OP_OpenRead 97 /* synopsis: root=P2 iDb=P3 */ +#define OP_OpenWrite 98 /* synopsis: root=P2 iDb=P3 */ +#define OP_OpenDup 99 #define OP_OpenAutoindex 100 /* synopsis: nColumn=P2 */ #define OP_OpenEphemeral 101 /* synopsis: nColumn=P2 */ #define OP_BitAnd 102 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */ #define OP_BitOr 103 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */ #define OP_ShiftLeft 104 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<>r[P1] */ +#define OP_ShiftRight 105 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] \ + */ #define OP_Add 106 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */ #define OP_Subtract 107 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */ #define OP_Multiply 108 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */ @@ -127,58 +132,61 @@ #define OP_RowCell 124 #define OP_Delete 125 #define OP_ResetCount 126 -#define OP_SorterCompare 127 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */ -#define OP_SorterData 128 /* synopsis: r[P2]=data */ -#define OP_RowData 129 /* synopsis: r[P2]=data */ -#define OP_Rowid 130 /* synopsis: r[P2]=rowid */ -#define OP_NullRow 131 -#define OP_SeekEnd 132 -#define OP_IdxInsert 133 /* synopsis: key=r[P2] */ -#define OP_SorterInsert 134 /* synopsis: key=r[P2] */ -#define OP_IdxDelete 135 /* synopsis: key=r[P2@P3] */ -#define OP_DeferredSeek 136 /* synopsis: Move P3 to P1.rowid if needed */ -#define OP_IdxRowid 137 /* synopsis: r[P2]=rowid */ -#define OP_FinishSeek 138 -#define OP_Destroy 139 -#define OP_Clear 140 -#define OP_ResetSorter 141 -#define OP_CreateBtree 142 /* synopsis: r[P2]=root iDb=P1 flags=P3 */ -#define OP_SqlExec 143 -#define OP_ParseSchema 144 -#define OP_LoadAnalysis 145 -#define OP_DropTable 146 -#define OP_DropIndex 147 -#define OP_DropTrigger 148 -#define OP_IntegrityCk 149 -#define OP_RowSetAdd 150 /* synopsis: rowset(P1)=r[P2] */ -#define OP_Param 151 -#define OP_Real 152 /* same as TK_FLOAT, synopsis: r[P2]=P4 */ -#define OP_FkCounter 153 /* synopsis: fkctr[P1]+=P2 */ -#define OP_MemMax 154 /* synopsis: r[P1]=max(r[P1],r[P2]) */ -#define OP_OffsetLimit 155 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */ -#define OP_AggInverse 156 /* synopsis: accum=r[P3] inverse(r[P2@P5]) */ -#define OP_AggStep 157 /* synopsis: accum=r[P3] step(r[P2@P5]) */ -#define OP_AggStep1 158 /* synopsis: accum=r[P3] step(r[P2@P5]) */ -#define OP_AggValue 159 /* synopsis: r[P3]=value N=P2 */ -#define OP_AggFinal 160 /* synopsis: accum=r[P1] N=P2 */ -#define OP_Expire 161 -#define OP_CursorLock 162 -#define OP_CursorUnlock 163 -#define OP_TableLock 164 /* synopsis: iDb=P1 root=P2 write=P3 */ -#define OP_VBegin 165 -#define OP_VCreate 166 -#define OP_VDestroy 167 -#define OP_VOpen 168 -#define OP_VColumn 169 /* synopsis: r[P3]=vcolumn(P2) */ -#define OP_VRename 170 -#define OP_Pagecount 171 -#define OP_MaxPgcnt 172 -#define OP_Trace 173 -#define OP_CursorHint 174 -#define OP_ReleaseReg 175 /* synopsis: release r[P1@P2] mask P3 */ -#define OP_Noop 176 -#define OP_Explain 177 -#define OP_Abortable 178 +#define OP_SorterCompare 127 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 \ + */ +#define OP_SorterData 128 /* synopsis: r[P2]=data */ +#define OP_RowData 129 /* synopsis: r[P2]=data */ +#define OP_Rowid 130 /* synopsis: r[P2]=rowid */ +#define OP_NullRow 131 +#define OP_SeekEnd 132 +#define OP_IdxInsert 133 /* synopsis: key=r[P2] */ +#define OP_SorterInsert 134 /* synopsis: key=r[P2] */ +#define OP_IdxDelete 135 /* synopsis: key=r[P2@P3] */ +#define OP_DeferredSeek 136 /* synopsis: Move P3 to P1.rowid if needed */ +#define OP_IdxRowid 137 /* synopsis: r[P2]=rowid */ +#define OP_FinishSeek 138 +#define OP_Destroy 139 +#define OP_Clear 140 +#define OP_ResetSorter 141 +#define OP_CreateBtree 142 /* synopsis: r[P2]=root iDb=P1 flags=P3 */ +#define OP_SqlExec 143 +#define OP_ParseSchema 144 +#define OP_LoadAnalysis 145 +#define OP_DropTable 146 +#define OP_DropIndex 147 +#define OP_DropTrigger 148 +#define OP_IntegrityCk 149 +#define OP_RowSetAdd 150 /* synopsis: rowset(P1)=r[P2] */ +#define OP_Param 151 +#define OP_Real 152 /* same as TK_FLOAT, synopsis: r[P2]=P4 */ +#define OP_FkCounter 153 /* synopsis: fkctr[P1]+=P2 */ +#define OP_MemMax 154 /* synopsis: r[P1]=max(r[P1],r[P2]) */ +#define OP_OffsetLimit \ + 155 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */ +#define OP_AggInverse 156 /* synopsis: accum=r[P3] inverse(r[P2@P5]) */ +#define OP_AggStep 157 /* synopsis: accum=r[P3] step(r[P2@P5]) */ +#define OP_AggStep1 158 /* synopsis: accum=r[P3] step(r[P2@P5]) */ +#define OP_AggValue 159 /* synopsis: r[P3]=value N=P2 */ +#define OP_AggFinal 160 /* synopsis: accum=r[P1] N=P2 */ +#define OP_Expire 161 +#define OP_CursorLock 162 +#define OP_CursorUnlock 163 +#define OP_TableLock 164 /* synopsis: iDb=P1 root=P2 write=P3 */ +#define OP_VBegin 165 +#define OP_VCreate 166 +#define OP_VDestroy 167 +#define OP_VOpen 168 +#define OP_VColumn 169 /* synopsis: r[P3]=vcolumn(P2) */ +#define OP_VRename 170 +#define OP_Pagecount 171 +#define OP_MaxPgcnt 172 +#define OP_Trace 173 +#define OP_CursorHint 174 +#define OP_ReleaseReg 175 /* synopsis: release r[P1@P2] mask P3 */ +#define OP_Noop 176 +#define OP_Explain 177 +#define OP_Abortable 178 +/* clang-format off */ /* Properties such as "out2" or "jump" that are specified in ** comments following the "case" for each opcode in the vdbe.c diff --git a/third_party/sqlite3/os.c b/third_party/sqlite3/os.c index 693d78dc..d66b7c35 100644 --- a/third_party/sqlite3/os.c +++ b/third_party/sqlite3/os.c @@ -13,7 +13,8 @@ ** This file contains OS interface code that is common to all ** architectures. */ -#include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" +/* clang-format off */ /* ** If we compile with the SQLITE_TEST macro set, then the following block diff --git a/third_party/sqlite3/os.h b/third_party/sqlite3/os.h index f841d6ba..b3d0fbeb 100644 --- a/third_party/sqlite3/os.h +++ b/third_party/sqlite3/os.h @@ -19,12 +19,13 @@ */ #ifndef _SQLITE_OS_H_ #define _SQLITE_OS_H_ +/* clang-format off */ /* ** Attempt to automatically detect the operating system and setup the ** necessary pre-processor macros for it. */ -#include "os_setup.h" +#include "third_party/sqlite3/os_setup.h" /* If the SET_FULLSYNC macro is not defined above, then make it ** a no-op diff --git a/third_party/sqlite3/os_common.h b/third_party/sqlite3/os_common.h index 1ed4d7a8..f6b2dc37 100644 --- a/third_party/sqlite3/os_common.h +++ b/third_party/sqlite3/os_common.h @@ -19,6 +19,7 @@ */ #ifndef _OS_COMMON_H_ #define _OS_COMMON_H_ +/* clang-format off */ /* ** At least two bugs have slipped in because we changed the MEMORY_DEBUG @@ -39,7 +40,7 @@ ** hwtime.h contains inline assembler code for implementing ** high-performance timing routines. */ -#include "hwtime.h" +#include "third_party/sqlite3/hwtime.h" static sqlite_uint64 g_start; static sqlite_uint64 g_elapsed; diff --git a/third_party/sqlite3/os_setup.h b/third_party/sqlite3/os_setup.h index 08aaa119..fe0dded9 100644 --- a/third_party/sqlite3/os_setup.h +++ b/third_party/sqlite3/os_setup.h @@ -15,6 +15,7 @@ */ #ifndef SQLITE_OS_SETUP_H #define SQLITE_OS_SETUP_H +/* clang-format off */ /* ** Figure out if we are dealing with Unix, Windows, or some other operating diff --git a/third_party/sqlite3/os_unix.c b/third_party/sqlite3/os_unix.c index e3cfe35c..b6825a7e 100644 --- a/third_party/sqlite3/os_unix.c +++ b/third_party/sqlite3/os_unix.c @@ -43,8 +43,9 @@ ** * Definitions of sqlite3_vfs objects for all locking methods ** plus implementations of sqlite3_os_init() and sqlite3_os_end(). */ -#include "sqliteInt.h" -#if SQLITE_OS_UNIX /* This file is used on unix only */ +#include "third_party/sqlite3/sqliteInt.h" +#if SQLITE_OS_UNIX /* This file is used on unix only */ + /* clang-format off */ /* ** There are various methods for file locking used for concurrency @@ -87,16 +88,22 @@ /* ** standard include files. */ -#include -#include -#include -#include -#include -#include -#include -#include -#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 -# include +#include "libc/calls/calls.h" +#include "libc/calls/struct/flock.h" +#include "libc/calls/weirdtypes.h" +#include "libc/errno.h" +#include "libc/isystem/unistd.h" +#include "libc/runtime/sysconf.h" +#include "libc/sysv/consts/f.h" +#include "libc/sysv/consts/map.h" +#include "libc/sysv/consts/mremap.h" +#include "libc/sysv/consts/o.h" +#include "libc/sysv/consts/ok.h" +#include "libc/sysv/consts/prot.h" +#include "libc/time/struct/tm.h" +#include "libc/time/time.h" +#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE > 0 +#include "libc/mem/mem.h" #endif #if SQLITE_ENABLE_LOCKING_STYLE @@ -134,9 +141,10 @@ #if OS_VXWORKS -# include -# include -# include +#include +#include + +#include "libc/limits.h" #endif /* OS_VXWORKS */ #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE @@ -144,7 +152,7 @@ #endif #ifdef HAVE_UTIME -# include +#include "libc/time/time.h" #endif /* @@ -297,7 +305,7 @@ static pid_t randomnessPid = 0; /* ** Include code that is common to all os_*.c files */ -#include "os_common.h" +#include "third_party/sqlite3/os_common.h" /* ** Define various macros that are missing from some systems. @@ -861,27 +869,22 @@ static int robust_ftruncate(int h, sqlite3_int64 sz){ ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately. */ static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) { - assert( (sqliteIOErr == SQLITE_IOERR_LOCK) || - (sqliteIOErr == SQLITE_IOERR_UNLOCK) || - (sqliteIOErr == SQLITE_IOERR_RDLOCK) || - (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ); - switch (posixError) { - case EACCES: - case EAGAIN: - case ETIMEDOUT: - case EBUSY: - case EINTR: - case ENOLCK: - /* random NFS retry error, unless during file system support + assert((sqliteIOErr == SQLITE_IOERR_LOCK) || + (sqliteIOErr == SQLITE_IOERR_UNLOCK) || + (sqliteIOErr == SQLITE_IOERR_RDLOCK) || + (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK)); + // changed switch to if-else + if (posixError == EACCES || posixError == EAGAIN || posixError == ETIMEDOUT || + posixError == EBUSY || posixError == EINTR || posixError == ENOLCK) + /* random NFS retry error, unless during file system support * introspection, in which it actually means what it says */ return SQLITE_BUSY; - - case EPERM: + + else if (posixError == EPERM) return SQLITE_PERM; - - default: + + else return sqliteIOErr; - } } @@ -3382,17 +3385,17 @@ static int unixRead( ** prior to returning to the application by the sqlite3ApiExit() ** routine. */ - switch( pFile->lastErrno ){ - case ERANGE: - case EIO: + // changed switch to if-else + if (pFile->lastErrno == ERANGE || pFile->lastErrno == EIO #ifdef ENXIO - case ENXIO: + || pFile->lastErrno == ENXIO #endif #ifdef EDEVERR - case EDEVERR: + || pFile->lastErrno == EDEVERR #endif - return SQLITE_IOERR_CORRUPTFS; - } + ) + return SQLITE_IOERR_CORRUPTFS; + return SQLITE_IOERR_READ; }else{ storeLastErrno(pFile, 0); /* not a system error */ diff --git a/third_party/sqlite3/os_win.c b/third_party/sqlite3/os_win.c index d7c436ef..4b56d662 100644 --- a/third_party/sqlite3/os_win.c +++ b/third_party/sqlite3/os_win.c @@ -12,18 +12,19 @@ ** ** This file contains code that is specific to Windows. */ -#include "sqliteInt.h" -#if SQLITE_OS_WIN /* This file is used for Windows only */ +#include "third_party/sqlite3/sqliteInt.h" +#if SQLITE_OS_WIN /* This file is used for Windows only */ +/* clang-format off */ /* ** Include code that is common to all os_*.c files */ -#include "os_common.h" +#include "third_party/sqlite3/os_common.h" /* ** Include the header file for the Windows VFS. */ -#include "os_win.h" +#include "third_party/sqlite3/os_win.h" /* ** Compiling and using WAL mode requires several APIs that are only @@ -2193,9 +2194,8 @@ static void winLogIoerr(int nRetry, int lineno){ ** The MSVC CRT on Windows CE may not have a localtime() function. ** So define a substitute. */ -# include -struct tm *__cdecl localtime(const time_t *t) -{ +#include "libc/time/time.h" +struct tm *__cdecl localtime(const time_t *t) { static struct tm y; FILETIME uTm, lTm; SYSTEMTIME pTm; diff --git a/third_party/sqlite3/os_win.h b/third_party/sqlite3/os_win.h index 27714ed0..a51285b6 100644 --- a/third_party/sqlite3/os_win.h +++ b/third_party/sqlite3/os_win.h @@ -14,15 +14,17 @@ */ #ifndef SQLITE_OS_WIN_H #define SQLITE_OS_WIN_H +/* clang-format off */ /* ** Include the primary Windows SDK header file. */ -#include "windows.h" +#include "third_party/sqlite3/windows.h" #ifdef __CYGWIN__ -# include -# include /* amalgamator: dontcache */ +#include + +#include "libc/errno.h" /* amalgamator: dontcache */ #endif /* diff --git a/third_party/sqlite3/pager.c b/third_party/sqlite3/pager.c index cd9096ed..ff4be22a 100644 --- a/third_party/sqlite3/pager.c +++ b/third_party/sqlite3/pager.c @@ -10,7 +10,7 @@ ** ************************************************************************* ** This is the implementation of the page cache subsystem or "pager". -** +** ** The pager is used to access a database disk file. It implements ** atomic commit and rollback through the use of a journal file that ** is separate from the database file. The pager also implements file @@ -19,8 +19,9 @@ ** another is writing. */ #ifndef SQLITE_OMIT_DISKIO -#include "sqliteInt.h" -#include "wal.h" +#include "third_party/sqlite3/sqliteInt.h" +#include "third_party/sqlite3/wal.h" +/* clang-format off */ /******************* NOTES ON THE DESIGN OF THE PAGER ************************ diff --git a/third_party/sqlite3/pager.h b/third_party/sqlite3/pager.h index 8d899bd1..68a66cc9 100644 --- a/third_party/sqlite3/pager.h +++ b/third_party/sqlite3/pager.h @@ -13,6 +13,7 @@ ** subsystem. The page cache subsystem reads and writes a file a page ** at a time and provides a journal for rollback. */ +/* clang-format off */ #ifndef SQLITE_PAGER_H #define SQLITE_PAGER_H diff --git a/third_party/sqlite3/parse.c b/third_party/sqlite3/parse.c index 050b2b67..08f25a18 100644 --- a/third_party/sqlite3/parse.c +++ b/third_party/sqlite3/parse.c @@ -13,16 +13,17 @@ ************************************************************************* ** This file contains SQLite's SQL parser. ** -** The canonical source code to this file ("parse.y") is a Lemon grammar +** The canonical source code to this file ("parse.y") is a Lemon grammar ** file that specifies the input grammar and actions to take while parsing. -** That input file is processed by Lemon to generate a C-language +** That input file is processed by Lemon to generate a C-language ** implementation of a parser for the given grammer. You might be reading ** this comment as part of the translated C-code. Edits should be made ** to the original parse.y sources. */ #line 58 "parse.y" +/* clang-format off */ -#include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" /* ** Disable all error recovery processing in the parser push-down @@ -1441,8 +1442,8 @@ struct yyParser { typedef struct yyParser yyParser; #ifndef NDEBUG -#include -#include +#include "libc/assert.h" +#include "libc/stdio/stdio.h" static FILE *yyTraceFILE = 0; static char *yyTracePrompt = 0; #endif /* NDEBUG */ diff --git a/third_party/sqlite3/pcache.c b/third_party/sqlite3/pcache.c index 36829be4..7f3b9093 100644 --- a/third_party/sqlite3/pcache.c +++ b/third_party/sqlite3/pcache.c @@ -11,7 +11,8 @@ ************************************************************************* ** This file implements that page cache. */ -#include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" +/* clang-format off */ /* ** A complete page cache is an instance of this structure. Every diff --git a/third_party/sqlite3/pcache.h b/third_party/sqlite3/pcache.h index eb55396a..77f3c008 100644 --- a/third_party/sqlite3/pcache.h +++ b/third_party/sqlite3/pcache.h @@ -10,8 +10,9 @@ ** ************************************************************************* ** This header file defines the interface that the sqlite page cache -** subsystem. +** subsystem. */ +/* clang-format off */ #ifndef _PCACHE_H_ diff --git a/third_party/sqlite3/pcache1.c b/third_party/sqlite3/pcache1.c index 3eae6b63..8f7b7584 100644 --- a/third_party/sqlite3/pcache1.c +++ b/third_party/sqlite3/pcache1.c @@ -63,7 +63,7 @@ ** ** The third case is a chunk of heap memory (defaulting to 100 pages worth) ** that is allocated when the page cache is created. The size of the local -** bulk allocation can be adjusted using +** bulk allocation can be adjusted using ** ** sqlite3_config(SQLITE_CONFIG_PAGECACHE, (void*)0, 0, N). ** @@ -80,7 +80,8 @@ ** show that method (3) with N==100 provides about a 5% performance boost for ** common workloads. */ -#include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" +/* clang-format off */ typedef struct PCache1 PCache1; typedef struct PgHdr1 PgHdr1; diff --git a/third_party/sqlite3/pragma.c b/third_party/sqlite3/pragma.c index 84f29c2f..9642ff03 100644 --- a/third_party/sqlite3/pragma.c +++ b/third_party/sqlite3/pragma.c @@ -11,7 +11,8 @@ ************************************************************************* ** This file contains code used to implement the PRAGMA command. */ -#include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" +/* clang-format off */ #if !defined(SQLITE_ENABLE_LOCKING_STYLE) # if defined(__APPLE__) @@ -28,7 +29,7 @@ ** lexicographical order to facility a binary search of the pragma name. ** Do not edit pragma.h directly. Edit and rerun the script in at ** ../tool/mkpragmatab.tcl. */ -#include "pragma.h" +#include "third_party/sqlite3/pragma.h" /* ** Interpret the given string as a safety level. Return 0 for OFF, diff --git a/third_party/sqlite3/pragma.h b/third_party/sqlite3/pragma.h index be99befb..1d218736 100644 --- a/third_party/sqlite3/pragma.h +++ b/third_party/sqlite3/pragma.h @@ -3,6 +3,7 @@ ** ../tool/mkpragmatab.tcl. To update the set of pragmas, edit ** that script and rerun it. */ +/* clang-format off */ /* The various pragma types */ #define PragTyp_ACTIVATE_EXTENSIONS 0 diff --git a/third_party/sqlite3/prepare.c b/third_party/sqlite3/prepare.c index eb4627f0..0653a726 100644 --- a/third_party/sqlite3/prepare.c +++ b/third_party/sqlite3/prepare.c @@ -13,7 +13,8 @@ ** interface, and routines that contribute to loading the database schema ** from disk. */ -#include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" +/* clang-format off */ /* ** Fill the InitData structure with an error message that indicates diff --git a/third_party/sqlite3/printf.c b/third_party/sqlite3/printf.c index 9aab863e..dbf540bd 100644 --- a/third_party/sqlite3/printf.c +++ b/third_party/sqlite3/printf.c @@ -1,6 +1,6 @@ /* ** The "printf" code that follows dates from the 1980's. It is in -** the public domain. +** the public domain. ** ************************************************************************** ** @@ -9,7 +9,8 @@ ** library, though the implementation here has enhancements to support ** SQLite. */ -#include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" +/* clang-format off */ /* ** Conversion types fall into various categories as defined by the diff --git a/third_party/sqlite3/random.c b/third_party/sqlite3/random.c index d4ae77c4..0eb6b8ff 100644 --- a/third_party/sqlite3/random.c +++ b/third_party/sqlite3/random.c @@ -15,7 +15,8 @@ ** Random numbers are used by some of the database backends in order ** to generate random integer keys for tables or random filenames. */ -#include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" +/* clang-format off */ /* All threads share a single random number generator. diff --git a/third_party/sqlite3/resolve.c b/third_party/sqlite3/resolve.c index 5ddfa4df..ab68d251 100644 --- a/third_party/sqlite3/resolve.c +++ b/third_party/sqlite3/resolve.c @@ -14,7 +14,8 @@ ** resolve all identifiers by associating them with a particular ** table and column. */ -#include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" +/* clang-format off */ /* ** Magic table number to mean the EXCLUDED table in an UPSERT statement. diff --git a/third_party/sqlite3/rowset.c b/third_party/sqlite3/rowset.c index 0562320a..e18e62f9 100644 --- a/third_party/sqlite3/rowset.c +++ b/third_party/sqlite3/rowset.c @@ -35,7 +35,7 @@ ** extracts the least value from the RowSet. ** ** The INSERT primitive might allocate additional memory. Memory is -** allocated in chunks so most INSERTs do no allocation. There is an +** allocated in chunks so most INSERTs do no allocation. There is an ** upper bound on the size of allocated memory. No memory is freed ** until DESTROY. ** @@ -61,7 +61,8 @@ ** be possible, but the feature was not used, so it was removed in order ** to simplify the code. */ -#include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" +/* clang-format off */ /* diff --git a/third_party/sqlite3/rtree.c b/third_party/sqlite3/rtree.c index f5b57a5e..5edc8958 100644 --- a/third_party/sqlite3/rtree.c +++ b/third_party/sqlite3/rtree.c @@ -12,6 +12,7 @@ ** This file contains code for implementations of the r-tree and r*-tree ** algorithms packaged as an SQLite virtual table module. */ +/* clang-format off */ /* ** Database Format of R-Tree Tables @@ -57,15 +58,15 @@ || (defined(SQLITE_ENABLE_RTREE) && !defined(SQLITE_OMIT_VIRTUALTABLE)) #ifndef SQLITE_CORE - #include "sqlite3ext.h" - SQLITE_EXTENSION_INIT1 +#include "third_party/sqlite3/sqlite3ext.h" +SQLITE_EXTENSION_INIT1 #else - #include "sqlite3.h" +#include "third_party/sqlite3/sqlite3.h" #endif int sqlite3GetToken(const unsigned char*,int*); /* In the SQLite core */ #ifndef SQLITE_AMALGAMATION -#include "sqlite3rtree.h" +#include "third_party/sqlite3/sqlite3rtree.h" typedef sqlite3_int64 i64; typedef sqlite3_uint64 u64; typedef unsigned char u8; @@ -79,10 +80,10 @@ typedef unsigned int u32; #endif #endif -#include -#include -#include -#include +#include "libc/assert.h" +#include "libc/mem/mem.h" +#include "libc/stdio/stdio.h" +#include "libc/str/str.h" /* The following macro is used to suppress compiler warnings. */ @@ -4366,7 +4367,7 @@ static void rtreecheck( /* Conditionally include the geopoly code */ #ifdef SQLITE_ENABLE_GEOPOLY -# include "geopoly.c" +#include "third_party/sqlite3/geopoly.c" #endif /* diff --git a/third_party/sqlite3/rtree.h b/third_party/sqlite3/rtree.h index 8f41500d..cb9cdd09 100644 --- a/third_party/sqlite3/rtree.h +++ b/third_party/sqlite3/rtree.h @@ -13,7 +13,8 @@ ** This header file is used by programs that want to link against the ** RTREE library. All it does is declare the sqlite3RtreeInit() interface. */ -#include "sqlite3.h" +#include "third_party/sqlite3/sqlite3.h" +/* clang-format off */ #ifdef SQLITE_OMIT_VIRTUALTABLE # undef SQLITE_ENABLE_RTREE diff --git a/third_party/sqlite3/select.c b/third_party/sqlite3/select.c index e2fa051e..7375221e 100644 --- a/third_party/sqlite3/select.c +++ b/third_party/sqlite3/select.c @@ -12,7 +12,8 @@ ** This file contains C code routines that are called by the parser ** to handle SELECT statements in SQLite. */ -#include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" +/* clang-format off */ /* ** An instance of the following object is used to record information about diff --git a/third_party/sqlite3/shell.c b/third_party/sqlite3/shell.c index 27de22a3..b60655f5 100644 --- a/third_party/sqlite3/shell.c +++ b/third_party/sqlite3/shell.c @@ -34,6 +34,7 @@ /* This needs to come before any includes for MSVC compiler */ #define _CRT_SECURE_NO_WARNINGS #endif +/* clang-format off */ /* ** Determine if we are dealing with WinRT, which provides only a subset of @@ -82,41 +83,42 @@ # define _LARGEFILE_SOURCE 1 #endif -#include -#include -#include -#include -#include "sqlite3.h" +#include "libc/assert.h" +#include "libc/fmt/conv.h" +#include "libc/fmt/fmt.h" +#include "libc/mem/mem.h" +#include "libc/stdio/stdio.h" +#include "libc/str/str.h" +#include "third_party/sqlite3/sqlite3.h" + typedef sqlite3_int64 i64; typedef sqlite3_uint64 u64; typedef unsigned char u8; #if SQLITE_USER_AUTHENTICATION -# include "sqlite3userauth.h" +#include "third_party/sqlite3/sqlite3userauth.h" #endif -#include -#include +#include "libc/str/str.h" #if !defined(_WIN32) && !defined(WIN32) -# include -# if !defined(__RTP__) && !defined(_WRS_KERNEL) -# include -# endif +#include "libc/calls/sigbits.h" +#if !defined(__RTP__) && !defined(_WRS_KERNEL) +#include "third_party/musl/passwd.h" +#endif #endif #if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__) -# include -# include -# define GETPID getpid -# if defined(__MINGW32__) -# define DIRENT dirent -# ifndef S_ISLNK -# define S_ISLNK(mode) (0) -# endif -# endif +#include "libc/calls/calls.h" +#include "libc/isystem/unistd.h" +#define GETPID getpid +#if defined(__MINGW32__) +#define DIRENT dirent +#ifndef S_ISLNK +#define S_ISLNK(mode) (0) +#endif +#endif #else # define GETPID (int)GetCurrentProcessId #endif -#include -#include +#include "libc/calls/weirdtypes.h" #if HAVE_READLINE # include @@ -137,12 +139,12 @@ typedef unsigned char u8; #elif HAVE_LINENOISE -# include "linenoise.h" -# define shell_add_history(X) linenoiseHistoryAdd(X) -# define shell_read_history(X) linenoiseHistoryLoad(X) -# define shell_write_history(X) linenoiseHistorySave(X) -# define shell_stifle_history(X) linenoiseHistorySetMaxLen(X) -# define shell_readline(X) linenoise(X) +#include "third_party/sqlite3/linenoise.h" +#define shell_add_history(X) linenoiseHistoryAdd(X) +#define shell_read_history(X) linenoiseHistoryLoad(X) +#define shell_write_history(X) linenoiseHistorySave(X) +#define shell_stifle_history(X) linenoiseHistorySetMaxLen(X) +#define shell_readline(X) linenoise(X) #else @@ -176,17 +178,14 @@ typedef unsigned char u8; # define pclose _pclose # endif #else - /* Make sure isatty() has a prototype. */ - extern int isatty(int); +/* Make sure isatty() has a prototype. */ -# if !defined(__RTP__) && !defined(_WRS_KERNEL) - /* popen and pclose are not C89 functions and so are - ** sometimes omitted from the header */ - extern FILE *popen(const char*,const char*); - extern int pclose(FILE*); -# else -# define SQLITE_OMIT_POPEN 1 -# endif +#if !defined(__RTP__) && !defined(_WRS_KERNEL) +/* popen and pclose are not C89 functions and so are +** sometimes omitted from the "libc/stdio/stdio.h" header */ +#else +#define SQLITE_OMIT_POPEN 1 +#endif #endif #if defined(_WIN32_WCE) @@ -255,8 +254,8 @@ static sqlite3_int64 timeOfDay(void){ } #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux) -#include -#include +#include "libc/sysv/consts/rusage.h" +#include "libc/time/time.h" /* VxWorks does not support getrusage() as far as we can determine */ #if defined(_WRS_KERNEL) || defined(__RTP__) @@ -1059,25 +1058,23 @@ static void shellAddSchemaName( #define WIN32_LEAN_AND_MEAN #endif -#include "windows.h" +#include "third_party/sqlite3/windows.h" /* ** We need several support functions from the SQLite core. */ -/* #include "sqlite3.h" */ +/* #include "third_party/sqlite3/sqlite3.h" */ /* ** We need several things from the ANSI and MSVCRT headers. */ -#include -#include -#include -#include -#include -#include -#include +#include "libc/calls/weirdtypes.h" +#include "libc/errno.h" +#include "libc/limits.h" +#include "libc/mem/mem.h" +#include "libc/stdio/stdio.h" /* ** We may need several defines that should have been in "sys/stat.h". @@ -1211,7 +1208,7 @@ extern INT closedir(LPDIR dirp); */ #if defined(_WIN32) && defined(_MSC_VER) -/* #include "test_windirent.h" */ +/* #include "third_party/sqlite3/test_windirent.h" */ /* ** Implementation of the POSIX getenv() function using the Win32 API. @@ -1419,11 +1416,10 @@ INT closedir( ** is used. If SIZE is included it must be one of the integers 224, 256, ** 384, or 512, to determine SHA3 hash variant that is computed. */ -/* #include "sqlite3ext.h" */ +/* #include "third_party/sqlite3/sqlite3ext.h" */ SQLITE_EXTENSION_INIT1 -#include -#include -#include +#include "libc/assert.h" +#include "libc/str/str.h" #ifndef SQLITE_AMALGAMATION /* typedef sqlite3_uint64 u64; */ @@ -2192,38 +2188,18 @@ int sqlite3_shathree_init( ** And the paths returned in the "name" column of the table are also ** relative to directory $dir. */ -/* #include "sqlite3ext.h" */ +/* #include "third_party/sqlite3/sqlite3ext.h" */ SQLITE_EXTENSION_INIT1 -#include -#include -#include - -#include -#include -#include -#if !defined(_WIN32) && !defined(WIN32) -# include -# include -# include -# include -#else -# include "windows.h" -# include -# include -/* # include "test_windirent.h" */ -# define dirent DIRENT -# ifndef chmod -# define chmod _chmod -# endif -# ifndef stat -# define stat _stat -# endif -# define mkdir(path,mode) _mkdir(path) -# define lstat(path,buf) stat(path,buf) -#endif -#include -#include - +#include "libc/assert.h" +#include "libc/calls/calls.h" +#include "libc/calls/weirdtypes.h" +#include "libc/stdio/stdio.h" +#include "libc/str/str.h" +#include "libc/calls/sigbits.h" +#include "libc/isystem/unistd.h" +#include "libc/time/time.h" +#include "libc/errno.h" +#include "libc/time/time.h" /* ** Structure of the fsdir() table-valued function @@ -3155,11 +3131,10 @@ int sqlite3_fileio_init( ** faster than any human can type. ** */ -/* #include "sqlite3ext.h" */ +/* #include "third_party/sqlite3/sqlite3ext.h" */ SQLITE_EXTENSION_INIT1 -#include -#include -#include +#include "libc/assert.h" +#include "libc/str/str.h" #ifndef SQLITE_OMIT_VIRTUALTABLE @@ -3672,10 +3647,10 @@ int sqlite3_completion_init( ** If the file being opened is a plain database (not an appended one), then ** this shim is a pass-through into the default underlying VFS. (rule 3) **/ -/* #include "sqlite3ext.h" */ +/* #include "third_party/sqlite3/sqlite3ext.h" */ SQLITE_EXTENSION_INIT1 -#include -#include +#include "libc/assert.h" +#include "libc/str/str.h" /* The append mark at the end of the database is: ** @@ -4319,9 +4294,9 @@ int sqlite3_appendvfs_init( ** This extension is used to implement the --memtrace option of the ** command-line shell. */ -#include -#include -#include +#include "libc/assert.h" +#include "libc/stdio/stdio.h" +#include "libc/str/str.h" /* The original memory allocation routines */ static sqlite3_mem_methods memtraceBase; @@ -4436,11 +4411,10 @@ int sqlite3MemTraceDeactivate(void){ ** is *not* limited integers that can be expressed as a ** 64-bit machine integer. */ -/* #include "sqlite3ext.h" */ +/* #include "third_party/sqlite3/sqlite3ext.h" */ SQLITE_EXTENSION_INIT1 -#include -#include -#include +#include "libc/assert.h" +#include "libc/str/str.h" /* ** Compare text in lexicographic order, except strings of digits @@ -4518,12 +4492,11 @@ int sqlite3_uint_init( ** ** The focus here is on simplicity and correctness, not performance. */ -/* #include "sqlite3ext.h" */ +/* #include "third_party/sqlite3/sqlite3ext.h" */ SQLITE_EXTENSION_INIT1 -#include -#include -#include -#include +#include "libc/assert.h" +#include "libc/mem/mem.h" +#include "libc/str/str.h" /* Mark a function parameter as unused, to suppress nuisance compiler ** warnings. */ @@ -5226,10 +5199,10 @@ int sqlite3_decimal_init( ** FROM pow2, c WHERE pow2.x=ieee754_exponent(c.bin); ** */ -/* #include "sqlite3ext.h" */ +/* #include "third_party/sqlite3/sqlite3ext.h" */ SQLITE_EXTENSION_INIT1 -#include -#include +#include "libc/assert.h" +#include "libc/str/str.h" /* Mark a function parameter as unused, to suppress nuisance compiler ** warnings. */ @@ -5501,10 +5474,10 @@ int sqlite3_ieee_init( ** encourages the query planner to order joins such that the bounds of the ** series are well-defined. */ -/* #include "sqlite3ext.h" */ +/* #include "third_party/sqlite3/sqlite3ext.h" */ SQLITE_EXTENSION_INIT1 -#include -#include +#include "libc/assert.h" +#include "libc/str/str.h" #ifndef SQLITE_OMIT_VIRTUALTABLE @@ -5906,13 +5879,12 @@ int sqlite3_series_init( ** * No support for zip64 extensions ** * Only the "inflate/deflate" (zlib) compression method is supported */ -/* #include "sqlite3ext.h" */ +/* #include "third_party/sqlite3/sqlite3ext.h" */ SQLITE_EXTENSION_INIT1 -#include -#include -#include - -#include +#include "libc/assert.h" +#include "libc/stdio/stdio.h" +#include "libc/str/str.h" +#include "third_party/zlib/zlib.h" #ifndef SQLITE_OMIT_VIRTUALTABLE @@ -8089,10 +8061,10 @@ int sqlite3_zipfile_init( ** for working with sqlar archives and used by the shell tool's built-in ** sqlar support. */ -/* #include "sqlite3ext.h" */ +/* #include "third_party/sqlite3/sqlite3ext.h" */ SQLITE_EXTENSION_INIT1 -#include -#include +#include "libc/assert.h" +#include "third_party/zlib/zlib.h" /* ** Implementation of the "sqlar_compress(X)" SQL function. @@ -8215,7 +8187,7 @@ int sqlite3_sqlar_init( */ #if !defined(SQLITEEXPERT_H) #define SQLITEEXPERT_H 1 -/* #include "sqlite3.h" */ +/* #include "third_party/sqlite3/sqlite3.h" */ typedef struct sqlite3expert sqlite3expert; @@ -8384,10 +8356,10 @@ void sqlite3_expert_destroy(sqlite3expert*); ** ************************************************************************* */ -/* #include "sqlite3expert.h" */ -#include -#include -#include +/* #include "third_party/sqlite3/sqlite3expert.h" */ +#include "libc/assert.h" +#include "libc/stdio/stdio.h" +#include "libc/str/str.h" #ifndef SQLITE_OMIT_VIRTUALTABLE @@ -10412,15 +10384,15 @@ void sqlite3_expert_destroy(sqlite3expert *p){ ** It contains one entry for each b-tree pointer between a parent and ** child page in the database. */ -#if !defined(SQLITEINT_H) -/* #include "sqlite3ext.h" */ +#if !defined(SQLITEINT_H) +/* #include "third_party/sqlite3/sqlite3ext.h" */ /* typedef unsigned char u8; */ #endif SQLITE_EXTENSION_INIT1 -#include -#include +#include "libc/assert.h" +#include "libc/str/str.h" #define DBDATA_PADDING_BYTES 100 @@ -21018,6 +20990,8 @@ int SQLITE_CDECL wmain(int argc, wchar_t **wargv){ setBinaryMode(stdin, 0); setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */ + setvbuf(stdin, (char *)NULL, _IONBF, BUFSIZ); + setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ); stdin_is_interactive = isatty(0); stdout_is_console = isatty(1); diff --git a/third_party/sqlite3/shell.c.in b/third_party/sqlite3/shell.c.in index 2ec454ff..c96d3ecf 100644 --- a/third_party/sqlite3/shell.c.in +++ b/third_party/sqlite3/shell.c.in @@ -16,6 +16,7 @@ /* This needs to come before any includes for MSVC compiler */ #define _CRT_SECURE_NO_WARNINGS #endif +/* clang-format off */ /* ** Determine if we are dealing with WinRT, which provides only a subset of diff --git a/third_party/sqlite3/sqlite3.h b/third_party/sqlite3/sqlite3.h index 19ee767f..284b958c 100644 --- a/third_party/sqlite3/sqlite3.h +++ b/third_party/sqlite3/sqlite3.h @@ -32,7 +32,8 @@ */ #ifndef SQLITE3_H #define SQLITE3_H -#include /* Needed for the definition of va_list */ +/* Needed for the definition of va_list */ +/* clang-format off */ /* ** Make sure we can call this stuff from C++. @@ -9587,7 +9588,7 @@ SQLITE_API int sqlite3_system_errno(sqlite3*); ** the most recent version. */ typedef struct sqlite3_snapshot { - unsigned char hidden[48]; + unsigned char dummyhidden[48]; } sqlite3_snapshot; /* diff --git a/third_party/sqlite3/sqlite3.mk b/third_party/sqlite3/sqlite3.mk new file mode 100644 index 00000000..3b009baa --- /dev/null +++ b/third_party/sqlite3/sqlite3.mk @@ -0,0 +1,102 @@ +#-*-mode:makefile-gmake;indent-tabs-mode:t;tab-width:8;coding:utf-8-*-┐ +#───vi: set et ft=make ts=8 tw=8 fenc=utf-8 :vi───────────────────────┘ + +PKGS += THIRD_PARTY_SQLITE3 + +THIRD_PARTY_SQLITE3_ARTIFACTS += THIRD_PARTY_SQLITE3_A +THIRD_PARTY_SQLITE3 = $(THIRD_PARTY_SQLITE3_A_DEPS) $(THIRD_PARTY_SQLITE3_A) $(THIRD_PARTY_SQLITE3_COMS) +THIRD_PARTY_SQLITE3_A = o/$(MODE)/third_party/sqlite3/libsqlite3.a +THIRD_PARTY_SQLITE3_A_FILES := $(wildcard third_party/sqlite3/*) +THIRD_PARTY_SQLITE3_A_HDRS = $(filter %.h,$(THIRD_PARTY_SQLITE3_A_FILES)) +THIRD_PARTY_SQLITE3_A_SRCS_C = $(filter-out %/geopoly.c,$(filter %.c,$(THIRD_PARTY_SQLITE3_A_FILES))) +THIRD_PARTY_SQLITE3_BINS = $(THIRD_PARTY_SQLITE3_COMS) $(THIRD_PARTY_SQLITE3_COMS:%=%.dbg) + +THIRD_PARTY_SQLITE3_A_SRCS = \ + $(THIRD_PARTY_SQLITE3_A_SRCS_C) + +THIRD_PARTY_SQLITE3_A_OBJS = \ + $(THIRD_PARTY_SQLITE3_A_SRCS_C:%.c=o/$(MODE)/%.o) + +THIRD_PARTY_SQLITE3_COMS = \ + o/$(MODE)/third_party/sqlite3/sqlite3.com + +THIRD_PARTY_SQLITE3_A_CHECKS = \ + $(THIRD_PARTY_SQLITE3_A).pkg \ + $(THIRD_PARTY_SQLITE3_A_HDRS:%=o/$(MODE)/%.ok) + +THIRD_PARTY_SQLITE3_A_DIRECTDEPS = \ + LIBC_ALG \ + LIBC_BITS \ + LIBC_CALLS \ + LIBC_FMT \ + LIBC_INTRIN \ + LIBC_MEM \ + LIBC_NEXGEN32E \ + LIBC_RUNTIME \ + LIBC_STDIO \ + LIBC_STR \ + LIBC_STUBS \ + LIBC_SYSV \ + LIBC_SYSV_CALLS \ + LIBC_TIME \ + LIBC_TINYMATH \ + LIBC_UNICODE \ + THIRD_PARTY_GDTOA \ + THIRD_PARTY_MUSL \ + THIRD_PARTY_ZLIB + +THIRD_PARTY_SQLITE3_A_DEPS := \ + $(call uniq,$(foreach x,$(THIRD_PARTY_SQLITE3_A_DIRECTDEPS),$($(x)))) + +o/$(MODE)/third_party/sqlite3/sqlite3.com.dbg: \ + $(THIRD_PARTY_SQLITE3_A_DEPS) \ + $(THIRD_PARTY_SQLITE3_A) \ + o/$(MODE)/third_party/sqlite3/shell.o \ + $(CRT) \ + $(APE) + -@$(APELINK) + +$(THIRD_PARTY_SQLITE3_A): \ + third_party/sqlite3/ \ + $(THIRD_PARTY_SQLITE3_A).pkg \ + $(filter-out %/shell.o,$(THIRD_PARTY_SQLITE3_A_OBJS)) + +$(THIRD_PARTY_SQLITE3_A).pkg: \ + $(filter-out %/shell.o,$(THIRD_PARTY_SQLITE3_A_OBJS)) \ + $(foreach x,$(THIRD_PARTY_SQLITE3_A_DIRECTDEPS),$($(x)_A).pkg) + +$(THIRD_PARTY_SQLITE3_A_OBJS): \ + OVERRIDE_CFLAGS = \ + -DSTACK_FRAME_UNLIMITED \ + -DSQLITE_CORE \ + -DSQLITE_OS_UNIX=1 \ + -DBUILD_sqlite -DNDEBUG \ + -DSQLITE_THREADSAFE=0 \ + -DSQLITE_OMIT_LOAD_EXTENSION=1 \ + -DSQLITE_ENABLE_MATH_FUNCTIONS \ + -DSQLITE_ENABLE_FTS3 \ + -DSQLITE_ENABLE_FTS4 \ + -DSQLITE_ENABLE_FTS5 \ + -DSQLITE_ENABLE_JSON1 \ + -DSQLITE_ENABLE_GEOPOLY \ + -DSQLITE_ENABLE_RTREE \ + -DSQLITE_ENABLE_SESSION \ + -DSQLITE_ENABLE_PREUPDATE_HOOK \ + -DSQLITE_TEMP_STORE=1 \ + -DHAVE_READLINE=0 \ + -DHAVE_EDITLINE=0 \ + -DSQLITE_ENABLE_JSON1 \ + -DSQLITE_ENABLE_RTREE \ + -DSQLITE_ENABLE_EXPLAIN_COMMENTS \ + -DSQLITE_ENABLE_UNKNOWN_SQL_FUNCTION \ + -DSQLITE_ENABLE_STMTVTAB \ + -DSQLITE_ENABLE_DBPAGE_VTAB \ + -DSQLITE_ENABLE_DBSTAT_VTAB \ + -DSQLITE_ENABLE_BYTECODE_VTAB \ + -DSQLITE_ENABLE_OFFSET_SQL_FUNC \ + -DSQLITE_ENABLE_DESERIALIZE + +.PHONY: o/$(MODE)/third_party/sqlite3 +o/$(MODE)/third_party/sqlite3: \ + $(THIRD_PARTY_SQLITE3_BINS) \ + $(THIRD_PARTY_SQLITE3_CHECKS) diff --git a/third_party/sqlite3/sqlite3ext.h b/third_party/sqlite3/sqlite3ext.h index 217601fd..c35a3fd3 100644 --- a/third_party/sqlite3/sqlite3ext.h +++ b/third_party/sqlite3/sqlite3ext.h @@ -12,12 +12,13 @@ ** This header file defines the SQLite interface for use by ** shared libraries that want to be imported as extensions into ** an SQLite instance. Shared libraries that intend to be loaded -** as extensions by SQLite should #include this file instead of +** as extensions by SQLite should #include this file instead of ** sqlite3.h. */ #ifndef SQLITE3EXT_H #define SQLITE3EXT_H -#include "sqlite3.h" +#include "third_party/sqlite3/sqlite3.h" +/* clang-format off */ /* ** The following structure holds pointers to all of the SQLite API diff --git a/third_party/sqlite3/sqlite3rbu.c b/third_party/sqlite3/sqlite3rbu.c index c5f80984..2c8de1b3 100644 --- a/third_party/sqlite3/sqlite3rbu.c +++ b/third_party/sqlite3/sqlite3rbu.c @@ -11,7 +11,7 @@ ************************************************************************* ** ** -** OVERVIEW +** OVERVIEW ** ** The RBU extension requires that the RBU update be packaged as an ** SQLite database. The tables it expects to find are described in @@ -19,34 +19,34 @@ ** that the user wishes to write to, a corresponding data_xyz table is ** created in the RBU database and populated with one row for each row to ** update, insert or delete from the target table. -** +** ** The update proceeds in three stages: -** +** ** 1) The database is updated. The modified database pages are written ** to a *-oal file. A *-oal file is just like a *-wal file, except ** that it is named "-oal" instead of "-wal". ** Because regular SQLite clients do not look for file named ** "-oal", they go on using the original database in ** rollback mode while the *-oal file is being generated. -** +** ** During this stage RBU does not update the database by writing ** directly to the target tables. Instead it creates "imposter" ** tables using the SQLITE_TESTCTRL_IMPOSTER interface that it uses ** to update each b-tree individually. All updates required by each ** b-tree are completed before moving on to the next, and all ** updates are done in sorted key order. -** +** ** 2) The "-oal" file is moved to the equivalent "-wal" ** location using a call to rename(2). Before doing this the RBU ** module takes an EXCLUSIVE lock on the database file, ensuring ** that there are no other active readers. -** +** ** Once the EXCLUSIVE lock is released, any other database readers ** detect the new *-wal file and read the database in wal mode. At ** this point they see the new version of the database - including ** the updates made as part of the RBU update. -** -** 3) The new *-wal file is checkpointed. This proceeds in the same way +** +** 3) The new *-wal file is checkpointed. This proceeds in the same way ** as a regular database checkpoint, except that a single frame is ** checkpointed each time sqlite3rbu_step() is called. If the RBU ** handle is closed before the entire *-wal file is checkpointed, @@ -55,7 +55,7 @@ ** the future. ** ** POTENTIAL PROBLEMS -** +** ** The rename() call might not be portable. And RBU is not currently ** syncing the directory after renaming the file. ** @@ -77,20 +77,21 @@ ** fields are collected. This means we're probably writing a lot more ** data to disk when saving the state of an ongoing update to the RBU ** update database than is strictly necessary. -** +** */ +/* clang-format off */ -#include -#include -#include - -#include "sqlite3.h" +#include "libc/assert.h" +#include "libc/calls/calls.h" +#include "libc/stdio/stdio.h" +#include "libc/str/str.h" +#include "third_party/sqlite3/sqlite3.h" #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU) -#include "sqlite3rbu.h" +#include "third_party/sqlite3/sqlite3rbu.h" #if defined(_WIN32_WCE) -#include "windows.h" +#include "third_party/sqlite3/windows.h" #endif /* Maximum number of prepared UPDATE statements held by this module */ diff --git a/third_party/sqlite3/sqlite3rbu.h b/third_party/sqlite3/sqlite3rbu.h index 69d89500..6224b60a 100644 --- a/third_party/sqlite3/sqlite3rbu.h +++ b/third_party/sqlite3/sqlite3rbu.h @@ -10,8 +10,9 @@ ** ************************************************************************* ** -** This file contains the public interface for the RBU extension. +** This file contains the public interface for the RBU extension. */ +/* clang-format off */ /* ** SUMMARY @@ -267,7 +268,7 @@ #ifndef _SQLITE3RBU_H #define _SQLITE3RBU_H -#include "sqlite3.h" /* Required for error code definitions */ +#include "third_party/sqlite3/sqlite3.h" /* Required for error code definitions */ #ifdef __cplusplus extern "C" { diff --git a/third_party/sqlite3/sqlite3rtree.h b/third_party/sqlite3/sqlite3rtree.h index 9976c2d2..6bf99d26 100644 --- a/third_party/sqlite3/sqlite3rtree.h +++ b/third_party/sqlite3/sqlite3rtree.h @@ -10,11 +10,12 @@ ** ************************************************************************* */ +/* clang-format off */ #ifndef _SQLITE3RTREE_H_ #define _SQLITE3RTREE_H_ -#include +#include "third_party/sqlite3/sqlite3.h" #ifdef __cplusplus extern "C" { diff --git a/third_party/sqlite3/sqlite3session.c b/third_party/sqlite3/sqlite3session.c index 8210056a..1bf4415d 100644 --- a/third_party/sqlite3/sqlite3session.c +++ b/third_party/sqlite3/sqlite3session.c @@ -1,12 +1,12 @@ - +/* clang-format off */ #if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK) -#include "sqlite3session.h" -#include -#include +#include "libc/assert.h" +#include "libc/str/str.h" +#include "third_party/sqlite3/sqlite3session.h" #ifndef SQLITE_AMALGAMATION -# include "sqliteInt.h" -# include "vdbeInt.h" +#include "third_party/sqlite3/sqliteInt.h" +#include "third_party/sqlite3/vdbeInt.h" #endif typedef struct SessionTable SessionTable; @@ -18,11 +18,11 @@ typedef struct SessionInput SessionInput; ** Minimum chunk size used by streaming versions of functions. */ #ifndef SESSIONS_STRM_CHUNK_SIZE -# ifdef SQLITE_TEST -# define SESSIONS_STRM_CHUNK_SIZE 64 -# else -# define SESSIONS_STRM_CHUNK_SIZE 1024 -# endif +#ifdef SQLITE_TEST +#define SESSIONS_STRM_CHUNK_SIZE 64 +#else +#define SESSIONS_STRM_CHUNK_SIZE 1024 +#endif #endif static int sessions_strm_chunk_size = SESSIONS_STRM_CHUNK_SIZE; @@ -30,76 +30,76 @@ static int sessions_strm_chunk_size = SESSIONS_STRM_CHUNK_SIZE; typedef struct SessionHook SessionHook; struct SessionHook { void *pCtx; - int (*xOld)(void*,int,sqlite3_value**); - int (*xNew)(void*,int,sqlite3_value**); - int (*xCount)(void*); - int (*xDepth)(void*); + int (*xOld)(void *, int, sqlite3_value **); + int (*xNew)(void *, int, sqlite3_value **); + int (*xCount)(void *); + int (*xDepth)(void *); }; /* ** Session handle structure. */ struct sqlite3_session { - sqlite3 *db; /* Database handle session is attached to */ - char *zDb; /* Name of database session is attached to */ - int bEnable; /* True if currently recording */ - int bIndirect; /* True if all changes are indirect */ - int bAutoAttach; /* True to auto-attach tables */ - int rc; /* Non-zero if an error has occurred */ - void *pFilterCtx; /* First argument to pass to xTableFilter */ + sqlite3 *db; /* Database handle session is attached to */ + char *zDb; /* Name of database session is attached to */ + int bEnable; /* True if currently recording */ + int bIndirect; /* True if all changes are indirect */ + int bAutoAttach; /* True to auto-attach tables */ + int rc; /* Non-zero if an error has occurred */ + void *pFilterCtx; /* First argument to pass to xTableFilter */ int (*xTableFilter)(void *pCtx, const char *zTab); - i64 nMalloc; /* Number of bytes of data allocated */ - sqlite3_value *pZeroBlob; /* Value containing X'' */ - sqlite3_session *pNext; /* Next session object on same db. */ - SessionTable *pTable; /* List of attached tables */ - SessionHook hook; /* APIs to grab new and old data with */ + i64 nMalloc; /* Number of bytes of data allocated */ + sqlite3_value *pZeroBlob; /* Value containing X'' */ + sqlite3_session *pNext; /* Next session object on same db. */ + SessionTable *pTable; /* List of attached tables */ + SessionHook hook; /* APIs to grab new and old data with */ }; /* ** Instances of this structure are used to build strings or binary records. */ struct SessionBuffer { - u8 *aBuf; /* Pointer to changeset buffer */ - int nBuf; /* Size of buffer aBuf */ - int nAlloc; /* Size of allocation containing aBuf */ + u8 *aBuf; /* Pointer to changeset buffer */ + int nBuf; /* Size of buffer aBuf */ + int nAlloc; /* Size of allocation containing aBuf */ }; /* -** An object of this type is used internally as an abstraction for +** An object of this type is used internally as an abstraction for ** input data. Input data may be supplied either as a single large buffer ** (e.g. sqlite3changeset_start()) or using a stream function (e.g. ** sqlite3changeset_start_strm()). */ struct SessionInput { - int bNoDiscard; /* If true, do not discard in InputBuffer() */ - int iCurrent; /* Offset in aData[] of current change */ - int iNext; /* Offset in aData[] of next change */ - u8 *aData; /* Pointer to buffer containing changeset */ - int nData; /* Number of bytes in aData */ + int bNoDiscard; /* If true, do not discard in InputBuffer() */ + int iCurrent; /* Offset in aData[] of current change */ + int iNext; /* Offset in aData[] of next change */ + u8 *aData; /* Pointer to buffer containing changeset */ + int nData; /* Number of bytes in aData */ - SessionBuffer buf; /* Current read buffer */ - int (*xInput)(void*, void*, int*); /* Input stream call (or NULL) */ - void *pIn; /* First argument to xInput */ - int bEof; /* Set to true after xInput finished */ + SessionBuffer buf; /* Current read buffer */ + int (*xInput)(void *, void *, int *); /* Input stream call (or NULL) */ + void *pIn; /* First argument to xInput */ + int bEof; /* Set to true after xInput finished */ }; /* ** Structure for changeset iterators. */ struct sqlite3_changeset_iter { - SessionInput in; /* Input buffer or stream */ - SessionBuffer tblhdr; /* Buffer to hold apValue/zTab/abPK/ */ - int bPatchset; /* True if this is a patchset */ - int bInvert; /* True to invert changeset */ - int bSkipEmpty; /* Skip noop UPDATE changes */ - int rc; /* Iterator error code */ - sqlite3_stmt *pConflict; /* Points to conflicting row, if any */ - char *zTab; /* Current table */ - int nCol; /* Number of columns in zTab */ - int op; /* Current operation */ - int bIndirect; /* True if current change was indirect */ - u8 *abPK; /* Primary key array */ - sqlite3_value **apValue; /* old.* and new.* values */ + SessionInput in; /* Input buffer or stream */ + SessionBuffer tblhdr; /* Buffer to hold apValue/zTab/abPK/ */ + int bPatchset; /* True if this is a patchset */ + int bInvert; /* True to invert changeset */ + int bSkipEmpty; /* Skip noop UPDATE changes */ + int rc; /* Iterator error code */ + sqlite3_stmt *pConflict; /* Points to conflicting row, if any */ + char *zTab; /* Current table */ + int nCol; /* Number of columns in zTab */ + int op; /* Current operation */ + int bIndirect; /* True if current change was indirect */ + u8 *abPK; /* Primary key array */ + sqlite3_value **apValue; /* old.* and new.* values */ }; /* @@ -117,21 +117,21 @@ struct sqlite3_changeset_iter { */ struct SessionTable { SessionTable *pNext; - char *zName; /* Local name of table */ - int nCol; /* Number of columns in table zName */ - int bStat1; /* True if this is sqlite_stat1 */ - const char **azCol; /* Column names */ - u8 *abPK; /* Array of primary key flags */ - int nEntry; /* Total number of entries in hash table */ - int nChange; /* Size of apChange[] array */ - SessionChange **apChange; /* Hash table buckets */ + char *zName; /* Local name of table */ + int nCol; /* Number of columns in table zName */ + int bStat1; /* True if this is sqlite_stat1 */ + const char **azCol; /* Column names */ + u8 *abPK; /* Array of primary key flags */ + int nEntry; /* Total number of entries in hash table */ + int nChange; /* Size of apChange[] array */ + SessionChange **apChange; /* Hash table buckets */ }; -/* +/* ** RECORD FORMAT: ** -** The following record format is similar to (but not compatible with) that -** used in SQLite database files. This format is used as part of the +** The following record format is similar to (but not compatible with) that +** used in SQLite database files. This format is used as part of the ** change-set binary format, and so must be architecture independent. ** ** Unlike the SQLite database record format, each field is self-contained - @@ -165,7 +165,7 @@ struct SessionTable { ** Real values: ** An 8-byte big-endian IEEE 754-2008 real value. ** -** Varint values are encoded in the same way as varints in the SQLite +** Varint values are encoded in the same way as varints in the SQLite ** record format. ** ** CHANGESET FORMAT: @@ -197,7 +197,7 @@ struct SessionTable { ** ** The new.* record that is part of each INSERT change contains the values ** that make up the new row. Similarly, the old.* record that is part of each -** DELETE change contains the values that made up the row that was deleted +** DELETE change contains the values that made up the row that was deleted ** from the database. In the changeset format, the records that are part ** of INSERT or DELETE changes never contain any undefined (type byte 0x00) ** fields. @@ -206,8 +206,8 @@ struct SessionTable { ** associated with table columns that are not PRIMARY KEY columns and are ** not modified by the UPDATE change are set to "undefined". Other fields ** are set to the values that made up the row before the UPDATE that the -** change records took place. Within the new.* record, fields associated -** with table columns modified by the UPDATE change contain the new +** change records took place. Within the new.* record, fields associated +** with table columns modified by the UPDATE change contain the new ** values. Fields associated with table columns that are not modified ** are set to "undefined". ** @@ -233,7 +233,7 @@ struct SessionTable { ** ** As in the changeset format, each field of the single record that is part ** of a patchset change is associated with the correspondingly positioned -** table column, counting from left to right within the CREATE TABLE +** table column, counting from left to right within the CREATE TABLE ** statement. ** ** For a DELETE change, all fields within the record except those associated @@ -251,7 +251,7 @@ struct SessionTable { ** ** REBASE BLOB FORMAT: ** -** A rebase blob may be output by sqlite3changeset_apply_v2() and its +** A rebase blob may be output by sqlite3changeset_apply_v2() and its ** streaming equivalent for use with the sqlite3_rebaser APIs to rebase ** existing changesets. A rebase blob contains one entry for each conflict ** resolved using either the OMIT or REPLACE strategies within the apply_v2() @@ -275,7 +275,7 @@ struct SessionTable { ** ** In a rebase blob, the first field is set to SQLITE_INSERT if the change ** that caused the conflict was an INSERT or UPDATE, or to SQLITE_DELETE if -** it was a DELETE. The second field is set to 0x01 if the conflict +** it was a DELETE. The second field is set to 0x01 if the conflict ** resolution strategy was REPLACE, or 0x00 if it was OMIT. ** ** If the change that caused the conflict was a DELETE, then the single @@ -291,145 +291,146 @@ struct SessionTable { ** this structure stored in a SessionTable.aChange[] hash table. */ struct SessionChange { - int op; /* One of UPDATE, DELETE, INSERT */ - int bIndirect; /* True if this change is "indirect" */ - int nRecord; /* Number of bytes in buffer aRecord[] */ - u8 *aRecord; /* Buffer containing old.* record */ - SessionChange *pNext; /* For hash-table collisions */ + int op; /* One of UPDATE, DELETE, INSERT */ + int bIndirect; /* True if this change is "indirect" */ + int nRecord; /* Number of bytes in buffer aRecord[] */ + u8 *aRecord; /* Buffer containing old.* record */ + SessionChange *pNext; /* For hash-table collisions */ }; /* -** Write a varint with value iVal into the buffer at aBuf. Return the +** Write a varint with value iVal into the buffer at aBuf. Return the ** number of bytes written. */ -static int sessionVarintPut(u8 *aBuf, int iVal){ +static int sessionVarintPut(u8 *aBuf, int iVal) { return putVarint32(aBuf, iVal); } /* ** Return the number of bytes required to store value iVal as a varint. */ -static int sessionVarintLen(int iVal){ +static int sessionVarintLen(int iVal) { return sqlite3VarintLen(iVal); } /* -** Read a varint value from aBuf[] into *piVal. Return the number of +** Read a varint value from aBuf[] into *piVal. Return the number of ** bytes read. */ -static int sessionVarintGet(u8 *aBuf, int *piVal){ +static int sessionVarintGet(u8 *aBuf, int *piVal) { return getVarint32(aBuf, *piVal); } /* Load an unaligned and unsigned 32-bit integer */ -#define SESSION_UINT32(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3]) +#define SESSION_UINT32(x) \ + (((u32)(x)[0] << 24) | ((x)[1] << 16) | ((x)[2] << 8) | (x)[3]) /* ** Read a 64-bit big-endian integer value from buffer aRec[]. Return ** the value read. */ -static sqlite3_int64 sessionGetI64(u8 *aRec){ +static sqlite3_int64 sessionGetI64(u8 *aRec) { u64 x = SESSION_UINT32(aRec); - u32 y = SESSION_UINT32(aRec+4); - x = (x<<32) + y; + u32 y = SESSION_UINT32(aRec + 4); + x = (x << 32) + y; return (sqlite3_int64)x; } /* ** Write a 64-bit big-endian integer value to the buffer aBuf[]. */ -static void sessionPutI64(u8 *aBuf, sqlite3_int64 i){ - aBuf[0] = (i>>56) & 0xFF; - aBuf[1] = (i>>48) & 0xFF; - aBuf[2] = (i>>40) & 0xFF; - aBuf[3] = (i>>32) & 0xFF; - aBuf[4] = (i>>24) & 0xFF; - aBuf[5] = (i>>16) & 0xFF; - aBuf[6] = (i>> 8) & 0xFF; - aBuf[7] = (i>> 0) & 0xFF; +static void sessionPutI64(u8 *aBuf, sqlite3_int64 i) { + aBuf[0] = (i >> 56) & 0xFF; + aBuf[1] = (i >> 48) & 0xFF; + aBuf[2] = (i >> 40) & 0xFF; + aBuf[3] = (i >> 32) & 0xFF; + aBuf[4] = (i >> 24) & 0xFF; + aBuf[5] = (i >> 16) & 0xFF; + aBuf[6] = (i >> 8) & 0xFF; + aBuf[7] = (i >> 0) & 0xFF; } /* ** This function is used to serialize the contents of value pValue (see ** comment titled "RECORD FORMAT" above). ** -** If it is non-NULL, the serialized form of the value is written to +** If it is non-NULL, the serialized form of the value is written to ** buffer aBuf. *pnWrite is set to the number of bytes written before ** returning. Or, if aBuf is NULL, the only thing this function does is ** set *pnWrite. ** ** If no error occurs, SQLITE_OK is returned. Or, if an OOM error occurs -** within a call to sqlite3_value_text() (may fail if the db is utf-16)) +** within a call to sqlite3_value_text() (may fail if the db is utf-16)) ** SQLITE_NOMEM is returned. */ static int sessionSerializeValue( - u8 *aBuf, /* If non-NULL, write serialized value here */ - sqlite3_value *pValue, /* Value to serialize */ - sqlite3_int64 *pnWrite /* IN/OUT: Increment by bytes written */ -){ - int nByte; /* Size of serialized value in bytes */ + u8 *aBuf, /* If non-NULL, write serialized value here */ + sqlite3_value *pValue, /* Value to serialize */ + sqlite3_int64 *pnWrite /* IN/OUT: Increment by bytes written */ +) { + int nByte; /* Size of serialized value in bytes */ + + if (pValue) { + int eType; /* Value type (SQLITE_NULL, TEXT etc.) */ - if( pValue ){ - int eType; /* Value type (SQLITE_NULL, TEXT etc.) */ - eType = sqlite3_value_type(pValue); - if( aBuf ) aBuf[0] = eType; - - switch( eType ){ - case SQLITE_NULL: + if (aBuf) aBuf[0] = eType; + + switch (eType) { + case SQLITE_NULL: nByte = 1; break; - - case SQLITE_INTEGER: + + case SQLITE_INTEGER: case SQLITE_FLOAT: - if( aBuf ){ + if (aBuf) { /* TODO: SQLite does something special to deal with mixed-endian ** floating point values (e.g. ARM7). This code probably should ** too. */ u64 i; - if( eType==SQLITE_INTEGER ){ + if (eType == SQLITE_INTEGER) { i = (u64)sqlite3_value_int64(pValue); - }else{ + } else { double r; - assert( sizeof(double)==8 && sizeof(u64)==8 ); + assert(sizeof(double) == 8 && sizeof(u64) == 8); r = sqlite3_value_double(pValue); memcpy(&i, &r, 8); } sessionPutI64(&aBuf[1], i); } - nByte = 9; + nByte = 9; break; - + default: { u8 *z; int n; int nVarint; - - assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB ); - if( eType==SQLITE_TEXT ){ + + assert(eType == SQLITE_TEXT || eType == SQLITE_BLOB); + if (eType == SQLITE_TEXT) { z = (u8 *)sqlite3_value_text(pValue); - }else{ + } else { z = (u8 *)sqlite3_value_blob(pValue); } n = sqlite3_value_bytes(pValue); - if( z==0 && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM; + if (z == 0 && (eType != SQLITE_BLOB || n > 0)) return SQLITE_NOMEM; nVarint = sessionVarintLen(n); - - if( aBuf ){ + + if (aBuf) { sessionVarintPut(&aBuf[1], n); - if( n ) memcpy(&aBuf[nVarint + 1], z, n); + if (n) memcpy(&aBuf[nVarint + 1], z, n); } - + nByte = 1 + nVarint + n; break; } } - }else{ + } else { nByte = 1; - if( aBuf ) aBuf[0] = '\0'; + if (aBuf) aBuf[0] = '\0'; } - if( pnWrite ) *pnWrite += nByte; + if (pnWrite) *pnWrite += nByte; return SQLITE_OK; } @@ -438,9 +439,9 @@ static int sessionSerializeValue( ** pSession is not NULL, increase the sqlite3_session.nMalloc variable ** by the number of bytes allocated. */ -static void *sessionMalloc64(sqlite3_session *pSession, i64 nByte){ +static void *sessionMalloc64(sqlite3_session *pSession, i64 nByte) { void *pRet = sqlite3_malloc64(nByte); - if( pSession ) pSession->nMalloc += sqlite3_msize(pRet); + if (pSession) pSession->nMalloc += sqlite3_msize(pRet); return pRet; } @@ -449,8 +450,8 @@ static void *sessionMalloc64(sqlite3_session *pSession, i64 nByte){ ** call to sessionMalloc64(). If pSession is not NULL, decrease the ** sqlite3_session.nMalloc counter by the number of bytes freed. */ -static void sessionFree(sqlite3_session *pSession, void *pFree){ - if( pSession ) pSession->nMalloc -= sqlite3_msize(pFree); +static void sessionFree(sqlite3_session *pSession, void *pFree) { + if (pSession) pSession->nMalloc -= sqlite3_msize(pFree); sqlite3_free(pFree); } @@ -475,18 +476,18 @@ static void sessionFree(sqlite3_session *pSession, void *pFree){ ** Append the hash of the 64-bit integer passed as the second argument to the ** hash-key value passed as the first. Return the new hash-key value. */ -static unsigned int sessionHashAppendI64(unsigned int h, i64 i){ +static unsigned int sessionHashAppendI64(unsigned int h, i64 i) { h = HASH_APPEND(h, i & 0xFFFFFFFF); - return HASH_APPEND(h, (i>>32)&0xFFFFFFFF); + return HASH_APPEND(h, (i >> 32) & 0xFFFFFFFF); } /* -** Append the hash of the blob passed via the second and third arguments to +** Append the hash of the blob passed via the second and third arguments to ** the hash-key value passed as the first. Return the new hash-key value. */ -static unsigned int sessionHashAppendBlob(unsigned int h, int n, const u8 *z){ +static unsigned int sessionHashAppendBlob(unsigned int h, int n, const u8 *z) { int i; - for(i=0; inCol==pSession->hook.xCount(pSession->hook.pCtx) ); - for(i=0; inCol; i++){ - if( pTab->abPK[i] ){ + assert(*pbNullPK == 0); + assert(pTab->nCol == pSession->hook.xCount(pSession->hook.pCtx)); + for (i = 0; i < pTab->nCol; i++) { + if (pTab->abPK[i]) { int rc; int eType; sqlite3_value *pVal; - if( bNew ){ + if (bNew) { rc = pSession->hook.xNew(pSession->hook.pCtx, i, &pVal); - }else{ + } else { rc = pSession->hook.xOld(pSession->hook.pCtx, i, &pVal); } - if( rc!=SQLITE_OK ) return rc; + if (rc != SQLITE_OK) return rc; eType = sqlite3_value_type(pVal); h = sessionHashAppendType(h, eType); - if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){ + if (eType == SQLITE_INTEGER || eType == SQLITE_FLOAT) { i64 iVal; - if( eType==SQLITE_INTEGER ){ + if (eType == SQLITE_INTEGER) { iVal = sqlite3_value_int64(pVal); - }else{ + } else { double rVal = sqlite3_value_double(pVal); - assert( sizeof(iVal)==8 && sizeof(rVal)==8 ); + assert(sizeof(iVal) == 8 && sizeof(rVal) == 8); memcpy(&iVal, &rVal, 8); } h = sessionHashAppendI64(h, iVal); - }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){ + } else if (eType == SQLITE_TEXT || eType == SQLITE_BLOB) { const u8 *z; int n; - if( eType==SQLITE_TEXT ){ + if (eType == SQLITE_TEXT) { z = (const u8 *)sqlite3_value_text(pVal); - }else{ + } else { z = (const u8 *)sqlite3_value_blob(pVal); } n = sqlite3_value_bytes(pVal); - if( !z && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM; + if (!z && (eType != SQLITE_BLOB || n > 0)) return SQLITE_NOMEM; h = sessionHashAppendBlob(h, n, z); - }else{ - assert( eType==SQLITE_NULL ); - assert( pTab->bStat1==0 || i!=1 ); + } else { + assert(eType == SQLITE_NULL); + assert(pTab->bStat1 == 0 || i != 1); *pbNullPK = 1; } } @@ -574,12 +575,12 @@ static int sessionPreupdateHash( ** Return the number of bytes of space occupied by the value (including ** the type byte). */ -static int sessionSerialLen(u8 *a){ +static int sessionSerialLen(u8 *a) { int e = *a; int n; - if( e==0 || e==0xFF ) return 1; - if( e==SQLITE_NULL ) return 1; - if( e==SQLITE_INTEGER || e==SQLITE_FLOAT ) return 9; + if (e == 0 || e == 0xFF) return 1; + if (e == SQLITE_NULL) return 1; + if (e == SQLITE_INTEGER || e == SQLITE_FLOAT) return 9; return sessionVarintGet(&a[1], &n) + 1 + n; } @@ -593,42 +594,41 @@ static int sessionSerialLen(u8 *a){ ** a patchset DELETE. In this case the non-PK fields are omitted entirely. */ static unsigned int sessionChangeHash( - SessionTable *pTab, /* Table handle */ - int bPkOnly, /* Record consists of PK fields only */ - u8 *aRecord, /* Change record */ - int nBucket /* Assume this many buckets in hash table */ -){ - unsigned int h = 0; /* Value to return */ - int i; /* Used to iterate through columns */ - u8 *a = aRecord; /* Used to iterate through change record */ + SessionTable *pTab, /* Table handle */ + int bPkOnly, /* Record consists of PK fields only */ + u8 *aRecord, /* Change record */ + int nBucket /* Assume this many buckets in hash table */ +) { + unsigned int h = 0; /* Value to return */ + int i; /* Used to iterate through columns */ + u8 *a = aRecord; /* Used to iterate through change record */ - for(i=0; inCol; i++){ + for (i = 0; i < pTab->nCol; i++) { int eType = *a; int isPK = pTab->abPK[i]; - if( bPkOnly && isPK==0 ) continue; + if (bPkOnly && isPK == 0) continue; - /* It is not possible for eType to be SQLITE_NULL here. The session + /* It is not possible for eType to be SQLITE_NULL here. The session ** module does not record changes for rows with NULL values stored in ** primary key columns. */ - assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT - || eType==SQLITE_TEXT || eType==SQLITE_BLOB - || eType==SQLITE_NULL || eType==0 - ); - assert( !isPK || (eType!=0 && eType!=SQLITE_NULL) ); + assert(eType == SQLITE_INTEGER || eType == SQLITE_FLOAT || + eType == SQLITE_TEXT || eType == SQLITE_BLOB || + eType == SQLITE_NULL || eType == 0); + assert(!isPK || (eType != 0 && eType != SQLITE_NULL)); - if( isPK ){ + if (isPK) { a++; h = sessionHashAppendType(h, eType); - if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){ + if (eType == SQLITE_INTEGER || eType == SQLITE_FLOAT) { h = sessionHashAppendI64(h, sessionGetI64(a)); a += 8; - }else{ - int n; + } else { + int n; a += sessionVarintGet(a, &n); h = sessionHashAppendBlob(h, n, a); a += n; } - }else{ + } else { a += sessionSerialLen(a); } } @@ -638,33 +638,33 @@ static unsigned int sessionChangeHash( /* ** Arguments aLeft and aRight are pointers to change records for table pTab. ** This function returns true if the two records apply to the same row (i.e. -** have the same values stored in the primary key columns), or false +** have the same values stored in the primary key columns), or false ** otherwise. */ static int sessionChangeEqual( - SessionTable *pTab, /* Table used for PK definition */ - int bLeftPkOnly, /* True if aLeft[] contains PK fields only */ - u8 *aLeft, /* Change record */ - int bRightPkOnly, /* True if aRight[] contains PK fields only */ - u8 *aRight /* Change record */ -){ - u8 *a1 = aLeft; /* Cursor to iterate through aLeft */ - u8 *a2 = aRight; /* Cursor to iterate through aRight */ - int iCol; /* Used to iterate through table columns */ + SessionTable *pTab, /* Table used for PK definition */ + int bLeftPkOnly, /* True if aLeft[] contains PK fields only */ + u8 *aLeft, /* Change record */ + int bRightPkOnly, /* True if aRight[] contains PK fields only */ + u8 *aRight /* Change record */ +) { + u8 *a1 = aLeft; /* Cursor to iterate through aLeft */ + u8 *a2 = aRight; /* Cursor to iterate through aRight */ + int iCol; /* Used to iterate through table columns */ - for(iCol=0; iColnCol; iCol++){ - if( pTab->abPK[iCol] ){ + for (iCol = 0; iCol < pTab->nCol; iCol++) { + if (pTab->abPK[iCol]) { int n1 = sessionSerialLen(a1); int n2 = sessionSerialLen(a2); - if( n1!=n2 || memcmp(a1, a2, n1) ){ + if (n1 != n2 || memcmp(a1, a2, n1)) { return 0; } a1 += n1; a2 += n2; - }else{ - if( bLeftPkOnly==0 ) a1 += sessionSerialLen(a1); - if( bRightPkOnly==0 ) a2 += sessionSerialLen(a2); + } else { + if (bLeftPkOnly == 0) a1 += sessionSerialLen(a1); + if (bRightPkOnly == 0) a2 += sessionSerialLen(a2); } } @@ -675,33 +675,28 @@ static int sessionChangeEqual( ** Arguments aLeft and aRight both point to buffers containing change ** records with nCol columns. This function "merges" the two records into ** a single records which is written to the buffer at *paOut. *paOut is -** then set to point to one byte after the last byte written before +** then set to point to one byte after the last byte written before ** returning. ** -** The merging of records is done as follows: For each column, if the +** The merging of records is done as follows: For each column, if the ** aRight record contains a value for the column, copy the value from ** their. Otherwise, if aLeft contains a value, copy it. If neither ** record contains a value for a given column, then neither does the ** output record. */ -static void sessionMergeRecord( - u8 **paOut, - int nCol, - u8 *aLeft, - u8 *aRight -){ - u8 *a1 = aLeft; /* Cursor used to iterate through aLeft */ - u8 *a2 = aRight; /* Cursor used to iterate through aRight */ - u8 *aOut = *paOut; /* Output cursor */ - int iCol; /* Used to iterate from 0 to nCol */ +static void sessionMergeRecord(u8 **paOut, int nCol, u8 *aLeft, u8 *aRight) { + u8 *a1 = aLeft; /* Cursor used to iterate through aLeft */ + u8 *a2 = aRight; /* Cursor used to iterate through aRight */ + u8 *aOut = *paOut; /* Output cursor */ + int iCol; /* Used to iterate from 0 to nCol */ - for(iCol=0; iColnCol; i++){ + for (i = 0; i < pTab->nCol; i++) { int nOld; u8 *aOld; int nNew; @@ -795,16 +789,16 @@ static int sessionMergeUpdate( aOld = sessionMergeValue(&aOld1, &aOld2, &nOld); aNew = sessionMergeValue(&aNew1, &aNew2, &nNew); - if( pTab->abPK[i] || nOld!=nNew || memcmp(aOld, aNew, nNew) ){ - if( pTab->abPK[i]==0 ) bRequired = 1; + if (pTab->abPK[i] || nOld != nNew || memcmp(aOld, aNew, nNew)) { + if (pTab->abPK[i] == 0) bRequired = 1; memcpy(aOut, aOld, nOld); aOut += nOld; - }else{ + } else { *(aOut++) = '\0'; } } - if( !bRequired ) return 0; + if (!bRequired) return 0; } /* Write the new.* vector */ @@ -812,7 +806,7 @@ static int sessionMergeUpdate( aOld2 = aOldRecord2; aNew1 = aNewRecord1; aNew2 = aNewRecord2; - for(i=0; inCol; i++){ + for (i = 0; i < pTab->nCol; i++) { int nOld; u8 *aOld; int nNew; @@ -820,11 +814,10 @@ static int sessionMergeUpdate( aOld = sessionMergeValue(&aOld1, &aOld2, &nOld); aNew = sessionMergeValue(&aNew1, &aNew2, &nNew); - if( bPatchset==0 - && (pTab->abPK[i] || (nOld==nNew && 0==memcmp(aOld, aNew, nNew))) - ){ + if (bPatchset == 0 && + (pTab->abPK[i] || (nOld == nNew && 0 == memcmp(aOld, aNew, nNew)))) { *(aOut++) = '\0'; - }else{ + } else { memcpy(aOut, aNew, nNew); aOut += nNew; } @@ -842,65 +835,64 @@ static int sessionMergeUpdate( ** false. */ static int sessionPreupdateEqual( - sqlite3_session *pSession, /* Session object that owns SessionTable */ - SessionTable *pTab, /* Table associated with change */ - SessionChange *pChange, /* Change to compare to */ - int op /* Current pre-update operation */ -){ - int iCol; /* Used to iterate through columns */ - u8 *a = pChange->aRecord; /* Cursor used to scan change record */ + sqlite3_session *pSession, /* Session object that owns SessionTable */ + SessionTable *pTab, /* Table associated with change */ + SessionChange *pChange, /* Change to compare to */ + int op /* Current pre-update operation */ +) { + int iCol; /* Used to iterate through columns */ + u8 *a = pChange->aRecord; /* Cursor used to scan change record */ - assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE ); - for(iCol=0; iColnCol; iCol++){ - if( !pTab->abPK[iCol] ){ + assert(op == SQLITE_INSERT || op == SQLITE_UPDATE || op == SQLITE_DELETE); + for (iCol = 0; iCol < pTab->nCol; iCol++) { + if (!pTab->abPK[iCol]) { a += sessionSerialLen(a); - }else{ - sqlite3_value *pVal; /* Value returned by preupdate_new/old */ - int rc; /* Error code from preupdate_new/old */ - int eType = *a++; /* Type of value from change record */ + } else { + sqlite3_value *pVal; /* Value returned by preupdate_new/old */ + int rc; /* Error code from preupdate_new/old */ + int eType = *a++; /* Type of value from change record */ /* The following calls to preupdate_new() and preupdate_old() can not ** fail. This is because they cache their return values, and by the ** time control flows to here they have already been called once from ** within sessionPreupdateHash(). The first two asserts below verify ** this (that the method has already been called). */ - if( op==SQLITE_INSERT ){ + if (op == SQLITE_INSERT) { /* assert( db->pPreUpdate->pNewUnpacked || db->pPreUpdate->aNew ); */ rc = pSession->hook.xNew(pSession->hook.pCtx, iCol, &pVal); - }else{ + } else { /* assert( db->pPreUpdate->pUnpacked ); */ rc = pSession->hook.xOld(pSession->hook.pCtx, iCol, &pVal); } - assert( rc==SQLITE_OK ); - if( sqlite3_value_type(pVal)!=eType ) return 0; + assert(rc == SQLITE_OK); + if (sqlite3_value_type(pVal) != eType) return 0; /* A SessionChange object never has a NULL value in a PK column */ - assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT - || eType==SQLITE_BLOB || eType==SQLITE_TEXT - ); + assert(eType == SQLITE_INTEGER || eType == SQLITE_FLOAT || + eType == SQLITE_BLOB || eType == SQLITE_TEXT); - if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){ + if (eType == SQLITE_INTEGER || eType == SQLITE_FLOAT) { i64 iVal = sessionGetI64(a); a += 8; - if( eType==SQLITE_INTEGER ){ - if( sqlite3_value_int64(pVal)!=iVal ) return 0; - }else{ + if (eType == SQLITE_INTEGER) { + if (sqlite3_value_int64(pVal) != iVal) return 0; + } else { double rVal; - assert( sizeof(iVal)==8 && sizeof(rVal)==8 ); + assert(sizeof(iVal) == 8 && sizeof(rVal) == 8); memcpy(&rVal, &iVal, 8); - if( sqlite3_value_double(pVal)!=rVal ) return 0; + if (sqlite3_value_double(pVal) != rVal) return 0; } - }else{ + } else { int n; const u8 *z; a += sessionVarintGet(a, &n); - if( sqlite3_value_bytes(pVal)!=n ) return 0; - if( eType==SQLITE_TEXT ){ + if (sqlite3_value_bytes(pVal) != n) return 0; + if (eType == SQLITE_TEXT) { z = sqlite3_value_text(pVal); - }else{ + } else { z = sqlite3_value_blob(pVal); } - if( n>0 && memcmp(a, z, n) ) return 0; + if (n > 0 && memcmp(a, z, n)) return 0; a += n; } } @@ -910,7 +902,7 @@ static int sessionPreupdateEqual( } /* -** If required, grow the hash table used to store changes on table pTab +** If required, grow the hash table used to store changes on table pTab ** (part of the session pSession). If a fatal OOM error occurs, set the ** session object to failed and return SQLITE_ERROR. Otherwise, return ** SQLITE_OK. @@ -921,31 +913,29 @@ static int sessionPreupdateEqual( ** it is not required for correct operation. */ static int sessionGrowHash( - sqlite3_session *pSession, /* For memory accounting. May be NULL */ - int bPatchset, - SessionTable *pTab -){ - if( pTab->nChange==0 || pTab->nEntry>=(pTab->nChange/2) ){ + sqlite3_session *pSession, /* For memory accounting. May be NULL */ + int bPatchset, SessionTable *pTab) { + if (pTab->nChange == 0 || pTab->nEntry >= (pTab->nChange / 2)) { int i; SessionChange **apNew; - sqlite3_int64 nNew = 2*(sqlite3_int64)(pTab->nChange ? pTab->nChange : 128); + sqlite3_int64 nNew = + 2 * (sqlite3_int64)(pTab->nChange ? pTab->nChange : 128); - apNew = (SessionChange**)sessionMalloc64( - pSession, sizeof(SessionChange*) * nNew - ); - if( apNew==0 ){ - if( pTab->nChange==0 ){ + apNew = (SessionChange **)sessionMalloc64(pSession, + sizeof(SessionChange *) * nNew); + if (apNew == 0) { + if (pTab->nChange == 0) { return SQLITE_ERROR; } return SQLITE_OK; } memset(apNew, 0, sizeof(SessionChange *) * nNew); - for(i=0; inChange; i++){ + for (i = 0; i < pTab->nChange; i++) { SessionChange *p; SessionChange *pNext; - for(p=pTab->apChange[i]; p; p=pNext){ - int bPkOnly = (p->op==SQLITE_DELETE && bPatchset); + for (p = pTab->apChange[i]; p; p = pNext) { + int bPkOnly = (p->op == SQLITE_DELETE && bPatchset); int iHash = sessionChangeHash(pTab, bPkOnly, p->aRecord, nNew); pNext = p->pNext; p->pNext = apNew[iHash]; @@ -987,15 +977,15 @@ static int sessionGrowHash( ** be freed using sqlite3_free() by the caller */ static int sessionTableInfo( - sqlite3_session *pSession, /* For memory accounting. May be NULL */ - sqlite3 *db, /* Database connection */ - const char *zDb, /* Name of attached database (e.g. "main") */ - const char *zThis, /* Table name */ - int *pnCol, /* OUT: number of columns */ - const char **pzTab, /* OUT: Copy of zThis */ - const char ***pazCol, /* OUT: Array of column names for table */ - u8 **pabPK /* OUT: Array of booleans - true for PK col */ -){ + sqlite3_session *pSession, /* For memory accounting. May be NULL */ + sqlite3 *db, /* Database connection */ + const char *zDb, /* Name of attached database (e.g. "main") */ + const char *zThis, /* Table name */ + int *pnCol, /* OUT: number of columns */ + const char **pzTab, /* OUT: Copy of zThis */ + const char ***pazCol, /* OUT: Array of column names for table */ + u8 **pabPK /* OUT: Array of booleans - true for PK col */ +) { char *zPragma; sqlite3_stmt *pStmt; int rc; @@ -1007,84 +997,81 @@ static int sessionTableInfo( char **azCol = 0; u8 *abPK = 0; - assert( pazCol && pabPK ); + assert(pazCol && pabPK); nThis = sqlite3Strlen30(zThis); - if( nThis==12 && 0==sqlite3_stricmp("sqlite_stat1", zThis) ){ + if (nThis == 12 && 0 == sqlite3_stricmp("sqlite_stat1", zThis)) { rc = sqlite3_table_column_metadata(db, zDb, zThis, 0, 0, 0, 0, 0, 0); - if( rc==SQLITE_OK ){ + if (rc == SQLITE_OK) { /* For sqlite_stat1, pretend that (tbl,idx) is the PRIMARY KEY. */ - zPragma = sqlite3_mprintf( - "SELECT 0, 'tbl', '', 0, '', 1 UNION ALL " - "SELECT 1, 'idx', '', 0, '', 2 UNION ALL " - "SELECT 2, 'stat', '', 0, '', 0" - ); - }else if( rc==SQLITE_ERROR ){ + zPragma = sqlite3_mprintf("SELECT 0, 'tbl', '', 0, '', 1 UNION ALL " + "SELECT 1, 'idx', '', 0, '', 2 UNION ALL " + "SELECT 2, 'stat', '', 0, '', 0"); + } else if (rc == SQLITE_ERROR) { zPragma = sqlite3_mprintf(""); - }else{ + } else { return rc; } - }else{ + } else { zPragma = sqlite3_mprintf("PRAGMA '%q'.table_info('%q')", zDb, zThis); } - if( !zPragma ) return SQLITE_NOMEM; + if (!zPragma) return SQLITE_NOMEM; rc = sqlite3_prepare_v2(db, zPragma, -1, &pStmt, 0); sqlite3_free(zPragma); - if( rc!=SQLITE_OK ) return rc; + if (rc != SQLITE_OK) return rc; nByte = nThis + 1; - while( SQLITE_ROW==sqlite3_step(pStmt) ){ + while (SQLITE_ROW == sqlite3_step(pStmt)) { nByte += sqlite3_column_bytes(pStmt, 1); nDbCol++; } rc = sqlite3_reset(pStmt); - if( rc==SQLITE_OK ){ + if (rc == SQLITE_OK) { nByte += nDbCol * (sizeof(const char *) + sizeof(u8) + 1); pAlloc = sessionMalloc64(pSession, nByte); - if( pAlloc==0 ){ + if (pAlloc == 0) { rc = SQLITE_NOMEM; } } - if( rc==SQLITE_OK ){ + if (rc == SQLITE_OK) { azCol = (char **)pAlloc; pAlloc = (u8 *)&azCol[nDbCol]; abPK = (u8 *)pAlloc; pAlloc = &abPK[nDbCol]; - if( pzTab ){ - memcpy(pAlloc, zThis, nThis+1); + if (pzTab) { + memcpy(pAlloc, zThis, nThis + 1); *pzTab = (char *)pAlloc; - pAlloc += nThis+1; + pAlloc += nThis + 1; } - + i = 0; - while( SQLITE_ROW==sqlite3_step(pStmt) ){ + while (SQLITE_ROW == sqlite3_step(pStmt)) { int nName = sqlite3_column_bytes(pStmt, 1); const unsigned char *zName = sqlite3_column_text(pStmt, 1); - if( zName==0 ) break; - memcpy(pAlloc, zName, nName+1); + if (zName == 0) break; + memcpy(pAlloc, zName, nName + 1); azCol[i] = (char *)pAlloc; - pAlloc += nName+1; + pAlloc += nName + 1; abPK[i] = sqlite3_column_int(pStmt, 5); i++; } rc = sqlite3_reset(pStmt); - } /* If successful, populate the output variables. Otherwise, zero them and ** free any allocation made. An error code will be returned in this case. */ - if( rc==SQLITE_OK ){ + if (rc == SQLITE_OK) { *pazCol = (const char **)azCol; *pabPK = abPK; *pnCol = nDbCol; - }else{ + } else { *pazCol = 0; *pabPK = 0; *pnCol = 0; - if( pzTab ) *pzTab = 0; + if (pzTab) *pzTab = 0; sessionFree(pSession, azCol); } sqlite3_finalize(pStmt); @@ -1100,30 +1087,30 @@ static int sessionTableInfo( ** If an error occurs, an error code is stored in sqlite3_session.rc and ** non-zero returned. Or, if no error occurs but the table has no primary ** key, sqlite3_session.rc is left set to SQLITE_OK and non-zero returned to -** indicate that updates on this table should be ignored. SessionTable.abPK +** indicate that updates on this table should be ignored. SessionTable.abPK ** is set to NULL in this case. */ -static int sessionInitTable(sqlite3_session *pSession, SessionTable *pTab){ - if( pTab->nCol==0 ){ +static int sessionInitTable(sqlite3_session *pSession, SessionTable *pTab) { + if (pTab->nCol == 0) { u8 *abPK; - assert( pTab->azCol==0 || pTab->abPK==0 ); - pSession->rc = sessionTableInfo(pSession, pSession->db, pSession->zDb, - pTab->zName, &pTab->nCol, 0, &pTab->azCol, &abPK - ); - if( pSession->rc==SQLITE_OK ){ + assert(pTab->azCol == 0 || pTab->abPK == 0); + pSession->rc = + sessionTableInfo(pSession, pSession->db, pSession->zDb, pTab->zName, + &pTab->nCol, 0, &pTab->azCol, &abPK); + if (pSession->rc == SQLITE_OK) { int i; - for(i=0; inCol; i++){ - if( abPK[i] ){ + for (i = 0; i < pTab->nCol; i++) { + if (abPK[i]) { pTab->abPK = abPK; break; } } - if( 0==sqlite3_stricmp("sqlite_stat1", pTab->zName) ){ + if (0 == sqlite3_stricmp("sqlite_stat1", pTab->zName)) { pTab->bStat1 = 1; } } } - return (pSession->rc || pTab->abPK==0); + return (pSession->rc || pTab->abPK == 0); } /* @@ -1137,38 +1124,37 @@ struct SessionStat1Ctx { SessionHook hook; sqlite3_session *pSession; }; -static int sessionStat1Old(void *pCtx, int iCol, sqlite3_value **ppVal){ - SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx; +static int sessionStat1Old(void *pCtx, int iCol, sqlite3_value **ppVal) { + SessionStat1Ctx *p = (SessionStat1Ctx *)pCtx; sqlite3_value *pVal = 0; int rc = p->hook.xOld(p->hook.pCtx, iCol, &pVal); - if( rc==SQLITE_OK && iCol==1 && sqlite3_value_type(pVal)==SQLITE_NULL ){ + if (rc == SQLITE_OK && iCol == 1 && sqlite3_value_type(pVal) == SQLITE_NULL) { pVal = p->pSession->pZeroBlob; } *ppVal = pVal; return rc; } -static int sessionStat1New(void *pCtx, int iCol, sqlite3_value **ppVal){ - SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx; +static int sessionStat1New(void *pCtx, int iCol, sqlite3_value **ppVal) { + SessionStat1Ctx *p = (SessionStat1Ctx *)pCtx; sqlite3_value *pVal = 0; int rc = p->hook.xNew(p->hook.pCtx, iCol, &pVal); - if( rc==SQLITE_OK && iCol==1 && sqlite3_value_type(pVal)==SQLITE_NULL ){ + if (rc == SQLITE_OK && iCol == 1 && sqlite3_value_type(pVal) == SQLITE_NULL) { pVal = p->pSession->pZeroBlob; } *ppVal = pVal; return rc; } -static int sessionStat1Count(void *pCtx){ - SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx; +static int sessionStat1Count(void *pCtx) { + SessionStat1Ctx *p = (SessionStat1Ctx *)pCtx; return p->hook.xCount(p->hook.pCtx); } -static int sessionStat1Depth(void *pCtx){ - SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx; +static int sessionStat1Depth(void *pCtx) { + SessionStat1Ctx *p = (SessionStat1Ctx *)pCtx; return p->hook.xDepth(p->hook.pCtx); } - /* -** This function is only called from with a pre-update-hook reporting a +** This function is only called from with a pre-update-hook reporting a ** change on table pTab (attached to session pSession). The type of change ** (UPDATE, INSERT, DELETE) is specified by the first argument. ** @@ -1176,44 +1162,44 @@ static int sessionStat1Depth(void *pCtx){ ** to the changed-rows hash table associated with table pTab. */ static void sessionPreupdateOneChange( - int op, /* One of SQLITE_UPDATE, INSERT, DELETE */ - sqlite3_session *pSession, /* Session object pTab is attached to */ - SessionTable *pTab /* Table that change applies to */ -){ - int iHash; - int bNull = 0; + int op, /* One of SQLITE_UPDATE, INSERT, DELETE */ + sqlite3_session *pSession, /* Session object pTab is attached to */ + SessionTable *pTab /* Table that change applies to */ +) { + int iHash; + int bNull = 0; int rc = SQLITE_OK; - SessionStat1Ctx stat1 = {{0,0,0,0,0},0}; + SessionStat1Ctx stat1 = {{0, 0, 0, 0, 0}, 0}; - if( pSession->rc ) return; + if (pSession->rc) return; /* Load table details if required */ - if( sessionInitTable(pSession, pTab) ) return; + if (sessionInitTable(pSession, pTab)) return; - /* Check the number of columns in this xPreUpdate call matches the + /* Check the number of columns in this xPreUpdate call matches the ** number of columns in the table. */ - if( pTab->nCol!=pSession->hook.xCount(pSession->hook.pCtx) ){ + if (pTab->nCol != pSession->hook.xCount(pSession->hook.pCtx)) { pSession->rc = SQLITE_SCHEMA; return; } /* Grow the hash table if required */ - if( sessionGrowHash(pSession, 0, pTab) ){ + if (sessionGrowHash(pSession, 0, pTab)) { pSession->rc = SQLITE_NOMEM; return; } - if( pTab->bStat1 ){ + if (pTab->bStat1) { stat1.hook = pSession->hook; stat1.pSession = pSession; - pSession->hook.pCtx = (void*)&stat1; + pSession->hook.pCtx = (void *)&stat1; pSession->hook.xNew = sessionStat1New; pSession->hook.xOld = sessionStat1Old; pSession->hook.xCount = sessionStat1Count; pSession->hook.xDepth = sessionStat1Depth; - if( pSession->pZeroBlob==0 ){ + if (pSession->pZeroBlob == 0) { sqlite3_value *p = sqlite3ValueNew(0); - if( p==0 ){ + if (p == 0) { rc = SQLITE_NOMEM; goto error_out; } @@ -1225,72 +1211,73 @@ static void sessionPreupdateOneChange( /* Calculate the hash-key for this change. If the primary key of the row ** includes a NULL value, exit early. Such changes are ignored by the ** session module. */ - rc = sessionPreupdateHash(pSession, pTab, op==SQLITE_INSERT, &iHash, &bNull); - if( rc!=SQLITE_OK ) goto error_out; + rc = + sessionPreupdateHash(pSession, pTab, op == SQLITE_INSERT, &iHash, &bNull); + if (rc != SQLITE_OK) goto error_out; - if( bNull==0 ){ + if (bNull == 0) { /* Search the hash table for an existing record for this row. */ SessionChange *pC; - for(pC=pTab->apChange[iHash]; pC; pC=pC->pNext){ - if( sessionPreupdateEqual(pSession, pTab, pC, op) ) break; + for (pC = pTab->apChange[iHash]; pC; pC = pC->pNext) { + if (sessionPreupdateEqual(pSession, pTab, pC, op)) break; } - if( pC==0 ){ + if (pC == 0) { /* Create a new change object containing all the old values (if ** this is an SQLITE_UPDATE or SQLITE_DELETE), or just the PK ** values (if this is an INSERT). */ SessionChange *pChange; /* New change object */ sqlite3_int64 nByte; /* Number of bytes to allocate */ int i; /* Used to iterate through columns */ - - assert( rc==SQLITE_OK ); + + assert(rc == SQLITE_OK); pTab->nEntry++; - + /* Figure out how large an allocation is required */ nByte = sizeof(SessionChange); - for(i=0; inCol; i++){ + for (i = 0; i < pTab->nCol; i++) { sqlite3_value *p = 0; - if( op!=SQLITE_INSERT ){ - TESTONLY(int trc = ) pSession->hook.xOld(pSession->hook.pCtx, i, &p); - assert( trc==SQLITE_OK ); - }else if( pTab->abPK[i] ){ - TESTONLY(int trc = ) pSession->hook.xNew(pSession->hook.pCtx, i, &p); - assert( trc==SQLITE_OK ); + if (op != SQLITE_INSERT) { + TESTONLY(int trc =) pSession->hook.xOld(pSession->hook.pCtx, i, &p); + assert(trc == SQLITE_OK); + } else if (pTab->abPK[i]) { + TESTONLY(int trc =) pSession->hook.xNew(pSession->hook.pCtx, i, &p); + assert(trc == SQLITE_OK); } /* This may fail if SQLite value p contains a utf-16 string that must ** be converted to utf-8 and an OOM error occurs while doing so. */ rc = sessionSerializeValue(0, p, &nByte); - if( rc!=SQLITE_OK ) goto error_out; + if (rc != SQLITE_OK) goto error_out; } - + /* Allocate the change object */ pChange = (SessionChange *)sessionMalloc64(pSession, nByte); - if( !pChange ){ + if (!pChange) { rc = SQLITE_NOMEM; goto error_out; - }else{ + } else { memset(pChange, 0, sizeof(SessionChange)); pChange->aRecord = (u8 *)&pChange[1]; } - + /* Populate the change object. None of the preupdate_old(), ** preupdate_new() or SerializeValue() calls below may fail as all ** required values and encodings have already been cached in memory. ** It is not possible for an OOM to occur in this block. */ nByte = 0; - for(i=0; inCol; i++){ + for (i = 0; i < pTab->nCol; i++) { sqlite3_value *p = 0; - if( op!=SQLITE_INSERT ){ + if (op != SQLITE_INSERT) { pSession->hook.xOld(pSession->hook.pCtx, i, &p); - }else if( pTab->abPK[i] ){ + } else if (pTab->abPK[i]) { pSession->hook.xNew(pSession->hook.pCtx, i, &p); } sessionSerializeValue(&pChange->aRecord[nByte], p, &nByte); } /* Add the change to the hash-table */ - if( pSession->bIndirect || pSession->hook.xDepth(pSession->hook.pCtx) ){ + if (pSession->bIndirect || pSession->hook.xDepth(pSession->hook.pCtx)) { pChange->bIndirect = 1; } pChange->nRecord = nByte; @@ -1298,56 +1285,52 @@ static void sessionPreupdateOneChange( pChange->pNext = pTab->apChange[iHash]; pTab->apChange[iHash] = pChange; - }else if( pC->bIndirect ){ + } else if (pC->bIndirect) { /* If the existing change is considered "indirect", but this current ** change is "direct", mark the change object as direct. */ - if( pSession->hook.xDepth(pSession->hook.pCtx)==0 - && pSession->bIndirect==0 - ){ + if (pSession->hook.xDepth(pSession->hook.pCtx) == 0 && + pSession->bIndirect == 0) { pC->bIndirect = 0; } } } /* If an error has occurred, mark the session object as failed. */ - error_out: - if( pTab->bStat1 ){ +error_out: + if (pTab->bStat1) { pSession->hook = stat1.hook; } - if( rc!=SQLITE_OK ){ + if (rc != SQLITE_OK) { pSession->rc = rc; } } -static int sessionFindTable( - sqlite3_session *pSession, - const char *zName, - SessionTable **ppTab -){ +static int sessionFindTable(sqlite3_session *pSession, const char *zName, + SessionTable **ppTab) { int rc = SQLITE_OK; int nName = sqlite3Strlen30(zName); SessionTable *pRet; /* Search for an existing table */ - for(pRet=pSession->pTable; pRet; pRet=pRet->pNext){ - if( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) ) break; + for (pRet = pSession->pTable; pRet; pRet = pRet->pNext) { + if (0 == sqlite3_strnicmp(pRet->zName, zName, nName + 1)) break; } - if( pRet==0 && pSession->bAutoAttach ){ + if (pRet == 0 && pSession->bAutoAttach) { /* If there is a table-filter configured, invoke it. If it returns 0, ** do not automatically add the new table. */ - if( pSession->xTableFilter==0 - || pSession->xTableFilter(pSession->pFilterCtx, zName) - ){ + if (pSession->xTableFilter == 0 || + pSession->xTableFilter(pSession->pFilterCtx, zName)) { rc = sqlite3session_attach(pSession, zName); - if( rc==SQLITE_OK ){ - for(pRet=pSession->pTable; pRet->pNext; pRet=pRet->pNext); - assert( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) ); + if (rc == SQLITE_OK) { + for (pRet = pSession->pTable; pRet->pNext; pRet = pRet->pNext) + ; + assert(0 == sqlite3_strnicmp(pRet->zName, zName, nName + 1)); } } } - assert( rc==SQLITE_OK || pRet==0 ); + assert(rc == SQLITE_OK || pRet == 0); *ppTab = pRet; return rc; } @@ -1356,34 +1339,35 @@ static int sessionFindTable( ** The 'pre-update' hook registered by this module with SQLite databases. */ static void xPreUpdate( - void *pCtx, /* Copy of third arg to preupdate_hook() */ - sqlite3 *db, /* Database handle */ - int op, /* SQLITE_UPDATE, DELETE or INSERT */ - char const *zDb, /* Database name */ - char const *zName, /* Table name */ - sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */ - sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */ -){ + void *pCtx, /* Copy of third arg to preupdate_hook() */ + sqlite3 *db, /* Database handle */ + int op, /* SQLITE_UPDATE, DELETE or INSERT */ + char const *zDb, /* Database name */ + char const *zName, /* Table name */ + sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */ + sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */ +) { sqlite3_session *pSession; int nDb = sqlite3Strlen30(zDb); - assert( sqlite3_mutex_held(db->mutex) ); + assert(sqlite3_mutex_held(db->mutex)); - for(pSession=(sqlite3_session *)pCtx; pSession; pSession=pSession->pNext){ + for (pSession = (sqlite3_session *)pCtx; pSession; + pSession = pSession->pNext) { SessionTable *pTab; - /* If this session is attached to a different database ("main", "temp" - ** etc.), or if it is not currently enabled, there is nothing to do. Skip + /* If this session is attached to a different database ("main", "temp" + ** etc.), or if it is not currently enabled, there is nothing to do. Skip ** to the next session object attached to this database. */ - if( pSession->bEnable==0 ) continue; - if( pSession->rc ) continue; - if( sqlite3_strnicmp(zDb, pSession->zDb, nDb+1) ) continue; + if (pSession->bEnable == 0) continue; + if (pSession->rc) continue; + if (sqlite3_strnicmp(zDb, pSession->zDb, nDb + 1)) continue; pSession->rc = sessionFindTable(pSession, zName, &pTab); - if( pTab ){ - assert( pSession->rc==SQLITE_OK ); + if (pTab) { + assert(pSession->rc == SQLITE_OK); sessionPreupdateOneChange(op, pSession, pTab); - if( op==SQLITE_UPDATE ){ + if (op == SQLITE_UPDATE) { sessionPreupdateOneChange(SQLITE_INSERT, pSession, pTab); } } @@ -1393,27 +1377,25 @@ static void xPreUpdate( /* ** The pre-update hook implementations. */ -static int sessionPreupdateOld(void *pCtx, int iVal, sqlite3_value **ppVal){ - return sqlite3_preupdate_old((sqlite3*)pCtx, iVal, ppVal); +static int sessionPreupdateOld(void *pCtx, int iVal, sqlite3_value **ppVal) { + return sqlite3_preupdate_old((sqlite3 *)pCtx, iVal, ppVal); } -static int sessionPreupdateNew(void *pCtx, int iVal, sqlite3_value **ppVal){ - return sqlite3_preupdate_new((sqlite3*)pCtx, iVal, ppVal); +static int sessionPreupdateNew(void *pCtx, int iVal, sqlite3_value **ppVal) { + return sqlite3_preupdate_new((sqlite3 *)pCtx, iVal, ppVal); } -static int sessionPreupdateCount(void *pCtx){ - return sqlite3_preupdate_count((sqlite3*)pCtx); +static int sessionPreupdateCount(void *pCtx) { + return sqlite3_preupdate_count((sqlite3 *)pCtx); } -static int sessionPreupdateDepth(void *pCtx){ - return sqlite3_preupdate_depth((sqlite3*)pCtx); +static int sessionPreupdateDepth(void *pCtx) { + return sqlite3_preupdate_depth((sqlite3 *)pCtx); } /* ** Install the pre-update hooks on the session object passed as the only ** argument. */ -static void sessionPreupdateHooks( - sqlite3_session *pSession -){ - pSession->hook.pCtx = (void*)pSession->db; +static void sessionPreupdateHooks(sqlite3_session *pSession) { + pSession->hook.pCtx = (void *)pSession->db; pSession->hook.xOld = sessionPreupdateOld; pSession->hook.xNew = sessionPreupdateNew; pSession->hook.xCount = sessionPreupdateCount; @@ -1429,21 +1411,21 @@ struct SessionDiffCtx { /* ** The diff hook implementations. */ -static int sessionDiffOld(void *pCtx, int iVal, sqlite3_value **ppVal){ - SessionDiffCtx *p = (SessionDiffCtx*)pCtx; - *ppVal = sqlite3_column_value(p->pStmt, iVal+p->nOldOff); +static int sessionDiffOld(void *pCtx, int iVal, sqlite3_value **ppVal) { + SessionDiffCtx *p = (SessionDiffCtx *)pCtx; + *ppVal = sqlite3_column_value(p->pStmt, iVal + p->nOldOff); return SQLITE_OK; } -static int sessionDiffNew(void *pCtx, int iVal, sqlite3_value **ppVal){ - SessionDiffCtx *p = (SessionDiffCtx*)pCtx; +static int sessionDiffNew(void *pCtx, int iVal, sqlite3_value **ppVal) { + SessionDiffCtx *p = (SessionDiffCtx *)pCtx; *ppVal = sqlite3_column_value(p->pStmt, iVal); - return SQLITE_OK; + return SQLITE_OK; } -static int sessionDiffCount(void *pCtx){ - SessionDiffCtx *p = (SessionDiffCtx*)pCtx; +static int sessionDiffCount(void *pCtx) { + SessionDiffCtx *p = (SessionDiffCtx *)pCtx; return p->nOldOff ? p->nOldOff : sqlite3_column_count(p->pStmt); } -static int sessionDiffDepth(void *pCtx){ +static int sessionDiffDepth(void *pCtx) { return 0; } @@ -1451,65 +1433,56 @@ static int sessionDiffDepth(void *pCtx){ ** Install the diff hooks on the session object passed as the only ** argument. */ -static void sessionDiffHooks( - sqlite3_session *pSession, - SessionDiffCtx *pDiffCtx -){ - pSession->hook.pCtx = (void*)pDiffCtx; +static void sessionDiffHooks(sqlite3_session *pSession, + SessionDiffCtx *pDiffCtx) { + pSession->hook.pCtx = (void *)pDiffCtx; pSession->hook.xOld = sessionDiffOld; pSession->hook.xNew = sessionDiffNew; pSession->hook.xCount = sessionDiffCount; pSession->hook.xDepth = sessionDiffDepth; } -static char *sessionExprComparePK( - int nCol, - const char *zDb1, const char *zDb2, - const char *zTab, - const char **azCol, u8 *abPK -){ +static char *sessionExprComparePK(int nCol, const char *zDb1, const char *zDb2, + const char *zTab, const char **azCol, + u8 *abPK) { int i; const char *zSep = ""; char *zRet = 0; - for(i=0; inCol, zDb1, zDb2, pTab->zName,zExpr); + char *zStmt = + sessionSelectFindNew(pTab->nCol, zDb1, zDb2, pTab->zName, zExpr); - if( zStmt==0 ){ + if (zStmt == 0) { rc = SQLITE_NOMEM; - }else{ + } else { sqlite3_stmt *pStmt; rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0); - if( rc==SQLITE_OK ){ - SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx; + if (rc == SQLITE_OK) { + SessionDiffCtx *pDiffCtx = (SessionDiffCtx *)pSession->hook.pCtx; pDiffCtx->pStmt = pStmt; pDiffCtx->nOldOff = 0; - while( SQLITE_ROW==sqlite3_step(pStmt) ){ + while (SQLITE_ROW == sqlite3_step(pStmt)) { sessionPreupdateOneChange(op, pSession, pTab); } rc = sqlite3_finalize(pStmt); @@ -1563,35 +1528,30 @@ static int sessionDiffFindNew( return rc; } -static int sessionDiffFindModified( - sqlite3_session *pSession, - SessionTable *pTab, - const char *zFrom, - const char *zExpr -){ +static int sessionDiffFindModified(sqlite3_session *pSession, + SessionTable *pTab, const char *zFrom, + const char *zExpr) { int rc = SQLITE_OK; - char *zExpr2 = sessionExprCompareOther(pTab->nCol, - pSession->zDb, zFrom, pTab->zName, pTab->azCol, pTab->abPK - ); - if( zExpr2==0 ){ + char *zExpr2 = sessionExprCompareOther(pTab->nCol, pSession->zDb, zFrom, + pTab->zName, pTab->azCol, pTab->abPK); + if (zExpr2 == 0) { rc = SQLITE_NOMEM; - }else{ + } else { char *zStmt = sqlite3_mprintf( "SELECT * FROM \"%w\".\"%w\", \"%w\".\"%w\" WHERE %s AND (%z)", - pSession->zDb, pTab->zName, zFrom, pTab->zName, zExpr, zExpr2 - ); - if( zStmt==0 ){ + pSession->zDb, pTab->zName, zFrom, pTab->zName, zExpr, zExpr2); + if (zStmt == 0) { rc = SQLITE_NOMEM; - }else{ + } else { sqlite3_stmt *pStmt; rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0); - if( rc==SQLITE_OK ){ - SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx; + if (rc == SQLITE_OK) { + SessionDiffCtx *pDiffCtx = (SessionDiffCtx *)pSession->hook.pCtx; pDiffCtx->pStmt = pStmt; pDiffCtx->nOldOff = pTab->nCol; - while( SQLITE_ROW==sqlite3_step(pStmt) ){ + while (SQLITE_ROW == sqlite3_step(pStmt)) { sessionPreupdateOneChange(SQLITE_UPDATE, pSession, pTab); } rc = sqlite3_finalize(pStmt); @@ -1603,12 +1563,8 @@ static int sessionDiffFindModified( return rc; } -int sqlite3session_diff( - sqlite3_session *pSession, - const char *zFrom, - const char *zTbl, - char **pzErrMsg -){ +int sqlite3session_diff(sqlite3_session *pSession, const char *zFrom, + const char *zTbl, char **pzErrMsg) { const char *zDb = pSession->zDb; int rc = pSession->rc; SessionDiffCtx d; @@ -1617,78 +1573,77 @@ int sqlite3session_diff( sessionDiffHooks(pSession, &d); sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db)); - if( pzErrMsg ) *pzErrMsg = 0; - if( rc==SQLITE_OK ){ + if (pzErrMsg) *pzErrMsg = 0; + if (rc == SQLITE_OK) { char *zExpr = 0; sqlite3 *db = pSession->db; - SessionTable *pTo; /* Table zTbl */ + SessionTable *pTo; /* Table zTbl */ /* Locate and if necessary initialize the target table object */ rc = sessionFindTable(pSession, zTbl, &pTo); - if( pTo==0 ) goto diff_out; - if( sessionInitTable(pSession, pTo) ){ + if (pTo == 0) goto diff_out; + if (sessionInitTable(pSession, pTo)) { rc = pSession->rc; goto diff_out; } /* Check the table schemas match */ - if( rc==SQLITE_OK ){ + if (rc == SQLITE_OK) { int bHasPk = 0; int bMismatch = 0; - int nCol; /* Columns in zFrom.zTbl */ + int nCol; /* Columns in zFrom.zTbl */ u8 *abPK; const char **azCol = 0; rc = sessionTableInfo(0, db, zFrom, zTbl, &nCol, 0, &azCol, &abPK); - if( rc==SQLITE_OK ){ - if( pTo->nCol!=nCol ){ + if (rc == SQLITE_OK) { + if (pTo->nCol != nCol) { bMismatch = 1; - }else{ + } else { int i; - for(i=0; iabPK[i]!=abPK[i] ) bMismatch = 1; - if( sqlite3_stricmp(azCol[i], pTo->azCol[i]) ) bMismatch = 1; - if( abPK[i] ) bHasPk = 1; + for (i = 0; i < nCol; i++) { + if (pTo->abPK[i] != abPK[i]) bMismatch = 1; + if (sqlite3_stricmp(azCol[i], pTo->azCol[i])) bMismatch = 1; + if (abPK[i]) bHasPk = 1; } } } - sqlite3_free((char*)azCol); - if( bMismatch ){ - if( pzErrMsg ){ + sqlite3_free((char *)azCol); + if (bMismatch) { + if (pzErrMsg) { *pzErrMsg = sqlite3_mprintf("table schemas do not match"); } rc = SQLITE_SCHEMA; } - if( bHasPk==0 ){ + if (bHasPk == 0) { /* Ignore tables with no primary keys */ goto diff_out; } } - if( rc==SQLITE_OK ){ - zExpr = sessionExprComparePK(pTo->nCol, - zDb, zFrom, pTo->zName, pTo->azCol, pTo->abPK - ); + if (rc == SQLITE_OK) { + zExpr = sessionExprComparePK(pTo->nCol, zDb, zFrom, pTo->zName, + pTo->azCol, pTo->abPK); } /* Find new rows */ - if( rc==SQLITE_OK ){ + if (rc == SQLITE_OK) { rc = sessionDiffFindNew(SQLITE_INSERT, pSession, pTo, zDb, zFrom, zExpr); } /* Find old rows */ - if( rc==SQLITE_OK ){ + if (rc == SQLITE_OK) { rc = sessionDiffFindNew(SQLITE_DELETE, pSession, pTo, zFrom, zDb, zExpr); } /* Find modified rows */ - if( rc==SQLITE_OK ){ + if (rc == SQLITE_OK) { rc = sessionDiffFindModified(pSession, pTo, zFrom, zExpr); } sqlite3_free(zExpr); } - diff_out: +diff_out: sessionPreupdateHooks(pSession); sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db)); return rc; @@ -1699,10 +1654,10 @@ int sqlite3session_diff( ** database zDb attached to connection db. */ int sqlite3session_create( - sqlite3 *db, /* Database handle */ - const char *zDb, /* Name of db (e.g. "main") */ - sqlite3_session **ppSession /* OUT: New session object */ -){ + sqlite3 *db, /* Database handle */ + const char *zDb, /* Name of db (e.g. "main") */ + sqlite3_session **ppSession /* OUT: New session object */ +) { sqlite3_session *pNew; /* Newly allocated session object */ sqlite3_session *pOld; /* Session object already attached to db */ int nDb = sqlite3Strlen30(zDb); /* Length of zDb in bytes */ @@ -1712,19 +1667,20 @@ int sqlite3session_create( /* Allocate and populate the new session object. */ pNew = (sqlite3_session *)sqlite3_malloc64(sizeof(sqlite3_session) + nDb + 1); - if( !pNew ) return SQLITE_NOMEM; + if (!pNew) return SQLITE_NOMEM; memset(pNew, 0, sizeof(sqlite3_session)); pNew->db = db; pNew->zDb = (char *)&pNew[1]; pNew->bEnable = 1; - memcpy(pNew->zDb, zDb, nDb+1); + memcpy(pNew->zDb, zDb, nDb + 1); sessionPreupdateHooks(pNew); - /* Add the new session object to the linked list of session objects + /* Add the new session object to the linked list of session objects ** attached to database handle $db. Do this under the cover of the db ** handle mutex. */ sqlite3_mutex_enter(sqlite3_db_mutex(db)); - pOld = (sqlite3_session*)sqlite3_preupdate_hook(db, xPreUpdate, (void*)pNew); + pOld = + (sqlite3_session *)sqlite3_preupdate_hook(db, xPreUpdate, (void *)pNew); pNew->pNext = pOld; sqlite3_mutex_leave(sqlite3_db_mutex(db)); @@ -1736,22 +1692,22 @@ int sqlite3session_create( ** Free the list of table objects passed as the first argument. The contents ** of the changed-rows hash tables are also deleted. */ -static void sessionDeleteTable(sqlite3_session *pSession, SessionTable *pList){ +static void sessionDeleteTable(sqlite3_session *pSession, SessionTable *pList) { SessionTable *pNext; SessionTable *pTab; - for(pTab=pList; pTab; pTab=pNext){ + for (pTab = pList; pTab; pTab = pNext) { int i; pNext = pTab->pNext; - for(i=0; inChange; i++){ + for (i = 0; i < pTab->nChange; i++) { SessionChange *p; SessionChange *pNextChange; - for(p=pTab->apChange[i]; p; p=pNextChange){ + for (p = pTab->apChange[i]; p; p = pNextChange) { pNextChange = p->pNext; sessionFree(pSession, p); } } - sessionFree(pSession, (char*)pTab->azCol); /* cast works around VC++ bug */ + sessionFree(pSession, (char *)pTab->azCol); /* cast works around VC++ bug */ sessionFree(pSession, pTab->apChange); sessionFree(pSession, pTab); } @@ -1760,7 +1716,7 @@ static void sessionDeleteTable(sqlite3_session *pSession, SessionTable *pList){ /* ** Delete a session object previously allocated using sqlite3session_create(). */ -void sqlite3session_delete(sqlite3_session *pSession){ +void sqlite3session_delete(sqlite3_session *pSession) { sqlite3 *db = pSession->db; sqlite3_session *pHead; sqlite3_session **pp; @@ -1768,24 +1724,24 @@ void sqlite3session_delete(sqlite3_session *pSession){ /* Unlink the session from the linked list of sessions attached to the ** database handle. Hold the db mutex while doing so. */ sqlite3_mutex_enter(sqlite3_db_mutex(db)); - pHead = (sqlite3_session*)sqlite3_preupdate_hook(db, 0, 0); - for(pp=&pHead; ALWAYS((*pp)!=0); pp=&((*pp)->pNext)){ - if( (*pp)==pSession ){ + pHead = (sqlite3_session *)sqlite3_preupdate_hook(db, 0, 0); + for (pp = &pHead; ALWAYS((*pp) != 0); pp = &((*pp)->pNext)) { + if ((*pp) == pSession) { *pp = (*pp)->pNext; - if( pHead ) sqlite3_preupdate_hook(db, xPreUpdate, (void*)pHead); + if (pHead) sqlite3_preupdate_hook(db, xPreUpdate, (void *)pHead); break; } } sqlite3_mutex_leave(sqlite3_db_mutex(db)); sqlite3ValueFree(pSession->pZeroBlob); - /* Delete all attached table objects. And the contents of their + /* Delete all attached table objects. And the contents of their ** associated hash-tables. */ sessionDeleteTable(pSession, pSession->pTable); - /* Assert that all allocations have been freed and then free the + /* Assert that all allocations have been freed and then free the ** session object itself. */ - assert( pSession->nMalloc==0 ); + assert(pSession->nMalloc == 0); sqlite3_free(pSession); } @@ -1793,10 +1749,9 @@ void sqlite3session_delete(sqlite3_session *pSession){ ** Set a table filter on a Session Object. */ void sqlite3session_table_filter( - sqlite3_session *pSession, - int(*xFilter)(void*, const char*), - void *pCtx /* First argument passed to xFilter */ -){ + sqlite3_session *pSession, int (*xFilter)(void *, const char *), + void *pCtx /* First argument passed to xFilter */ +) { pSession->bAutoAttach = 1; pSession->pFilterCtx = pCtx; pSession->xTableFilter = xFilter; @@ -1810,43 +1765,43 @@ void sqlite3session_table_filter( ** not matter if the PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias) ** or not. */ -int sqlite3session_attach( - sqlite3_session *pSession, /* Session object */ - const char *zName /* Table name */ -){ +int sqlite3session_attach(sqlite3_session *pSession, /* Session object */ + const char *zName /* Table name */ +) { int rc = SQLITE_OK; sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db)); - if( !zName ){ + if (!zName) { pSession->bAutoAttach = 1; - }else{ - SessionTable *pTab; /* New table object (if required) */ - int nName; /* Number of bytes in string zName */ + } else { + SessionTable *pTab; /* New table object (if required) */ + int nName; /* Number of bytes in string zName */ /* First search for an existing entry. If one is found, this call is ** a no-op. Return early. */ nName = sqlite3Strlen30(zName); - for(pTab=pSession->pTable; pTab; pTab=pTab->pNext){ - if( 0==sqlite3_strnicmp(pTab->zName, zName, nName+1) ) break; + for (pTab = pSession->pTable; pTab; pTab = pTab->pNext) { + if (0 == sqlite3_strnicmp(pTab->zName, zName, nName + 1)) break; } - if( !pTab ){ + if (!pTab) { /* Allocate new SessionTable object. */ int nByte = sizeof(SessionTable) + nName + 1; - pTab = (SessionTable*)sessionMalloc64(pSession, nByte); - if( !pTab ){ + pTab = (SessionTable *)sessionMalloc64(pSession, nByte); + if (!pTab) { rc = SQLITE_NOMEM; - }else{ + } else { /* Populate the new SessionTable object and link it into the list. - ** The new object must be linked onto the end of the list, not + ** The new object must be linked onto the end of the list, not ** simply added to the start of it in order to ensure that tables ** appear in the correct order when a changeset or patchset is ** eventually generated. */ SessionTable **ppTab; memset(pTab, 0, sizeof(SessionTable)); pTab->zName = (char *)&pTab[1]; - memcpy(pTab->zName, zName, nName+1); - for(ppTab=&pSession->pTable; *ppTab; ppTab=&(*ppTab)->pNext); + memcpy(pTab->zName, zName, nName + 1); + for (ppTab = &pSession->pTable; *ppTab; ppTab = &(*ppTab)->pNext) + ; *ppTab = pTab; } } @@ -1863,23 +1818,23 @@ int sqlite3session_attach( ** If successful, return zero. Otherwise, if an OOM condition is encountered, ** set *pRc to SQLITE_NOMEM and return non-zero. */ -static int sessionBufferGrow(SessionBuffer *p, size_t nByte, int *pRc){ - if( *pRc==SQLITE_OK && (size_t)(p->nAlloc-p->nBuf)nAlloc - p->nBuf) < nByte) { u8 *aNew; i64 nNew = p->nAlloc ? p->nAlloc : 128; do { - nNew = nNew*2; - }while( (size_t)(nNew-p->nBuf)nBuf) < nByte); aNew = (u8 *)sqlite3_realloc64(p->aBuf, nNew); - if( 0==aNew ){ + if (0 == aNew) { *pRc = SQLITE_NOMEM; - }else{ + } else { p->aBuf = aNew; p->nAlloc = nNew; } } - return (*pRc!=SQLITE_OK); + return (*pRc != SQLITE_OK); } /* @@ -1890,88 +1845,81 @@ static int sessionBufferGrow(SessionBuffer *p, size_t nByte, int *pRc){ ** Otherwise, if an error occurs, *pRc is set to an SQLite error code ** before returning. */ -static void sessionAppendValue(SessionBuffer *p, sqlite3_value *pVal, int *pRc){ +static void sessionAppendValue(SessionBuffer *p, sqlite3_value *pVal, + int *pRc) { int rc = *pRc; - if( rc==SQLITE_OK ){ + if (rc == SQLITE_OK) { sqlite3_int64 nByte = 0; rc = sessionSerializeValue(0, pVal, &nByte); sessionBufferGrow(p, nByte, &rc); - if( rc==SQLITE_OK ){ + if (rc == SQLITE_OK) { rc = sessionSerializeValue(&p->aBuf[p->nBuf], pVal, 0); p->nBuf += nByte; - }else{ + } else { *pRc = rc; } } } /* -** This function is a no-op if *pRc is other than SQLITE_OK when it is -** called. Otherwise, append a single byte to the buffer. +** This function is a no-op if *pRc is other than SQLITE_OK when it is +** called. Otherwise, append a single byte to the buffer. ** ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before ** returning. */ -static void sessionAppendByte(SessionBuffer *p, u8 v, int *pRc){ - if( 0==sessionBufferGrow(p, 1, pRc) ){ +static void sessionAppendByte(SessionBuffer *p, u8 v, int *pRc) { + if (0 == sessionBufferGrow(p, 1, pRc)) { p->aBuf[p->nBuf++] = v; } } /* -** This function is a no-op if *pRc is other than SQLITE_OK when it is -** called. Otherwise, append a single varint to the buffer. +** This function is a no-op if *pRc is other than SQLITE_OK when it is +** called. Otherwise, append a single varint to the buffer. ** ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before ** returning. */ -static void sessionAppendVarint(SessionBuffer *p, int v, int *pRc){ - if( 0==sessionBufferGrow(p, 9, pRc) ){ +static void sessionAppendVarint(SessionBuffer *p, int v, int *pRc) { + if (0 == sessionBufferGrow(p, 9, pRc)) { p->nBuf += sessionVarintPut(&p->aBuf[p->nBuf], v); } } /* -** This function is a no-op if *pRc is other than SQLITE_OK when it is -** called. Otherwise, append a blob of data to the buffer. +** This function is a no-op if *pRc is other than SQLITE_OK when it is +** called. Otherwise, append a blob of data to the buffer. ** ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before ** returning. */ -static void sessionAppendBlob( - SessionBuffer *p, - const u8 *aBlob, - int nBlob, - int *pRc -){ - if( nBlob>0 && 0==sessionBufferGrow(p, nBlob, pRc) ){ +static void sessionAppendBlob(SessionBuffer *p, const u8 *aBlob, int nBlob, + int *pRc) { + if (nBlob > 0 && 0 == sessionBufferGrow(p, nBlob, pRc)) { memcpy(&p->aBuf[p->nBuf], aBlob, nBlob); p->nBuf += nBlob; } } /* -** This function is a no-op if *pRc is other than SQLITE_OK when it is +** This function is a no-op if *pRc is other than SQLITE_OK when it is ** called. Otherwise, append a string to the buffer. All bytes in the string ** up to (but not including) the nul-terminator are written to the buffer. ** ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before ** returning. */ -static void sessionAppendStr( - SessionBuffer *p, - const char *zStr, - int *pRc -){ +static void sessionAppendStr(SessionBuffer *p, const char *zStr, int *pRc) { int nStr = sqlite3Strlen30(zStr); - if( 0==sessionBufferGrow(p, nStr, pRc) ){ + if (0 == sessionBufferGrow(p, nStr, pRc)) { memcpy(&p->aBuf[p->nBuf], zStr, nStr); p->nBuf += nStr; } } /* -** This function is a no-op if *pRc is other than SQLITE_OK when it is +** This function is a no-op if *pRc is other than SQLITE_OK when it is ** called. Otherwise, append the string representation of integer iVal ** to the buffer. No nul-terminator is written. ** @@ -1979,36 +1927,36 @@ static void sessionAppendStr( ** returning. */ static void sessionAppendInteger( - SessionBuffer *p, /* Buffer to append to */ - int iVal, /* Value to write the string rep. of */ - int *pRc /* IN/OUT: Error code */ -){ + SessionBuffer *p, /* Buffer to append to */ + int iVal, /* Value to write the string rep. of */ + int *pRc /* IN/OUT: Error code */ +) { char aBuf[24]; - sqlite3_snprintf(sizeof(aBuf)-1, aBuf, "%d", iVal); + sqlite3_snprintf(sizeof(aBuf) - 1, aBuf, "%d", iVal); sessionAppendStr(p, aBuf, pRc); } /* -** This function is a no-op if *pRc is other than SQLITE_OK when it is +** This function is a no-op if *pRc is other than SQLITE_OK when it is ** called. Otherwise, append the string zStr enclosed in quotes (") and -** with any embedded quote characters escaped to the buffer. No +** with any embedded quote characters escaped to the buffer. No ** nul-terminator byte is written. ** ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before ** returning. */ static void sessionAppendIdent( - SessionBuffer *p, /* Buffer to a append to */ - const char *zStr, /* String to quote, escape and append */ - int *pRc /* IN/OUT: Error code */ -){ - int nStr = sqlite3Strlen30(zStr)*2 + 2 + 1; - if( 0==sessionBufferGrow(p, nStr, pRc) ){ + SessionBuffer *p, /* Buffer to a append to */ + const char *zStr, /* String to quote, escape and append */ + int *pRc /* IN/OUT: Error code */ +) { + int nStr = sqlite3Strlen30(zStr) * 2 + 2 + 1; + if (0 == sessionBufferGrow(p, nStr, pRc)) { char *zOut = (char *)&p->aBuf[p->nBuf]; const char *zIn = zStr; *zOut++ = '"'; - while( *zIn ){ - if( *zIn=='"' ) *zOut++ = '"'; + while (*zIn) { + if (*zIn == '"') *zOut++ = '"'; *zOut++ = *(zIn++); } *zOut++ = '"'; @@ -2023,39 +1971,39 @@ static void sessionAppendIdent( ** to to the buffer. */ static void sessionAppendCol( - SessionBuffer *p, /* Buffer to append to */ - sqlite3_stmt *pStmt, /* Handle pointing to row containing value */ - int iCol, /* Column to read value from */ - int *pRc /* IN/OUT: Error code */ -){ - if( *pRc==SQLITE_OK ){ + SessionBuffer *p, /* Buffer to append to */ + sqlite3_stmt *pStmt, /* Handle pointing to row containing value */ + int iCol, /* Column to read value from */ + int *pRc /* IN/OUT: Error code */ +) { + if (*pRc == SQLITE_OK) { int eType = sqlite3_column_type(pStmt, iCol); sessionAppendByte(p, (u8)eType, pRc); - if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){ + if (eType == SQLITE_INTEGER || eType == SQLITE_FLOAT) { sqlite3_int64 i; u8 aBuf[8]; - if( eType==SQLITE_INTEGER ){ + if (eType == SQLITE_INTEGER) { i = sqlite3_column_int64(pStmt, iCol); - }else{ + } else { double r = sqlite3_column_double(pStmt, iCol); memcpy(&i, &r, 8); } sessionPutI64(aBuf, i); sessionAppendBlob(p, aBuf, 8, pRc); } - if( eType==SQLITE_BLOB || eType==SQLITE_TEXT ){ + if (eType == SQLITE_BLOB || eType == SQLITE_TEXT) { u8 *z; int nByte; - if( eType==SQLITE_BLOB ){ + if (eType == SQLITE_BLOB) { z = (u8 *)sqlite3_column_blob(pStmt, iCol); - }else{ + } else { z = (u8 *)sqlite3_column_text(pStmt, iCol); } nByte = sqlite3_column_bytes(pStmt, iCol); - if( z || (eType==SQLITE_BLOB && nByte==0) ){ + if (z || (eType == SQLITE_BLOB && nByte == 0)) { sessionAppendVarint(p, nByte, pRc); sessionAppendBlob(p, z, nByte, pRc); - }else{ + } else { *pRc = SQLITE_NOMEM; } } @@ -2064,8 +2012,8 @@ static void sessionAppendCol( /* ** -** This function appends an update change to the buffer (see the comments -** under "CHANGESET FORMAT" at the top of the file). An update change +** This function appends an update change to the buffer (see the comments +** under "CHANGESET FORMAT" at the top of the file). An update change ** consists of: ** ** 1 byte: SQLITE_UPDATE (0x17) @@ -2080,34 +2028,34 @@ static void sessionAppendCol( ** If all of the old.* values are equal to their corresponding new.* value ** (i.e. nothing has changed), then no data at all is appended to the buffer. ** -** Otherwise, the old.* record contains all primary key values and the -** original values of any fields that have been modified. The new.* record +** Otherwise, the old.* record contains all primary key values and the +** original values of any fields that have been modified. The new.* record ** contains the new values of only those fields that have been modified. -*/ +*/ static int sessionAppendUpdate( - SessionBuffer *pBuf, /* Buffer to append to */ - int bPatchset, /* True for "patchset", 0 for "changeset" */ - sqlite3_stmt *pStmt, /* Statement handle pointing at new row */ - SessionChange *p, /* Object containing old values */ - u8 *abPK /* Boolean array - true for PK columns */ -){ + SessionBuffer *pBuf, /* Buffer to append to */ + int bPatchset, /* True for "patchset", 0 for "changeset" */ + sqlite3_stmt *pStmt, /* Statement handle pointing at new row */ + SessionChange *p, /* Object containing old values */ + u8 *abPK /* Boolean array - true for PK columns */ +) { int rc = SQLITE_OK; - SessionBuffer buf2 = {0,0,0}; /* Buffer to accumulate new.* record in */ - int bNoop = 1; /* Set to zero if any values are modified */ - int nRewind = pBuf->nBuf; /* Set to zero if any values are modified */ - int i; /* Used to iterate through columns */ - u8 *pCsr = p->aRecord; /* Used to iterate through old.* values */ + SessionBuffer buf2 = {0, 0, 0}; /* Buffer to accumulate new.* record in */ + int bNoop = 1; /* Set to zero if any values are modified */ + int nRewind = pBuf->nBuf; /* Set to zero if any values are modified */ + int i; /* Used to iterate through columns */ + u8 *pCsr = p->aRecord; /* Used to iterate through old.* values */ sessionAppendByte(pBuf, SQLITE_UPDATE, &rc); sessionAppendByte(pBuf, p->bIndirect, &rc); - for(i=0; inBuf = nRewind; - }else{ + } else { sessionAppendBlob(pBuf, buf2.aBuf, buf2.nBuf, &rc); } sqlite3_free(buf2.aBuf); @@ -2184,30 +2132,30 @@ static int sessionAppendUpdate( ** format otherwise. */ static int sessionAppendDelete( - SessionBuffer *pBuf, /* Buffer to append to */ - int bPatchset, /* True for "patchset", 0 for "changeset" */ - SessionChange *p, /* Object containing old values */ - int nCol, /* Number of columns in table */ - u8 *abPK /* Boolean array - true for PK columns */ -){ + SessionBuffer *pBuf, /* Buffer to append to */ + int bPatchset, /* True for "patchset", 0 for "changeset" */ + SessionChange *p, /* Object containing old values */ + int nCol, /* Number of columns in table */ + u8 *abPK /* Boolean array - true for PK columns */ +) { int rc = SQLITE_OK; sessionAppendByte(pBuf, SQLITE_DELETE, &rc); sessionAppendByte(pBuf, p->bIndirect, &rc); - if( bPatchset==0 ){ + if (bPatchset == 0) { sessionAppendBlob(pBuf, p->aRecord, p->nRecord, &rc); - }else{ + } else { int i; u8 *a = p->aRecord; - for(i=0; iaRecord)==p->nRecord ); + assert((a - p->aRecord) == p->nRecord); } return rc; @@ -2239,25 +2187,25 @@ static int sessionAppendDelete( ** SELECT * FROM zDb.zTab WHERE pk1 = ? AND pk2 = ? AND ... */ static int sessionSelectStmt( - sqlite3 *db, /* Database handle */ - const char *zDb, /* Database name */ - const char *zTab, /* Table name */ - int nCol, /* Number of columns in table */ - const char **azCol, /* Names of table columns */ - u8 *abPK, /* PRIMARY KEY array */ - sqlite3_stmt **ppStmt /* OUT: Prepared SELECT statement */ -){ + sqlite3 *db, /* Database handle */ + const char *zDb, /* Database name */ + const char *zTab, /* Table name */ + int nCol, /* Number of columns in table */ + const char **azCol, /* Names of table columns */ + u8 *abPK, /* PRIMARY KEY array */ + sqlite3_stmt **ppStmt /* OUT: Prepared SELECT statement */ +) { int rc = SQLITE_OK; char *zSql = 0; int nSql = -1; - if( 0==sqlite3_stricmp("sqlite_stat1", zTab) ){ + if (0 == sqlite3_stricmp("sqlite_stat1", zTab)) { zSql = sqlite3_mprintf( "SELECT tbl, ?2, stat FROM %Q.sqlite_stat1 WHERE tbl IS ?1 AND " - "idx IS (CASE WHEN ?2=X'' THEN NULL ELSE ?2 END)", zDb - ); - if( zSql==0 ) rc = SQLITE_NOMEM; - }else{ + "idx IS (CASE WHEN ?2=X'' THEN NULL ELSE ?2 END)", + zDb); + if (zSql == 0) rc = SQLITE_NOMEM; + } else { int i; const char *zSep = ""; SessionBuffer buf = {0, 0, 0}; @@ -2267,20 +2215,20 @@ static int sessionSelectStmt( sessionAppendStr(&buf, ".", &rc); sessionAppendIdent(&buf, zTab, &rc); sessionAppendStr(&buf, " WHERE ", &rc); - for(i=0; iaRecord; - for(i=0; inCol, pRc); sessionAppendBlob(pBuf, pTab->abPK, pTab->nCol, pRc); - sessionAppendBlob(pBuf, (u8 *)pTab->zName, (int)strlen(pTab->zName)+1, pRc); + sessionAppendBlob(pBuf, (u8 *)pTab->zName, (int)strlen(pTab->zName) + 1, pRc); } /* @@ -2386,52 +2335,53 @@ static void sessionAppendTableHdr( ** ** If no error occurs, SQLITE_OK is returned and the new changeset/patchset ** stored in output variables *pnChangeset and *ppChangeset. Or, if an error -** occurs, an SQLite error code is returned and both output variables set +** occurs, an SQLite error code is returned and both output variables set ** to 0. */ static int sessionGenerateChangeset( - sqlite3_session *pSession, /* Session object */ - int bPatchset, /* True for patchset, false for changeset */ - int (*xOutput)(void *pOut, const void *pData, int nData), - void *pOut, /* First argument for xOutput */ - int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */ - void **ppChangeset /* OUT: Buffer containing changeset */ -){ - sqlite3 *db = pSession->db; /* Source database handle */ - SessionTable *pTab; /* Used to iterate through attached tables */ - SessionBuffer buf = {0,0,0}; /* Buffer in which to accumlate changeset */ - int rc; /* Return code */ + sqlite3_session *pSession, /* Session object */ + int bPatchset, /* True for patchset, false for changeset */ + int (*xOutput)(void *pOut, const void *pData, int nData), + void *pOut, /* First argument for xOutput */ + int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */ + void **ppChangeset /* OUT: Buffer containing changeset */ +) { + sqlite3 *db = pSession->db; /* Source database handle */ + SessionTable *pTab; /* Used to iterate through attached tables */ + SessionBuffer buf = {0, 0, 0}; /* Buffer in which to accumlate changeset */ + int rc; /* Return code */ - assert( xOutput==0 || (pnChangeset==0 && ppChangeset==0 ) ); + assert(xOutput == 0 || (pnChangeset == 0 && ppChangeset == 0)); /* Zero the output variables in case an error occurs. If this session ** object is already in the error state (sqlite3_session.rc != SQLITE_OK), ** this call will be a no-op. */ - if( xOutput==0 ){ + if (xOutput == 0) { *pnChangeset = 0; *ppChangeset = 0; } - if( pSession->rc ) return pSession->rc; + if (pSession->rc) return pSession->rc; rc = sqlite3_exec(pSession->db, "SAVEPOINT changeset", 0, 0, 0); - if( rc!=SQLITE_OK ) return rc; + if (rc != SQLITE_OK) return rc; sqlite3_mutex_enter(sqlite3_db_mutex(db)); - for(pTab=pSession->pTable; rc==SQLITE_OK && pTab; pTab=pTab->pNext){ - if( pTab->nEntry ){ + for (pTab = pSession->pTable; rc == SQLITE_OK && pTab; pTab = pTab->pNext) { + if (pTab->nEntry) { const char *zName = pTab->zName; - int nCol; /* Number of columns in table */ - u8 *abPK; /* Primary key array */ - const char **azCol = 0; /* Table columns */ - int i; /* Used to iterate through hash buckets */ - sqlite3_stmt *pSel = 0; /* SELECT statement to query table pTab */ - int nRewind = buf.nBuf; /* Initial size of write buffer */ - int nNoop; /* Size of buffer after writing tbl header */ + int nCol; /* Number of columns in table */ + u8 *abPK; /* Primary key array */ + const char **azCol = 0; /* Table columns */ + int i; /* Used to iterate through hash buckets */ + sqlite3_stmt *pSel = 0; /* SELECT statement to query table pTab */ + int nRewind = buf.nBuf; /* Initial size of write buffer */ + int nNoop; /* Size of buffer after writing tbl header */ /* Check the table schema is still Ok. */ - rc = sessionTableInfo(0, db, pSession->zDb, zName, &nCol, 0,&azCol,&abPK); - if( !rc && (pTab->nCol!=nCol || memcmp(abPK, pTab->abPK, nCol)) ){ + rc = sessionTableInfo(0, db, pSession->zDb, zName, &nCol, 0, &azCol, + &abPK); + if (!rc && (pTab->nCol != nCol || memcmp(abPK, pTab->abPK, nCol))) { rc = SQLITE_SCHEMA; } @@ -2439,66 +2389,62 @@ static int sessionGenerateChangeset( sessionAppendTableHdr(&buf, bPatchset, pTab, &rc); /* Build and compile a statement to execute: */ - if( rc==SQLITE_OK ){ - rc = sessionSelectStmt( - db, pSession->zDb, zName, nCol, azCol, abPK, &pSel); + if (rc == SQLITE_OK) { + rc = sessionSelectStmt(db, pSession->zDb, zName, nCol, azCol, abPK, + &pSel); } nNoop = buf.nBuf; - for(i=0; inChange && rc==SQLITE_OK; i++){ - SessionChange *p; /* Used to iterate through changes */ + for (i = 0; i < pTab->nChange && rc == SQLITE_OK; i++) { + SessionChange *p; /* Used to iterate through changes */ - for(p=pTab->apChange[i]; rc==SQLITE_OK && p; p=p->pNext){ + for (p = pTab->apChange[i]; rc == SQLITE_OK && p; p = p->pNext) { rc = sessionSelectBind(pSel, nCol, abPK, p); - if( rc!=SQLITE_OK ) continue; - if( sqlite3_step(pSel)==SQLITE_ROW ){ - if( p->op==SQLITE_INSERT ){ + if (rc != SQLITE_OK) continue; + if (sqlite3_step(pSel) == SQLITE_ROW) { + if (p->op == SQLITE_INSERT) { int iCol; sessionAppendByte(&buf, SQLITE_INSERT, &rc); sessionAppendByte(&buf, p->bIndirect, &rc); - for(iCol=0; iColop!=SQLITE_INSERT ){ + } else if (p->op != SQLITE_INSERT) { rc = sessionAppendDelete(&buf, bPatchset, p, nCol, abPK); } - if( rc==SQLITE_OK ){ + if (rc == SQLITE_OK) { rc = sqlite3_reset(pSel); } /* If the buffer is now larger than sessions_strm_chunk_size, pass ** its contents to the xOutput() callback. */ - if( xOutput - && rc==SQLITE_OK - && buf.nBuf>nNoop - && buf.nBuf>sessions_strm_chunk_size - ){ - rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf); + if (xOutput && rc == SQLITE_OK && buf.nBuf > nNoop && + buf.nBuf > sessions_strm_chunk_size) { + rc = xOutput(pOut, (void *)buf.aBuf, buf.nBuf); nNoop = -1; buf.nBuf = 0; } - } } sqlite3_finalize(pSel); - if( buf.nBuf==nNoop ){ + if (buf.nBuf == nNoop) { buf.nBuf = nRewind; } - sqlite3_free((char*)azCol); /* cast works around VC++ bug */ + sqlite3_free((char *)azCol); /* cast works around VC++ bug */ } } - if( rc==SQLITE_OK ){ - if( xOutput==0 ){ + if (rc == SQLITE_OK) { + if (xOutput == 0) { *pnChangeset = buf.nBuf; *ppChangeset = buf.aBuf; buf.aBuf = 0; - }else if( buf.nBuf>0 ){ - rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf); + } else if (buf.nBuf > 0) { + rc = xOutput(pOut, (void *)buf.aBuf, buf.nBuf); } } @@ -2509,64 +2455,62 @@ static int sessionGenerateChangeset( } /* -** Obtain a changeset object containing all changes recorded by the +** Obtain a changeset object containing all changes recorded by the ** session object passed as the first argument. ** -** It is the responsibility of the caller to eventually free the buffer +** It is the responsibility of the caller to eventually free the buffer ** using sqlite3_free(). */ int sqlite3session_changeset( - sqlite3_session *pSession, /* Session object */ - int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */ - void **ppChangeset /* OUT: Buffer containing changeset */ -){ + sqlite3_session *pSession, /* Session object */ + int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */ + void **ppChangeset /* OUT: Buffer containing changeset */ +) { return sessionGenerateChangeset(pSession, 0, 0, 0, pnChangeset, ppChangeset); } /* ** Streaming version of sqlite3session_changeset(). */ -int sqlite3session_changeset_strm( - sqlite3_session *pSession, - int (*xOutput)(void *pOut, const void *pData, int nData), - void *pOut -){ +int sqlite3session_changeset_strm(sqlite3_session *pSession, + int (*xOutput)(void *pOut, const void *pData, + int nData), + void *pOut) { return sessionGenerateChangeset(pSession, 0, xOutput, pOut, 0, 0); } /* ** Streaming version of sqlite3session_patchset(). */ -int sqlite3session_patchset_strm( - sqlite3_session *pSession, - int (*xOutput)(void *pOut, const void *pData, int nData), - void *pOut -){ +int sqlite3session_patchset_strm(sqlite3_session *pSession, + int (*xOutput)(void *pOut, const void *pData, + int nData), + void *pOut) { return sessionGenerateChangeset(pSession, 1, xOutput, pOut, 0, 0); } /* -** Obtain a patchset object containing all changes recorded by the +** Obtain a patchset object containing all changes recorded by the ** session object passed as the first argument. ** -** It is the responsibility of the caller to eventually free the buffer +** It is the responsibility of the caller to eventually free the buffer ** using sqlite3_free(). */ int sqlite3session_patchset( - sqlite3_session *pSession, /* Session object */ - int *pnPatchset, /* OUT: Size of buffer at *ppChangeset */ - void **ppPatchset /* OUT: Buffer containing changeset */ -){ + sqlite3_session *pSession, /* Session object */ + int *pnPatchset, /* OUT: Size of buffer at *ppChangeset */ + void **ppPatchset /* OUT: Buffer containing changeset */ +) { return sessionGenerateChangeset(pSession, 1, 0, 0, pnPatchset, ppPatchset); } /* ** Enable or disable the session object passed as the first argument. */ -int sqlite3session_enable(sqlite3_session *pSession, int bEnable){ +int sqlite3session_enable(sqlite3_session *pSession, int bEnable) { int ret; sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db)); - if( bEnable>=0 ){ + if (bEnable >= 0) { pSession->bEnable = bEnable; } ret = pSession->bEnable; @@ -2577,10 +2521,10 @@ int sqlite3session_enable(sqlite3_session *pSession, int bEnable){ /* ** Enable or disable the session object passed as the first argument. */ -int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect){ +int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect) { int ret; sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db)); - if( bIndirect>=0 ){ + if (bIndirect >= 0) { pSession->bIndirect = bIndirect; } ret = pSession->bIndirect; @@ -2592,23 +2536,23 @@ int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect){ ** Return true if there have been no changes to monitored tables recorded ** by the session object passed as the only argument. */ -int sqlite3session_isempty(sqlite3_session *pSession){ +int sqlite3session_isempty(sqlite3_session *pSession) { int ret = 0; SessionTable *pTab; sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db)); - for(pTab=pSession->pTable; pTab && ret==0; pTab=pTab->pNext){ - ret = (pTab->nEntry>0); + for (pTab = pSession->pTable; pTab && ret == 0; pTab = pTab->pNext) { + ret = (pTab->nEntry > 0); } sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db)); - return (ret==0); + return (ret == 0); } /* ** Return the amount of heap memory in use. */ -sqlite3_int64 sqlite3session_memory_used(sqlite3_session *pSession){ +sqlite3_int64 sqlite3session_memory_used(sqlite3_session *pSession) { return pSession->nMalloc; } @@ -2616,18 +2560,17 @@ sqlite3_int64 sqlite3session_memory_used(sqlite3_session *pSession){ ** Do the work for either sqlite3changeset_start() or start_strm(). */ static int sessionChangesetStart( - sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */ - int (*xInput)(void *pIn, void *pData, int *pnData), - void *pIn, - int nChangeset, /* Size of buffer pChangeset in bytes */ - void *pChangeset, /* Pointer to buffer containing changeset */ - int bInvert, /* True to invert changeset */ - int bSkipEmpty /* True to skip empty UPDATE changes */ -){ - sqlite3_changeset_iter *pRet; /* Iterator to return */ - int nByte; /* Number of bytes to allocate for iterator */ + sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */ + int (*xInput)(void *pIn, void *pData, int *pnData), void *pIn, + int nChangeset, /* Size of buffer pChangeset in bytes */ + void *pChangeset, /* Pointer to buffer containing changeset */ + int bInvert, /* True to invert changeset */ + int bSkipEmpty /* True to skip empty UPDATE changes */ +) { + sqlite3_changeset_iter *pRet; /* Iterator to return */ + int nByte; /* Number of bytes to allocate for iterator */ - assert( xInput==0 || (pChangeset==0 && nChangeset==0) ); + assert(xInput == 0 || (pChangeset == 0 && nChangeset == 0)); /* Zero the output variable in case an error occurs. */ *pp = 0; @@ -2635,7 +2578,7 @@ static int sessionChangesetStart( /* Allocate and initialize the iterator structure. */ nByte = sizeof(sqlite3_changeset_iter); pRet = (sqlite3_changeset_iter *)sqlite3_malloc(nByte); - if( !pRet ) return SQLITE_NOMEM; + if (!pRet) return SQLITE_NOMEM; memset(pRet, 0, sizeof(sqlite3_changeset_iter)); pRet->in.aData = (u8 *)pChangeset; pRet->in.nData = nChangeset; @@ -2654,18 +2597,17 @@ static int sessionChangesetStart( ** Create an iterator used to iterate through the contents of a changeset. */ int sqlite3changeset_start( - sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */ - int nChangeset, /* Size of buffer pChangeset in bytes */ - void *pChangeset /* Pointer to buffer containing changeset */ -){ + sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */ + int nChangeset, /* Size of buffer pChangeset in bytes */ + void *pChangeset /* Pointer to buffer containing changeset */ +) { return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset, 0, 0); } int sqlite3changeset_start_v2( - sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */ - int nChangeset, /* Size of buffer pChangeset in bytes */ - void *pChangeset, /* Pointer to buffer containing changeset */ - int flags -){ + sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */ + int nChangeset, /* Size of buffer pChangeset in bytes */ + void *pChangeset, /* Pointer to buffer containing changeset */ + int flags) { int bInvert = !!(flags & SQLITE_CHANGESETSTART_INVERT); return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset, bInvert, 0); } @@ -2674,18 +2616,13 @@ int sqlite3changeset_start_v2( ** Streaming version of sqlite3changeset_start(). */ int sqlite3changeset_start_strm( - sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */ - int (*xInput)(void *pIn, void *pData, int *pnData), - void *pIn -){ + sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */ + int (*xInput)(void *pIn, void *pData, int *pnData), void *pIn) { return sessionChangesetStart(pp, xInput, pIn, 0, 0, 0, 0); } int sqlite3changeset_start_v2_strm( - sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */ - int (*xInput)(void *pIn, void *pData, int *pnData), - void *pIn, - int flags -){ + sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */ + int (*xInput)(void *pIn, void *pData, int *pnData), void *pIn, int flags) { int bInvert = !!(flags & SQLITE_CHANGESETSTART_INVERT); return sessionChangesetStart(pp, xInput, pIn, 0, 0, bInvert, 0); } @@ -2694,11 +2631,11 @@ int sqlite3changeset_start_v2_strm( ** If the SessionInput object passed as the only argument is a streaming ** object and the buffer is full, discard some data to free up space. */ -static void sessionDiscardData(SessionInput *pIn){ - if( pIn->xInput && pIn->iNext>=sessions_strm_chunk_size ){ +static void sessionDiscardData(SessionInput *pIn) { + if (pIn->xInput && pIn->iNext >= sessions_strm_chunk_size) { int nMove = pIn->buf.nBuf - pIn->iNext; - assert( nMove>=0 ); - if( nMove>0 ){ + assert(nMove >= 0); + if (nMove > 0) { memmove(pIn->buf.aBuf, &pIn->buf.aBuf[pIn->iNext], nMove); } pIn->buf.nBuf -= pIn->iNext; @@ -2714,18 +2651,19 @@ static void sessionDiscardData(SessionInput *pIn){ ** ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise. */ -static int sessionInputBuffer(SessionInput *pIn, int nByte){ +static int sessionInputBuffer(SessionInput *pIn, int nByte) { int rc = SQLITE_OK; - if( pIn->xInput ){ - while( !pIn->bEof && (pIn->iNext+nByte)>=pIn->nData && rc==SQLITE_OK ){ + if (pIn->xInput) { + while (!pIn->bEof && (pIn->iNext + nByte) >= pIn->nData && + rc == SQLITE_OK) { int nNew = sessions_strm_chunk_size; - if( pIn->bNoDiscard==0 ) sessionDiscardData(pIn); - if( SQLITE_OK==sessionBufferGrow(&pIn->buf, nNew, &rc) ){ + if (pIn->bNoDiscard == 0) sessionDiscardData(pIn); + if (SQLITE_OK == sessionBufferGrow(&pIn->buf, nNew, &rc)) { rc = pIn->xInput(pIn->pIn, &pIn->buf.aBuf[pIn->buf.nBuf], &nNew); - if( nNew==0 ){ + if (nNew == 0) { pIn->bEof = 1; - }else{ + } else { pIn->buf.nBuf += nNew; } } @@ -2742,19 +2680,18 @@ static int sessionInputBuffer(SessionInput *pIn, int nByte){ ** that contains nCol values. This function advances the pointer *ppRec ** until it points to the byte immediately following that record. */ -static void sessionSkipRecord( - u8 **ppRec, /* IN/OUT: Record pointer */ - int nCol /* Number of values in record */ -){ +static void sessionSkipRecord(u8 **ppRec, /* IN/OUT: Record pointer */ + int nCol /* Number of values in record */ +) { u8 *aRec = *ppRec; int i; - for(i=0; iiNext>=pIn->nData ){ + if (rc == SQLITE_OK) { + if (pIn->iNext >= pIn->nData) { rc = SQLITE_CORRUPT_BKPT; - }else{ + } else { eType = pIn->aData[pIn->iNext++]; - assert( apOut[i]==0 ); - if( eType ){ - if( pbEmpty ) *pbEmpty = 0; + assert(apOut[i] == 0); + if (eType) { + if (pbEmpty) *pbEmpty = 0; apOut[i] = sqlite3ValueNew(0); - if( !apOut[i] ) rc = SQLITE_NOMEM; + if (!apOut[i]) rc = SQLITE_NOMEM; } } } - if( rc==SQLITE_OK ){ + if (rc == SQLITE_OK) { u8 *aVal = &pIn->aData[pIn->iNext]; - if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){ + if (eType == SQLITE_TEXT || eType == SQLITE_BLOB) { int nByte; pIn->iNext += sessionVarintGet(aVal, &nByte); rc = sessionInputBuffer(pIn, nByte); - if( rc==SQLITE_OK ){ - if( nByte<0 || nByte>pIn->nData-pIn->iNext ){ + if (rc == SQLITE_OK) { + if (nByte < 0 || nByte > pIn->nData - pIn->iNext) { rc = SQLITE_CORRUPT_BKPT; - }else{ - u8 enc = (eType==SQLITE_TEXT ? SQLITE_UTF8 : 0); - rc = sessionValueSetStr(apOut[i],&pIn->aData[pIn->iNext],nByte,enc); + } else { + u8 enc = (eType == SQLITE_TEXT ? SQLITE_UTF8 : 0); + rc = sessionValueSetStr(apOut[i], &pIn->aData[pIn->iNext], nByte, + enc); pIn->iNext += nByte; } } } - if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){ + if (eType == SQLITE_INTEGER || eType == SQLITE_FLOAT) { sqlite3_int64 v = sessionGetI64(aVal); - if( eType==SQLITE_INTEGER ){ + if (eType == SQLITE_INTEGER) { sqlite3VdbeMemSetInt64(apOut[i], v); - }else{ + } else { double d; memcpy(&d, &v, 8); sqlite3VdbeMemSetDouble(apOut[i], d); @@ -2880,42 +2817,43 @@ static int sessionReadRecord( ** + array of PK flags (1 byte per column), ** + table name (nul terminated). ** -** This function ensures that all of the above is present in the input +** This function ensures that all of the above is present in the input ** buffer (i.e. that it can be accessed without any calls to xInput()). ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code. ** The input pointer is not moved. */ -static int sessionChangesetBufferTblhdr(SessionInput *pIn, int *pnByte){ +static int sessionChangesetBufferTblhdr(SessionInput *pIn, int *pnByte) { int rc = SQLITE_OK; int nCol = 0; int nRead = 0; rc = sessionInputBuffer(pIn, 9); - if( rc==SQLITE_OK ){ + if (rc == SQLITE_OK) { nRead += sessionVarintGet(&pIn->aData[pIn->iNext + nRead], &nCol); /* The hard upper limit for the number of columns in an SQLite - ** database table is, according to sqliteLimit.h, 32676. So - ** consider any table-header that purports to have more than 65536 - ** columns to be corrupt. This is convenient because otherwise, - ** if the (nCol>65536) condition below were omitted, a sufficiently - ** large value for nCol may cause nRead to wrap around and become + ** database table is, according to sqliteLimit.h, 32676. So + ** consider any table-header that purports to have more than 65536 + ** columns to be corrupt. This is convenient because otherwise, + ** if the (nCol>65536) condition below were omitted, a sufficiently + ** large value for nCol may cause nRead to wrap around and become ** negative. Leading to a crash. */ - if( nCol<0 || nCol>65536 ){ + if (nCol < 0 || nCol > 65536) { rc = SQLITE_CORRUPT_BKPT; - }else{ - rc = sessionInputBuffer(pIn, nRead+nCol+100); + } else { + rc = sessionInputBuffer(pIn, nRead + nCol + 100); nRead += nCol; } } - while( rc==SQLITE_OK ){ - while( (pIn->iNext + nRead)nData && pIn->aData[pIn->iNext + nRead] ){ + while (rc == SQLITE_OK) { + while ((pIn->iNext + nRead) < pIn->nData && + pIn->aData[pIn->iNext + nRead]) { nRead++; } - if( (pIn->iNext + nRead)nData ) break; + if ((pIn->iNext + nRead) < pIn->nData) break; rc = sessionInputBuffer(pIn, nRead + 100); } - *pnByte = nRead+1; + *pnByte = nRead + 1; return rc; } @@ -2929,24 +2867,24 @@ static int sessionChangesetBufferTblhdr(SessionInput *pIn, int *pnByte){ ** final value of *pnByte is undefined in this case. */ static int sessionChangesetBufferRecord( - SessionInput *pIn, /* Input data */ - int nCol, /* Number of columns in record */ - int *pnByte /* OUT: Size of record in bytes */ -){ + SessionInput *pIn, /* Input data */ + int nCol, /* Number of columns in record */ + int *pnByte /* OUT: Size of record in bytes */ +) { int rc = SQLITE_OK; int nByte = 0; int i; - for(i=0; rc==SQLITE_OK && iaData[pIn->iNext + nByte++]; - if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){ + if (eType == SQLITE_TEXT || eType == SQLITE_BLOB) { int n; - nByte += sessionVarintGet(&pIn->aData[pIn->iNext+nByte], &n); + nByte += sessionVarintGet(&pIn->aData[pIn->iNext + nByte], &n); nByte += n; rc = sessionInputBuffer(pIn, nByte); - }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){ + } else if (eType == SQLITE_INTEGER || eType == SQLITE_FLOAT) { nByte += 8; } } @@ -2963,8 +2901,8 @@ static int sessionChangesetBufferRecord( ** + array of PK flags (1 byte per column), ** + table name (nul terminated). ** -** This function decodes the table-header and populates the p->nCol, -** p->zTab and p->abPK[] variables accordingly. The p->apValue[] array is +** This function decodes the table-header and populates the p->nCol, +** p->zTab and p->abPK[] variables accordingly. The p->apValue[] array is ** also allocated or resized according to the new value of p->nCol. The ** input pointer is left pointing to the byte following the table header. ** @@ -2972,41 +2910,41 @@ static int sessionChangesetBufferRecord( ** is returned and the final values of the various fields enumerated above ** are undefined. */ -static int sessionChangesetReadTblhdr(sqlite3_changeset_iter *p){ +static int sessionChangesetReadTblhdr(sqlite3_changeset_iter *p) { int rc; int nCopy; - assert( p->rc==SQLITE_OK ); + assert(p->rc == SQLITE_OK); rc = sessionChangesetBufferTblhdr(&p->in, &nCopy); - if( rc==SQLITE_OK ){ + if (rc == SQLITE_OK) { int nByte; int nVarint; nVarint = sessionVarintGet(&p->in.aData[p->in.iNext], &p->nCol); - if( p->nCol>0 ){ + if (p->nCol > 0) { nCopy -= nVarint; p->in.iNext += nVarint; - nByte = p->nCol * sizeof(sqlite3_value*) * 2 + nCopy; + nByte = p->nCol * sizeof(sqlite3_value *) * 2 + nCopy; p->tblhdr.nBuf = 0; sessionBufferGrow(&p->tblhdr, nByte, &rc); - }else{ + } else { rc = SQLITE_CORRUPT_BKPT; } } - if( rc==SQLITE_OK ){ - size_t iPK = sizeof(sqlite3_value*)*p->nCol*2; + if (rc == SQLITE_OK) { + size_t iPK = sizeof(sqlite3_value *) * p->nCol * 2; memset(p->tblhdr.aBuf, 0, iPK); memcpy(&p->tblhdr.aBuf[iPK], &p->in.aData[p->in.iNext], nCopy); p->in.iNext += nCopy; } - p->apValue = (sqlite3_value**)p->tblhdr.aBuf; - if( p->apValue==0 ){ + p->apValue = (sqlite3_value **)p->tblhdr.aBuf; + if (p->apValue == 0) { p->abPK = 0; p->zTab = 0; - }else{ - p->abPK = (u8*)&p->apValue[p->nCol*2]; - p->zTab = p->abPK ? (char*)&p->abPK[p->nCol] : 0; + } else { + p->abPK = (u8 *)&p->apValue[p->nCol * 2]; + p->zTab = p->abPK ? (char *)&p->abPK[p->nCol] : 0; } return (p->rc = rc); } @@ -3022,27 +2960,26 @@ static int sessionChangesetReadTblhdr(sqlite3_changeset_iter *p){ ** sessionChangesetNext() does that. This function does not. */ static int sessionChangesetNextOne( - sqlite3_changeset_iter *p, /* Changeset iterator */ - u8 **paRec, /* If non-NULL, store record pointer here */ - int *pnRec, /* If non-NULL, store size of record here */ - int *pbNew, /* If non-NULL, true if new table */ - int *pbEmpty -){ + sqlite3_changeset_iter *p, /* Changeset iterator */ + u8 **paRec, /* If non-NULL, store record pointer here */ + int *pnRec, /* If non-NULL, store size of record here */ + int *pbNew, /* If non-NULL, true if new table */ + int *pbEmpty) { int i; u8 op; - assert( (paRec==0 && pnRec==0) || (paRec && pnRec) ); - assert( pbEmpty==0 || *pbEmpty==0 ); + assert((paRec == 0 && pnRec == 0) || (paRec && pnRec)); + assert(pbEmpty == 0 || *pbEmpty == 0); /* If the iterator is in the error-state, return immediately. */ - if( p->rc!=SQLITE_OK ) return p->rc; + if (p->rc != SQLITE_OK) return p->rc; /* Free the current contents of p->apValue[], if any. */ - if( p->apValue ){ - for(i=0; inCol*2; i++){ + if (p->apValue) { + for (i = 0; i < p->nCol * 2; i++) { sqlite3ValueFree(p->apValue[i]); } - memset(p->apValue, 0, sizeof(sqlite3_value*)*p->nCol*2); + memset(p->apValue, 0, sizeof(sqlite3_value *) * p->nCol * 2); } /* Make sure the buffer contains at least 10 bytes of input data, or all @@ -3050,10 +2987,10 @@ static int sessionChangesetNextOne( ** sufficient either for the 'T' or 'P' byte and the varint that follows ** it, or for the two single byte values otherwise. */ p->rc = sessionInputBuffer(&p->in, 2); - if( p->rc!=SQLITE_OK ) return p->rc; + if (p->rc != SQLITE_OK) return p->rc; /* If the iterator is already at the end of the changeset, return DONE. */ - if( p->in.iNext>=p->in.nData ){ + if (p->in.iNext >= p->in.nData) { return SQLITE_DONE; } @@ -3061,77 +2998,82 @@ static int sessionChangesetNextOne( p->in.iCurrent = p->in.iNext; op = p->in.aData[p->in.iNext++]; - while( op=='T' || op=='P' ){ - if( pbNew ) *pbNew = 1; - p->bPatchset = (op=='P'); - if( sessionChangesetReadTblhdr(p) ) return p->rc; - if( (p->rc = sessionInputBuffer(&p->in, 2)) ) return p->rc; + while (op == 'T' || op == 'P') { + if (pbNew) *pbNew = 1; + p->bPatchset = (op == 'P'); + if (sessionChangesetReadTblhdr(p)) return p->rc; + if ((p->rc = sessionInputBuffer(&p->in, 2))) return p->rc; p->in.iCurrent = p->in.iNext; - if( p->in.iNext>=p->in.nData ) return SQLITE_DONE; + if (p->in.iNext >= p->in.nData) return SQLITE_DONE; op = p->in.aData[p->in.iNext++]; } - if( p->zTab==0 || (p->bPatchset && p->bInvert) ){ + if (p->zTab == 0 || (p->bPatchset && p->bInvert)) { /* The first record in the changeset is not a table header. Must be a ** corrupt changeset. */ - assert( p->in.iNext==1 || p->zTab ); + assert(p->in.iNext == 1 || p->zTab); return (p->rc = SQLITE_CORRUPT_BKPT); } p->op = op; p->bIndirect = p->in.aData[p->in.iNext++]; - if( p->op!=SQLITE_UPDATE && p->op!=SQLITE_DELETE && p->op!=SQLITE_INSERT ){ + if (p->op != SQLITE_UPDATE && p->op != SQLITE_DELETE && + p->op != SQLITE_INSERT) { return (p->rc = SQLITE_CORRUPT_BKPT); } - if( paRec ){ - int nVal; /* Number of values to buffer */ - if( p->bPatchset==0 && op==SQLITE_UPDATE ){ + if (paRec) { + int nVal; /* Number of values to buffer */ + if (p->bPatchset == 0 && op == SQLITE_UPDATE) { nVal = p->nCol * 2; - }else if( p->bPatchset && op==SQLITE_DELETE ){ + } else if (p->bPatchset && op == SQLITE_DELETE) { nVal = 0; - for(i=0; inCol; i++) if( p->abPK[i] ) nVal++; - }else{ + for (i = 0; i < p->nCol; i++) + if (p->abPK[i]) nVal++; + } else { nVal = p->nCol; } p->rc = sessionChangesetBufferRecord(&p->in, nVal, pnRec); - if( p->rc!=SQLITE_OK ) return p->rc; + if (p->rc != SQLITE_OK) return p->rc; *paRec = &p->in.aData[p->in.iNext]; p->in.iNext += *pnRec; - }else{ + } else { sqlite3_value **apOld = (p->bInvert ? &p->apValue[p->nCol] : p->apValue); sqlite3_value **apNew = (p->bInvert ? p->apValue : &p->apValue[p->nCol]); /* If this is an UPDATE or DELETE, read the old.* record. */ - if( p->op!=SQLITE_INSERT && (p->bPatchset==0 || p->op==SQLITE_DELETE) ){ + if (p->op != SQLITE_INSERT && + (p->bPatchset == 0 || p->op == SQLITE_DELETE)) { u8 *abPK = p->bPatchset ? p->abPK : 0; p->rc = sessionReadRecord(&p->in, p->nCol, abPK, apOld, 0); - if( p->rc!=SQLITE_OK ) return p->rc; + if (p->rc != SQLITE_OK) return p->rc; } /* If this is an INSERT or UPDATE, read the new.* record. */ - if( p->op!=SQLITE_DELETE ){ + if (p->op != SQLITE_DELETE) { p->rc = sessionReadRecord(&p->in, p->nCol, 0, apNew, pbEmpty); - if( p->rc!=SQLITE_OK ) return p->rc; + if (p->rc != SQLITE_OK) return p->rc; } - if( (p->bPatchset || p->bInvert) && p->op==SQLITE_UPDATE ){ + if ((p->bPatchset || p->bInvert) && p->op == SQLITE_UPDATE) { /* If this is an UPDATE that is part of a patchset, then all PK and ** modified fields are present in the new.* record. The old.* record ** is currently completely empty. This block shifts the PK fields from ** new.* to old.*, to accommodate the code that reads these arrays. */ - for(i=0; inCol; i++){ - assert( p->bPatchset==0 || p->apValue[i]==0 ); - if( p->abPK[i] ){ - assert( p->apValue[i]==0 ); - p->apValue[i] = p->apValue[i+p->nCol]; - if( p->apValue[i]==0 ) return (p->rc = SQLITE_CORRUPT_BKPT); - p->apValue[i+p->nCol] = 0; + for (i = 0; i < p->nCol; i++) { + assert(p->bPatchset == 0 || p->apValue[i] == 0); + if (p->abPK[i]) { + assert(p->apValue[i] == 0); + p->apValue[i] = p->apValue[i + p->nCol]; + if (p->apValue[i] == 0) return (p->rc = SQLITE_CORRUPT_BKPT); + p->apValue[i + p->nCol] = 0; } } - }else if( p->bInvert ){ - if( p->op==SQLITE_INSERT ) p->op = SQLITE_DELETE; - else if( p->op==SQLITE_DELETE ) p->op = SQLITE_INSERT; + } else if (p->bInvert) { + if (p->op == SQLITE_INSERT) + p->op = SQLITE_DELETE; + else if (p->op == SQLITE_DELETE) + p->op = SQLITE_INSERT; } } @@ -3149,23 +3091,23 @@ static int sessionChangesetNextOne( ** record is written to *paRec before returning and the number of bytes in ** the record to *pnRec. ** -** Either way, this function returns SQLITE_ROW if the iterator is -** successfully advanced to the next change in the changeset, an SQLite -** error code if an error occurs, or SQLITE_DONE if there are no further +** Either way, this function returns SQLITE_ROW if the iterator is +** successfully advanced to the next change in the changeset, an SQLite +** error code if an error occurs, or SQLITE_DONE if there are no further ** changes in the changeset. */ static int sessionChangesetNext( - sqlite3_changeset_iter *p, /* Changeset iterator */ - u8 **paRec, /* If non-NULL, store record pointer here */ - int *pnRec, /* If non-NULL, store size of record here */ - int *pbNew /* If non-NULL, true if new table */ -){ + sqlite3_changeset_iter *p, /* Changeset iterator */ + u8 **paRec, /* If non-NULL, store record pointer here */ + int *pnRec, /* If non-NULL, store size of record here */ + int *pbNew /* If non-NULL, true if new table */ +) { int bEmpty; int rc; do { bEmpty = 0; rc = sessionChangesetNextOne(p, paRec, pnRec, pbNew, &bEmpty); - }while( rc==SQLITE_ROW && p->bSkipEmpty && bEmpty); + } while (rc == SQLITE_ROW && p->bSkipEmpty && bEmpty); return rc; } @@ -3177,7 +3119,7 @@ static int sessionChangesetNext( ** This function may not be called on iterators passed to a conflict handler ** callback by changeset_apply(). */ -int sqlite3changeset_next(sqlite3_changeset_iter *p){ +int sqlite3changeset_next(sqlite3_changeset_iter *p) { return sessionChangesetNext(p, 0, 0, 0); } @@ -3186,17 +3128,16 @@ int sqlite3changeset_next(sqlite3_changeset_iter *p){ ** from a changeset iterator. It may only be called after changeset_next() ** has returned SQLITE_ROW. */ -int sqlite3changeset_op( - sqlite3_changeset_iter *pIter, /* Iterator handle */ - const char **pzTab, /* OUT: Pointer to table name */ - int *pnCol, /* OUT: Number of columns in table */ - int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */ - int *pbIndirect /* OUT: True if change is indirect */ -){ +int sqlite3changeset_op(sqlite3_changeset_iter *pIter, /* Iterator handle */ + const char **pzTab, /* OUT: Pointer to table name */ + int *pnCol, /* OUT: Number of columns in table */ + int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */ + int *pbIndirect /* OUT: True if change is indirect */ +) { *pOp = pIter->op; *pnCol = pIter->nCol; *pzTab = pIter->zTab; - if( pbIndirect ) *pbIndirect = pIter->bIndirect; + if (pbIndirect) *pbIndirect = pIter->bIndirect; return SQLITE_OK; } @@ -3207,12 +3148,12 @@ int sqlite3changeset_op( ** SQLITE_ROW. */ int sqlite3changeset_pk( - sqlite3_changeset_iter *pIter, /* Iterator object */ - unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */ - int *pnCol /* OUT: Number of entries in output array */ -){ + sqlite3_changeset_iter *pIter, /* Iterator object */ + unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */ + int *pnCol /* OUT: Number of entries in output array */ +) { *pabPK = pIter->abPK; - if( pnCol ) *pnCol = pIter->nCol; + if (pnCol) *pnCol = pIter->nCol; return SQLITE_OK; } @@ -3230,14 +3171,14 @@ int sqlite3changeset_pk( ** not modified. Otherwise, SQLITE_OK. */ int sqlite3changeset_old( - sqlite3_changeset_iter *pIter, /* Changeset iterator */ - int iVal, /* Index of old.* value to retrieve */ - sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */ -){ - if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_DELETE ){ + sqlite3_changeset_iter *pIter, /* Changeset iterator */ + int iVal, /* Index of old.* value to retrieve */ + sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */ +) { + if (pIter->op != SQLITE_UPDATE && pIter->op != SQLITE_DELETE) { return SQLITE_MISUSE; } - if( iVal<0 || iVal>=pIter->nCol ){ + if (iVal < 0 || iVal >= pIter->nCol) { return SQLITE_RANGE; } *ppValue = pIter->apValue[iVal]; @@ -3258,17 +3199,17 @@ int sqlite3changeset_old( ** not modified. Otherwise, SQLITE_OK. */ int sqlite3changeset_new( - sqlite3_changeset_iter *pIter, /* Changeset iterator */ - int iVal, /* Index of new.* value to retrieve */ - sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */ -){ - if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_INSERT ){ + sqlite3_changeset_iter *pIter, /* Changeset iterator */ + int iVal, /* Index of new.* value to retrieve */ + sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */ +) { + if (pIter->op != SQLITE_UPDATE && pIter->op != SQLITE_INSERT) { return SQLITE_MISUSE; } - if( iVal<0 || iVal>=pIter->nCol ){ + if (iVal < 0 || iVal >= pIter->nCol) { return SQLITE_RANGE; } - *ppValue = pIter->apValue[pIter->nCol+iVal]; + *ppValue = pIter->apValue[pIter->nCol + iVal]; return SQLITE_OK; } @@ -3277,12 +3218,13 @@ int sqlite3changeset_new( ** sqlite3changeset_new() and sqlite3changeset_old() functions, except that ** they omit all error checking and return a pointer to the requested value. */ -#define sessionChangesetNew(pIter, iVal) (pIter)->apValue[(pIter)->nCol+(iVal)] +#define sessionChangesetNew(pIter, iVal) \ + (pIter)->apValue[(pIter)->nCol + (iVal)] #define sessionChangesetOld(pIter, iVal) (pIter)->apValue[(iVal)] /* ** This function may only be called with a changeset iterator that has been -** passed to an SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT +** passed to an SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT ** conflict-handler function. Otherwise, SQLITE_MISUSE is returned. ** ** If successful, *ppValue is set to point to an sqlite3_value structure @@ -3292,14 +3234,14 @@ int sqlite3changeset_new( ** code is returned. Otherwise, SQLITE_OK. */ int sqlite3changeset_conflict( - sqlite3_changeset_iter *pIter, /* Changeset iterator */ - int iVal, /* Index of conflict record value to fetch */ - sqlite3_value **ppValue /* OUT: Value from conflicting row */ -){ - if( !pIter->pConflict ){ + sqlite3_changeset_iter *pIter, /* Changeset iterator */ + int iVal, /* Index of conflict record value to fetch */ + sqlite3_value **ppValue /* OUT: Value from conflicting row */ +) { + if (!pIter->pConflict) { return SQLITE_MISUSE; } - if( iVal<0 || iVal>=pIter->nCol ){ + if (iVal < 0 || iVal >= pIter->nCol) { return SQLITE_RANGE; } *ppValue = sqlite3_column_value(pIter->pConflict, iVal); @@ -3315,30 +3257,29 @@ int sqlite3changeset_conflict( ** In all other cases this function returns SQLITE_MISUSE. */ int sqlite3changeset_fk_conflicts( - sqlite3_changeset_iter *pIter, /* Changeset iterator */ - int *pnOut /* OUT: Number of FK violations */ -){ - if( pIter->pConflict || pIter->apValue ){ + sqlite3_changeset_iter *pIter, /* Changeset iterator */ + int *pnOut /* OUT: Number of FK violations */ +) { + if (pIter->pConflict || pIter->apValue) { return SQLITE_MISUSE; } *pnOut = pIter->nCol; return SQLITE_OK; } - /* ** Finalize an iterator allocated with sqlite3changeset_start(). ** ** This function may not be called on iterators passed to a conflict handler ** callback by changeset_apply(). */ -int sqlite3changeset_finalize(sqlite3_changeset_iter *p){ +int sqlite3changeset_finalize(sqlite3_changeset_iter *p) { int rc = SQLITE_OK; - if( p ){ - int i; /* Used to iterate through p->apValue[] */ + if (p) { + int i; /* Used to iterate through p->apValue[] */ rc = p->rc; - if( p->apValue ){ - for(i=0; inCol*2; i++) sqlite3ValueFree(p->apValue[i]); + if (p->apValue) { + for (i = 0; i < p->nCol * 2; i++) sqlite3ValueFree(p->apValue[i]); } sqlite3_free(p->tblhdr.aBuf); sqlite3_free(p->in.buf.aBuf); @@ -3348,37 +3289,36 @@ int sqlite3changeset_finalize(sqlite3_changeset_iter *p){ } static int sessionChangesetInvert( - SessionInput *pInput, /* Input changeset */ - int (*xOutput)(void *pOut, const void *pData, int nData), - void *pOut, - int *pnInverted, /* OUT: Number of bytes in output changeset */ - void **ppInverted /* OUT: Inverse of pChangeset */ -){ - int rc = SQLITE_OK; /* Return value */ - SessionBuffer sOut; /* Output buffer */ - int nCol = 0; /* Number of cols in current table */ - u8 *abPK = 0; /* PK array for current table */ - sqlite3_value **apVal = 0; /* Space for values for UPDATE inversion */ - SessionBuffer sPK = {0, 0, 0}; /* PK array for current table */ + SessionInput *pInput, /* Input changeset */ + int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut, + int *pnInverted, /* OUT: Number of bytes in output changeset */ + void **ppInverted /* OUT: Inverse of pChangeset */ +) { + int rc = SQLITE_OK; /* Return value */ + SessionBuffer sOut; /* Output buffer */ + int nCol = 0; /* Number of cols in current table */ + u8 *abPK = 0; /* PK array for current table */ + sqlite3_value **apVal = 0; /* Space for values for UPDATE inversion */ + SessionBuffer sPK = {0, 0, 0}; /* PK array for current table */ /* Initialize the output buffer */ memset(&sOut, 0, sizeof(SessionBuffer)); /* Zero the output variables in case an error occurs. */ - if( ppInverted ){ + if (ppInverted) { *ppInverted = 0; *pnInverted = 0; } - while( 1 ){ + while (1) { u8 eType; /* Test for EOF. */ - if( (rc = sessionInputBuffer(pInput, 2)) ) goto finished_invert; - if( pInput->iNext>=pInput->nData ) break; + if ((rc = sessionInputBuffer(pInput, 2))) goto finished_invert; + if (pInput->iNext >= pInput->nData) break; eType = pInput->aData[pInput->iNext]; - switch( eType ){ + switch (eType) { case 'T': { /* A 'table' record consists of: ** @@ -3390,15 +3330,16 @@ static int sessionChangesetInvert( int nByte; int nVar; pInput->iNext++; - if( (rc = sessionChangesetBufferTblhdr(pInput, &nByte)) ){ + if ((rc = sessionChangesetBufferTblhdr(pInput, &nByte))) { goto finished_invert; } nVar = sessionVarintGet(&pInput->aData[pInput->iNext], &nCol); sPK.nBuf = 0; - sessionAppendBlob(&sPK, &pInput->aData[pInput->iNext+nVar], nCol, &rc); + sessionAppendBlob(&sPK, &pInput->aData[pInput->iNext + nVar], nCol, + &rc); sessionAppendByte(&sOut, eType, &rc); sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc); - if( rc ) goto finished_invert; + if (rc) goto finished_invert; pInput->iNext += nByte; sqlite3_free(apVal); @@ -3410,46 +3351,47 @@ static int sessionChangesetInvert( case SQLITE_INSERT: case SQLITE_DELETE: { int nByte; - int bIndirect = pInput->aData[pInput->iNext+1]; - int eType2 = (eType==SQLITE_DELETE ? SQLITE_INSERT : SQLITE_DELETE); + int bIndirect = pInput->aData[pInput->iNext + 1]; + int eType2 = (eType == SQLITE_DELETE ? SQLITE_INSERT : SQLITE_DELETE); pInput->iNext += 2; - assert( rc==SQLITE_OK ); + assert(rc == SQLITE_OK); rc = sessionChangesetBufferRecord(pInput, nCol, &nByte); sessionAppendByte(&sOut, eType2, &rc); sessionAppendByte(&sOut, bIndirect, &rc); sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc); pInput->iNext += nByte; - if( rc ) goto finished_invert; + if (rc) goto finished_invert; break; } case SQLITE_UPDATE: { int iCol; - if( 0==apVal ){ - apVal = (sqlite3_value **)sqlite3_malloc64(sizeof(apVal[0])*nCol*2); - if( 0==apVal ){ + if (0 == apVal) { + apVal = + (sqlite3_value **)sqlite3_malloc64(sizeof(apVal[0]) * nCol * 2); + if (0 == apVal) { rc = SQLITE_NOMEM; goto finished_invert; } - memset(apVal, 0, sizeof(apVal[0])*nCol*2); + memset(apVal, 0, sizeof(apVal[0]) * nCol * 2); } /* Write the header for the new UPDATE change. Same as the original. */ sessionAppendByte(&sOut, eType, &rc); - sessionAppendByte(&sOut, pInput->aData[pInput->iNext+1], &rc); + sessionAppendByte(&sOut, pInput->aData[pInput->iNext + 1], &rc); /* Read the old.* and new.* records for the update change. */ pInput->iNext += 2; rc = sessionReadRecord(pInput, nCol, 0, &apVal[0], 0); - if( rc==SQLITE_OK ){ + if (rc == SQLITE_OK) { rc = sessionReadRecord(pInput, nCol, 0, &apVal[nCol], 0); } /* Write the new old.* record. Consists of the PK columns from the ** original old.* record, and the other values from the original ** new.* record. */ - for(iCol=0; iCol=sessions_strm_chunk_size ){ + assert(rc == SQLITE_OK); + if (xOutput && sOut.nBuf >= sessions_strm_chunk_size) { rc = xOutput(pOut, sOut.aBuf, sOut.nBuf); sOut.nBuf = 0; - if( rc!=SQLITE_OK ) goto finished_invert; + if (rc != SQLITE_OK) goto finished_invert; } } - assert( rc==SQLITE_OK ); - if( pnInverted ){ + assert(rc == SQLITE_OK); + if (pnInverted) { *pnInverted = sOut.nBuf; *ppInverted = sOut.aBuf; sOut.aBuf = 0; - }else if( sOut.nBuf>0 ){ + } else if (sOut.nBuf > 0) { rc = xOutput(pOut, sOut.aBuf, sOut.nBuf); } - finished_invert: +finished_invert: sqlite3_free(sOut.aBuf); sqlite3_free(apVal); sqlite3_free(sPK.aBuf); return rc; } - /* ** Invert a changeset object. */ int sqlite3changeset_invert( - int nChangeset, /* Number of bytes in input */ - const void *pChangeset, /* Input changeset */ - int *pnInverted, /* OUT: Number of bytes in output changeset */ - void **ppInverted /* OUT: Inverse of pChangeset */ -){ + int nChangeset, /* Number of bytes in input */ + const void *pChangeset, /* Input changeset */ + int *pnInverted, /* OUT: Number of bytes in output changeset */ + void **ppInverted /* OUT: Inverse of pChangeset */ +) { SessionInput sInput; /* Set up the input stream */ memset(&sInput, 0, sizeof(SessionInput)); sInput.nData = nChangeset; - sInput.aData = (u8*)pChangeset; + sInput.aData = (u8 *)pChangeset; return sessionChangesetInvert(&sInput, 0, 0, pnInverted, ppInverted); } @@ -3526,11 +3467,8 @@ int sqlite3changeset_invert( ** Streaming version of sqlite3changeset_invert(). */ int sqlite3changeset_invert_strm( - int (*xInput)(void *pIn, void *pData, int *pnData), - void *pIn, - int (*xOutput)(void *pOut, const void *pData, int nData), - void *pOut -){ + int (*xInput)(void *pIn, void *pData, int *pnData), void *pIn, + int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut) { SessionInput sInput; int rc; @@ -3544,7 +3482,6 @@ int sqlite3changeset_invert_strm( return rc; } - typedef struct SessionUpdate SessionUpdate; struct SessionUpdate { sqlite3_stmt *pStmt; @@ -3555,21 +3492,21 @@ struct SessionUpdate { typedef struct SessionApplyCtx SessionApplyCtx; struct SessionApplyCtx { sqlite3 *db; - sqlite3_stmt *pDelete; /* DELETE statement */ - sqlite3_stmt *pInsert; /* INSERT statement */ - sqlite3_stmt *pSelect; /* SELECT statement */ - int nCol; /* Size of azCol[] and abPK[] arrays */ - const char **azCol; /* Array of column names */ - u8 *abPK; /* Boolean array - true if column is in PK */ - u32 *aUpdateMask; /* Used by sessionUpdateFind */ + sqlite3_stmt *pDelete; /* DELETE statement */ + sqlite3_stmt *pInsert; /* INSERT statement */ + sqlite3_stmt *pSelect; /* SELECT statement */ + int nCol; /* Size of azCol[] and abPK[] arrays */ + const char **azCol; /* Array of column names */ + u8 *abPK; /* Boolean array - true if column is in PK */ + u32 *aUpdateMask; /* Used by sessionUpdateFind */ SessionUpdate *pUp; - int bStat1; /* True if table is sqlite_stat1 */ - int bDeferConstraints; /* True to defer constraints */ - int bInvertConstraints; /* Invert when iterating constraints buffer */ - SessionBuffer constraints; /* Deferred constraints are stored here */ - SessionBuffer rebase; /* Rebase information (if any) here */ - u8 bRebaseStarted; /* If table header is already in rebase */ - u8 bRebase; /* True to collect rebase information */ + int bStat1; /* True if table is sqlite_stat1 */ + int bDeferConstraints; /* True to defer constraints */ + int bInvertConstraints; /* Invert when iterating constraints buffer */ + SessionBuffer constraints; /* Deferred constraints are stored here */ + SessionBuffer rebase; /* Rebase information (if any) here */ + u8 bRebaseStarted; /* If table header is already in rebase */ + u8 bRebase; /* True to collect rebase information */ }; /* Number of prepared UPDATE statements to cache. */ @@ -3581,45 +3518,41 @@ struct SessionApplyCtx { ** ** UPDATE tbl SET col = ?, col2 = ? WHERE pk1 IS ? AND pk2 IS ? */ -static int sessionUpdateFind( - sqlite3_changeset_iter *pIter, - SessionApplyCtx *p, - int bPatchset, - sqlite3_stmt **ppStmt -){ +static int sessionUpdateFind(sqlite3_changeset_iter *pIter, SessionApplyCtx *p, + int bPatchset, sqlite3_stmt **ppStmt) { int rc = SQLITE_OK; SessionUpdate *pUp = 0; int nCol = pIter->nCol; - int nU32 = (pIter->nCol+33)/32; + int nU32 = (pIter->nCol + 33) / 32; int ii; - if( p->aUpdateMask==0 ){ - p->aUpdateMask = sqlite3_malloc(nU32*sizeof(u32)); - if( p->aUpdateMask==0 ){ + if (p->aUpdateMask == 0) { + p->aUpdateMask = sqlite3_malloc(nU32 * sizeof(u32)); + if (p->aUpdateMask == 0) { rc = SQLITE_NOMEM; } } - if( rc==SQLITE_OK ){ - memset(p->aUpdateMask, 0, nU32*sizeof(u32)); + if (rc == SQLITE_OK) { + memset(p->aUpdateMask, 0, nU32 * sizeof(u32)); rc = SQLITE_CORRUPT; - for(ii=0; iinCol; ii++){ - if( sessionChangesetNew(pIter, ii) ){ - p->aUpdateMask[ii/32] |= (1<<(ii%32)); + for (ii = 0; ii < pIter->nCol; ii++) { + if (sessionChangesetNew(pIter, ii)) { + p->aUpdateMask[ii / 32] |= (1 << (ii % 32)); rc = SQLITE_OK; } } } - if( rc==SQLITE_OK ){ - if( bPatchset ) p->aUpdateMask[nCol/32] |= (1<<(nCol%32)); + if (rc == SQLITE_OK) { + if (bPatchset) p->aUpdateMask[nCol / 32] |= (1 << (nCol % 32)); - if( p->pUp ){ + if (p->pUp) { int nUp = 0; SessionUpdate **pp = &p->pUp; - while( 1 ){ + while (1) { nUp++; - if( 0==memcmp(p->aUpdateMask, (*pp)->aMask, nU32*sizeof(u32)) ){ + if (0 == memcmp(p->aUpdateMask, (*pp)->aMask, nU32 * sizeof(u32))) { pUp = *pp; *pp = pUp->pNext; pUp->pNext = p->pUp; @@ -3627,10 +3560,10 @@ static int sessionUpdateFind( break; } - if( (*pp)->pNext ){ + if ((*pp)->pNext) { pp = &(*pp)->pNext; - }else{ - if( nUp>=SESSION_UPDATE_CACHE_SZ ){ + } else { + if (nUp >= SESSION_UPDATE_CACHE_SZ) { sqlite3_finalize((*pp)->pStmt); sqlite3_free(*pp); *pp = 0; @@ -3640,31 +3573,31 @@ static int sessionUpdateFind( } } - if( pUp==0 ){ - int nByte = sizeof(SessionUpdate) * nU32*sizeof(u32); - int bStat1 = (sqlite3_stricmp(pIter->zTab, "sqlite_stat1")==0); - pUp = (SessionUpdate*)sqlite3_malloc(nByte); - if( pUp==0 ){ + if (pUp == 0) { + int nByte = sizeof(SessionUpdate) * nU32 * sizeof(u32); + int bStat1 = (sqlite3_stricmp(pIter->zTab, "sqlite_stat1") == 0); + pUp = (SessionUpdate *)sqlite3_malloc(nByte); + if (pUp == 0) { rc = SQLITE_NOMEM; - }else{ + } else { const char *zSep = ""; SessionBuffer buf; memset(&buf, 0, sizeof(buf)); - pUp->aMask = (u32*)&pUp[1]; - memcpy(pUp->aMask, p->aUpdateMask, nU32*sizeof(u32)); + pUp->aMask = (u32 *)&pUp[1]; + memcpy(pUp->aMask, p->aUpdateMask, nU32 * sizeof(u32)); sessionAppendStr(&buf, "UPDATE main.", &rc); sessionAppendIdent(&buf, pIter->zTab, &rc); sessionAppendStr(&buf, " SET ", &rc); /* Create the assignments part of the UPDATE */ - for(ii=0; iinCol; ii++){ - if( p->abPK[ii]==0 && sessionChangesetNew(pIter, ii) ){ + for (ii = 0; ii < pIter->nCol; ii++) { + if (p->abPK[ii] == 0 && sessionChangesetNew(pIter, ii)) { sessionAppendStr(&buf, zSep, &rc); sessionAppendIdent(&buf, p->azCol[ii], &rc); sessionAppendStr(&buf, " = ?", &rc); - sessionAppendInteger(&buf, ii*2+1, &rc); + sessionAppendInteger(&buf, ii * 2 + 1, &rc); zSep = ", "; } } @@ -3672,34 +3605,36 @@ static int sessionUpdateFind( /* Create the WHERE clause part of the UPDATE */ zSep = ""; sessionAppendStr(&buf, " WHERE ", &rc); - for(ii=0; iinCol; ii++){ - if( p->abPK[ii] || (bPatchset==0 && sessionChangesetOld(pIter, ii)) ){ + for (ii = 0; ii < pIter->nCol; ii++) { + if (p->abPK[ii] || + (bPatchset == 0 && sessionChangesetOld(pIter, ii))) { sessionAppendStr(&buf, zSep, &rc); - if( bStat1 && ii==1 ){ - assert( sqlite3_stricmp(p->azCol[ii], "idx")==0 ); - sessionAppendStr(&buf, + if (bStat1 && ii == 1) { + assert(sqlite3_stricmp(p->azCol[ii], "idx") == 0); + sessionAppendStr( + &buf, "idx IS CASE " "WHEN length(?4)=0 AND typeof(?4)='blob' THEN NULL " - "ELSE ?4 END ", &rc - ); - }else{ + "ELSE ?4 END ", + &rc); + } else { sessionAppendIdent(&buf, p->azCol[ii], &rc); sessionAppendStr(&buf, " IS ?", &rc); - sessionAppendInteger(&buf, ii*2+2, &rc); + sessionAppendInteger(&buf, ii * 2 + 2, &rc); } zSep = " AND "; } } - if( rc==SQLITE_OK ){ - char *zSql = (char*)buf.aBuf; + if (rc == SQLITE_OK) { + char *zSql = (char *)buf.aBuf; rc = sqlite3_prepare_v2(p->db, zSql, buf.nBuf, &pUp->pStmt, 0); } - if( rc!=SQLITE_OK ){ + if (rc != SQLITE_OK) { sqlite3_free(pUp); pUp = 0; - }else{ + } else { pUp->pNext = p->pUp; p->pUp = pUp; } @@ -3708,10 +3643,10 @@ static int sessionUpdateFind( } } - assert( (rc==SQLITE_OK)==(pUp!=0) ); - if( pUp ){ + assert((rc == SQLITE_OK) == (pUp != 0)); + if (pUp) { *ppStmt = pUp->pStmt; - }else{ + } else { *ppStmt = 0; } return rc; @@ -3720,10 +3655,10 @@ static int sessionUpdateFind( /* ** Free all cached UPDATE statements. */ -static void sessionUpdateFree(SessionApplyCtx *p){ +static void sessionUpdateFree(SessionApplyCtx *p) { SessionUpdate *pUp; SessionUpdate *pNext; - for(pUp=p->pUp; pUp; pUp=pNext){ + for (pUp = p->pUp; pUp; pUp = pNext) { pNext = pUp->pNext; sqlite3_finalize(pUp->pStmt); sqlite3_free(pUp); @@ -3751,10 +3686,10 @@ static void sessionUpdateFree(SessionApplyCtx *p){ ** pointing to the prepared version of the SQL statement. */ static int sessionDeleteRow( - sqlite3 *db, /* Database handle */ - const char *zTab, /* Table name */ - SessionApplyCtx *p /* Session changeset-apply context */ -){ + sqlite3 *db, /* Database handle */ + const char *zTab, /* Table name */ + SessionApplyCtx *p /* Session changeset-apply context */ +) { int i; const char *zSep = ""; int rc = SQLITE_OK; @@ -3765,36 +3700,36 @@ static int sessionDeleteRow( sessionAppendIdent(&buf, zTab, &rc); sessionAppendStr(&buf, " WHERE ", &rc); - for(i=0; inCol; i++){ - if( p->abPK[i] ){ + for (i = 0; i < p->nCol; i++) { + if (p->abPK[i]) { nPk++; sessionAppendStr(&buf, zSep, &rc); sessionAppendIdent(&buf, p->azCol[i], &rc); sessionAppendStr(&buf, " = ?", &rc); - sessionAppendInteger(&buf, i+1, &rc); + sessionAppendInteger(&buf, i + 1, &rc); zSep = " AND "; } } - if( nPknCol ){ + if (nPk < p->nCol) { sessionAppendStr(&buf, " AND (?", &rc); - sessionAppendInteger(&buf, p->nCol+1, &rc); + sessionAppendInteger(&buf, p->nCol + 1, &rc); sessionAppendStr(&buf, " OR ", &rc); zSep = ""; - for(i=0; inCol; i++){ - if( !p->abPK[i] ){ + for (i = 0; i < p->nCol; i++) { + if (!p->abPK[i]) { sessionAppendStr(&buf, zSep, &rc); sessionAppendIdent(&buf, p->azCol[i], &rc); sessionAppendStr(&buf, " IS ?", &rc); - sessionAppendInteger(&buf, i+1, &rc); + sessionAppendInteger(&buf, i + 1, &rc); zSep = "AND "; } } sessionAppendStr(&buf, ")", &rc); } - if( rc==SQLITE_OK ){ + if (rc == SQLITE_OK) { rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pDelete, 0); } sqlite3_free(buf.aBuf); @@ -3816,12 +3751,12 @@ static int sessionDeleteRow( ** pointing to the prepared version of the SQL statement. */ static int sessionSelectRow( - sqlite3 *db, /* Database handle */ - const char *zTab, /* Table name */ - SessionApplyCtx *p /* Session changeset-apply context */ -){ - return sessionSelectStmt( - db, "main", zTab, p->nCol, p->azCol, p->abPK, &p->pSelect); + sqlite3 *db, /* Database handle */ + const char *zTab, /* Table name */ + SessionApplyCtx *p /* Session changeset-apply context */ +) { + return sessionSelectStmt(db, "main", zTab, p->nCol, p->azCol, p->abPK, + &p->pSelect); } /* @@ -3834,10 +3769,10 @@ static int sessionSelectRow( ** pointing to the prepared version of the SQL statement. */ static int sessionInsertRow( - sqlite3 *db, /* Database handle */ - const char *zTab, /* Table name */ - SessionApplyCtx *p /* Session changeset-apply context */ -){ + sqlite3 *db, /* Database handle */ + const char *zTab, /* Table name */ + SessionApplyCtx *p /* Session changeset-apply context */ +) { int rc = SQLITE_OK; int i; SessionBuffer buf = {0, 0, 0}; @@ -3845,68 +3780,68 @@ static int sessionInsertRow( sessionAppendStr(&buf, "INSERT INTO main.", &rc); sessionAppendIdent(&buf, zTab, &rc); sessionAppendStr(&buf, "(", &rc); - for(i=0; inCol; i++){ - if( i!=0 ) sessionAppendStr(&buf, ", ", &rc); + for (i = 0; i < p->nCol; i++) { + if (i != 0) sessionAppendStr(&buf, ", ", &rc); sessionAppendIdent(&buf, p->azCol[i], &rc); } sessionAppendStr(&buf, ") VALUES(?", &rc); - for(i=1; inCol; i++){ + for (i = 1; i < p->nCol; i++) { sessionAppendStr(&buf, ", ?", &rc); } sessionAppendStr(&buf, ")", &rc); - if( rc==SQLITE_OK ){ + if (rc == SQLITE_OK) { rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pInsert, 0); } sqlite3_free(buf.aBuf); return rc; } -static int sessionPrepare(sqlite3 *db, sqlite3_stmt **pp, const char *zSql){ +static int sessionPrepare(sqlite3 *db, sqlite3_stmt **pp, const char *zSql) { return sqlite3_prepare_v2(db, zSql, -1, pp, 0); } /* ** Prepare statements for applying changes to the sqlite_stat1 table. ** These are similar to those created by sessionSelectRow(), -** sessionInsertRow(), sessionUpdateRow() and sessionDeleteRow() for +** sessionInsertRow(), sessionUpdateRow() and sessionDeleteRow() for ** other tables. */ -static int sessionStat1Sql(sqlite3 *db, SessionApplyCtx *p){ +static int sessionStat1Sql(sqlite3 *db, SessionApplyCtx *p) { int rc = sessionSelectRow(db, "sqlite_stat1", p); - if( rc==SQLITE_OK ){ - rc = sessionPrepare(db, &p->pInsert, + if (rc == SQLITE_OK) { + rc = sessionPrepare( + db, &p->pInsert, "INSERT INTO main.sqlite_stat1 VALUES(?1, " "CASE WHEN length(?2)=0 AND typeof(?2)='blob' THEN NULL ELSE ?2 END, " - "?3)" - ); + "?3)"); } - if( rc==SQLITE_OK ){ - rc = sessionPrepare(db, &p->pDelete, + if (rc == SQLITE_OK) { + rc = sessionPrepare( + db, &p->pDelete, "DELETE FROM main.sqlite_stat1 WHERE tbl=?1 AND idx IS " "CASE WHEN length(?2)=0 AND typeof(?2)='blob' THEN NULL ELSE ?2 END " - "AND (?4 OR stat IS ?3)" - ); + "AND (?4 OR stat IS ?3)"); } return rc; } /* -** A wrapper around sqlite3_bind_value() that detects an extra problem. +** A wrapper around sqlite3_bind_value() that detects an extra problem. ** See comments in the body of this function for details. */ static int sessionBindValue( - sqlite3_stmt *pStmt, /* Statement to bind value to */ - int i, /* Parameter number to bind to */ - sqlite3_value *pVal /* Value to bind */ -){ + sqlite3_stmt *pStmt, /* Statement to bind value to */ + int i, /* Parameter number to bind to */ + sqlite3_value *pVal /* Value to bind */ +) { int eType = sqlite3_value_type(pVal); /* COVERAGE: The (pVal->z==0) branch is never true using current versions ** of SQLite. If a malloc fails in an sqlite3_value_xxx() function, either ** the (pVal->z) variable remains as it was or the type of the value is ** set to SQLITE_NULL. */ - if( (eType==SQLITE_TEXT || eType==SQLITE_BLOB) && pVal->z==0 ){ + if ((eType == SQLITE_TEXT || eType == SQLITE_BLOB) && pVal->z == 0) { /* This condition occurs when an earlier OOM in a call to ** sqlite3_value_text() or sqlite3_value_blob() (perhaps from within ** a conflict-handler) has zeroed the pVal->z pointer. Return NOMEM. */ @@ -3916,45 +3851,45 @@ static int sessionBindValue( } /* -** Iterator pIter must point to an SQLITE_INSERT entry. This function +** Iterator pIter must point to an SQLITE_INSERT entry. This function ** transfers new.* values from the current iterator entry to statement ** pStmt. The table being inserted into has nCol columns. ** -** New.* value $i from the iterator is bound to variable ($i+1) of +** New.* value $i from the iterator is bound to variable ($i+1) of ** statement pStmt. If parameter abPK is NULL, all values from 0 to (nCol-1) ** are transfered to the statement. Otherwise, if abPK is not NULL, it points -** to an array nCol elements in size. In this case only those values for -** which abPK[$i] is true are read from the iterator and bound to the +** to an array nCol elements in size. In this case only those values for +** which abPK[$i] is true are read from the iterator and bound to the ** statement. ** ** An SQLite error code is returned if an error occurs. Otherwise, SQLITE_OK. */ static int sessionBindRow( - sqlite3_changeset_iter *pIter, /* Iterator to read values from */ - int(*xValue)(sqlite3_changeset_iter *, int, sqlite3_value **), - int nCol, /* Number of columns */ - u8 *abPK, /* If not NULL, bind only if true */ - sqlite3_stmt *pStmt /* Bind values to this statement */ -){ + sqlite3_changeset_iter *pIter, /* Iterator to read values from */ + int (*xValue)(sqlite3_changeset_iter *, int, sqlite3_value **), + int nCol, /* Number of columns */ + u8 *abPK, /* If not NULL, bind only if true */ + sqlite3_stmt *pStmt /* Bind values to this statement */ +) { int i; int rc = SQLITE_OK; /* Neither sqlite3changeset_old or sqlite3changeset_new can fail if the - ** argument iterator points to a suitable entry. Make sure that xValue - ** is one of these to guarantee that it is safe to ignore the return + ** argument iterator points to a suitable entry. Make sure that xValue + ** is one of these to guarantee that it is safe to ignore the return ** in the code below. */ - assert( xValue==sqlite3changeset_old || xValue==sqlite3changeset_new ); + assert(xValue == sqlite3changeset_old || xValue == sqlite3changeset_new); - for(i=0; rc==SQLITE_OK && ibRebase ){ + if (p->bRebase) { int i; int eOp = pIter->op; - if( p->bRebaseStarted==0 ){ + if (p->bRebaseStarted == 0) { /* Append a table-header to the rebase buffer */ const char *zTab = pIter->zTab; sessionAppendByte(&p->rebase, 'T', &rc); sessionAppendVarint(&p->rebase, p->nCol, &rc); sessionAppendBlob(&p->rebase, p->abPK, p->nCol, &rc); - sessionAppendBlob(&p->rebase, (u8*)zTab, (int)strlen(zTab)+1, &rc); + sessionAppendBlob(&p->rebase, (u8 *)zTab, (int)strlen(zTab) + 1, &rc); p->bRebaseStarted = 1; } - assert( eType==SQLITE_CHANGESET_REPLACE||eType==SQLITE_CHANGESET_OMIT ); - assert( eOp==SQLITE_DELETE || eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE ); + assert(eType == SQLITE_CHANGESET_REPLACE || eType == SQLITE_CHANGESET_OMIT); + assert(eOp == SQLITE_DELETE || eOp == SQLITE_INSERT || + eOp == SQLITE_UPDATE); - sessionAppendByte(&p->rebase, - (eOp==SQLITE_DELETE ? SQLITE_DELETE : SQLITE_INSERT), &rc - ); - sessionAppendByte(&p->rebase, (eType==SQLITE_CHANGESET_REPLACE), &rc); - for(i=0; inCol; i++){ + sessionAppendByte(&p->rebase, + (eOp == SQLITE_DELETE ? SQLITE_DELETE : SQLITE_INSERT), + &rc); + sessionAppendByte(&p->rebase, (eType == SQLITE_CHANGESET_REPLACE), &rc); + for (i = 0; i < p->nCol; i++) { sqlite3_value *pVal = 0; - if( eOp==SQLITE_DELETE || (eOp==SQLITE_UPDATE && p->abPK[i]) ){ + if (eOp == SQLITE_DELETE || (eOp == SQLITE_UPDATE && p->abPK[i])) { sqlite3changeset_old(pIter, i, &pVal); - }else{ + } else { sqlite3changeset_new(pIter, i, &pVal); } sessionAppendValue(&p->rebase, pVal, &rc); @@ -4083,19 +4018,19 @@ static int sessionRebaseAdd( ** is set to non-zero before returning SQLITE_OK. ** ** If the conflict handler returns SQLITE_CHANGESET_ABORT, SQLITE_ABORT is -** returned. Or, if the conflict handler returns an invalid value, +** returned. Or, if the conflict handler returns an invalid value, ** SQLITE_MISUSE. If the conflict handler returns SQLITE_CHANGESET_OMIT, ** this function returns SQLITE_OK. */ static int sessionConflictHandler( - int eType, /* Either CHANGESET_DATA or CONFLICT */ - SessionApplyCtx *p, /* changeset_apply() context */ - sqlite3_changeset_iter *pIter, /* Changeset iterator */ - int(*xConflict)(void *, int, sqlite3_changeset_iter*), - void *pCtx, /* First argument for conflict handler */ - int *pbReplace /* OUT: Set to true if PK row is found */ -){ - int res = 0; /* Value returned by conflict handler */ + int eType, /* Either CHANGESET_DATA or CONFLICT */ + SessionApplyCtx *p, /* changeset_apply() context */ + sqlite3_changeset_iter *pIter, /* Changeset iterator */ + int (*xConflict)(void *, int, sqlite3_changeset_iter *), + void *pCtx, /* First argument for conflict handler */ + int *pbReplace /* OUT: Set to true if PK row is found */ +) { + int res = 0; /* Value returned by conflict handler */ int rc; int nCol; int op; @@ -4103,42 +4038,42 @@ static int sessionConflictHandler( sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0); - assert( eType==SQLITE_CHANGESET_CONFLICT || eType==SQLITE_CHANGESET_DATA ); - assert( SQLITE_CHANGESET_CONFLICT+1==SQLITE_CHANGESET_CONSTRAINT ); - assert( SQLITE_CHANGESET_DATA+1==SQLITE_CHANGESET_NOTFOUND ); + assert(eType == SQLITE_CHANGESET_CONFLICT || eType == SQLITE_CHANGESET_DATA); + assert(SQLITE_CHANGESET_CONFLICT + 1 == SQLITE_CHANGESET_CONSTRAINT); + assert(SQLITE_CHANGESET_DATA + 1 == SQLITE_CHANGESET_NOTFOUND); /* Bind the new.* PRIMARY KEY values to the SELECT statement. */ - if( pbReplace ){ + if (pbReplace) { rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect); - }else{ + } else { rc = SQLITE_OK; } - if( rc==SQLITE_ROW ){ + if (rc == SQLITE_ROW) { /* There exists another row with the new.* primary key. */ pIter->pConflict = p->pSelect; res = xConflict(pCtx, eType, pIter); pIter->pConflict = 0; rc = sqlite3_reset(p->pSelect); - }else if( rc==SQLITE_OK ){ - if( p->bDeferConstraints && eType==SQLITE_CHANGESET_CONFLICT ){ + } else if (rc == SQLITE_OK) { + if (p->bDeferConstraints && eType == SQLITE_CHANGESET_CONFLICT) { /* Instead of invoking the conflict handler, append the change blob ** to the SessionApplyCtx.constraints buffer. */ u8 *aBlob = &pIter->in.aData[pIter->in.iCurrent]; int nBlob = pIter->in.iNext - pIter->in.iCurrent; sessionAppendBlob(&p->constraints, aBlob, nBlob, &rc); return SQLITE_OK; - }else{ + } else { /* No other row with the new.* primary key. */ - res = xConflict(pCtx, eType+1, pIter); - if( res==SQLITE_CHANGESET_REPLACE ) rc = SQLITE_MISUSE; + res = xConflict(pCtx, eType + 1, pIter); + if (res == SQLITE_CHANGESET_REPLACE) rc = SQLITE_MISUSE; } } - if( rc==SQLITE_OK ){ - switch( res ){ + if (rc == SQLITE_OK) { + switch (res) { case SQLITE_CHANGESET_REPLACE: - assert( pbReplace ); + assert(pbReplace); *pbReplace = 1; break; @@ -4153,7 +4088,7 @@ static int sessionConflictHandler( rc = SQLITE_MISUSE; break; } - if( rc==SQLITE_OK ){ + if (rc == SQLITE_OK) { rc = sessionRebaseAdd(p, res, pIter); } } @@ -4173,38 +4108,38 @@ static int sessionConflictHandler( ** to true before returning. In this case the caller will invoke this function ** again, this time with pbRetry set to NULL. ** -** If argument pbReplace is NULL and a CHANGESET_CONFLICT conflict is +** If argument pbReplace is NULL and a CHANGESET_CONFLICT conflict is ** encountered invoke the conflict handler with CHANGESET_CONSTRAINT instead. ** Or, if pbReplace is not NULL, invoke it with CHANGESET_CONFLICT. If such ** an invocation returns SQLITE_CHANGESET_REPLACE, set *pbReplace to true ** before retrying. In this case the caller attempts to remove the conflicting -** row before invoking this function again, this time with pbReplace set +** row before invoking this function again, this time with pbReplace set ** to NULL. ** ** If any conflict handler returns SQLITE_CHANGESET_ABORT, this function -** returns SQLITE_ABORT. Otherwise, if no error occurs, SQLITE_OK is +** returns SQLITE_ABORT. Otherwise, if no error occurs, SQLITE_OK is ** returned. */ static int sessionApplyOneOp( - sqlite3_changeset_iter *pIter, /* Changeset iterator */ - SessionApplyCtx *p, /* changeset_apply() context */ - int(*xConflict)(void *, int, sqlite3_changeset_iter *), - void *pCtx, /* First argument for the conflict handler */ - int *pbReplace, /* OUT: True to remove PK row and retry */ - int *pbRetry /* OUT: True to retry. */ -){ + sqlite3_changeset_iter *pIter, /* Changeset iterator */ + SessionApplyCtx *p, /* changeset_apply() context */ + int (*xConflict)(void *, int, sqlite3_changeset_iter *), + void *pCtx, /* First argument for the conflict handler */ + int *pbReplace, /* OUT: True to remove PK row and retry */ + int *pbRetry /* OUT: True to retry. */ +) { const char *zDummy; int op; int nCol; int rc = SQLITE_OK; - assert( p->pDelete && p->pInsert && p->pSelect ); - assert( p->azCol && p->abPK ); - assert( !pbReplace || *pbReplace==0 ); + assert(p->pDelete && p->pInsert && p->pSelect); + assert(p->azCol && p->abPK); + assert(!pbReplace || *pbReplace == 0); sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0); - if( op==SQLITE_DELETE ){ + if (op == SQLITE_DELETE) { /* Bind values to the DELETE statement. If conflict handling is required, ** bind values for all columns and set bound variable (nCol+1) to true. @@ -4219,89 +4154,84 @@ static int sessionApplyOneOp( */ u8 *abPK = (pIter->bPatchset ? p->abPK : 0); rc = sessionBindRow(pIter, sqlite3changeset_old, nCol, abPK, p->pDelete); - if( rc==SQLITE_OK && sqlite3_bind_parameter_count(p->pDelete)>nCol ){ - rc = sqlite3_bind_int(p->pDelete, nCol+1, (pbRetry==0 || abPK)); + if (rc == SQLITE_OK && sqlite3_bind_parameter_count(p->pDelete) > nCol) { + rc = sqlite3_bind_int(p->pDelete, nCol + 1, (pbRetry == 0 || abPK)); } - if( rc!=SQLITE_OK ) return rc; + if (rc != SQLITE_OK) return rc; sqlite3_step(p->pDelete); rc = sqlite3_reset(p->pDelete); - if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){ - rc = sessionConflictHandler( - SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry - ); - }else if( (rc&0xff)==SQLITE_CONSTRAINT ){ - rc = sessionConflictHandler( - SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0 - ); + if (rc == SQLITE_OK && sqlite3_changes(p->db) == 0) { + rc = sessionConflictHandler(SQLITE_CHANGESET_DATA, p, pIter, xConflict, + pCtx, pbRetry); + } else if ((rc & 0xff) == SQLITE_CONSTRAINT) { + rc = sessionConflictHandler(SQLITE_CHANGESET_CONFLICT, p, pIter, + xConflict, pCtx, 0); } - }else if( op==SQLITE_UPDATE ){ + } else if (op == SQLITE_UPDATE) { int i; sqlite3_stmt *pUp = 0; - int bPatchset = (pbRetry==0 || pIter->bPatchset); + int bPatchset = (pbRetry == 0 || pIter->bPatchset); rc = sessionUpdateFind(pIter, p, bPatchset, &pUp); /* Bind values to the UPDATE statement. */ - for(i=0; rc==SQLITE_OK && iabPK[i] || (bPatchset==0 && pOld) ){ - rc = sessionBindValue(pUp, i*2+2, pOld); + if (p->abPK[i] || (bPatchset == 0 && pOld)) { + rc = sessionBindValue(pUp, i * 2 + 2, pOld); } - if( rc==SQLITE_OK && pNew ){ - rc = sessionBindValue(pUp, i*2+1, pNew); + if (rc == SQLITE_OK && pNew) { + rc = sessionBindValue(pUp, i * 2 + 1, pNew); } } - if( rc!=SQLITE_OK ) return rc; + if (rc != SQLITE_OK) return rc; /* Attempt the UPDATE. In the case of a NOTFOUND or DATA conflict, ** the result will be SQLITE_OK with 0 rows modified. */ sqlite3_step(pUp); rc = sqlite3_reset(pUp); - if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){ + if (rc == SQLITE_OK && sqlite3_changes(p->db) == 0) { /* A NOTFOUND or DATA error. Search the table to see if it contains ** a row with a matching primary key. If so, this is a DATA conflict. ** Otherwise, if there is no primary key match, it is a NOTFOUND. */ - rc = sessionConflictHandler( - SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry - ); + rc = sessionConflictHandler(SQLITE_CHANGESET_DATA, p, pIter, xConflict, + pCtx, pbRetry); - }else if( (rc&0xff)==SQLITE_CONSTRAINT ){ + } else if ((rc & 0xff) == SQLITE_CONSTRAINT) { /* This is always a CONSTRAINT conflict. */ - rc = sessionConflictHandler( - SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0 - ); + rc = sessionConflictHandler(SQLITE_CHANGESET_CONFLICT, p, pIter, + xConflict, pCtx, 0); } - }else{ - assert( op==SQLITE_INSERT ); - if( p->bStat1 ){ + } else { + assert(op == SQLITE_INSERT); + if (p->bStat1) { /* Check if there is a conflicting row. For sqlite_stat1, this needs - ** to be done using a SELECT, as there is no PRIMARY KEY in the + ** to be done using a SELECT, as there is no PRIMARY KEY in the ** database schema to throw an exception if a duplicate is inserted. */ rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect); - if( rc==SQLITE_ROW ){ + if (rc == SQLITE_ROW) { rc = SQLITE_CONSTRAINT; sqlite3_reset(p->pSelect); } } - if( rc==SQLITE_OK ){ + if (rc == SQLITE_OK) { rc = sessionBindRow(pIter, sqlite3changeset_new, nCol, 0, p->pInsert); - if( rc!=SQLITE_OK ) return rc; + if (rc != SQLITE_OK) return rc; sqlite3_step(p->pInsert); rc = sqlite3_reset(p->pInsert); } - if( (rc&0xff)==SQLITE_CONSTRAINT ){ - rc = sessionConflictHandler( - SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, pbReplace - ); + if ((rc & 0xff) == SQLITE_CONSTRAINT) { + rc = sessionConflictHandler(SQLITE_CHANGESET_CONFLICT, p, pIter, + xConflict, pCtx, pbReplace); } } @@ -4314,32 +4244,32 @@ static int sessionApplyOneOp( ** the conflict handler callback. ** ** The difference between this function and sessionApplyOne() is that this -** function handles the case where the conflict-handler is invoked and +** function handles the case where the conflict-handler is invoked and ** returns SQLITE_CHANGESET_REPLACE - indicating that the change should be ** retried in some manner. */ static int sessionApplyOneWithRetry( - sqlite3 *db, /* Apply change to "main" db of this handle */ - sqlite3_changeset_iter *pIter, /* Changeset iterator to read change from */ - SessionApplyCtx *pApply, /* Apply context */ - int(*xConflict)(void*, int, sqlite3_changeset_iter*), - void *pCtx /* First argument passed to xConflict */ -){ + sqlite3 *db, /* Apply change to "main" db of this handle */ + sqlite3_changeset_iter *pIter, /* Changeset iterator to read change from */ + SessionApplyCtx *pApply, /* Apply context */ + int (*xConflict)(void *, int, sqlite3_changeset_iter *), + void *pCtx /* First argument passed to xConflict */ +) { int bReplace = 0; int bRetry = 0; int rc; rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, &bReplace, &bRetry); - if( rc==SQLITE_OK ){ + if (rc == SQLITE_OK) { /* If the bRetry flag is set, the change has not been applied due to an ** SQLITE_CHANGESET_DATA problem (i.e. this is an UPDATE or DELETE and ** a row with the correct PK is present in the db, but one or more other - ** fields do not contain the expected values) and the conflict handler + ** fields do not contain the expected values) and the conflict handler ** returned SQLITE_CHANGESET_REPLACE. In this case retry the operation, ** but pass NULL as the final argument so that sessionApplyOneOp() ignores ** the SQLITE_CHANGESET_DATA problem. */ - if( bRetry ){ - assert( pIter->op==SQLITE_UPDATE || pIter->op==SQLITE_DELETE ); + if (bRetry) { + assert(pIter->op == SQLITE_UPDATE || pIter->op == SQLITE_DELETE); rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0); } @@ -4348,22 +4278,22 @@ static int sessionApplyOneWithRetry( ** specified primary key and the conflict handler returned ** SQLITE_CHANGESET_REPLACE. In this case remove the conflicting row ** before reattempting the INSERT. */ - else if( bReplace ){ - assert( pIter->op==SQLITE_INSERT ); + else if (bReplace) { + assert(pIter->op == SQLITE_INSERT); rc = sqlite3_exec(db, "SAVEPOINT replace_op", 0, 0, 0); - if( rc==SQLITE_OK ){ - rc = sessionBindRow(pIter, - sqlite3changeset_new, pApply->nCol, pApply->abPK, pApply->pDelete); - sqlite3_bind_int(pApply->pDelete, pApply->nCol+1, 1); + if (rc == SQLITE_OK) { + rc = sessionBindRow(pIter, sqlite3changeset_new, pApply->nCol, + pApply->abPK, pApply->pDelete); + sqlite3_bind_int(pApply->pDelete, pApply->nCol + 1, 1); } - if( rc==SQLITE_OK ){ + if (rc == SQLITE_OK) { sqlite3_step(pApply->pDelete); rc = sqlite3_reset(pApply->pDelete); } - if( rc==SQLITE_OK ){ + if (rc == SQLITE_OK) { rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0); } - if( rc==SQLITE_OK ){ + if (rc == SQLITE_OK) { rc = sqlite3_exec(db, "RELEASE replace_op", 0, 0, 0); } } @@ -4376,46 +4306,42 @@ static int sessionApplyOneWithRetry( ** Retry the changes accumulated in the pApply->constraints buffer. */ static int sessionRetryConstraints( - sqlite3 *db, - int bPatchset, - const char *zTab, - SessionApplyCtx *pApply, - int(*xConflict)(void*, int, sqlite3_changeset_iter*), - void *pCtx /* First argument passed to xConflict */ -){ + sqlite3 *db, int bPatchset, const char *zTab, SessionApplyCtx *pApply, + int (*xConflict)(void *, int, sqlite3_changeset_iter *), + void *pCtx /* First argument passed to xConflict */ +) { int rc = SQLITE_OK; - while( pApply->constraints.nBuf ){ + while (pApply->constraints.nBuf) { sqlite3_changeset_iter *pIter2 = 0; SessionBuffer cons = pApply->constraints; memset(&pApply->constraints, 0, sizeof(SessionBuffer)); - rc = sessionChangesetStart( - &pIter2, 0, 0, cons.nBuf, cons.aBuf, pApply->bInvertConstraints, 1 - ); - if( rc==SQLITE_OK ){ - size_t nByte = 2*pApply->nCol*sizeof(sqlite3_value*); + rc = sessionChangesetStart(&pIter2, 0, 0, cons.nBuf, cons.aBuf, + pApply->bInvertConstraints, 1); + if (rc == SQLITE_OK) { + size_t nByte = 2 * pApply->nCol * sizeof(sqlite3_value *); int rc2; pIter2->bPatchset = bPatchset; - pIter2->zTab = (char*)zTab; + pIter2->zTab = (char *)zTab; pIter2->nCol = pApply->nCol; pIter2->abPK = pApply->abPK; sessionBufferGrow(&pIter2->tblhdr, nByte, &rc); - pIter2->apValue = (sqlite3_value**)pIter2->tblhdr.aBuf; - if( rc==SQLITE_OK ) memset(pIter2->apValue, 0, nByte); + pIter2->apValue = (sqlite3_value **)pIter2->tblhdr.aBuf; + if (rc == SQLITE_OK) memset(pIter2->apValue, 0, nByte); - while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter2) ){ + while (rc == SQLITE_OK && SQLITE_ROW == sqlite3changeset_next(pIter2)) { rc = sessionApplyOneWithRetry(db, pIter2, pApply, xConflict, pCtx); } rc2 = sqlite3changeset_finalize(pIter2); - if( rc==SQLITE_OK ) rc = rc2; + if (rc == SQLITE_OK) rc = rc2; } - assert( pApply->bDeferConstraints || pApply->constraints.nBuf==0 ); + assert(pApply->bDeferConstraints || pApply->constraints.nBuf == 0); sqlite3_free(cons.aBuf); - if( rc!=SQLITE_OK ) break; - if( pApply->constraints.nBuf>=cons.nBuf ){ + if (rc != SQLITE_OK) break; + if (pApply->constraints.nBuf >= cons.nBuf) { /* No progress was made on the last round. */ pApply->bDeferConstraints = 0; } @@ -4426,64 +4352,62 @@ static int sessionRetryConstraints( /* ** Argument pIter is a changeset iterator that has been initialized, but -** not yet passed to sqlite3changeset_next(). This function applies the +** not yet passed to sqlite3changeset_next(). This function applies the ** changeset to the main database attached to handle "db". The supplied ** conflict handler callback is invoked to resolve any conflicts encountered ** while applying the change. */ static int sessionChangesetApply( - sqlite3 *db, /* Apply change to "main" db of this handle */ - sqlite3_changeset_iter *pIter, /* Changeset to apply */ - int(*xFilter)( - void *pCtx, /* Copy of sixth arg to _apply() */ - const char *zTab /* Table name */ - ), - int(*xConflict)( - void *pCtx, /* Copy of fifth arg to _apply() */ - int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ - sqlite3_changeset_iter *p /* Handle describing change and conflict */ - ), - void *pCtx, /* First argument passed to xConflict */ - void **ppRebase, int *pnRebase, /* OUT: Rebase information */ - int flags /* SESSION_APPLY_XXX flags */ -){ + sqlite3 *db, /* Apply change to "main" db of this handle */ + sqlite3_changeset_iter *pIter, /* Changeset to apply */ + int (*xFilter)(void *pCtx, /* Copy of sixth arg to _apply() */ + const char *zTab /* Table name */ + ), + int (*xConflict)( + void *pCtx, /* Copy of fifth arg to _apply() */ + int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ + sqlite3_changeset_iter *p /* Handle describing change and conflict */ + ), + void *pCtx, /* First argument passed to xConflict */ + void **ppRebase, int *pnRebase, /* OUT: Rebase information */ + int flags /* SESSION_APPLY_XXX flags */ +) { int schemaMismatch = 0; - int rc = SQLITE_OK; /* Return code */ - const char *zTab = 0; /* Name of current table */ - int nTab = 0; /* Result of sqlite3Strlen30(zTab) */ - SessionApplyCtx sApply; /* changeset_apply() context object */ + int rc = SQLITE_OK; /* Return code */ + const char *zTab = 0; /* Name of current table */ + int nTab = 0; /* Result of sqlite3Strlen30(zTab) */ + SessionApplyCtx sApply; /* changeset_apply() context object */ int bPatchset; - assert( xConflict!=0 ); + assert(xConflict != 0); pIter->in.bNoDiscard = 1; memset(&sApply, 0, sizeof(sApply)); sApply.bRebase = (ppRebase && pnRebase); sApply.bInvertConstraints = !!(flags & SQLITE_CHANGESETAPPLY_INVERT); sqlite3_mutex_enter(sqlite3_db_mutex(db)); - if( (flags & SQLITE_CHANGESETAPPLY_NOSAVEPOINT)==0 ){ + if ((flags & SQLITE_CHANGESETAPPLY_NOSAVEPOINT) == 0) { rc = sqlite3_exec(db, "SAVEPOINT changeset_apply", 0, 0, 0); } - if( rc==SQLITE_OK ){ + if (rc == SQLITE_OK) { rc = sqlite3_exec(db, "PRAGMA defer_foreign_keys = 1", 0, 0, 0); } - while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter) ){ + while (rc == SQLITE_OK && SQLITE_ROW == sqlite3changeset_next(pIter)) { int nCol; int op; const char *zNew; - + sqlite3changeset_op(pIter, &zNew, &nCol, &op, 0); - if( zTab==0 || sqlite3_strnicmp(zNew, zTab, nTab+1) ){ + if (zTab == 0 || sqlite3_strnicmp(zNew, zTab, nTab + 1)) { u8 *abPK; - rc = sessionRetryConstraints( - db, pIter->bPatchset, zTab, &sApply, xConflict, pCtx - ); - if( rc!=SQLITE_OK ) break; + rc = sessionRetryConstraints(db, pIter->bPatchset, zTab, &sApply, + xConflict, pCtx); + if (rc != SQLITE_OK) break; sessionUpdateFree(&sApply); - sqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */ + sqlite3_free((char *)sApply.azCol); /* cast works around VC++ bug */ sqlite3_finalize(sApply.pDelete); sqlite3_finalize(sApply.pInsert); sqlite3_finalize(sApply.pSelect); @@ -4499,63 +4423,57 @@ static int sessionChangesetApply( sApply.bRebaseStarted = 0; memset(&sApply.constraints, 0, sizeof(SessionBuffer)); - /* If an xFilter() callback was specified, invoke it now. If the + /* If an xFilter() callback was specified, invoke it now. If the ** xFilter callback returns zero, skip this table. If it returns ** non-zero, proceed. */ - schemaMismatch = (xFilter && (0==xFilter(pCtx, zNew))); - if( schemaMismatch ){ + schemaMismatch = (xFilter && (0 == xFilter(pCtx, zNew))); + if (schemaMismatch) { zTab = sqlite3_mprintf("%s", zNew); - if( zTab==0 ){ + if (zTab == 0) { rc = SQLITE_NOMEM; break; } nTab = (int)strlen(zTab); sApply.azCol = (const char **)zTab; - }else{ + } else { int nMinCol = 0; int i; sqlite3changeset_pk(pIter, &abPK, 0); - rc = sessionTableInfo(0, - db, "main", zNew, &sApply.nCol, &zTab, &sApply.azCol, &sApply.abPK - ); - if( rc!=SQLITE_OK ) break; - for(i=0; ibPatchset; - if( rc==SQLITE_OK ){ + if (rc == SQLITE_OK) { rc = sqlite3changeset_finalize(pIter); - }else{ + } else { sqlite3changeset_finalize(pIter); } - if( rc==SQLITE_OK ){ + if (rc == SQLITE_OK) { rc = sessionRetryConstraints(db, bPatchset, zTab, &sApply, xConflict, pCtx); } - if( rc==SQLITE_OK ){ + if (rc == SQLITE_OK) { int nFk, notUsed; sqlite3_db_status(db, SQLITE_DBSTATUS_DEFERRED_FKS, &nFk, ¬Used, 0); - if( nFk!=0 ){ + if (nFk != 0) { int res = SQLITE_CHANGESET_ABORT; sqlite3_changeset_iter sIter; memset(&sIter, 0, sizeof(sIter)); sIter.nCol = nFk; res = xConflict(pCtx, SQLITE_CHANGESET_FOREIGN_KEY, &sIter); - if( res!=SQLITE_CHANGESET_OMIT ){ + if (res != SQLITE_CHANGESET_OMIT) { rc = SQLITE_CONSTRAINT; } } } sqlite3_exec(db, "PRAGMA defer_foreign_keys = 0", 0, 0, 0); - if( (flags & SQLITE_CHANGESETAPPLY_NOSAVEPOINT)==0 ){ - if( rc==SQLITE_OK ){ + if ((flags & SQLITE_CHANGESETAPPLY_NOSAVEPOINT) == 0) { + if (rc == SQLITE_OK) { rc = sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0); - }else{ + } else { sqlite3_exec(db, "ROLLBACK TO changeset_apply", 0, 0, 0); sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0); } } - assert( sApply.bRebase || sApply.rebase.nBuf==0 ); - if( rc==SQLITE_OK && bPatchset==0 && sApply.bRebase ){ - *ppRebase = (void*)sApply.rebase.aBuf; + assert(sApply.bRebase || sApply.rebase.nBuf == 0); + if (rc == SQLITE_OK && bPatchset == 0 && sApply.bRebase) { + *ppRebase = (void *)sApply.rebase.aBuf; *pnRebase = sApply.rebase.nBuf; sApply.rebase.aBuf = 0; } @@ -4618,41 +4536,37 @@ static int sessionChangesetApply( sqlite3_finalize(sApply.pInsert); sqlite3_finalize(sApply.pDelete); sqlite3_finalize(sApply.pSelect); - sqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */ - sqlite3_free((char*)sApply.constraints.aBuf); - sqlite3_free((char*)sApply.rebase.aBuf); + sqlite3_free((char *)sApply.azCol); /* cast works around VC++ bug */ + sqlite3_free((char *)sApply.constraints.aBuf); + sqlite3_free((char *)sApply.rebase.aBuf); sqlite3_mutex_leave(sqlite3_db_mutex(db)); return rc; } /* -** Apply the changeset passed via pChangeset/nChangeset to the main +** Apply the changeset passed via pChangeset/nChangeset to the main ** database attached to handle "db". */ int sqlite3changeset_apply_v2( - sqlite3 *db, /* Apply change to "main" db of this handle */ - int nChangeset, /* Size of changeset in bytes */ - void *pChangeset, /* Changeset blob */ - int(*xFilter)( - void *pCtx, /* Copy of sixth arg to _apply() */ - const char *zTab /* Table name */ - ), - int(*xConflict)( - void *pCtx, /* Copy of sixth arg to _apply() */ - int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ - sqlite3_changeset_iter *p /* Handle describing change and conflict */ - ), - void *pCtx, /* First argument passed to xConflict */ - void **ppRebase, int *pnRebase, - int flags -){ - sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */ + sqlite3 *db, /* Apply change to "main" db of this handle */ + int nChangeset, /* Size of changeset in bytes */ + void *pChangeset, /* Changeset blob */ + int (*xFilter)(void *pCtx, /* Copy of sixth arg to _apply() */ + const char *zTab /* Table name */ + ), + int (*xConflict)( + void *pCtx, /* Copy of sixth arg to _apply() */ + int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ + sqlite3_changeset_iter *p /* Handle describing change and conflict */ + ), + void *pCtx, /* First argument passed to xConflict */ + void **ppRebase, int *pnRebase, int flags) { + sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */ int bInv = !!(flags & SQLITE_CHANGESETAPPLY_INVERT); int rc = sessionChangesetStart(&pIter, 0, 0, nChangeset, pChangeset, bInv, 1); - if( rc==SQLITE_OK ){ - rc = sessionChangesetApply( - db, pIter, xFilter, xConflict, pCtx, ppRebase, pnRebase, flags - ); + if (rc == SQLITE_OK) { + rc = sessionChangesetApply(db, pIter, xFilter, xConflict, pCtx, ppRebase, + pnRebase, flags); } return rc; } @@ -4663,23 +4577,21 @@ int sqlite3changeset_apply_v2( ** to resolve any conflicts encountered while applying the change. */ int sqlite3changeset_apply( - sqlite3 *db, /* Apply change to "main" db of this handle */ - int nChangeset, /* Size of changeset in bytes */ - void *pChangeset, /* Changeset blob */ - int(*xFilter)( - void *pCtx, /* Copy of sixth arg to _apply() */ - const char *zTab /* Table name */ - ), - int(*xConflict)( - void *pCtx, /* Copy of fifth arg to _apply() */ - int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ - sqlite3_changeset_iter *p /* Handle describing change and conflict */ - ), - void *pCtx /* First argument passed to xConflict */ -){ - return sqlite3changeset_apply_v2( - db, nChangeset, pChangeset, xFilter, xConflict, pCtx, 0, 0, 0 - ); + sqlite3 *db, /* Apply change to "main" db of this handle */ + int nChangeset, /* Size of changeset in bytes */ + void *pChangeset, /* Changeset blob */ + int (*xFilter)(void *pCtx, /* Copy of sixth arg to _apply() */ + const char *zTab /* Table name */ + ), + int (*xConflict)( + void *pCtx, /* Copy of fifth arg to _apply() */ + int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ + sqlite3_changeset_iter *p /* Handle describing change and conflict */ + ), + void *pCtx /* First argument passed to xConflict */ +) { + return sqlite3changeset_apply_v2(db, nChangeset, pChangeset, xFilter, + xConflict, pCtx, 0, 0, 0); } /* @@ -4688,59 +4600,53 @@ int sqlite3changeset_apply( ** to resolve any conflicts encountered while applying the change. */ int sqlite3changeset_apply_v2_strm( - sqlite3 *db, /* Apply change to "main" db of this handle */ - int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */ - void *pIn, /* First arg for xInput */ - int(*xFilter)( - void *pCtx, /* Copy of sixth arg to _apply() */ - const char *zTab /* Table name */ - ), - int(*xConflict)( - void *pCtx, /* Copy of sixth arg to _apply() */ - int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ - sqlite3_changeset_iter *p /* Handle describing change and conflict */ - ), - void *pCtx, /* First argument passed to xConflict */ - void **ppRebase, int *pnRebase, - int flags -){ - sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */ + sqlite3 *db, /* Apply change to "main" db of this handle */ + int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */ + void *pIn, /* First arg for xInput */ + int (*xFilter)(void *pCtx, /* Copy of sixth arg to _apply() */ + const char *zTab /* Table name */ + ), + int (*xConflict)( + void *pCtx, /* Copy of sixth arg to _apply() */ + int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ + sqlite3_changeset_iter *p /* Handle describing change and conflict */ + ), + void *pCtx, /* First argument passed to xConflict */ + void **ppRebase, int *pnRebase, int flags) { + sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */ int bInverse = !!(flags & SQLITE_CHANGESETAPPLY_INVERT); int rc = sessionChangesetStart(&pIter, xInput, pIn, 0, 0, bInverse, 1); - if( rc==SQLITE_OK ){ - rc = sessionChangesetApply( - db, pIter, xFilter, xConflict, pCtx, ppRebase, pnRebase, flags - ); + if (rc == SQLITE_OK) { + rc = sessionChangesetApply(db, pIter, xFilter, xConflict, pCtx, ppRebase, + pnRebase, flags); } return rc; } int sqlite3changeset_apply_strm( - sqlite3 *db, /* Apply change to "main" db of this handle */ - int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */ - void *pIn, /* First arg for xInput */ - int(*xFilter)( - void *pCtx, /* Copy of sixth arg to _apply() */ - const char *zTab /* Table name */ - ), - int(*xConflict)( - void *pCtx, /* Copy of sixth arg to _apply() */ - int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ - sqlite3_changeset_iter *p /* Handle describing change and conflict */ - ), - void *pCtx /* First argument passed to xConflict */ -){ - return sqlite3changeset_apply_v2_strm( - db, xInput, pIn, xFilter, xConflict, pCtx, 0, 0, 0 - ); + sqlite3 *db, /* Apply change to "main" db of this handle */ + int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */ + void *pIn, /* First arg for xInput */ + int (*xFilter)(void *pCtx, /* Copy of sixth arg to _apply() */ + const char *zTab /* Table name */ + ), + int (*xConflict)( + void *pCtx, /* Copy of sixth arg to _apply() */ + int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ + sqlite3_changeset_iter *p /* Handle describing change and conflict */ + ), + void *pCtx /* First argument passed to xConflict */ +) { + return sqlite3changeset_apply_v2_strm(db, xInput, pIn, xFilter, xConflict, + pCtx, 0, 0, 0); } /* ** sqlite3_changegroup handle. */ struct sqlite3_changegroup { - int rc; /* Error code */ - int bPatch; /* True to accumulate patchsets */ - SessionTable *pList; /* List of tables in current patch */ + int rc; /* Error code */ + int bPatch; /* True to accumulate patchsets */ + SessionTable *pList; /* List of tables in current patch */ }; /* @@ -4749,42 +4655,42 @@ struct sqlite3_changegroup { ** allocated and a pointer to it stored in *ppNew. */ static int sessionChangeMerge( - SessionTable *pTab, /* Table structure */ - int bRebase, /* True for a rebase hash-table */ - int bPatchset, /* True for patchsets */ - SessionChange *pExist, /* Existing change */ - int op2, /* Second change operation */ - int bIndirect, /* True if second change is indirect */ - u8 *aRec, /* Second change record */ - int nRec, /* Number of bytes in aRec */ - SessionChange **ppNew /* OUT: Merged change */ -){ + SessionTable *pTab, /* Table structure */ + int bRebase, /* True for a rebase hash-table */ + int bPatchset, /* True for patchsets */ + SessionChange *pExist, /* Existing change */ + int op2, /* Second change operation */ + int bIndirect, /* True if second change is indirect */ + u8 *aRec, /* Second change record */ + int nRec, /* Number of bytes in aRec */ + SessionChange **ppNew /* OUT: Merged change */ +) { SessionChange *pNew = 0; int rc = SQLITE_OK; - if( !pExist ){ + if (!pExist) { pNew = (SessionChange *)sqlite3_malloc64(sizeof(SessionChange) + nRec); - if( !pNew ){ + if (!pNew) { return SQLITE_NOMEM; } memset(pNew, 0, sizeof(SessionChange)); pNew->op = op2; pNew->bIndirect = bIndirect; - pNew->aRecord = (u8*)&pNew[1]; - if( bIndirect==0 || bRebase==0 ){ + pNew->aRecord = (u8 *)&pNew[1]; + if (bIndirect == 0 || bRebase == 0) { pNew->nRecord = nRec; memcpy(pNew->aRecord, aRec, nRec); - }else{ + } else { int i; u8 *pIn = aRec; u8 *pOut = pNew->aRecord; - for(i=0; inCol; i++){ + for (i = 0; i < pTab->nCol; i++) { int nIn = sessionSerialLen(pIn); - if( *pIn==0 ){ + if (*pIn == 0) { *pOut++ = 0; - }else if( pTab->abPK[i]==0 ){ + } else if (pTab->abPK[i] == 0) { *pOut++ = 0xFF; - }else{ + } else { memcpy(pOut, pIn, nIn); pOut += nIn; } @@ -4792,15 +4698,15 @@ static int sessionChangeMerge( } pNew->nRecord = pOut - pNew->aRecord; } - }else if( bRebase ){ - if( pExist->op==SQLITE_DELETE && pExist->bIndirect ){ + } else if (bRebase) { + if (pExist->op == SQLITE_DELETE && pExist->bIndirect) { *ppNew = pExist; - }else{ + } else { sqlite3_int64 nByte = nRec + pExist->nRecord + sizeof(SessionChange); - pNew = (SessionChange*)sqlite3_malloc64(nByte); - if( pNew==0 ){ + pNew = (SessionChange *)sqlite3_malloc64(nByte); + if (pNew == 0) { rc = SQLITE_NOMEM; - }else{ + } else { int i; u8 *a1 = pExist->aRecord; u8 *a2 = aRec; @@ -4809,17 +4715,17 @@ static int sessionChangeMerge( memset(pNew, 0, nByte); pNew->bIndirect = bIndirect || pExist->bIndirect; pNew->op = op2; - pOut = pNew->aRecord = (u8*)&pNew[1]; + pOut = pNew->aRecord = (u8 *)&pNew[1]; - for(i=0; inCol; i++){ + for (i = 0; i < pTab->nCol; i++) { int n1 = sessionSerialLen(a1); int n2 = sessionSerialLen(a2); - if( *a1==0xFF || (pTab->abPK[i]==0 && bIndirect) ){ + if (*a1 == 0xFF || (pTab->abPK[i] == 0 && bIndirect)) { *pOut++ = 0xFF; - }else if( *a2==0 ){ + } else if (*a2 == 0) { memcpy(pOut, a1, n1); pOut += n1; - }else{ + } else { memcpy(pOut, a2, n2); pOut += n2; } @@ -4830,10 +4736,10 @@ static int sessionChangeMerge( } sqlite3_free(pExist); } - }else{ + } else { int op1 = pExist->op; - /* + /* ** op1=INSERT, op2=INSERT -> Unsupported. Discard op2. ** op1=INSERT, op2=UPDATE -> INSERT. ** op1=INSERT, op2=DELETE -> (none) @@ -4845,17 +4751,16 @@ static int sessionChangeMerge( ** op1=DELETE, op2=INSERT -> UPDATE. ** op1=DELETE, op2=UPDATE -> Unsupported. Discard op2. ** op1=DELETE, op2=DELETE -> Unsupported. Discard op2. - */ - if( (op1==SQLITE_INSERT && op2==SQLITE_INSERT) - || (op1==SQLITE_UPDATE && op2==SQLITE_INSERT) - || (op1==SQLITE_DELETE && op2==SQLITE_UPDATE) - || (op1==SQLITE_DELETE && op2==SQLITE_DELETE) - ){ + */ + if ((op1 == SQLITE_INSERT && op2 == SQLITE_INSERT) || + (op1 == SQLITE_UPDATE && op2 == SQLITE_INSERT) || + (op1 == SQLITE_DELETE && op2 == SQLITE_UPDATE) || + (op1 == SQLITE_DELETE && op2 == SQLITE_DELETE)) { pNew = pExist; - }else if( op1==SQLITE_INSERT && op2==SQLITE_DELETE ){ + } else if (op1 == SQLITE_INSERT && op2 == SQLITE_DELETE) { sqlite3_free(pExist); - assert( pNew==0 ); - }else{ + assert(pNew == 0); + } else { u8 *aExist = pExist->aRecord; sqlite3_int64 nByte; u8 *aCsr; @@ -4865,7 +4770,7 @@ static int sessionChangeMerge( ** may be generated by combining the input records. */ nByte = sizeof(SessionChange) + pExist->nRecord + nRec; pNew = (SessionChange *)sqlite3_malloc64(nByte); - if( !pNew ){ + if (!pNew) { sqlite3_free(pExist); return SQLITE_NOMEM; } @@ -4873,49 +4778,51 @@ static int sessionChangeMerge( pNew->bIndirect = (bIndirect && pExist->bIndirect); aCsr = pNew->aRecord = (u8 *)&pNew[1]; - if( op1==SQLITE_INSERT ){ /* INSERT + UPDATE */ + if (op1 == SQLITE_INSERT) { /* INSERT + UPDATE */ u8 *a1 = aRec; - assert( op2==SQLITE_UPDATE ); + assert(op2 == SQLITE_UPDATE); pNew->op = SQLITE_INSERT; - if( bPatchset==0 ) sessionSkipRecord(&a1, pTab->nCol); + if (bPatchset == 0) sessionSkipRecord(&a1, pTab->nCol); sessionMergeRecord(&aCsr, pTab->nCol, aExist, a1); - }else if( op1==SQLITE_DELETE ){ /* DELETE + INSERT */ - assert( op2==SQLITE_INSERT ); + } else if (op1 == SQLITE_DELETE) { /* DELETE + INSERT */ + assert(op2 == SQLITE_INSERT); pNew->op = SQLITE_UPDATE; - if( bPatchset ){ + if (bPatchset) { memcpy(aCsr, aRec, nRec); aCsr += nRec; - }else{ - if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aExist, 0,aRec,0) ){ + } else { + if (0 == + sessionMergeUpdate(&aCsr, pTab, bPatchset, aExist, 0, aRec, 0)) { sqlite3_free(pNew); pNew = 0; } } - }else if( op2==SQLITE_UPDATE ){ /* UPDATE + UPDATE */ + } else if (op2 == SQLITE_UPDATE) { /* UPDATE + UPDATE */ u8 *a1 = aExist; u8 *a2 = aRec; - assert( op1==SQLITE_UPDATE ); - if( bPatchset==0 ){ + assert(op1 == SQLITE_UPDATE); + if (bPatchset == 0) { sessionSkipRecord(&a1, pTab->nCol); sessionSkipRecord(&a2, pTab->nCol); } pNew->op = SQLITE_UPDATE; - if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aRec, aExist,a1,a2) ){ + if (0 == + sessionMergeUpdate(&aCsr, pTab, bPatchset, aRec, aExist, a1, a2)) { sqlite3_free(pNew); pNew = 0; } - }else{ /* UPDATE + DELETE */ - assert( op1==SQLITE_UPDATE && op2==SQLITE_DELETE ); + } else { /* UPDATE + DELETE */ + assert(op1 == SQLITE_UPDATE && op2 == SQLITE_DELETE); pNew->op = SQLITE_DELETE; - if( bPatchset ){ + if (bPatchset) { memcpy(aCsr, aRec, nRec); aCsr += nRec; - }else{ + } else { sessionMergeRecord(&aCsr, pTab->nCol, aRec, aExist); } } - if( pNew ){ + if (pNew) { pNew->nRecord = (int)(aCsr - pNew->aRecord); } sqlite3_free(pExist); @@ -4931,16 +4838,16 @@ static int sessionChangeMerge( ** the first argument to the changegroup hash tables. */ static int sessionChangesetToHash( - sqlite3_changeset_iter *pIter, /* Iterator to read from */ - sqlite3_changegroup *pGrp, /* Changegroup object to add changeset to */ - int bRebase /* True if hash table is for rebasing */ -){ + sqlite3_changeset_iter *pIter, /* Iterator to read from */ + sqlite3_changegroup *pGrp, /* Changegroup object to add changeset to */ + int bRebase /* True if hash table is for rebasing */ +) { u8 *aRec; int nRec; int rc = SQLITE_OK; SessionTable *pTab = 0; - while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec, 0) ){ + while (SQLITE_ROW == sessionChangesetNext(pIter, &aRec, &nRec, 0)) { const char *zNew; int nCol; int op; @@ -4950,69 +4857,69 @@ static int sessionChangesetToHash( SessionChange *pExist = 0; SessionChange **pp; - if( pGrp->pList==0 ){ + if (pGrp->pList == 0) { pGrp->bPatch = pIter->bPatchset; - }else if( pIter->bPatchset!=pGrp->bPatch ){ + } else if (pIter->bPatchset != pGrp->bPatch) { rc = SQLITE_ERROR; break; } sqlite3changeset_op(pIter, &zNew, &nCol, &op, &bIndirect); - if( !pTab || sqlite3_stricmp(zNew, pTab->zName) ){ + if (!pTab || sqlite3_stricmp(zNew, pTab->zName)) { /* Search the list for a matching table */ int nNew = (int)strlen(zNew); u8 *abPK; sqlite3changeset_pk(pIter, &abPK, 0); - for(pTab = pGrp->pList; pTab; pTab=pTab->pNext){ - if( 0==sqlite3_strnicmp(pTab->zName, zNew, nNew+1) ) break; + for (pTab = pGrp->pList; pTab; pTab = pTab->pNext) { + if (0 == sqlite3_strnicmp(pTab->zName, zNew, nNew + 1)) break; } - if( !pTab ){ + if (!pTab) { SessionTable **ppTab; - pTab = sqlite3_malloc64(sizeof(SessionTable) + nCol + nNew+1); - if( !pTab ){ + pTab = sqlite3_malloc64(sizeof(SessionTable) + nCol + nNew + 1); + if (!pTab) { rc = SQLITE_NOMEM; break; } memset(pTab, 0, sizeof(SessionTable)); pTab->nCol = nCol; - pTab->abPK = (u8*)&pTab[1]; + pTab->abPK = (u8 *)&pTab[1]; memcpy(pTab->abPK, abPK, nCol); - pTab->zName = (char*)&pTab->abPK[nCol]; - memcpy(pTab->zName, zNew, nNew+1); + pTab->zName = (char *)&pTab->abPK[nCol]; + memcpy(pTab->zName, zNew, nNew + 1); /* The new object must be linked on to the end of the list, not ** simply added to the start of it. This is to ensure that the - ** tables within the output of sqlite3changegroup_output() are in + ** tables within the output of sqlite3changegroup_output() are in ** the right order. */ - for(ppTab=&pGrp->pList; *ppTab; ppTab=&(*ppTab)->pNext); + for (ppTab = &pGrp->pList; *ppTab; ppTab = &(*ppTab)->pNext) + ; *ppTab = pTab; - }else if( pTab->nCol!=nCol || memcmp(pTab->abPK, abPK, nCol) ){ + } else if (pTab->nCol != nCol || memcmp(pTab->abPK, abPK, nCol)) { rc = SQLITE_SCHEMA; break; } } - if( sessionGrowHash(0, pIter->bPatchset, pTab) ){ + if (sessionGrowHash(0, pIter->bPatchset, pTab)) { rc = SQLITE_NOMEM; break; } - iHash = sessionChangeHash( - pTab, (pIter->bPatchset && op==SQLITE_DELETE), aRec, pTab->nChange - ); + iHash = sessionChangeHash(pTab, (pIter->bPatchset && op == SQLITE_DELETE), + aRec, pTab->nChange); - /* Search for existing entry. If found, remove it from the hash table. + /* Search for existing entry. If found, remove it from the hash table. ** Code below may link it back in. */ - for(pp=&pTab->apChange[iHash]; *pp; pp=&(*pp)->pNext){ + for (pp = &pTab->apChange[iHash]; *pp; pp = &(*pp)->pNext) { int bPkOnly1 = 0; int bPkOnly2 = 0; - if( pIter->bPatchset ){ - bPkOnly1 = (*pp)->op==SQLITE_DELETE; - bPkOnly2 = op==SQLITE_DELETE; + if (pIter->bPatchset) { + bPkOnly1 = (*pp)->op == SQLITE_DELETE; + bPkOnly2 = op == SQLITE_DELETE; } - if( sessionChangeEqual(pTab, bPkOnly1, (*pp)->aRecord, bPkOnly2, aRec) ){ + if (sessionChangeEqual(pTab, bPkOnly1, (*pp)->aRecord, bPkOnly2, aRec)) { pExist = *pp; *pp = (*pp)->pNext; pTab->nEntry--; @@ -5020,18 +4927,17 @@ static int sessionChangesetToHash( } } - rc = sessionChangeMerge(pTab, bRebase, - pIter->bPatchset, pExist, op, bIndirect, aRec, nRec, &pChange - ); - if( rc ) break; - if( pChange ){ + rc = sessionChangeMerge(pTab, bRebase, pIter->bPatchset, pExist, op, + bIndirect, aRec, nRec, &pChange); + if (rc) break; + if (pChange) { pChange->pNext = pTab->apChange[iHash]; pTab->apChange[iHash] = pChange; pTab->nEntry++; } } - if( rc==SQLITE_OK ) rc = pIter->rc; + if (rc == SQLITE_OK) rc = pIter->rc; return rc; } @@ -5041,7 +4947,7 @@ static int sessionChangesetToHash( ** ** If xOutput is not NULL, then the changeset/patchset is returned to the ** user via one or more calls to xOutput, as with the other streaming -** interfaces. +** interfaces. ** ** Or, if xOutput is NULL, then (*ppOut) is populated with a pointer to a ** buffer containing the output changeset before this function returns. In @@ -5053,33 +4959,32 @@ static int sessionChangesetToHash( ** error code. If an error occurs and xOutput is NULL, (*ppOut) and (*pnOut) ** are both set to 0 before returning. */ -static int sessionChangegroupOutput( - sqlite3_changegroup *pGrp, - int (*xOutput)(void *pOut, const void *pData, int nData), - void *pOut, - int *pnOut, - void **ppOut -){ +static int sessionChangegroupOutput(sqlite3_changegroup *pGrp, + int (*xOutput)(void *pOut, + const void *pData, + int nData), + void *pOut, int *pnOut, void **ppOut) { int rc = SQLITE_OK; SessionBuffer buf = {0, 0, 0}; SessionTable *pTab; - assert( xOutput==0 || (ppOut==0 && pnOut==0) ); + assert(xOutput == 0 || (ppOut == 0 && pnOut == 0)); /* Create the serialized output changeset based on the contents of the - ** hash tables attached to the SessionTable objects in list p->pList. + ** hash tables attached to the SessionTable objects in list p->pList. */ - for(pTab=pGrp->pList; rc==SQLITE_OK && pTab; pTab=pTab->pNext){ + for (pTab = pGrp->pList; rc == SQLITE_OK && pTab; pTab = pTab->pNext) { int i; - if( pTab->nEntry==0 ) continue; + if (pTab->nEntry == 0) continue; sessionAppendTableHdr(&buf, pGrp->bPatch, pTab, &rc); - for(i=0; inChange; i++){ + for (i = 0; i < pTab->nChange; i++) { SessionChange *p; - for(p=pTab->apChange[i]; p; p=p->pNext){ + for (p = pTab->apChange[i]; p; p = p->pNext) { sessionAppendByte(&buf, p->op, &rc); sessionAppendByte(&buf, p->bIndirect, &rc); sessionAppendBlob(&buf, p->aRecord, p->nRecord, &rc); - if( rc==SQLITE_OK && xOutput && buf.nBuf>=sessions_strm_chunk_size ){ + if (rc == SQLITE_OK && xOutput && + buf.nBuf >= sessions_strm_chunk_size) { rc = xOutput(pOut, buf.aBuf, buf.nBuf); buf.nBuf = 0; } @@ -5087,10 +4992,10 @@ static int sessionChangegroupOutput( } } - if( rc==SQLITE_OK ){ - if( xOutput ){ - if( buf.nBuf>0 ) rc = xOutput(pOut, buf.aBuf, buf.nBuf); - }else{ + if (rc == SQLITE_OK) { + if (xOutput) { + if (buf.nBuf > 0) rc = xOutput(pOut, buf.aBuf, buf.nBuf); + } else { *ppOut = buf.aBuf; *pnOut = buf.nBuf; buf.aBuf = 0; @@ -5104,13 +5009,13 @@ static int sessionChangegroupOutput( /* ** Allocate a new, empty, sqlite3_changegroup. */ -int sqlite3changegroup_new(sqlite3_changegroup **pp){ - int rc = SQLITE_OK; /* Return code */ - sqlite3_changegroup *p; /* New object */ - p = (sqlite3_changegroup*)sqlite3_malloc(sizeof(sqlite3_changegroup)); - if( p==0 ){ +int sqlite3changegroup_new(sqlite3_changegroup **pp) { + int rc = SQLITE_OK; /* Return code */ + sqlite3_changegroup *p; /* New object */ + p = (sqlite3_changegroup *)sqlite3_malloc(sizeof(sqlite3_changegroup)); + if (p == 0) { rc = SQLITE_NOMEM; - }else{ + } else { memset(p, 0, sizeof(sqlite3_changegroup)); } *pp = p; @@ -5121,12 +5026,12 @@ int sqlite3changegroup_new(sqlite3_changegroup **pp){ ** Add the changeset currently stored in buffer pData, size nData bytes, ** to changeset-group p. */ -int sqlite3changegroup_add(sqlite3_changegroup *pGrp, int nData, void *pData){ - sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */ - int rc; /* Return code */ +int sqlite3changegroup_add(sqlite3_changegroup *pGrp, int nData, void *pData) { + sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */ + int rc; /* Return code */ rc = sqlite3changeset_start(&pIter, nData, pData); - if( rc==SQLITE_OK ){ + if (rc == SQLITE_OK) { rc = sessionChangesetToHash(pIter, pGrp, 0); } sqlite3changeset_finalize(pIter); @@ -5137,27 +5042,23 @@ int sqlite3changegroup_add(sqlite3_changegroup *pGrp, int nData, void *pData){ ** Obtain a buffer containing a changeset representing the concatenation ** of all changesets added to the group so far. */ -int sqlite3changegroup_output( - sqlite3_changegroup *pGrp, - int *pnData, - void **ppData -){ +int sqlite3changegroup_output(sqlite3_changegroup *pGrp, int *pnData, + void **ppData) { return sessionChangegroupOutput(pGrp, 0, 0, pnData, ppData); } /* ** Streaming versions of changegroup_add(). */ -int sqlite3changegroup_add_strm( - sqlite3_changegroup *pGrp, - int (*xInput)(void *pIn, void *pData, int *pnData), - void *pIn -){ - sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */ - int rc; /* Return code */ +int sqlite3changegroup_add_strm(sqlite3_changegroup *pGrp, + int (*xInput)(void *pIn, void *pData, + int *pnData), + void *pIn) { + sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */ + int rc; /* Return code */ rc = sqlite3changeset_start_strm(&pIter, xInput, pIn); - if( rc==SQLITE_OK ){ + if (rc == SQLITE_OK) { rc = sessionChangesetToHash(pIter, pGrp, 0); } sqlite3changeset_finalize(pIter); @@ -5167,46 +5068,45 @@ int sqlite3changegroup_add_strm( /* ** Streaming versions of changegroup_output(). */ -int sqlite3changegroup_output_strm( - sqlite3_changegroup *pGrp, - int (*xOutput)(void *pOut, const void *pData, int nData), - void *pOut -){ +int sqlite3changegroup_output_strm(sqlite3_changegroup *pGrp, + int (*xOutput)(void *pOut, const void *pData, + int nData), + void *pOut) { return sessionChangegroupOutput(pGrp, xOutput, pOut, 0, 0); } /* ** Delete a changegroup object. */ -void sqlite3changegroup_delete(sqlite3_changegroup *pGrp){ - if( pGrp ){ +void sqlite3changegroup_delete(sqlite3_changegroup *pGrp) { + if (pGrp) { sessionDeleteTable(0, pGrp->pList); sqlite3_free(pGrp); } } -/* +/* ** Combine two changesets together. */ int sqlite3changeset_concat( - int nLeft, /* Number of bytes in lhs input */ - void *pLeft, /* Lhs input changeset */ - int nRight /* Number of bytes in rhs input */, - void *pRight, /* Rhs input changeset */ - int *pnOut, /* OUT: Number of bytes in output changeset */ - void **ppOut /* OUT: changeset (left right) */ -){ + int nLeft, /* Number of bytes in lhs input */ + void *pLeft, /* Lhs input changeset */ + int nRight /* Number of bytes in rhs input */, + void *pRight, /* Rhs input changeset */ + int *pnOut, /* OUT: Number of bytes in output changeset */ + void **ppOut /* OUT: changeset (left right) */ +) { sqlite3_changegroup *pGrp; int rc; rc = sqlite3changegroup_new(&pGrp); - if( rc==SQLITE_OK ){ + if (rc == SQLITE_OK) { rc = sqlite3changegroup_add(pGrp, nLeft, pLeft); } - if( rc==SQLITE_OK ){ + if (rc == SQLITE_OK) { rc = sqlite3changegroup_add(pGrp, nRight, pRight); } - if( rc==SQLITE_OK ){ + if (rc == SQLITE_OK) { rc = sqlite3changegroup_output(pGrp, pnOut, ppOut); } sqlite3changegroup_delete(pGrp); @@ -5218,24 +5118,20 @@ int sqlite3changeset_concat( ** Streaming version of sqlite3changeset_concat(). */ int sqlite3changeset_concat_strm( - int (*xInputA)(void *pIn, void *pData, int *pnData), - void *pInA, - int (*xInputB)(void *pIn, void *pData, int *pnData), - void *pInB, - int (*xOutput)(void *pOut, const void *pData, int nData), - void *pOut -){ + int (*xInputA)(void *pIn, void *pData, int *pnData), void *pInA, + int (*xInputB)(void *pIn, void *pData, int *pnData), void *pInB, + int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut) { sqlite3_changegroup *pGrp; int rc; rc = sqlite3changegroup_new(&pGrp); - if( rc==SQLITE_OK ){ + if (rc == SQLITE_OK) { rc = sqlite3changegroup_add_strm(pGrp, xInputA, pInA); } - if( rc==SQLITE_OK ){ + if (rc == SQLITE_OK) { rc = sqlite3changegroup_add_strm(pGrp, xInputB, pInB); } - if( rc==SQLITE_OK ){ + if (rc == SQLITE_OK) { rc = sqlite3changegroup_output_strm(pGrp, xOutput, pOut); } sqlite3changegroup_delete(pGrp); @@ -5247,33 +5143,33 @@ int sqlite3changeset_concat_strm( ** Changeset rebaser handle. */ struct sqlite3_rebaser { - sqlite3_changegroup grp; /* Hash table */ + sqlite3_changegroup grp; /* Hash table */ }; /* ** Buffers a1 and a2 must both contain a sessions module record nCol -** fields in size. This function appends an nCol sessions module +** fields in size. This function appends an nCol sessions module ** record to buffer pBuf that is a copy of a1, except that for ** each field that is undefined in a1[], swap in the field from a2[]. */ static void sessionAppendRecordMerge( - SessionBuffer *pBuf, /* Buffer to append to */ - int nCol, /* Number of columns in each record */ - u8 *a1, int n1, /* Record 1 */ - u8 *a2, int n2, /* Record 2 */ - int *pRc /* IN/OUT: error code */ -){ - sessionBufferGrow(pBuf, n1+n2, pRc); - if( *pRc==SQLITE_OK ){ + SessionBuffer *pBuf, /* Buffer to append to */ + int nCol, /* Number of columns in each record */ + u8 *a1, int n1, /* Record 1 */ + u8 *a2, int n2, /* Record 2 */ + int *pRc /* IN/OUT: error code */ +) { + sessionBufferGrow(pBuf, n1 + n2, pRc); + if (*pRc == SQLITE_OK) { int i; u8 *pOut = &pBuf->aBuf[pBuf->nBuf]; - for(i=0; inBuf = pOut-pBuf->aBuf; - assert( pBuf->nBuf<=pBuf->nAlloc ); + pBuf->nBuf = pOut - pBuf->aBuf; + assert(pBuf->nBuf <= pBuf->nAlloc); } } /* -** This function is called when rebasing a local UPDATE change against one +** This function is called when rebasing a local UPDATE change against one ** or more remote UPDATE changes. The aRec/nRec buffer contains the current ** old.* and new.* records for the change. The rebase buffer (a single ** record) is in aChange/nChange. The rebased change is appended to buffer ** pBuf. ** -** Rebasing the UPDATE involves: +** Rebasing the UPDATE involves: ** ** * Removing any changes to fields for which the corresponding field ** in the rebase buffer is set to "replaced" (type 0xFF). If this ** means the UPDATE change updates no fields, nothing is appended ** to the output buffer. ** -** * For each field modified by the local change for which the +** * For each field modified by the local change for which the ** corresponding field in the rebase buffer is not "undefined" (0x00) ** or "replaced" (0xFF), the old.* value is replaced by the value ** in the rebase buffer. */ static void sessionAppendPartialUpdate( - SessionBuffer *pBuf, /* Append record here */ - sqlite3_changeset_iter *pIter, /* Iterator pointed at local change */ - u8 *aRec, int nRec, /* Local change */ - u8 *aChange, int nChange, /* Record to rebase against */ - int *pRc /* IN/OUT: Return Code */ -){ - sessionBufferGrow(pBuf, 2+nRec+nChange, pRc); - if( *pRc==SQLITE_OK ){ + SessionBuffer *pBuf, /* Append record here */ + sqlite3_changeset_iter *pIter, /* Iterator pointed at local change */ + u8 *aRec, int nRec, /* Local change */ + u8 *aChange, int nChange, /* Record to rebase against */ + int *pRc /* IN/OUT: Return Code */ +) { + sessionBufferGrow(pBuf, 2 + nRec + nChange, pRc); + if (*pRc == SQLITE_OK) { int bData = 0; u8 *pOut = &pBuf->aBuf[pBuf->nBuf]; int i; @@ -5322,32 +5218,32 @@ static void sessionAppendPartialUpdate( *pOut++ = SQLITE_UPDATE; *pOut++ = pIter->bIndirect; - for(i=0; inCol; i++){ + for (i = 0; i < pIter->nCol; i++) { int n1 = sessionSerialLen(a1); int n2 = sessionSerialLen(a2); - if( pIter->abPK[i] || a2[0]==0 ){ - if( !pIter->abPK[i] && a1[0] ) bData = 1; + if (pIter->abPK[i] || a2[0] == 0) { + if (!pIter->abPK[i] && a1[0]) bData = 1; memcpy(pOut, a1, n1); pOut += n1; - }else if( a2[0]!=0xFF ){ + } else if (a2[0] != 0xFF) { bData = 1; memcpy(pOut, a2, n2); pOut += n2; - }else{ + } else { *pOut++ = '\0'; } a1 += n1; a2 += n2; } - if( bData ){ + if (bData) { a2 = aChange; - for(i=0; inCol; i++){ + for (i = 0; i < pIter->nCol; i++) { int n1 = sessionSerialLen(a1); int n2 = sessionSerialLen(a2); - if( pIter->abPK[i] || a2[0]!=0xFF ){ + if (pIter->abPK[i] || a2[0] != 0xFF) { memcpy(pOut, a1, n1); pOut += n1; - }else{ + } else { *pOut++ = '\0'; } a1 += n1; @@ -5359,48 +5255,48 @@ static void sessionAppendPartialUpdate( } /* -** pIter is configured to iterate through a changeset. This function rebases -** that changeset according to the current configuration of the rebaser +** pIter is configured to iterate through a changeset. This function rebases +** that changeset according to the current configuration of the rebaser ** object passed as the first argument. If no error occurs and argument xOutput ** is not NULL, then the changeset is returned to the caller by invoking ** xOutput zero or more times and SQLITE_OK returned. Or, if xOutput is NULL, ** then (*ppOut) is set to point to a buffer containing the rebased changeset ** before this function returns. In this case (*pnOut) is set to the size of ** the buffer in bytes. It is the responsibility of the caller to eventually -** free the (*ppOut) buffer using sqlite3_free(). +** free the (*ppOut) buffer using sqlite3_free(). ** ** If an error occurs, an SQLite error code is returned. If ppOut and ** pnOut are not NULL, then the two output parameters are set to 0 before ** returning. */ static int sessionRebase( - sqlite3_rebaser *p, /* Rebaser hash table */ - sqlite3_changeset_iter *pIter, /* Input data */ - int (*xOutput)(void *pOut, const void *pData, int nData), - void *pOut, /* Context for xOutput callback */ - int *pnOut, /* OUT: Number of bytes in output changeset */ - void **ppOut /* OUT: Inverse of pChangeset */ -){ + sqlite3_rebaser *p, /* Rebaser hash table */ + sqlite3_changeset_iter *pIter, /* Input data */ + int (*xOutput)(void *pOut, const void *pData, int nData), + void *pOut, /* Context for xOutput callback */ + int *pnOut, /* OUT: Number of bytes in output changeset */ + void **ppOut /* OUT: Inverse of pChangeset */ +) { int rc = SQLITE_OK; u8 *aRec = 0; int nRec = 0; int bNew = 0; SessionTable *pTab = 0; - SessionBuffer sOut = {0,0,0}; + SessionBuffer sOut = {0, 0, 0}; - while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec, &bNew) ){ + while (SQLITE_ROW == sessionChangesetNext(pIter, &aRec, &nRec, &bNew)) { SessionChange *pChange = 0; int bDone = 0; - if( bNew ){ + if (bNew) { const char *zTab = pIter->zTab; - for(pTab=p->grp.pList; pTab; pTab=pTab->pNext){ - if( 0==sqlite3_stricmp(pTab->zName, zTab) ) break; + for (pTab = p->grp.pList; pTab; pTab = pTab->pNext) { + if (0 == sqlite3_stricmp(pTab->zName, zTab)) break; } bNew = 0; /* A patchset may not be rebased */ - if( pIter->bPatchset ){ + if (pIter->bPatchset) { rc = SQLITE_ERROR; } @@ -5408,26 +5304,27 @@ static int sessionRebase( sessionAppendByte(&sOut, pIter->bPatchset ? 'P' : 'T', &rc); sessionAppendVarint(&sOut, pIter->nCol, &rc); sessionAppendBlob(&sOut, pIter->abPK, pIter->nCol, &rc); - sessionAppendBlob(&sOut,(u8*)pIter->zTab,(int)strlen(pIter->zTab)+1,&rc); + sessionAppendBlob(&sOut, (u8 *)pIter->zTab, (int)strlen(pIter->zTab) + 1, + &rc); } - if( pTab && rc==SQLITE_OK ){ + if (pTab && rc == SQLITE_OK) { int iHash = sessionChangeHash(pTab, 0, aRec, pTab->nChange); - for(pChange=pTab->apChange[iHash]; pChange; pChange=pChange->pNext){ - if( sessionChangeEqual(pTab, 0, aRec, 0, pChange->aRecord) ){ + for (pChange = pTab->apChange[iHash]; pChange; pChange = pChange->pNext) { + if (sessionChangeEqual(pTab, 0, aRec, 0, pChange->aRecord)) { break; } } } - if( pChange ){ - assert( pChange->op==SQLITE_DELETE || pChange->op==SQLITE_INSERT ); - switch( pIter->op ){ + if (pChange) { + assert(pChange->op == SQLITE_DELETE || pChange->op == SQLITE_INSERT); + switch (pIter->op) { case SQLITE_INSERT: - if( pChange->op==SQLITE_INSERT ){ + if (pChange->op == SQLITE_INSERT) { bDone = 1; - if( pChange->bIndirect==0 ){ + if (pChange->bIndirect == 0) { sessionAppendByte(&sOut, SQLITE_UPDATE, &rc); sessionAppendByte(&sOut, pIter->bIndirect, &rc); sessionAppendBlob(&sOut, pChange->aRecord, pChange->nRecord, &rc); @@ -5438,62 +5335,59 @@ static int sessionRebase( case SQLITE_UPDATE: bDone = 1; - if( pChange->op==SQLITE_DELETE ){ - if( pChange->bIndirect==0 ){ + if (pChange->op == SQLITE_DELETE) { + if (pChange->bIndirect == 0) { u8 *pCsr = aRec; sessionSkipRecord(&pCsr, pIter->nCol); sessionAppendByte(&sOut, SQLITE_INSERT, &rc); sessionAppendByte(&sOut, pIter->bIndirect, &rc); - sessionAppendRecordMerge(&sOut, pIter->nCol, - pCsr, nRec-(pCsr-aRec), - pChange->aRecord, pChange->nRecord, &rc - ); + sessionAppendRecordMerge(&sOut, pIter->nCol, pCsr, + nRec - (pCsr - aRec), pChange->aRecord, + pChange->nRecord, &rc); } - }else{ - sessionAppendPartialUpdate(&sOut, pIter, - aRec, nRec, pChange->aRecord, pChange->nRecord, &rc - ); + } else { + sessionAppendPartialUpdate(&sOut, pIter, aRec, nRec, + pChange->aRecord, pChange->nRecord, &rc); } break; default: - assert( pIter->op==SQLITE_DELETE ); + assert(pIter->op == SQLITE_DELETE); bDone = 1; - if( pChange->op==SQLITE_INSERT ){ + if (pChange->op == SQLITE_INSERT) { sessionAppendByte(&sOut, SQLITE_DELETE, &rc); sessionAppendByte(&sOut, pIter->bIndirect, &rc); - sessionAppendRecordMerge(&sOut, pIter->nCol, - pChange->aRecord, pChange->nRecord, aRec, nRec, &rc - ); + sessionAppendRecordMerge(&sOut, pIter->nCol, pChange->aRecord, + pChange->nRecord, aRec, nRec, &rc); } break; } } - if( bDone==0 ){ + if (bDone == 0) { sessionAppendByte(&sOut, pIter->op, &rc); sessionAppendByte(&sOut, pIter->bIndirect, &rc); sessionAppendBlob(&sOut, aRec, nRec, &rc); } - if( rc==SQLITE_OK && xOutput && sOut.nBuf>sessions_strm_chunk_size ){ + if (rc == SQLITE_OK && xOutput && sOut.nBuf > sessions_strm_chunk_size) { rc = xOutput(pOut, sOut.aBuf, sOut.nBuf); sOut.nBuf = 0; } - if( rc ) break; + if (rc) break; } - if( rc!=SQLITE_OK ){ + if (rc != SQLITE_OK) { sqlite3_free(sOut.aBuf); memset(&sOut, 0, sizeof(sOut)); } - if( rc==SQLITE_OK ){ - if( xOutput ){ - if( sOut.nBuf>0 ){ + if (rc == SQLITE_OK) { + if (xOutput) { + if (sOut.nBuf > 0) { rc = xOutput(pOut, sOut.aBuf, sOut.nBuf); } - }else{ - *ppOut = (void*)sOut.aBuf; + } else { + *ppOut = (void *)sOut.aBuf; *pnOut = sOut.nBuf; sOut.aBuf = 0; } @@ -5502,52 +5396,47 @@ static int sessionRebase( return rc; } -/* +/* ** Create a new rebaser object. */ -int sqlite3rebaser_create(sqlite3_rebaser **ppNew){ +int sqlite3rebaser_create(sqlite3_rebaser **ppNew) { int rc = SQLITE_OK; sqlite3_rebaser *pNew; pNew = sqlite3_malloc(sizeof(sqlite3_rebaser)); - if( pNew==0 ){ + if (pNew == 0) { rc = SQLITE_NOMEM; - }else{ + } else { memset(pNew, 0, sizeof(sqlite3_rebaser)); } *ppNew = pNew; return rc; } -/* +/* ** Call this one or more times to configure a rebaser. */ -int sqlite3rebaser_configure( - sqlite3_rebaser *p, - int nRebase, const void *pRebase -){ - sqlite3_changeset_iter *pIter = 0; /* Iterator opened on pData/nData */ - int rc; /* Return code */ - rc = sqlite3changeset_start(&pIter, nRebase, (void*)pRebase); - if( rc==SQLITE_OK ){ +int sqlite3rebaser_configure(sqlite3_rebaser *p, int nRebase, + const void *pRebase) { + sqlite3_changeset_iter *pIter = 0; /* Iterator opened on pData/nData */ + int rc; /* Return code */ + rc = sqlite3changeset_start(&pIter, nRebase, (void *)pRebase); + if (rc == SQLITE_OK) { rc = sessionChangesetToHash(pIter, &p->grp, 1); } sqlite3changeset_finalize(pIter); return rc; } -/* -** Rebase a changeset according to current rebaser configuration +/* +** Rebase a changeset according to current rebaser configuration */ -int sqlite3rebaser_rebase( - sqlite3_rebaser *p, - int nIn, const void *pIn, - int *pnOut, void **ppOut -){ - sqlite3_changeset_iter *pIter = 0; /* Iterator to skip through input */ - int rc = sqlite3changeset_start(&pIter, nIn, (void*)pIn); +int sqlite3rebaser_rebase(sqlite3_rebaser *p, int nIn, const void *pIn, + int *pnOut, void **ppOut) { + sqlite3_changeset_iter *pIter = 0; /* Iterator to skip through input */ + int rc = sqlite3changeset_start(&pIter, nIn, (void *)pIn); - if( rc==SQLITE_OK ){ + if (rc == SQLITE_OK) { rc = sessionRebase(p, pIter, 0, 0, pnOut, ppOut); sqlite3changeset_finalize(pIter); } @@ -5555,20 +5444,17 @@ int sqlite3rebaser_rebase( return rc; } -/* -** Rebase a changeset according to current rebaser configuration +/* +** Rebase a changeset according to current rebaser configuration */ int sqlite3rebaser_rebase_strm( - sqlite3_rebaser *p, - int (*xInput)(void *pIn, void *pData, int *pnData), - void *pIn, - int (*xOutput)(void *pOut, const void *pData, int nData), - void *pOut -){ - sqlite3_changeset_iter *pIter = 0; /* Iterator to skip through input */ + sqlite3_rebaser *p, int (*xInput)(void *pIn, void *pData, int *pnData), + void *pIn, int (*xOutput)(void *pOut, const void *pData, int nData), + void *pOut) { + sqlite3_changeset_iter *pIter = 0; /* Iterator to skip through input */ int rc = sqlite3changeset_start_strm(&pIter, xInput, pIn); - if( rc==SQLITE_OK ){ + if (rc == SQLITE_OK) { rc = sessionRebase(p, pIter, xOutput, pOut, 0, 0); sqlite3changeset_finalize(pIter); } @@ -5576,25 +5462,25 @@ int sqlite3rebaser_rebase_strm( return rc; } -/* -** Destroy a rebaser object +/* +** Destroy a rebaser object */ -void sqlite3rebaser_delete(sqlite3_rebaser *p){ - if( p ){ +void sqlite3rebaser_delete(sqlite3_rebaser *p) { + if (p) { sessionDeleteTable(0, p->grp.pList); sqlite3_free(p); } } -/* +/* ** Global configuration */ -int sqlite3session_config(int op, void *pArg){ +int sqlite3session_config(int op, void *pArg) { int rc = SQLITE_OK; - switch( op ){ + switch (op) { case SQLITE_SESSION_CONFIG_STRMSIZE: { - int *pInt = (int*)pArg; - if( *pInt>0 ){ + int *pInt = (int *)pArg; + if (*pInt > 0) { sessions_strm_chunk_size = *pInt; } *pInt = sessions_strm_chunk_size; diff --git a/third_party/sqlite3/sqlite3session.h b/third_party/sqlite3/sqlite3session.h index 9ebf360e..0e148dfd 100644 --- a/third_party/sqlite3/sqlite3session.h +++ b/third_party/sqlite3/sqlite3session.h @@ -1,6 +1,7 @@ #if !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) #define __SQLITESESSION_H_ 1 +/* clang-format off */ /* ** Make sure we can call this stuff from C++. @@ -9,7 +10,7 @@ extern "C" { #endif -#include "sqlite3.h" +#include "third_party/sqlite3/sqlite3.h" /* ** CAPI3REF: Session Object Handle diff --git a/third_party/sqlite3/sqlite3userauth.h b/third_party/sqlite3/sqlite3userauth.h index c7d23b93..a05e6fc8 100644 --- a/third_party/sqlite3/sqlite3userauth.h +++ b/third_party/sqlite3/sqlite3userauth.h @@ -20,6 +20,7 @@ ** additional information. */ #ifdef SQLITE_USER_AUTHENTICATION +/* clang-format off */ #ifdef __cplusplus extern "C" { diff --git a/third_party/sqlite3/sqliteInt.h b/third_party/sqlite3/sqliteInt.h index 799ed6ab..c7b2b0f7 100644 --- a/third_party/sqlite3/sqliteInt.h +++ b/third_party/sqlite3/sqliteInt.h @@ -14,6 +14,7 @@ */ #ifndef SQLITEINT_H #define SQLITEINT_H +/* clang-format off */ /* Special Comments: ** @@ -56,12 +57,12 @@ ** compiler warnings due to subsequent content in this file and other files ** that are included by this file. */ -#include "msvc.h" +#include "third_party/sqlite3/msvc.h" /* ** Special setup for VxWorks */ -#include "vxworks.h" +#include "third_party/sqlite3/vxworks.h" /* ** These #defines should enable >2GB file support on POSIX if the @@ -164,9 +165,9 @@ ** disabled. */ #if defined(_HAVE_MINGW_H) -# include "mingw.h" +#include "third_party/sqlite3/mingw.h" #elif defined(_HAVE__MINGW_H) -# include "_mingw.h" +#include "third_party/sqlite3/_mingw.h" #endif /* @@ -185,18 +186,18 @@ ** first in QNX. Also, the _USE_32BIT_TIME_T macro must appear first for ** MinGW. */ -#include "sqlite3.h" +#include "third_party/sqlite3/sqlite3.h" /* ** Include the configuration header output by 'configure' if we're using the ** autoconf-based build */ #if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H) -#include "config.h" +#include "third_party/sqlite3/config.h" #define SQLITECONFIG_H 1 #endif -#include "sqliteLimit.h" +#include "third_party/sqlite3/sqliteLimit.h" /* Disable nuisance warnings on Borland compilers */ #if defined(__BORLANDC__) @@ -227,10 +228,10 @@ ** Include standard header files as necessary */ #ifdef HAVE_STDINT_H -#include +#include "libc/calls/weirdtypes.h" #endif #ifdef HAVE_INTTYPES_H -#include +#include "libc/calls/weirdtypes.h" #endif /* @@ -268,9 +269,9 @@ ** inlined. */ #if defined(__GNUC__) -# define SQLITE_NOINLINE __attribute__((noinline)) -#elif defined(_MSC_VER) && _MSC_VER>=1310 -# define SQLITE_NOINLINE __declspec(noinline) +#define SQLITE_NOINLINE __attribute__((__noinline__)) +#elif defined(_MSC_VER) && _MSC_VER >= 1310 +#define SQLITE_NOINLINE __declspec(noinline) #else # define SQLITE_NOINLINE #endif @@ -583,13 +584,12 @@ #define likely(X) (X) #define unlikely(X) (X) -#include "hash.h" -#include "parse.h" -#include -#include -#include -#include -#include +#include "libc/assert.h" +#include "libc/mem/mem.h" +#include "libc/stdio/stdio.h" +#include "libc/str/str.h" +#include "third_party/sqlite3/hash.h" +#include "third_party/sqlite3/parse.h" /* ** Use a macro to replace memcpy() if compiled with SQLITE_INLINE_MEMCPY. @@ -1220,18 +1220,19 @@ typedef struct With With; ** just an array of integers. */ typedef int VList; +typedef u32 Pgno; /* ** Defer sourcing vdbe.h and btree.h until after the "u8" and ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque ** pointer types (i.e. FuncDef) defined above. */ -#include "pager.h" -#include "btree.h" -#include "vdbe.h" -#include "pcache.h" -#include "os.h" -#include "mutex.h" +#include "third_party/sqlite3/btree.h" +#include "third_party/sqlite3/mutex.h" +#include "third_party/sqlite3/os.h" +#include "third_party/sqlite3/pager.h" +#include "third_party/sqlite3/pcache.h" +#include "third_party/sqlite3/vdbe.h" /* The SQLITE_EXTRA_DURABLE compile-time option used to set the default ** synchronous setting to EXTRA. It is no longer supported. @@ -4097,7 +4098,7 @@ int sqlite3CantopenError(int); */ #if !defined(SQLITE_ASCII) || \ (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION)) -# include +#include "libc/str/str.h" #endif /* diff --git a/third_party/sqlite3/sqliteLimit.h b/third_party/sqlite3/sqliteLimit.h index 08703cb7..c7744509 100644 --- a/third_party/sqlite3/sqliteLimit.h +++ b/third_party/sqlite3/sqliteLimit.h @@ -9,9 +9,10 @@ ** May you share freely, never taking more than you give. ** ************************************************************************* -** +** ** This file defines various limits of what SQLite can process. */ +/* clang-format off */ /* ** The maximum length of a TEXT or BLOB in bytes. This also diff --git a/third_party/sqlite3/sqliteicu.h b/third_party/sqlite3/sqliteicu.h index 24a4d623..337f4852 100644 --- a/third_party/sqlite3/sqliteicu.h +++ b/third_party/sqlite3/sqliteicu.h @@ -13,7 +13,8 @@ ** This header file is used by programs that want to link against the ** ICU extension. All it does is declare the sqlite3IcuInit() interface. */ -#include "sqlite3.h" +#include "third_party/sqlite3/sqlite3.h" +/* clang-format off */ #ifdef __cplusplus extern "C" { diff --git a/third_party/sqlite3/status.c b/third_party/sqlite3/status.c index f0e307c2..b78ef041 100644 --- a/third_party/sqlite3/status.c +++ b/third_party/sqlite3/status.c @@ -13,8 +13,9 @@ ** This module implements the sqlite3_status() interface and related ** functionality. */ -#include "sqliteInt.h" -#include "vdbeInt.h" +#include "third_party/sqlite3/sqliteInt.h" +#include "third_party/sqlite3/vdbeInt.h" +/* clang-format off */ /* ** Variables in which to record status information. diff --git a/third_party/sqlite3/stmt.c b/third_party/sqlite3/stmt.c index 876b0e5c..b0a73c67 100644 --- a/third_party/sqlite3/stmt.c +++ b/third_party/sqlite3/stmt.c @@ -22,11 +22,12 @@ */ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_STMTVTAB) #if !defined(SQLITEINT_H) -#include "sqlite3ext.h" +#include "third_party/sqlite3/sqlite3ext.h" #endif SQLITE_EXTENSION_INIT1 -#include -#include +#include "libc/assert.h" +#include "libc/str/str.h" +/* clang-format off */ #ifndef SQLITE_OMIT_VIRTUALTABLE diff --git a/third_party/sqlite3/table.c b/third_party/sqlite3/table.c index db60a827..6289a168 100644 --- a/third_party/sqlite3/table.c +++ b/third_party/sqlite3/table.c @@ -16,7 +16,8 @@ ** These routines are in a separate files so that they will not be linked ** if they are not used. */ -#include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" +/* clang-format off */ #ifndef SQLITE_OMIT_GET_TABLE diff --git a/third_party/sqlite3/tclsqlite.c b/third_party/sqlite3/tclsqlite.c deleted file mode 100644 index d80c2525..00000000 --- a/third_party/sqlite3/tclsqlite.c +++ /dev/null @@ -1,4011 +0,0 @@ -/* -** 2001 September 15 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** A TCL Interface to SQLite. Append this file to sqlite3.c and -** compile the whole thing to build a TCL-enabled version of SQLite. -** -** Compile-time options: -** -** -DTCLSH Add a "main()" routine that works as a tclsh. -** -** -DTCLSH_INIT_PROC=name -** -** Invoke name(interp) to initialize the Tcl interpreter. -** If name(interp) returns a non-NULL string, then run -** that string as a Tcl script to launch the application. -** If name(interp) returns NULL, then run the regular -** tclsh-emulator code. -*/ -#ifdef TCLSH_INIT_PROC -# define TCLSH 1 -#endif - -/* -** If requested, include the SQLite compiler options file for MSVC. -*/ -#if defined(INCLUDE_MSVC_H) -# include "msvc.h" -#endif - -#if defined(INCLUDE_SQLITE_TCL_H) -# include "sqlite_tcl.h" -#else -# include "tcl.h" -# ifndef SQLITE_TCLAPI -# define SQLITE_TCLAPI -# endif -#endif -#include - -/* -** Some additional include files are needed if this file is not -** appended to the amalgamation. -*/ -#ifndef SQLITE_AMALGAMATION -# include "sqlite3.h" -# include -# include -# include - typedef unsigned char u8; -#endif -#include - -/* Used to get the current process ID */ -#if !defined(_WIN32) -# include -# include -# define GETPID getpid -#elif !defined(_WIN32_WCE) -# ifndef SQLITE_AMALGAMATION -# ifndef WIN32_LEAN_AND_MEAN -# define WIN32_LEAN_AND_MEAN -# endif -# include -# endif -# include -# define isatty(h) _isatty(h) -# define GETPID (int)GetCurrentProcessId -#endif - -/* - * Windows needs to know which symbols to export. Unix does not. - * BUILD_sqlite should be undefined for Unix. - */ -#ifdef BUILD_sqlite -#undef TCL_STORAGE_CLASS -#define TCL_STORAGE_CLASS DLLEXPORT -#endif /* BUILD_sqlite */ - -#define NUM_PREPARED_STMTS 10 -#define MAX_PREPARED_STMTS 100 - -/* Forward declaration */ -typedef struct SqliteDb SqliteDb; - -/* -** New SQL functions can be created as TCL scripts. Each such function -** is described by an instance of the following structure. -** -** Variable eType may be set to SQLITE_INTEGER, SQLITE_FLOAT, SQLITE_TEXT, -** SQLITE_BLOB or SQLITE_NULL. If it is SQLITE_NULL, then the implementation -** attempts to determine the type of the result based on the Tcl object. -** If it is SQLITE_TEXT or SQLITE_BLOB, then a text (sqlite3_result_text()) -** or blob (sqlite3_result_blob()) is returned. If it is SQLITE_INTEGER -** or SQLITE_FLOAT, then an attempt is made to return an integer or float -** value, falling back to float and then text if this is not possible. -*/ -typedef struct SqlFunc SqlFunc; -struct SqlFunc { - Tcl_Interp *interp; /* The TCL interpret to execute the function */ - Tcl_Obj *pScript; /* The Tcl_Obj representation of the script */ - SqliteDb *pDb; /* Database connection that owns this function */ - int useEvalObjv; /* True if it is safe to use Tcl_EvalObjv */ - int eType; /* Type of value to return */ - char *zName; /* Name of this function */ - SqlFunc *pNext; /* Next function on the list of them all */ -}; - -/* -** New collation sequences function can be created as TCL scripts. Each such -** function is described by an instance of the following structure. -*/ -typedef struct SqlCollate SqlCollate; -struct SqlCollate { - Tcl_Interp *interp; /* The TCL interpret to execute the function */ - char *zScript; /* The script to be run */ - SqlCollate *pNext; /* Next function on the list of them all */ -}; - -/* -** Prepared statements are cached for faster execution. Each prepared -** statement is described by an instance of the following structure. -*/ -typedef struct SqlPreparedStmt SqlPreparedStmt; -struct SqlPreparedStmt { - SqlPreparedStmt *pNext; /* Next in linked list */ - SqlPreparedStmt *pPrev; /* Previous on the list */ - sqlite3_stmt *pStmt; /* The prepared statement */ - int nSql; /* chars in zSql[] */ - const char *zSql; /* Text of the SQL statement */ - int nParm; /* Size of apParm array */ - Tcl_Obj **apParm; /* Array of referenced object pointers */ -}; - -typedef struct IncrblobChannel IncrblobChannel; - -/* -** There is one instance of this structure for each SQLite database -** that has been opened by the SQLite TCL interface. -** -** If this module is built with SQLITE_TEST defined (to create the SQLite -** testfixture executable), then it may be configured to use either -** sqlite3_prepare_v2() or sqlite3_prepare() to prepare SQL statements. -** If SqliteDb.bLegacyPrepare is true, sqlite3_prepare() is used. -*/ -struct SqliteDb { - sqlite3 *db; /* The "real" database structure. MUST BE FIRST */ - Tcl_Interp *interp; /* The interpreter used for this database */ - char *zBusy; /* The busy callback routine */ - char *zCommit; /* The commit hook callback routine */ - char *zTrace; /* The trace callback routine */ - char *zTraceV2; /* The trace_v2 callback routine */ - char *zProfile; /* The profile callback routine */ - char *zProgress; /* The progress callback routine */ - char *zBindFallback; /* Callback to invoke on a binding miss */ - char *zAuth; /* The authorization callback routine */ - int disableAuth; /* Disable the authorizer if it exists */ - char *zNull; /* Text to substitute for an SQL NULL value */ - SqlFunc *pFunc; /* List of SQL functions */ - Tcl_Obj *pUpdateHook; /* Update hook script (if any) */ - Tcl_Obj *pPreUpdateHook; /* Pre-update hook script (if any) */ - Tcl_Obj *pRollbackHook; /* Rollback hook script (if any) */ - Tcl_Obj *pWalHook; /* WAL hook script (if any) */ - Tcl_Obj *pUnlockNotify; /* Unlock notify script (if any) */ - SqlCollate *pCollate; /* List of SQL collation functions */ - int rc; /* Return code of most recent sqlite3_exec() */ - Tcl_Obj *pCollateNeeded; /* Collation needed script */ - SqlPreparedStmt *stmtList; /* List of prepared statements*/ - SqlPreparedStmt *stmtLast; /* Last statement in the list */ - int maxStmt; /* The next maximum number of stmtList */ - int nStmt; /* Number of statements in stmtList */ - IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */ - int nStep, nSort, nIndex; /* Statistics for most recent operation */ - int nVMStep; /* Another statistic for most recent operation */ - int nTransaction; /* Number of nested [transaction] methods */ - int openFlags; /* Flags used to open. (SQLITE_OPEN_URI) */ -#ifdef SQLITE_TEST - int bLegacyPrepare; /* True to use sqlite3_prepare() */ -#endif -}; - -struct IncrblobChannel { - sqlite3_blob *pBlob; /* sqlite3 blob handle */ - SqliteDb *pDb; /* Associated database connection */ - int iSeek; /* Current seek offset */ - Tcl_Channel channel; /* Channel identifier */ - IncrblobChannel *pNext; /* Linked list of all open incrblob channels */ - IncrblobChannel *pPrev; /* Linked list of all open incrblob channels */ -}; - -/* -** Compute a string length that is limited to what can be stored in -** lower 30 bits of a 32-bit signed integer. -*/ -static int strlen30(const char *z){ - const char *z2 = z; - while( *z2 ){ z2++; } - return 0x3fffffff & (int)(z2 - z); -} - - -#ifndef SQLITE_OMIT_INCRBLOB -/* -** Close all incrblob channels opened using database connection pDb. -** This is called when shutting down the database connection. -*/ -static void closeIncrblobChannels(SqliteDb *pDb){ - IncrblobChannel *p; - IncrblobChannel *pNext; - - for(p=pDb->pIncrblob; p; p=pNext){ - pNext = p->pNext; - - /* Note: Calling unregister here call Tcl_Close on the incrblob channel, - ** which deletes the IncrblobChannel structure at *p. So do not - ** call Tcl_Free() here. - */ - Tcl_UnregisterChannel(pDb->interp, p->channel); - } -} - -/* -** Close an incremental blob channel. -*/ -static int SQLITE_TCLAPI incrblobClose( - ClientData instanceData, - Tcl_Interp *interp -){ - IncrblobChannel *p = (IncrblobChannel *)instanceData; - int rc = sqlite3_blob_close(p->pBlob); - sqlite3 *db = p->pDb->db; - - /* Remove the channel from the SqliteDb.pIncrblob list. */ - if( p->pNext ){ - p->pNext->pPrev = p->pPrev; - } - if( p->pPrev ){ - p->pPrev->pNext = p->pNext; - } - if( p->pDb->pIncrblob==p ){ - p->pDb->pIncrblob = p->pNext; - } - - /* Free the IncrblobChannel structure */ - Tcl_Free((char *)p); - - if( rc!=SQLITE_OK ){ - Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE); - return TCL_ERROR; - } - return TCL_OK; -} - -/* -** Read data from an incremental blob channel. -*/ -static int SQLITE_TCLAPI incrblobInput( - ClientData instanceData, - char *buf, - int bufSize, - int *errorCodePtr -){ - IncrblobChannel *p = (IncrblobChannel *)instanceData; - int nRead = bufSize; /* Number of bytes to read */ - int nBlob; /* Total size of the blob */ - int rc; /* sqlite error code */ - - nBlob = sqlite3_blob_bytes(p->pBlob); - if( (p->iSeek+nRead)>nBlob ){ - nRead = nBlob-p->iSeek; - } - if( nRead<=0 ){ - return 0; - } - - rc = sqlite3_blob_read(p->pBlob, (void *)buf, nRead, p->iSeek); - if( rc!=SQLITE_OK ){ - *errorCodePtr = rc; - return -1; - } - - p->iSeek += nRead; - return nRead; -} - -/* -** Write data to an incremental blob channel. -*/ -static int SQLITE_TCLAPI incrblobOutput( - ClientData instanceData, - CONST char *buf, - int toWrite, - int *errorCodePtr -){ - IncrblobChannel *p = (IncrblobChannel *)instanceData; - int nWrite = toWrite; /* Number of bytes to write */ - int nBlob; /* Total size of the blob */ - int rc; /* sqlite error code */ - - nBlob = sqlite3_blob_bytes(p->pBlob); - if( (p->iSeek+nWrite)>nBlob ){ - *errorCodePtr = EINVAL; - return -1; - } - if( nWrite<=0 ){ - return 0; - } - - rc = sqlite3_blob_write(p->pBlob, (void *)buf, nWrite, p->iSeek); - if( rc!=SQLITE_OK ){ - *errorCodePtr = EIO; - return -1; - } - - p->iSeek += nWrite; - return nWrite; -} - -/* -** Seek an incremental blob channel. -*/ -static int SQLITE_TCLAPI incrblobSeek( - ClientData instanceData, - long offset, - int seekMode, - int *errorCodePtr -){ - IncrblobChannel *p = (IncrblobChannel *)instanceData; - - switch( seekMode ){ - case SEEK_SET: - p->iSeek = offset; - break; - case SEEK_CUR: - p->iSeek += offset; - break; - case SEEK_END: - p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset; - break; - - default: assert(!"Bad seekMode"); - } - - return p->iSeek; -} - - -static void SQLITE_TCLAPI incrblobWatch( - ClientData instanceData, - int mode -){ - /* NO-OP */ -} -static int SQLITE_TCLAPI incrblobHandle( - ClientData instanceData, - int dir, - ClientData *hPtr -){ - return TCL_ERROR; -} - -static Tcl_ChannelType IncrblobChannelType = { - "incrblob", /* typeName */ - TCL_CHANNEL_VERSION_2, /* version */ - incrblobClose, /* closeProc */ - incrblobInput, /* inputProc */ - incrblobOutput, /* outputProc */ - incrblobSeek, /* seekProc */ - 0, /* setOptionProc */ - 0, /* getOptionProc */ - incrblobWatch, /* watchProc (this is a no-op) */ - incrblobHandle, /* getHandleProc (always returns error) */ - 0, /* close2Proc */ - 0, /* blockModeProc */ - 0, /* flushProc */ - 0, /* handlerProc */ - 0, /* wideSeekProc */ -}; - -/* -** Create a new incrblob channel. -*/ -static int createIncrblobChannel( - Tcl_Interp *interp, - SqliteDb *pDb, - const char *zDb, - const char *zTable, - const char *zColumn, - sqlite_int64 iRow, - int isReadonly -){ - IncrblobChannel *p; - sqlite3 *db = pDb->db; - sqlite3_blob *pBlob; - int rc; - int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE); - - /* This variable is used to name the channels: "incrblob_[incr count]" */ - static int count = 0; - char zChannel[64]; - - rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob); - if( rc!=SQLITE_OK ){ - Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE); - return TCL_ERROR; - } - - p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel)); - p->iSeek = 0; - p->pBlob = pBlob; - - sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count); - p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags); - Tcl_RegisterChannel(interp, p->channel); - - /* Link the new channel into the SqliteDb.pIncrblob list. */ - p->pNext = pDb->pIncrblob; - p->pPrev = 0; - if( p->pNext ){ - p->pNext->pPrev = p; - } - pDb->pIncrblob = p; - p->pDb = pDb; - - Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE); - return TCL_OK; -} -#else /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */ - #define closeIncrblobChannels(pDb) -#endif - -/* -** Look at the script prefix in pCmd. We will be executing this script -** after first appending one or more arguments. This routine analyzes -** the script to see if it is safe to use Tcl_EvalObjv() on the script -** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much -** faster. -** -** Scripts that are safe to use with Tcl_EvalObjv() consists of a -** command name followed by zero or more arguments with no [...] or $ -** or {...} or ; to be seen anywhere. Most callback scripts consist -** of just a single procedure name and they meet this requirement. -*/ -static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){ - /* We could try to do something with Tcl_Parse(). But we will instead - ** just do a search for forbidden characters. If any of the forbidden - ** characters appear in pCmd, we will report the string as unsafe. - */ - const char *z; - int n; - z = Tcl_GetStringFromObj(pCmd, &n); - while( n-- > 0 ){ - int c = *(z++); - if( c=='$' || c=='[' || c==';' ) return 0; - } - return 1; -} - -/* -** Find an SqlFunc structure with the given name. Or create a new -** one if an existing one cannot be found. Return a pointer to the -** structure. -*/ -static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){ - SqlFunc *p, *pNew; - int nName = strlen30(zName); - pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + nName + 1 ); - pNew->zName = (char*)&pNew[1]; - memcpy(pNew->zName, zName, nName+1); - for(p=pDb->pFunc; p; p=p->pNext){ - if( sqlite3_stricmp(p->zName, pNew->zName)==0 ){ - Tcl_Free((char*)pNew); - return p; - } - } - pNew->interp = pDb->interp; - pNew->pDb = pDb; - pNew->pScript = 0; - pNew->pNext = pDb->pFunc; - pDb->pFunc = pNew; - return pNew; -} - -/* -** Free a single SqlPreparedStmt object. -*/ -static void dbFreeStmt(SqlPreparedStmt *pStmt){ -#ifdef SQLITE_TEST - if( sqlite3_sql(pStmt->pStmt)==0 ){ - Tcl_Free((char *)pStmt->zSql); - } -#endif - sqlite3_finalize(pStmt->pStmt); - Tcl_Free((char *)pStmt); -} - -/* -** Finalize and free a list of prepared statements -*/ -static void flushStmtCache(SqliteDb *pDb){ - SqlPreparedStmt *pPreStmt; - SqlPreparedStmt *pNext; - - for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pNext){ - pNext = pPreStmt->pNext; - dbFreeStmt(pPreStmt); - } - pDb->nStmt = 0; - pDb->stmtLast = 0; - pDb->stmtList = 0; -} - -/* -** TCL calls this procedure when an sqlite3 database command is -** deleted. -*/ -static void SQLITE_TCLAPI DbDeleteCmd(void *db){ - SqliteDb *pDb = (SqliteDb*)db; - flushStmtCache(pDb); - closeIncrblobChannels(pDb); - sqlite3_close(pDb->db); - while( pDb->pFunc ){ - SqlFunc *pFunc = pDb->pFunc; - pDb->pFunc = pFunc->pNext; - assert( pFunc->pDb==pDb ); - Tcl_DecrRefCount(pFunc->pScript); - Tcl_Free((char*)pFunc); - } - while( pDb->pCollate ){ - SqlCollate *pCollate = pDb->pCollate; - pDb->pCollate = pCollate->pNext; - Tcl_Free((char*)pCollate); - } - if( pDb->zBusy ){ - Tcl_Free(pDb->zBusy); - } - if( pDb->zTrace ){ - Tcl_Free(pDb->zTrace); - } - if( pDb->zTraceV2 ){ - Tcl_Free(pDb->zTraceV2); - } - if( pDb->zProfile ){ - Tcl_Free(pDb->zProfile); - } - if( pDb->zBindFallback ){ - Tcl_Free(pDb->zBindFallback); - } - if( pDb->zAuth ){ - Tcl_Free(pDb->zAuth); - } - if( pDb->zNull ){ - Tcl_Free(pDb->zNull); - } - if( pDb->pUpdateHook ){ - Tcl_DecrRefCount(pDb->pUpdateHook); - } - if( pDb->pPreUpdateHook ){ - Tcl_DecrRefCount(pDb->pPreUpdateHook); - } - if( pDb->pRollbackHook ){ - Tcl_DecrRefCount(pDb->pRollbackHook); - } - if( pDb->pWalHook ){ - Tcl_DecrRefCount(pDb->pWalHook); - } - if( pDb->pCollateNeeded ){ - Tcl_DecrRefCount(pDb->pCollateNeeded); - } - Tcl_Free((char*)pDb); -} - -/* -** This routine is called when a database file is locked while trying -** to execute SQL. -*/ -static int DbBusyHandler(void *cd, int nTries){ - SqliteDb *pDb = (SqliteDb*)cd; - int rc; - char zVal[30]; - - sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries); - rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0); - if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){ - return 0; - } - return 1; -} - -#ifndef SQLITE_OMIT_PROGRESS_CALLBACK -/* -** This routine is invoked as the 'progress callback' for the database. -*/ -static int DbProgressHandler(void *cd){ - SqliteDb *pDb = (SqliteDb*)cd; - int rc; - - assert( pDb->zProgress ); - rc = Tcl_Eval(pDb->interp, pDb->zProgress); - if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){ - return 1; - } - return 0; -} -#endif - -#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \ - !defined(SQLITE_OMIT_DEPRECATED) -/* -** This routine is called by the SQLite trace handler whenever a new -** block of SQL is executed. The TCL script in pDb->zTrace is executed. -*/ -static void DbTraceHandler(void *cd, const char *zSql){ - SqliteDb *pDb = (SqliteDb*)cd; - Tcl_DString str; - - Tcl_DStringInit(&str); - Tcl_DStringAppend(&str, pDb->zTrace, -1); - Tcl_DStringAppendElement(&str, zSql); - Tcl_Eval(pDb->interp, Tcl_DStringValue(&str)); - Tcl_DStringFree(&str); - Tcl_ResetResult(pDb->interp); -} -#endif - -#ifndef SQLITE_OMIT_TRACE -/* -** This routine is called by the SQLite trace_v2 handler whenever a new -** supported event is generated. Unsupported event types are ignored. -** The TCL script in pDb->zTraceV2 is executed, with the arguments for -** the event appended to it (as list elements). -*/ -static int DbTraceV2Handler( - unsigned type, /* One of the SQLITE_TRACE_* event types. */ - void *cd, /* The original context data pointer. */ - void *pd, /* Primary event data, depends on event type. */ - void *xd /* Extra event data, depends on event type. */ -){ - SqliteDb *pDb = (SqliteDb*)cd; - Tcl_Obj *pCmd; - - switch( type ){ - case SQLITE_TRACE_STMT: { - sqlite3_stmt *pStmt = (sqlite3_stmt *)pd; - char *zSql = (char *)xd; - - pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1); - Tcl_IncrRefCount(pCmd); - Tcl_ListObjAppendElement(pDb->interp, pCmd, - Tcl_NewWideIntObj((Tcl_WideInt)pStmt)); - Tcl_ListObjAppendElement(pDb->interp, pCmd, - Tcl_NewStringObj(zSql, -1)); - Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT); - Tcl_DecrRefCount(pCmd); - Tcl_ResetResult(pDb->interp); - break; - } - case SQLITE_TRACE_PROFILE: { - sqlite3_stmt *pStmt = (sqlite3_stmt *)pd; - sqlite3_int64 ns = *(sqlite3_int64*)xd; - - pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1); - Tcl_IncrRefCount(pCmd); - Tcl_ListObjAppendElement(pDb->interp, pCmd, - Tcl_NewWideIntObj((Tcl_WideInt)pStmt)); - Tcl_ListObjAppendElement(pDb->interp, pCmd, - Tcl_NewWideIntObj((Tcl_WideInt)ns)); - Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT); - Tcl_DecrRefCount(pCmd); - Tcl_ResetResult(pDb->interp); - break; - } - case SQLITE_TRACE_ROW: { - sqlite3_stmt *pStmt = (sqlite3_stmt *)pd; - - pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1); - Tcl_IncrRefCount(pCmd); - Tcl_ListObjAppendElement(pDb->interp, pCmd, - Tcl_NewWideIntObj((Tcl_WideInt)pStmt)); - Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT); - Tcl_DecrRefCount(pCmd); - Tcl_ResetResult(pDb->interp); - break; - } - case SQLITE_TRACE_CLOSE: { - sqlite3 *db = (sqlite3 *)pd; - - pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1); - Tcl_IncrRefCount(pCmd); - Tcl_ListObjAppendElement(pDb->interp, pCmd, - Tcl_NewWideIntObj((Tcl_WideInt)db)); - Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT); - Tcl_DecrRefCount(pCmd); - Tcl_ResetResult(pDb->interp); - break; - } - } - return SQLITE_OK; -} -#endif - -#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \ - !defined(SQLITE_OMIT_DEPRECATED) -/* -** This routine is called by the SQLite profile handler after a statement -** SQL has executed. The TCL script in pDb->zProfile is evaluated. -*/ -static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){ - SqliteDb *pDb = (SqliteDb*)cd; - Tcl_DString str; - char zTm[100]; - - sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm); - Tcl_DStringInit(&str); - Tcl_DStringAppend(&str, pDb->zProfile, -1); - Tcl_DStringAppendElement(&str, zSql); - Tcl_DStringAppendElement(&str, zTm); - Tcl_Eval(pDb->interp, Tcl_DStringValue(&str)); - Tcl_DStringFree(&str); - Tcl_ResetResult(pDb->interp); -} -#endif - -/* -** This routine is called when a transaction is committed. The -** TCL script in pDb->zCommit is executed. If it returns non-zero or -** if it throws an exception, the transaction is rolled back instead -** of being committed. -*/ -static int DbCommitHandler(void *cd){ - SqliteDb *pDb = (SqliteDb*)cd; - int rc; - - rc = Tcl_Eval(pDb->interp, pDb->zCommit); - if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){ - return 1; - } - return 0; -} - -static void DbRollbackHandler(void *clientData){ - SqliteDb *pDb = (SqliteDb*)clientData; - assert(pDb->pRollbackHook); - if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){ - Tcl_BackgroundError(pDb->interp); - } -} - -/* -** This procedure handles wal_hook callbacks. -*/ -static int DbWalHandler( - void *clientData, - sqlite3 *db, - const char *zDb, - int nEntry -){ - int ret = SQLITE_OK; - Tcl_Obj *p; - SqliteDb *pDb = (SqliteDb*)clientData; - Tcl_Interp *interp = pDb->interp; - assert(pDb->pWalHook); - - assert( db==pDb->db ); - p = Tcl_DuplicateObj(pDb->pWalHook); - Tcl_IncrRefCount(p); - Tcl_ListObjAppendElement(interp, p, Tcl_NewStringObj(zDb, -1)); - Tcl_ListObjAppendElement(interp, p, Tcl_NewIntObj(nEntry)); - if( TCL_OK!=Tcl_EvalObjEx(interp, p, 0) - || TCL_OK!=Tcl_GetIntFromObj(interp, Tcl_GetObjResult(interp), &ret) - ){ - Tcl_BackgroundError(interp); - } - Tcl_DecrRefCount(p); - - return ret; -} - -#if defined(SQLITE_TEST) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY) -static void setTestUnlockNotifyVars(Tcl_Interp *interp, int iArg, int nArg){ - char zBuf[64]; - sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", iArg); - Tcl_SetVar(interp, "sqlite_unlock_notify_arg", zBuf, TCL_GLOBAL_ONLY); - sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", nArg); - Tcl_SetVar(interp, "sqlite_unlock_notify_argcount", zBuf, TCL_GLOBAL_ONLY); -} -#else -# define setTestUnlockNotifyVars(x,y,z) -#endif - -#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY -static void DbUnlockNotify(void **apArg, int nArg){ - int i; - for(i=0; iinterp, i, nArg); - assert( pDb->pUnlockNotify); - Tcl_EvalObjEx(pDb->interp, pDb->pUnlockNotify, flags); - Tcl_DecrRefCount(pDb->pUnlockNotify); - pDb->pUnlockNotify = 0; - } -} -#endif - -#ifdef SQLITE_ENABLE_PREUPDATE_HOOK -/* -** Pre-update hook callback. -*/ -static void DbPreUpdateHandler( - void *p, - sqlite3 *db, - int op, - const char *zDb, - const char *zTbl, - sqlite_int64 iKey1, - sqlite_int64 iKey2 -){ - SqliteDb *pDb = (SqliteDb *)p; - Tcl_Obj *pCmd; - static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"}; - - assert( (SQLITE_DELETE-1)/9 == 0 ); - assert( (SQLITE_INSERT-1)/9 == 1 ); - assert( (SQLITE_UPDATE-1)/9 == 2 ); - assert( pDb->pPreUpdateHook ); - assert( db==pDb->db ); - assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE ); - - pCmd = Tcl_DuplicateObj(pDb->pPreUpdateHook); - Tcl_IncrRefCount(pCmd); - Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1)); - Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1)); - Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1)); - Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey1)); - Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey2)); - Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT); - Tcl_DecrRefCount(pCmd); -} -#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ - -static void DbUpdateHandler( - void *p, - int op, - const char *zDb, - const char *zTbl, - sqlite_int64 rowid -){ - SqliteDb *pDb = (SqliteDb *)p; - Tcl_Obj *pCmd; - static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"}; - - assert( (SQLITE_DELETE-1)/9 == 0 ); - assert( (SQLITE_INSERT-1)/9 == 1 ); - assert( (SQLITE_UPDATE-1)/9 == 2 ); - - assert( pDb->pUpdateHook ); - assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE ); - - pCmd = Tcl_DuplicateObj(pDb->pUpdateHook); - Tcl_IncrRefCount(pCmd); - Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1)); - Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1)); - Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1)); - Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid)); - Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT); - Tcl_DecrRefCount(pCmd); -} - -static void tclCollateNeeded( - void *pCtx, - sqlite3 *db, - int enc, - const char *zName -){ - SqliteDb *pDb = (SqliteDb *)pCtx; - Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded); - Tcl_IncrRefCount(pScript); - Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1)); - Tcl_EvalObjEx(pDb->interp, pScript, 0); - Tcl_DecrRefCount(pScript); -} - -/* -** This routine is called to evaluate an SQL collation function implemented -** using TCL script. -*/ -static int tclSqlCollate( - void *pCtx, - int nA, - const void *zA, - int nB, - const void *zB -){ - SqlCollate *p = (SqlCollate *)pCtx; - Tcl_Obj *pCmd; - - pCmd = Tcl_NewStringObj(p->zScript, -1); - Tcl_IncrRefCount(pCmd); - Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA)); - Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB)); - Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT); - Tcl_DecrRefCount(pCmd); - return (atoi(Tcl_GetStringResult(p->interp))); -} - -/* -** This routine is called to evaluate an SQL function implemented -** using TCL script. -*/ -static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){ - SqlFunc *p = sqlite3_user_data(context); - Tcl_Obj *pCmd; - int i; - int rc; - - if( argc==0 ){ - /* If there are no arguments to the function, call Tcl_EvalObjEx on the - ** script object directly. This allows the TCL compiler to generate - ** bytecode for the command on the first invocation and thus make - ** subsequent invocations much faster. */ - pCmd = p->pScript; - Tcl_IncrRefCount(pCmd); - rc = Tcl_EvalObjEx(p->interp, pCmd, 0); - Tcl_DecrRefCount(pCmd); - }else{ - /* If there are arguments to the function, make a shallow copy of the - ** script object, lappend the arguments, then evaluate the copy. - ** - ** By "shallow" copy, we mean only the outer list Tcl_Obj is duplicated. - ** The new Tcl_Obj contains pointers to the original list elements. - ** That way, when Tcl_EvalObjv() is run and shimmers the first element - ** of the list to tclCmdNameType, that alternate representation will - ** be preserved and reused on the next invocation. - */ - Tcl_Obj **aArg; - int nArg; - if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){ - sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1); - return; - } - pCmd = Tcl_NewListObj(nArg, aArg); - Tcl_IncrRefCount(pCmd); - for(i=0; i=-2147483647 && v<=2147483647 ){ - pVal = Tcl_NewIntObj((int)v); - }else{ - pVal = Tcl_NewWideIntObj(v); - } - break; - } - case SQLITE_FLOAT: { - double r = sqlite3_value_double(pIn); - pVal = Tcl_NewDoubleObj(r); - break; - } - case SQLITE_NULL: { - pVal = Tcl_NewStringObj(p->pDb->zNull, -1); - break; - } - default: { - int bytes = sqlite3_value_bytes(pIn); - pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes); - break; - } - } - rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal); - if( rc ){ - Tcl_DecrRefCount(pCmd); - sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1); - return; - } - } - if( !p->useEvalObjv ){ - /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd - ** is a list without a string representation. To prevent this from - ** happening, make sure pCmd has a valid string representation */ - Tcl_GetString(pCmd); - } - rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT); - Tcl_DecrRefCount(pCmd); - } - - if( rc && rc!=TCL_RETURN ){ - sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1); - }else{ - Tcl_Obj *pVar = Tcl_GetObjResult(p->interp); - int n; - u8 *data; - const char *zType = (pVar->typePtr ? pVar->typePtr->name : ""); - char c = zType[0]; - int eType = p->eType; - - if( eType==SQLITE_NULL ){ - if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){ - /* Only return a BLOB type if the Tcl variable is a bytearray and - ** has no string representation. */ - eType = SQLITE_BLOB; - }else if( (c=='b' && strcmp(zType,"boolean")==0) - || (c=='w' && strcmp(zType,"wideInt")==0) - || (c=='i' && strcmp(zType,"int")==0) - ){ - eType = SQLITE_INTEGER; - }else if( c=='d' && strcmp(zType,"double")==0 ){ - eType = SQLITE_FLOAT; - }else{ - eType = SQLITE_TEXT; - } - } - - switch( eType ){ - case SQLITE_BLOB: { - data = Tcl_GetByteArrayFromObj(pVar, &n); - sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT); - break; - } - case SQLITE_INTEGER: { - Tcl_WideInt v; - if( TCL_OK==Tcl_GetWideIntFromObj(0, pVar, &v) ){ - sqlite3_result_int64(context, v); - break; - } - /* fall-through */ - } - case SQLITE_FLOAT: { - double r; - if( TCL_OK==Tcl_GetDoubleFromObj(0, pVar, &r) ){ - sqlite3_result_double(context, r); - break; - } - /* fall-through */ - } - default: { - data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n); - sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT); - break; - } - } - - } -} - -#ifndef SQLITE_OMIT_AUTHORIZATION -/* -** This is the authentication function. It appends the authentication -** type code and the two arguments to zCmd[] then invokes the result -** on the interpreter. The reply is examined to determine if the -** authentication fails or succeeds. -*/ -static int auth_callback( - void *pArg, - int code, - const char *zArg1, - const char *zArg2, - const char *zArg3, - const char *zArg4 -#ifdef SQLITE_USER_AUTHENTICATION - ,const char *zArg5 -#endif -){ - const char *zCode; - Tcl_DString str; - int rc; - const char *zReply; - /* EVIDENCE-OF: R-38590-62769 The first parameter to the authorizer - ** callback is a copy of the third parameter to the - ** sqlite3_set_authorizer() interface. - */ - SqliteDb *pDb = (SqliteDb*)pArg; - if( pDb->disableAuth ) return SQLITE_OK; - - /* EVIDENCE-OF: R-56518-44310 The second parameter to the callback is an - ** integer action code that specifies the particular action to be - ** authorized. */ - switch( code ){ - case SQLITE_COPY : zCode="SQLITE_COPY"; break; - case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break; - case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break; - case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break; - case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break; - case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break; - case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break; - case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break; - case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break; - case SQLITE_DELETE : zCode="SQLITE_DELETE"; break; - case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break; - case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break; - case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break; - case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break; - case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break; - case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break; - case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break; - case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break; - case SQLITE_INSERT : zCode="SQLITE_INSERT"; break; - case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break; - case SQLITE_READ : zCode="SQLITE_READ"; break; - case SQLITE_SELECT : zCode="SQLITE_SELECT"; break; - case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break; - case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break; - case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break; - case SQLITE_DETACH : zCode="SQLITE_DETACH"; break; - case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break; - case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break; - case SQLITE_ANALYZE : zCode="SQLITE_ANALYZE"; break; - case SQLITE_CREATE_VTABLE : zCode="SQLITE_CREATE_VTABLE"; break; - case SQLITE_DROP_VTABLE : zCode="SQLITE_DROP_VTABLE"; break; - case SQLITE_FUNCTION : zCode="SQLITE_FUNCTION"; break; - case SQLITE_SAVEPOINT : zCode="SQLITE_SAVEPOINT"; break; - case SQLITE_RECURSIVE : zCode="SQLITE_RECURSIVE"; break; - default : zCode="????"; break; - } - Tcl_DStringInit(&str); - Tcl_DStringAppend(&str, pDb->zAuth, -1); - Tcl_DStringAppendElement(&str, zCode); - Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : ""); - Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : ""); - Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : ""); - Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : ""); -#ifdef SQLITE_USER_AUTHENTICATION - Tcl_DStringAppendElement(&str, zArg5 ? zArg5 : ""); -#endif - rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str)); - Tcl_DStringFree(&str); - zReply = rc==TCL_OK ? Tcl_GetStringResult(pDb->interp) : "SQLITE_DENY"; - if( strcmp(zReply,"SQLITE_OK")==0 ){ - rc = SQLITE_OK; - }else if( strcmp(zReply,"SQLITE_DENY")==0 ){ - rc = SQLITE_DENY; - }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){ - rc = SQLITE_IGNORE; - }else{ - rc = 999; - } - return rc; -} -#endif /* SQLITE_OMIT_AUTHORIZATION */ - -/* -** This routine reads a line of text from FILE in, stores -** the text in memory obtained from malloc() and returns a pointer -** to the text. NULL is returned at end of file, or if malloc() -** fails. -** -** The interface is like "readline" but no command-line editing -** is done. -** -** copied from shell.c from '.import' command -*/ -static char *local_getline(char *zPrompt, FILE *in){ - char *zLine; - int nLine; - int n; - - nLine = 100; - zLine = malloc( nLine ); - if( zLine==0 ) return 0; - n = 0; - while( 1 ){ - if( n+100>nLine ){ - nLine = nLine*2 + 100; - zLine = realloc(zLine, nLine); - if( zLine==0 ) return 0; - } - if( fgets(&zLine[n], nLine - n, in)==0 ){ - if( n==0 ){ - free(zLine); - return 0; - } - zLine[n] = 0; - break; - } - while( zLine[n] ){ n++; } - if( n>0 && zLine[n-1]=='\n' ){ - n--; - zLine[n] = 0; - break; - } - } - zLine = realloc( zLine, n+1 ); - return zLine; -} - - -/* -** This function is part of the implementation of the command: -** -** $db transaction [-deferred|-immediate|-exclusive] SCRIPT -** -** It is invoked after evaluating the script SCRIPT to commit or rollback -** the transaction or savepoint opened by the [transaction] command. -*/ -static int SQLITE_TCLAPI DbTransPostCmd( - ClientData data[], /* data[0] is the Sqlite3Db* for $db */ - Tcl_Interp *interp, /* Tcl interpreter */ - int result /* Result of evaluating SCRIPT */ -){ - static const char *const azEnd[] = { - "RELEASE _tcl_transaction", /* rc==TCL_ERROR, nTransaction!=0 */ - "COMMIT", /* rc!=TCL_ERROR, nTransaction==0 */ - "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction", - "ROLLBACK" /* rc==TCL_ERROR, nTransaction==0 */ - }; - SqliteDb *pDb = (SqliteDb*)data[0]; - int rc = result; - const char *zEnd; - - pDb->nTransaction--; - zEnd = azEnd[(rc==TCL_ERROR)*2 + (pDb->nTransaction==0)]; - - pDb->disableAuth++; - if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){ - /* This is a tricky scenario to handle. The most likely cause of an - ** error is that the exec() above was an attempt to commit the - ** top-level transaction that returned SQLITE_BUSY. Or, less likely, - ** that an IO-error has occurred. In either case, throw a Tcl exception - ** and try to rollback the transaction. - ** - ** But it could also be that the user executed one or more BEGIN, - ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing - ** this method's logic. Not clear how this would be best handled. - */ - if( rc!=TCL_ERROR ){ - Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0); - rc = TCL_ERROR; - } - sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0); - } - pDb->disableAuth--; - - return rc; -} - -/* -** Unless SQLITE_TEST is defined, this function is a simple wrapper around -** sqlite3_prepare_v2(). If SQLITE_TEST is defined, then it uses either -** sqlite3_prepare_v2() or legacy interface sqlite3_prepare(), depending -** on whether or not the [db_use_legacy_prepare] command has been used to -** configure the connection. -*/ -static int dbPrepare( - SqliteDb *pDb, /* Database object */ - const char *zSql, /* SQL to compile */ - sqlite3_stmt **ppStmt, /* OUT: Prepared statement */ - const char **pzOut /* OUT: Pointer to next SQL statement */ -){ - unsigned int prepFlags = 0; -#ifdef SQLITE_TEST - if( pDb->bLegacyPrepare ){ - return sqlite3_prepare(pDb->db, zSql, -1, ppStmt, pzOut); - } -#endif - /* If the statement cache is large, use the SQLITE_PREPARE_PERSISTENT - ** flags, which uses less lookaside memory. But if the cache is small, - ** omit that flag to make full use of lookaside */ - if( pDb->maxStmt>5 ) prepFlags = SQLITE_PREPARE_PERSISTENT; - - return sqlite3_prepare_v3(pDb->db, zSql, -1, prepFlags, ppStmt, pzOut); -} - -/* -** Search the cache for a prepared-statement object that implements the -** first SQL statement in the buffer pointed to by parameter zIn. If -** no such prepared-statement can be found, allocate and prepare a new -** one. In either case, bind the current values of the relevant Tcl -** variables to any $var, :var or @var variables in the statement. Before -** returning, set *ppPreStmt to point to the prepared-statement object. -** -** Output parameter *pzOut is set to point to the next SQL statement in -** buffer zIn, or to the '\0' byte at the end of zIn if there is no -** next statement. -** -** If successful, TCL_OK is returned. Otherwise, TCL_ERROR is returned -** and an error message loaded into interpreter pDb->interp. -*/ -static int dbPrepareAndBind( - SqliteDb *pDb, /* Database object */ - char const *zIn, /* SQL to compile */ - char const **pzOut, /* OUT: Pointer to next SQL statement */ - SqlPreparedStmt **ppPreStmt /* OUT: Object used to cache statement */ -){ - const char *zSql = zIn; /* Pointer to first SQL statement in zIn */ - sqlite3_stmt *pStmt = 0; /* Prepared statement object */ - SqlPreparedStmt *pPreStmt; /* Pointer to cached statement */ - int nSql; /* Length of zSql in bytes */ - int nVar = 0; /* Number of variables in statement */ - int iParm = 0; /* Next free entry in apParm */ - char c; - int i; - int needResultReset = 0; /* Need to invoke Tcl_ResetResult() */ - int rc = SQLITE_OK; /* Value to return */ - Tcl_Interp *interp = pDb->interp; - - *ppPreStmt = 0; - - /* Trim spaces from the start of zSql and calculate the remaining length. */ - while( (c = zSql[0])==' ' || c=='\t' || c=='\r' || c=='\n' ){ zSql++; } - nSql = strlen30(zSql); - - for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pPreStmt->pNext){ - int n = pPreStmt->nSql; - if( nSql>=n - && memcmp(pPreStmt->zSql, zSql, n)==0 - && (zSql[n]==0 || zSql[n-1]==';') - ){ - pStmt = pPreStmt->pStmt; - *pzOut = &zSql[pPreStmt->nSql]; - - /* When a prepared statement is found, unlink it from the - ** cache list. It will later be added back to the beginning - ** of the cache list in order to implement LRU replacement. - */ - if( pPreStmt->pPrev ){ - pPreStmt->pPrev->pNext = pPreStmt->pNext; - }else{ - pDb->stmtList = pPreStmt->pNext; - } - if( pPreStmt->pNext ){ - pPreStmt->pNext->pPrev = pPreStmt->pPrev; - }else{ - pDb->stmtLast = pPreStmt->pPrev; - } - pDb->nStmt--; - nVar = sqlite3_bind_parameter_count(pStmt); - break; - } - } - - /* If no prepared statement was found. Compile the SQL text. Also allocate - ** a new SqlPreparedStmt structure. */ - if( pPreStmt==0 ){ - int nByte; - - if( SQLITE_OK!=dbPrepare(pDb, zSql, &pStmt, pzOut) ){ - Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1)); - return TCL_ERROR; - } - if( pStmt==0 ){ - if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){ - /* A compile-time error in the statement. */ - Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1)); - return TCL_ERROR; - }else{ - /* The statement was a no-op. Continue to the next statement - ** in the SQL string. - */ - return TCL_OK; - } - } - - assert( pPreStmt==0 ); - nVar = sqlite3_bind_parameter_count(pStmt); - nByte = sizeof(SqlPreparedStmt) + nVar*sizeof(Tcl_Obj *); - pPreStmt = (SqlPreparedStmt*)Tcl_Alloc(nByte); - memset(pPreStmt, 0, nByte); - - pPreStmt->pStmt = pStmt; - pPreStmt->nSql = (int)(*pzOut - zSql); - pPreStmt->zSql = sqlite3_sql(pStmt); - pPreStmt->apParm = (Tcl_Obj **)&pPreStmt[1]; -#ifdef SQLITE_TEST - if( pPreStmt->zSql==0 ){ - char *zCopy = Tcl_Alloc(pPreStmt->nSql + 1); - memcpy(zCopy, zSql, pPreStmt->nSql); - zCopy[pPreStmt->nSql] = '\0'; - pPreStmt->zSql = zCopy; - } -#endif - } - assert( pPreStmt ); - assert( strlen30(pPreStmt->zSql)==pPreStmt->nSql ); - assert( 0==memcmp(pPreStmt->zSql, zSql, pPreStmt->nSql) ); - - /* Bind values to parameters that begin with $ or : */ - for(i=1; i<=nVar; i++){ - const char *zVar = sqlite3_bind_parameter_name(pStmt, i); - if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){ - Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0); - if( pVar==0 && pDb->zBindFallback!=0 ){ - Tcl_Obj *pCmd; - int rx; - pCmd = Tcl_NewStringObj(pDb->zBindFallback, -1); - Tcl_IncrRefCount(pCmd); - Tcl_ListObjAppendElement(interp, pCmd, Tcl_NewStringObj(zVar,-1)); - if( needResultReset ) Tcl_ResetResult(interp); - needResultReset = 1; - rx = Tcl_EvalObjEx(interp, pCmd, TCL_EVAL_DIRECT); - Tcl_DecrRefCount(pCmd); - if( rx==TCL_OK ){ - pVar = Tcl_GetObjResult(interp); - }else if( rx==TCL_ERROR ){ - rc = TCL_ERROR; - break; - }else{ - pVar = 0; - } - } - if( pVar ){ - int n; - u8 *data; - const char *zType = (pVar->typePtr ? pVar->typePtr->name : ""); - c = zType[0]; - if( zVar[0]=='@' || - (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){ - /* Load a BLOB type if the Tcl variable is a bytearray and - ** it has no string representation or the host - ** parameter name begins with "@". */ - data = Tcl_GetByteArrayFromObj(pVar, &n); - sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC); - Tcl_IncrRefCount(pVar); - pPreStmt->apParm[iParm++] = pVar; - }else if( c=='b' && strcmp(zType,"boolean")==0 ){ - Tcl_GetIntFromObj(interp, pVar, &n); - sqlite3_bind_int(pStmt, i, n); - }else if( c=='d' && strcmp(zType,"double")==0 ){ - double r; - Tcl_GetDoubleFromObj(interp, pVar, &r); - sqlite3_bind_double(pStmt, i, r); - }else if( (c=='w' && strcmp(zType,"wideInt")==0) || - (c=='i' && strcmp(zType,"int")==0) ){ - Tcl_WideInt v; - Tcl_GetWideIntFromObj(interp, pVar, &v); - sqlite3_bind_int64(pStmt, i, v); - }else{ - data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n); - sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC); - Tcl_IncrRefCount(pVar); - pPreStmt->apParm[iParm++] = pVar; - } - }else{ - sqlite3_bind_null(pStmt, i); - } - if( needResultReset ) Tcl_ResetResult(pDb->interp); - } - } - pPreStmt->nParm = iParm; - *ppPreStmt = pPreStmt; - if( needResultReset && rc==TCL_OK ) Tcl_ResetResult(pDb->interp); - - return rc; -} - -/* -** Release a statement reference obtained by calling dbPrepareAndBind(). -** There should be exactly one call to this function for each call to -** dbPrepareAndBind(). -** -** If the discard parameter is non-zero, then the statement is deleted -** immediately. Otherwise it is added to the LRU list and may be returned -** by a subsequent call to dbPrepareAndBind(). -*/ -static void dbReleaseStmt( - SqliteDb *pDb, /* Database handle */ - SqlPreparedStmt *pPreStmt, /* Prepared statement handle to release */ - int discard /* True to delete (not cache) the pPreStmt */ -){ - int i; - - /* Free the bound string and blob parameters */ - for(i=0; inParm; i++){ - Tcl_DecrRefCount(pPreStmt->apParm[i]); - } - pPreStmt->nParm = 0; - - if( pDb->maxStmt<=0 || discard ){ - /* If the cache is turned off, deallocated the statement */ - dbFreeStmt(pPreStmt); - }else{ - /* Add the prepared statement to the beginning of the cache list. */ - pPreStmt->pNext = pDb->stmtList; - pPreStmt->pPrev = 0; - if( pDb->stmtList ){ - pDb->stmtList->pPrev = pPreStmt; - } - pDb->stmtList = pPreStmt; - if( pDb->stmtLast==0 ){ - assert( pDb->nStmt==0 ); - pDb->stmtLast = pPreStmt; - }else{ - assert( pDb->nStmt>0 ); - } - pDb->nStmt++; - - /* If we have too many statement in cache, remove the surplus from - ** the end of the cache list. */ - while( pDb->nStmt>pDb->maxStmt ){ - SqlPreparedStmt *pLast = pDb->stmtLast; - pDb->stmtLast = pLast->pPrev; - pDb->stmtLast->pNext = 0; - pDb->nStmt--; - dbFreeStmt(pLast); - } - } -} - -/* -** Structure used with dbEvalXXX() functions: -** -** dbEvalInit() -** dbEvalStep() -** dbEvalFinalize() -** dbEvalRowInfo() -** dbEvalColumnValue() -*/ -typedef struct DbEvalContext DbEvalContext; -struct DbEvalContext { - SqliteDb *pDb; /* Database handle */ - Tcl_Obj *pSql; /* Object holding string zSql */ - const char *zSql; /* Remaining SQL to execute */ - SqlPreparedStmt *pPreStmt; /* Current statement */ - int nCol; /* Number of columns returned by pStmt */ - int evalFlags; /* Flags used */ - Tcl_Obj *pArray; /* Name of array variable */ - Tcl_Obj **apColName; /* Array of column names */ -}; - -#define SQLITE_EVAL_WITHOUTNULLS 0x00001 /* Unset array(*) for NULL */ - -/* -** Release any cache of column names currently held as part of -** the DbEvalContext structure passed as the first argument. -*/ -static void dbReleaseColumnNames(DbEvalContext *p){ - if( p->apColName ){ - int i; - for(i=0; inCol; i++){ - Tcl_DecrRefCount(p->apColName[i]); - } - Tcl_Free((char *)p->apColName); - p->apColName = 0; - } - p->nCol = 0; -} - -/* -** Initialize a DbEvalContext structure. -** -** If pArray is not NULL, then it contains the name of a Tcl array -** variable. The "*" member of this array is set to a list containing -** the names of the columns returned by the statement as part of each -** call to dbEvalStep(), in order from left to right. e.g. if the names -** of the returned columns are a, b and c, it does the equivalent of the -** tcl command: -** -** set ${pArray}(*) {a b c} -*/ -static void dbEvalInit( - DbEvalContext *p, /* Pointer to structure to initialize */ - SqliteDb *pDb, /* Database handle */ - Tcl_Obj *pSql, /* Object containing SQL script */ - Tcl_Obj *pArray, /* Name of Tcl array to set (*) element of */ - int evalFlags /* Flags controlling evaluation */ -){ - memset(p, 0, sizeof(DbEvalContext)); - p->pDb = pDb; - p->zSql = Tcl_GetString(pSql); - p->pSql = pSql; - Tcl_IncrRefCount(pSql); - if( pArray ){ - p->pArray = pArray; - Tcl_IncrRefCount(pArray); - } - p->evalFlags = evalFlags; -} - -/* -** Obtain information about the row that the DbEvalContext passed as the -** first argument currently points to. -*/ -static void dbEvalRowInfo( - DbEvalContext *p, /* Evaluation context */ - int *pnCol, /* OUT: Number of column names */ - Tcl_Obj ***papColName /* OUT: Array of column names */ -){ - /* Compute column names */ - if( 0==p->apColName ){ - sqlite3_stmt *pStmt = p->pPreStmt->pStmt; - int i; /* Iterator variable */ - int nCol; /* Number of columns returned by pStmt */ - Tcl_Obj **apColName = 0; /* Array of column names */ - - p->nCol = nCol = sqlite3_column_count(pStmt); - if( nCol>0 && (papColName || p->pArray) ){ - apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol ); - for(i=0; iapColName = apColName; - } - - /* If results are being stored in an array variable, then create - ** the array(*) entry for that array - */ - if( p->pArray ){ - Tcl_Interp *interp = p->pDb->interp; - Tcl_Obj *pColList = Tcl_NewObj(); - Tcl_Obj *pStar = Tcl_NewStringObj("*", -1); - - for(i=0; ipArray, pStar, pColList, 0); - Tcl_DecrRefCount(pStar); - } - } - - if( papColName ){ - *papColName = p->apColName; - } - if( pnCol ){ - *pnCol = p->nCol; - } -} - -/* -** Return one of TCL_OK, TCL_BREAK or TCL_ERROR. If TCL_ERROR is -** returned, then an error message is stored in the interpreter before -** returning. -** -** A return value of TCL_OK means there is a row of data available. The -** data may be accessed using dbEvalRowInfo() and dbEvalColumnValue(). This -** is analogous to a return of SQLITE_ROW from sqlite3_step(). If TCL_BREAK -** is returned, then the SQL script has finished executing and there are -** no further rows available. This is similar to SQLITE_DONE. -*/ -static int dbEvalStep(DbEvalContext *p){ - const char *zPrevSql = 0; /* Previous value of p->zSql */ - - while( p->zSql[0] || p->pPreStmt ){ - int rc; - if( p->pPreStmt==0 ){ - zPrevSql = (p->zSql==zPrevSql ? 0 : p->zSql); - rc = dbPrepareAndBind(p->pDb, p->zSql, &p->zSql, &p->pPreStmt); - if( rc!=TCL_OK ) return rc; - }else{ - int rcs; - SqliteDb *pDb = p->pDb; - SqlPreparedStmt *pPreStmt = p->pPreStmt; - sqlite3_stmt *pStmt = pPreStmt->pStmt; - - rcs = sqlite3_step(pStmt); - if( rcs==SQLITE_ROW ){ - return TCL_OK; - } - if( p->pArray ){ - dbEvalRowInfo(p, 0, 0); - } - rcs = sqlite3_reset(pStmt); - - pDb->nStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_FULLSCAN_STEP,1); - pDb->nSort = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_SORT,1); - pDb->nIndex = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_AUTOINDEX,1); - pDb->nVMStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_VM_STEP,1); - dbReleaseColumnNames(p); - p->pPreStmt = 0; - - if( rcs!=SQLITE_OK ){ - /* If a run-time error occurs, report the error and stop reading - ** the SQL. */ - dbReleaseStmt(pDb, pPreStmt, 1); -#if SQLITE_TEST - if( p->pDb->bLegacyPrepare && rcs==SQLITE_SCHEMA && zPrevSql ){ - /* If the runtime error was an SQLITE_SCHEMA, and the database - ** handle is configured to use the legacy sqlite3_prepare() - ** interface, retry prepare()/step() on the same SQL statement. - ** This only happens once. If there is a second SQLITE_SCHEMA - ** error, the error will be returned to the caller. */ - p->zSql = zPrevSql; - continue; - } -#endif - Tcl_SetObjResult(pDb->interp, - Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1)); - return TCL_ERROR; - }else{ - dbReleaseStmt(pDb, pPreStmt, 0); - } - } - } - - /* Finished */ - return TCL_BREAK; -} - -/* -** Free all resources currently held by the DbEvalContext structure passed -** as the first argument. There should be exactly one call to this function -** for each call to dbEvalInit(). -*/ -static void dbEvalFinalize(DbEvalContext *p){ - if( p->pPreStmt ){ - sqlite3_reset(p->pPreStmt->pStmt); - dbReleaseStmt(p->pDb, p->pPreStmt, 0); - p->pPreStmt = 0; - } - if( p->pArray ){ - Tcl_DecrRefCount(p->pArray); - p->pArray = 0; - } - Tcl_DecrRefCount(p->pSql); - dbReleaseColumnNames(p); -} - -/* -** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains -** the value for the iCol'th column of the row currently pointed to by -** the DbEvalContext structure passed as the first argument. -*/ -static Tcl_Obj *dbEvalColumnValue(DbEvalContext *p, int iCol){ - sqlite3_stmt *pStmt = p->pPreStmt->pStmt; - switch( sqlite3_column_type(pStmt, iCol) ){ - case SQLITE_BLOB: { - int bytes = sqlite3_column_bytes(pStmt, iCol); - const char *zBlob = sqlite3_column_blob(pStmt, iCol); - if( !zBlob ) bytes = 0; - return Tcl_NewByteArrayObj((u8*)zBlob, bytes); - } - case SQLITE_INTEGER: { - sqlite_int64 v = sqlite3_column_int64(pStmt, iCol); - if( v>=-2147483647 && v<=2147483647 ){ - return Tcl_NewIntObj((int)v); - }else{ - return Tcl_NewWideIntObj(v); - } - } - case SQLITE_FLOAT: { - return Tcl_NewDoubleObj(sqlite3_column_double(pStmt, iCol)); - } - case SQLITE_NULL: { - return Tcl_NewStringObj(p->pDb->zNull, -1); - } - } - - return Tcl_NewStringObj((char*)sqlite3_column_text(pStmt, iCol), -1); -} - -/* -** If using Tcl version 8.6 or greater, use the NR functions to avoid -** recursive evalution of scripts by the [db eval] and [db trans] -** commands. Even if the headers used while compiling the extension -** are 8.6 or newer, the code still tests the Tcl version at runtime. -** This allows stubs-enabled builds to be used with older Tcl libraries. -*/ -#if TCL_MAJOR_VERSION>8 || (TCL_MAJOR_VERSION==8 && TCL_MINOR_VERSION>=6) -# define SQLITE_TCL_NRE 1 -static int DbUseNre(void){ - int major, minor; - Tcl_GetVersion(&major, &minor, 0, 0); - return( (major==8 && minor>=6) || major>8 ); -} -#else -/* -** Compiling using headers earlier than 8.6. In this case NR cannot be -** used, so DbUseNre() to always return zero. Add #defines for the other -** Tcl_NRxxx() functions to prevent them from causing compilation errors, -** even though the only invocations of them are within conditional blocks -** of the form: -** -** if( DbUseNre() ) { ... } -*/ -# define SQLITE_TCL_NRE 0 -# define DbUseNre() 0 -# define Tcl_NRAddCallback(a,b,c,d,e,f) (void)0 -# define Tcl_NREvalObj(a,b,c) 0 -# define Tcl_NRCreateCommand(a,b,c,d,e,f) (void)0 -#endif - -/* -** This function is part of the implementation of the command: -** -** $db eval SQL ?ARRAYNAME? SCRIPT -*/ -static int SQLITE_TCLAPI DbEvalNextCmd( - ClientData data[], /* data[0] is the (DbEvalContext*) */ - Tcl_Interp *interp, /* Tcl interpreter */ - int result /* Result so far */ -){ - int rc = result; /* Return code */ - - /* The first element of the data[] array is a pointer to a DbEvalContext - ** structure allocated using Tcl_Alloc(). The second element of data[] - ** is a pointer to a Tcl_Obj containing the script to run for each row - ** returned by the queries encapsulated in data[0]. */ - DbEvalContext *p = (DbEvalContext *)data[0]; - Tcl_Obj *pScript = (Tcl_Obj *)data[1]; - Tcl_Obj *pArray = p->pArray; - - while( (rc==TCL_OK || rc==TCL_CONTINUE) && TCL_OK==(rc = dbEvalStep(p)) ){ - int i; - int nCol; - Tcl_Obj **apColName; - dbEvalRowInfo(p, &nCol, &apColName); - for(i=0; ievalFlags & SQLITE_EVAL_WITHOUTNULLS)!=0 - && sqlite3_column_type(p->pPreStmt->pStmt, i)==SQLITE_NULL - ){ - Tcl_UnsetVar2(interp, Tcl_GetString(pArray), - Tcl_GetString(apColName[i]), 0); - }else{ - Tcl_ObjSetVar2(interp, pArray, apColName[i], dbEvalColumnValue(p,i), 0); - } - } - - /* The required interpreter variables are now populated with the data - ** from the current row. If using NRE, schedule callbacks to evaluate - ** script pScript, then to invoke this function again to fetch the next - ** row (or clean up if there is no next row or the script throws an - ** exception). After scheduling the callbacks, return control to the - ** caller. - ** - ** If not using NRE, evaluate pScript directly and continue with the - ** next iteration of this while(...) loop. */ - if( DbUseNre() ){ - Tcl_NRAddCallback(interp, DbEvalNextCmd, (void*)p, (void*)pScript, 0, 0); - return Tcl_NREvalObj(interp, pScript, 0); - }else{ - rc = Tcl_EvalObjEx(interp, pScript, 0); - } - } - - Tcl_DecrRefCount(pScript); - dbEvalFinalize(p); - Tcl_Free((char *)p); - - if( rc==TCL_OK || rc==TCL_BREAK ){ - Tcl_ResetResult(interp); - rc = TCL_OK; - } - return rc; -} - -/* -** This function is used by the implementations of the following database -** handle sub-commands: -** -** $db update_hook ?SCRIPT? -** $db wal_hook ?SCRIPT? -** $db commit_hook ?SCRIPT? -** $db preupdate hook ?SCRIPT? -*/ -static void DbHookCmd( - Tcl_Interp *interp, /* Tcl interpreter */ - SqliteDb *pDb, /* Database handle */ - Tcl_Obj *pArg, /* SCRIPT argument (or NULL) */ - Tcl_Obj **ppHook /* Pointer to member of SqliteDb */ -){ - sqlite3 *db = pDb->db; - - if( *ppHook ){ - Tcl_SetObjResult(interp, *ppHook); - if( pArg ){ - Tcl_DecrRefCount(*ppHook); - *ppHook = 0; - } - } - if( pArg ){ - assert( !(*ppHook) ); - if( Tcl_GetCharLength(pArg)>0 ){ - *ppHook = pArg; - Tcl_IncrRefCount(*ppHook); - } - } - -#ifdef SQLITE_ENABLE_PREUPDATE_HOOK - sqlite3_preupdate_hook(db, (pDb->pPreUpdateHook?DbPreUpdateHandler:0), pDb); -#endif - sqlite3_update_hook(db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb); - sqlite3_rollback_hook(db, (pDb->pRollbackHook?DbRollbackHandler:0), pDb); - sqlite3_wal_hook(db, (pDb->pWalHook?DbWalHandler:0), pDb); -} - -/* -** The "sqlite" command below creates a new Tcl command for each -** connection it opens to an SQLite database. This routine is invoked -** whenever one of those connection-specific commands is executed -** in Tcl. For example, if you run Tcl code like this: -** -** sqlite3 db1 "my_database" -** db1 close -** -** The first command opens a connection to the "my_database" database -** and calls that connection "db1". The second command causes this -** subroutine to be invoked. -*/ -static int SQLITE_TCLAPI DbObjCmd( - void *cd, - Tcl_Interp *interp, - int objc, - Tcl_Obj *const*objv -){ - SqliteDb *pDb = (SqliteDb*)cd; - int choice; - int rc = TCL_OK; - static const char *DB_strs[] = { - "authorizer", "backup", "bind_fallback", - "busy", "cache", "changes", - "close", "collate", "collation_needed", - "commit_hook", "complete", "config", - "copy", "deserialize", "enable_load_extension", - "errorcode", "eval", "exists", - "function", "incrblob", "interrupt", - "last_insert_rowid", "nullvalue", "onecolumn", - "preupdate", "profile", "progress", - "rekey", "restore", "rollback_hook", - "serialize", "status", "timeout", - "total_changes", "trace", "trace_v2", - "transaction", "unlock_notify", "update_hook", - "version", "wal_hook", 0 - }; - enum DB_enum { - DB_AUTHORIZER, DB_BACKUP, DB_BIND_FALLBACK, - DB_BUSY, DB_CACHE, DB_CHANGES, - DB_CLOSE, DB_COLLATE, DB_COLLATION_NEEDED, - DB_COMMIT_HOOK, DB_COMPLETE, DB_CONFIG, - DB_COPY, DB_DESERIALIZE, DB_ENABLE_LOAD_EXTENSION, - DB_ERRORCODE, DB_EVAL, DB_EXISTS, - DB_FUNCTION, DB_INCRBLOB, DB_INTERRUPT, - DB_LAST_INSERT_ROWID, DB_NULLVALUE, DB_ONECOLUMN, - DB_PREUPDATE, DB_PROFILE, DB_PROGRESS, - DB_REKEY, DB_RESTORE, DB_ROLLBACK_HOOK, - DB_SERIALIZE, DB_STATUS, DB_TIMEOUT, - DB_TOTAL_CHANGES, DB_TRACE, DB_TRACE_V2, - DB_TRANSACTION, DB_UNLOCK_NOTIFY, DB_UPDATE_HOOK, - DB_VERSION, DB_WAL_HOOK - }; - /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */ - - if( objc<2 ){ - Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ..."); - return TCL_ERROR; - } - if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){ - return TCL_ERROR; - } - - switch( (enum DB_enum)choice ){ - - /* $db authorizer ?CALLBACK? - ** - ** Invoke the given callback to authorize each SQL operation as it is - ** compiled. 5 arguments are appended to the callback before it is - ** invoked: - ** - ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...) - ** (2) First descriptive name (depends on authorization type) - ** (3) Second descriptive name - ** (4) Name of the database (ex: "main", "temp") - ** (5) Name of trigger that is doing the access - ** - ** The callback should return on of the following strings: SQLITE_OK, - ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error. - ** - ** If this method is invoked with no arguments, the current authorization - ** callback string is returned. - */ - case DB_AUTHORIZER: { -#ifdef SQLITE_OMIT_AUTHORIZATION - Tcl_AppendResult(interp, "authorization not available in this build", - (char*)0); - return TCL_ERROR; -#else - if( objc>3 ){ - Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?"); - return TCL_ERROR; - }else if( objc==2 ){ - if( pDb->zAuth ){ - Tcl_AppendResult(interp, pDb->zAuth, (char*)0); - } - }else{ - char *zAuth; - int len; - if( pDb->zAuth ){ - Tcl_Free(pDb->zAuth); - } - zAuth = Tcl_GetStringFromObj(objv[2], &len); - if( zAuth && len>0 ){ - pDb->zAuth = Tcl_Alloc( len + 1 ); - memcpy(pDb->zAuth, zAuth, len+1); - }else{ - pDb->zAuth = 0; - } - if( pDb->zAuth ){ - typedef int (*sqlite3_auth_cb)( - void*,int,const char*,const char*, - const char*,const char*); - pDb->interp = interp; - sqlite3_set_authorizer(pDb->db,(sqlite3_auth_cb)auth_callback,pDb); - }else{ - sqlite3_set_authorizer(pDb->db, 0, 0); - } - } -#endif - break; - } - - /* $db backup ?DATABASE? FILENAME - ** - ** Open or create a database file named FILENAME. Transfer the - ** content of local database DATABASE (default: "main") into the - ** FILENAME database. - */ - case DB_BACKUP: { - const char *zDestFile; - const char *zSrcDb; - sqlite3 *pDest; - sqlite3_backup *pBackup; - - if( objc==3 ){ - zSrcDb = "main"; - zDestFile = Tcl_GetString(objv[2]); - }else if( objc==4 ){ - zSrcDb = Tcl_GetString(objv[2]); - zDestFile = Tcl_GetString(objv[3]); - }else{ - Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME"); - return TCL_ERROR; - } - rc = sqlite3_open_v2(zDestFile, &pDest, - SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE| pDb->openFlags, 0); - if( rc!=SQLITE_OK ){ - Tcl_AppendResult(interp, "cannot open target database: ", - sqlite3_errmsg(pDest), (char*)0); - sqlite3_close(pDest); - return TCL_ERROR; - } - pBackup = sqlite3_backup_init(pDest, "main", pDb->db, zSrcDb); - if( pBackup==0 ){ - Tcl_AppendResult(interp, "backup failed: ", - sqlite3_errmsg(pDest), (char*)0); - sqlite3_close(pDest); - return TCL_ERROR; - } - while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){} - sqlite3_backup_finish(pBackup); - if( rc==SQLITE_DONE ){ - rc = TCL_OK; - }else{ - Tcl_AppendResult(interp, "backup failed: ", - sqlite3_errmsg(pDest), (char*)0); - rc = TCL_ERROR; - } - sqlite3_close(pDest); - break; - } - - /* $db bind_fallback ?CALLBACK? - ** - ** When resolving bind parameters in an SQL statement, if the parameter - ** cannot be associated with a TCL variable then invoke CALLBACK with a - ** single argument that is the name of the parameter and use the return - ** value of the CALLBACK as the binding. If CALLBACK returns something - ** other than TCL_OK or TCL_ERROR then bind a NULL. - ** - ** If CALLBACK is an empty string, then revert to the default behavior - ** which is to set the binding to NULL. - ** - ** If CALLBACK returns an error, that causes the statement execution to - ** abort. Hence, to configure a connection so that it throws an error - ** on an attempt to bind an unknown variable, do something like this: - ** - ** proc bind_error {name} {error "no such variable: $name"} - ** db bind_fallback bind_error - */ - case DB_BIND_FALLBACK: { - if( objc>3 ){ - Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?"); - return TCL_ERROR; - }else if( objc==2 ){ - if( pDb->zBindFallback ){ - Tcl_AppendResult(interp, pDb->zBindFallback, (char*)0); - } - }else{ - char *zCallback; - int len; - if( pDb->zBindFallback ){ - Tcl_Free(pDb->zBindFallback); - } - zCallback = Tcl_GetStringFromObj(objv[2], &len); - if( zCallback && len>0 ){ - pDb->zBindFallback = Tcl_Alloc( len + 1 ); - memcpy(pDb->zBindFallback, zCallback, len+1); - }else{ - pDb->zBindFallback = 0; - } - } - break; - } - - /* $db busy ?CALLBACK? - ** - ** Invoke the given callback if an SQL statement attempts to open - ** a locked database file. - */ - case DB_BUSY: { - if( objc>3 ){ - Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK"); - return TCL_ERROR; - }else if( objc==2 ){ - if( pDb->zBusy ){ - Tcl_AppendResult(interp, pDb->zBusy, (char*)0); - } - }else{ - char *zBusy; - int len; - if( pDb->zBusy ){ - Tcl_Free(pDb->zBusy); - } - zBusy = Tcl_GetStringFromObj(objv[2], &len); - if( zBusy && len>0 ){ - pDb->zBusy = Tcl_Alloc( len + 1 ); - memcpy(pDb->zBusy, zBusy, len+1); - }else{ - pDb->zBusy = 0; - } - if( pDb->zBusy ){ - pDb->interp = interp; - sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb); - }else{ - sqlite3_busy_handler(pDb->db, 0, 0); - } - } - break; - } - - /* $db cache flush - ** $db cache size n - ** - ** Flush the prepared statement cache, or set the maximum number of - ** cached statements. - */ - case DB_CACHE: { - char *subCmd; - int n; - - if( objc<=2 ){ - Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?"); - return TCL_ERROR; - } - subCmd = Tcl_GetStringFromObj( objv[2], 0 ); - if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){ - if( objc!=3 ){ - Tcl_WrongNumArgs(interp, 2, objv, "flush"); - return TCL_ERROR; - }else{ - flushStmtCache( pDb ); - } - }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){ - if( objc!=4 ){ - Tcl_WrongNumArgs(interp, 2, objv, "size n"); - return TCL_ERROR; - }else{ - if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){ - Tcl_AppendResult( interp, "cannot convert \"", - Tcl_GetStringFromObj(objv[3],0), "\" to integer", (char*)0); - return TCL_ERROR; - }else{ - if( n<0 ){ - flushStmtCache( pDb ); - n = 0; - }else if( n>MAX_PREPARED_STMTS ){ - n = MAX_PREPARED_STMTS; - } - pDb->maxStmt = n; - } - } - }else{ - Tcl_AppendResult( interp, "bad option \"", - Tcl_GetStringFromObj(objv[2],0), "\": must be flush or size", - (char*)0); - return TCL_ERROR; - } - break; - } - - /* $db changes - ** - ** Return the number of rows that were modified, inserted, or deleted by - ** the most recent INSERT, UPDATE or DELETE statement, not including - ** any changes made by trigger programs. - */ - case DB_CHANGES: { - Tcl_Obj *pResult; - if( objc!=2 ){ - Tcl_WrongNumArgs(interp, 2, objv, ""); - return TCL_ERROR; - } - pResult = Tcl_GetObjResult(interp); - Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db)); - break; - } - - /* $db close - ** - ** Shutdown the database - */ - case DB_CLOSE: { - Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0)); - break; - } - - /* - ** $db collate NAME SCRIPT - ** - ** Create a new SQL collation function called NAME. Whenever - ** that function is called, invoke SCRIPT to evaluate the function. - */ - case DB_COLLATE: { - SqlCollate *pCollate; - char *zName; - char *zScript; - int nScript; - if( objc!=4 ){ - Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT"); - return TCL_ERROR; - } - zName = Tcl_GetStringFromObj(objv[2], 0); - zScript = Tcl_GetStringFromObj(objv[3], &nScript); - pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 ); - if( pCollate==0 ) return TCL_ERROR; - pCollate->interp = interp; - pCollate->pNext = pDb->pCollate; - pCollate->zScript = (char*)&pCollate[1]; - pDb->pCollate = pCollate; - memcpy(pCollate->zScript, zScript, nScript+1); - if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8, - pCollate, tclSqlCollate) ){ - Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE); - return TCL_ERROR; - } - break; - } - - /* - ** $db collation_needed SCRIPT - ** - ** Create a new SQL collation function called NAME. Whenever - ** that function is called, invoke SCRIPT to evaluate the function. - */ - case DB_COLLATION_NEEDED: { - if( objc!=3 ){ - Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT"); - return TCL_ERROR; - } - if( pDb->pCollateNeeded ){ - Tcl_DecrRefCount(pDb->pCollateNeeded); - } - pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]); - Tcl_IncrRefCount(pDb->pCollateNeeded); - sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded); - break; - } - - /* $db commit_hook ?CALLBACK? - ** - ** Invoke the given callback just before committing every SQL transaction. - ** If the callback throws an exception or returns non-zero, then the - ** transaction is aborted. If CALLBACK is an empty string, the callback - ** is disabled. - */ - case DB_COMMIT_HOOK: { - if( objc>3 ){ - Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?"); - return TCL_ERROR; - }else if( objc==2 ){ - if( pDb->zCommit ){ - Tcl_AppendResult(interp, pDb->zCommit, (char*)0); - } - }else{ - const char *zCommit; - int len; - if( pDb->zCommit ){ - Tcl_Free(pDb->zCommit); - } - zCommit = Tcl_GetStringFromObj(objv[2], &len); - if( zCommit && len>0 ){ - pDb->zCommit = Tcl_Alloc( len + 1 ); - memcpy(pDb->zCommit, zCommit, len+1); - }else{ - pDb->zCommit = 0; - } - if( pDb->zCommit ){ - pDb->interp = interp; - sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb); - }else{ - sqlite3_commit_hook(pDb->db, 0, 0); - } - } - break; - } - - /* $db complete SQL - ** - ** Return TRUE if SQL is a complete SQL statement. Return FALSE if - ** additional lines of input are needed. This is similar to the - ** built-in "info complete" command of Tcl. - */ - case DB_COMPLETE: { -#ifndef SQLITE_OMIT_COMPLETE - Tcl_Obj *pResult; - int isComplete; - if( objc!=3 ){ - Tcl_WrongNumArgs(interp, 2, objv, "SQL"); - return TCL_ERROR; - } - isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) ); - pResult = Tcl_GetObjResult(interp); - Tcl_SetBooleanObj(pResult, isComplete); -#endif - break; - } - - /* $db config ?OPTION? ?BOOLEAN? - ** - ** Configure the database connection using the sqlite3_db_config() - ** interface. - */ - case DB_CONFIG: { - static const struct DbConfigChoices { - const char *zName; - int op; - } aDbConfig[] = { - { "defensive", SQLITE_DBCONFIG_DEFENSIVE }, - { "dqs_ddl", SQLITE_DBCONFIG_DQS_DDL }, - { "dqs_dml", SQLITE_DBCONFIG_DQS_DML }, - { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY }, - { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG }, - { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER }, - { "enable_view", SQLITE_DBCONFIG_ENABLE_VIEW }, - { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER }, - { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE }, - { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT }, - { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION }, - { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE }, - { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE }, - { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP }, - { "trusted_schema", SQLITE_DBCONFIG_TRUSTED_SCHEMA }, - { "writable_schema", SQLITE_DBCONFIG_WRITABLE_SCHEMA }, - }; - Tcl_Obj *pResult; - int ii; - if( objc>4 ){ - Tcl_WrongNumArgs(interp, 2, objv, "?OPTION? ?BOOLEAN?"); - return TCL_ERROR; - } - if( objc==2 ){ - /* With no arguments, list all configuration options and with the - ** current value */ - pResult = Tcl_NewListObj(0,0); - for(ii=0; iidb, aDbConfig[ii].op, -1, &v); - Tcl_ListObjAppendElement(interp, pResult, - Tcl_NewStringObj(aDbConfig[ii].zName,-1)); - Tcl_ListObjAppendElement(interp, pResult, - Tcl_NewIntObj(v)); - } - }else{ - const char *zOpt = Tcl_GetString(objv[2]); - int onoff = -1; - int v = 0; - if( zOpt[0]=='-' ) zOpt++; - for(ii=0; ii=sizeof(aDbConfig)/sizeof(aDbConfig[0]) ){ - Tcl_AppendResult(interp, "unknown config option: \"", zOpt, - "\"", (void*)0); - return TCL_ERROR; - } - if( objc==4 ){ - if( Tcl_GetBooleanFromObj(interp, objv[3], &onoff) ){ - return TCL_ERROR; - } - } - sqlite3_db_config(pDb->db, aDbConfig[ii].op, onoff, &v); - pResult = Tcl_NewIntObj(v); - } - Tcl_SetObjResult(interp, pResult); - break; - } - - /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR? - ** - ** Copy data into table from filename, optionally using SEPARATOR - ** as column separators. If a column contains a null string, or the - ** value of NULLINDICATOR, a NULL is inserted for the column. - ** conflict-algorithm is one of the sqlite conflict algorithms: - ** rollback, abort, fail, ignore, replace - ** On success, return the number of lines processed, not necessarily same - ** as 'db changes' due to conflict-algorithm selected. - ** - ** This code is basically an implementation/enhancement of - ** the sqlite3 shell.c ".import" command. - ** - ** This command usage is equivalent to the sqlite2.x COPY statement, - ** which imports file data into a table using the PostgreSQL COPY file format: - ** $db copy $conflit_algo $table_name $filename \t \\N - */ - case DB_COPY: { - char *zTable; /* Insert data into this table */ - char *zFile; /* The file from which to extract data */ - char *zConflict; /* The conflict algorithm to use */ - sqlite3_stmt *pStmt; /* A statement */ - int nCol; /* Number of columns in the table */ - int nByte; /* Number of bytes in an SQL string */ - int i, j; /* Loop counters */ - int nSep; /* Number of bytes in zSep[] */ - int nNull; /* Number of bytes in zNull[] */ - char *zSql; /* An SQL statement */ - char *zLine; /* A single line of input from the file */ - char **azCol; /* zLine[] broken up into columns */ - const char *zCommit; /* How to commit changes */ - FILE *in; /* The input file */ - int lineno = 0; /* Line number of input file */ - char zLineNum[80]; /* Line number print buffer */ - Tcl_Obj *pResult; /* interp result */ - - const char *zSep; - const char *zNull; - if( objc<5 || objc>7 ){ - Tcl_WrongNumArgs(interp, 2, objv, - "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?"); - return TCL_ERROR; - } - if( objc>=6 ){ - zSep = Tcl_GetStringFromObj(objv[5], 0); - }else{ - zSep = "\t"; - } - if( objc>=7 ){ - zNull = Tcl_GetStringFromObj(objv[6], 0); - }else{ - zNull = ""; - } - zConflict = Tcl_GetStringFromObj(objv[2], 0); - zTable = Tcl_GetStringFromObj(objv[3], 0); - zFile = Tcl_GetStringFromObj(objv[4], 0); - nSep = strlen30(zSep); - nNull = strlen30(zNull); - if( nSep==0 ){ - Tcl_AppendResult(interp,"Error: non-null separator required for copy", - (char*)0); - return TCL_ERROR; - } - if(strcmp(zConflict, "rollback") != 0 && - strcmp(zConflict, "abort" ) != 0 && - strcmp(zConflict, "fail" ) != 0 && - strcmp(zConflict, "ignore" ) != 0 && - strcmp(zConflict, "replace" ) != 0 ) { - Tcl_AppendResult(interp, "Error: \"", zConflict, - "\", conflict-algorithm must be one of: rollback, " - "abort, fail, ignore, or replace", (char*)0); - return TCL_ERROR; - } - zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable); - if( zSql==0 ){ - Tcl_AppendResult(interp, "Error: no such table: ", zTable, (char*)0); - return TCL_ERROR; - } - nByte = strlen30(zSql); - rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0); - sqlite3_free(zSql); - if( rc ){ - Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0); - nCol = 0; - }else{ - nCol = sqlite3_column_count(pStmt); - } - sqlite3_finalize(pStmt); - if( nCol==0 ) { - return TCL_ERROR; - } - zSql = malloc( nByte + 50 + nCol*2 ); - if( zSql==0 ) { - Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0); - return TCL_ERROR; - } - sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?", - zConflict, zTable); - j = strlen30(zSql); - for(i=1; idb, zSql, -1, &pStmt, 0); - free(zSql); - if( rc ){ - Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), (char*)0); - sqlite3_finalize(pStmt); - return TCL_ERROR; - } - in = fopen(zFile, "rb"); - if( in==0 ){ - Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, (char*)0); - sqlite3_finalize(pStmt); - return TCL_ERROR; - } - azCol = malloc( sizeof(azCol[0])*(nCol+1) ); - if( azCol==0 ) { - Tcl_AppendResult(interp, "Error: can't malloc()", (char*)0); - fclose(in); - return TCL_ERROR; - } - (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0); - zCommit = "COMMIT"; - while( (zLine = local_getline(0, in))!=0 ){ - char *z; - lineno++; - azCol[0] = zLine; - for(i=0, z=zLine; *z; z++){ - if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){ - *z = 0; - i++; - if( i0 && strcmp(azCol[i], zNull)==0) - || strlen30(azCol[i])==0 - ){ - sqlite3_bind_null(pStmt, i+1); - }else{ - sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC); - } - } - sqlite3_step(pStmt); - rc = sqlite3_reset(pStmt); - free(zLine); - if( rc!=SQLITE_OK ){ - Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), (char*)0); - zCommit = "ROLLBACK"; - break; - } - } - free(azCol); - fclose(in); - sqlite3_finalize(pStmt); - (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0); - - if( zCommit[0] == 'C' ){ - /* success, set result as number of lines processed */ - pResult = Tcl_GetObjResult(interp); - Tcl_SetIntObj(pResult, lineno); - rc = TCL_OK; - }else{ - /* failure, append lineno where failed */ - sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno); - Tcl_AppendResult(interp,", failed while processing line: ",zLineNum, - (char*)0); - rc = TCL_ERROR; - } - break; - } - - /* - ** $db deserialize ?-maxsize N? ?-readonly BOOL? ?DATABASE? VALUE - ** - ** Reopen DATABASE (default "main") using the content in $VALUE - */ - case DB_DESERIALIZE: { -#ifndef SQLITE_ENABLE_DESERIALIZE - Tcl_AppendResult(interp, "MEMDB not available in this build", - (char*)0); - rc = TCL_ERROR; -#else - const char *zSchema = 0; - Tcl_Obj *pValue = 0; - unsigned char *pBA; - unsigned char *pData; - int len, xrc; - sqlite3_int64 mxSize = 0; - int i; - int isReadonly = 0; - - - if( objc<3 ){ - Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? VALUE"); - rc = TCL_ERROR; - break; - } - for(i=2; i0 ){ - Tcl_AppendResult(interp, "out of memory", (char*)0); - rc = TCL_ERROR; - }else{ - int flags; - if( len>0 ) memcpy(pData, pBA, len); - if( isReadonly ){ - flags = SQLITE_DESERIALIZE_FREEONCLOSE | SQLITE_DESERIALIZE_READONLY; - }else{ - flags = SQLITE_DESERIALIZE_FREEONCLOSE | SQLITE_DESERIALIZE_RESIZEABLE; - } - xrc = sqlite3_deserialize(pDb->db, zSchema, pData, len, len, flags); - if( xrc ){ - Tcl_AppendResult(interp, "unable to set MEMDB content", (char*)0); - rc = TCL_ERROR; - } - if( mxSize>0 ){ - sqlite3_file_control(pDb->db, zSchema,SQLITE_FCNTL_SIZE_LIMIT,&mxSize); - } - } -deserialize_error: -#endif - break; - } - - /* - ** $db enable_load_extension BOOLEAN - ** - ** Turn the extension loading feature on or off. It if off by - ** default. - */ - case DB_ENABLE_LOAD_EXTENSION: { -#ifndef SQLITE_OMIT_LOAD_EXTENSION - int onoff; - if( objc!=3 ){ - Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN"); - return TCL_ERROR; - } - if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){ - return TCL_ERROR; - } - sqlite3_enable_load_extension(pDb->db, onoff); - break; -#else - Tcl_AppendResult(interp, "extension loading is turned off at compile-time", - (char*)0); - return TCL_ERROR; -#endif - } - - /* - ** $db errorcode - ** - ** Return the numeric error code that was returned by the most recent - ** call to sqlite3_exec(). - */ - case DB_ERRORCODE: { - Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db))); - break; - } - - /* - ** $db exists $sql - ** $db onecolumn $sql - ** - ** The onecolumn method is the equivalent of: - ** lindex [$db eval $sql] 0 - */ - case DB_EXISTS: - case DB_ONECOLUMN: { - Tcl_Obj *pResult = 0; - DbEvalContext sEval; - if( objc!=3 ){ - Tcl_WrongNumArgs(interp, 2, objv, "SQL"); - return TCL_ERROR; - } - - dbEvalInit(&sEval, pDb, objv[2], 0, 0); - rc = dbEvalStep(&sEval); - if( choice==DB_ONECOLUMN ){ - if( rc==TCL_OK ){ - pResult = dbEvalColumnValue(&sEval, 0); - }else if( rc==TCL_BREAK ){ - Tcl_ResetResult(interp); - } - }else if( rc==TCL_BREAK || rc==TCL_OK ){ - pResult = Tcl_NewBooleanObj(rc==TCL_OK); - } - dbEvalFinalize(&sEval); - if( pResult ) Tcl_SetObjResult(interp, pResult); - - if( rc==TCL_BREAK ){ - rc = TCL_OK; - } - break; - } - - /* - ** $db eval ?options? $sql ?array? ?{ ...code... }? - ** - ** The SQL statement in $sql is evaluated. For each row, the values are - ** placed in elements of the array named "array" and ...code... is executed. - ** If "array" and "code" are omitted, then no callback is every invoked. - ** If "array" is an empty string, then the values are placed in variables - ** that have the same name as the fields extracted by the query. - */ - case DB_EVAL: { - int evalFlags = 0; - const char *zOpt; - while( objc>3 && (zOpt = Tcl_GetString(objv[2]))!=0 && zOpt[0]=='-' ){ - if( strcmp(zOpt, "-withoutnulls")==0 ){ - evalFlags |= SQLITE_EVAL_WITHOUTNULLS; - } - else{ - Tcl_AppendResult(interp, "unknown option: \"", zOpt, "\"", (void*)0); - return TCL_ERROR; - } - objc--; - objv++; - } - if( objc<3 || objc>5 ){ - Tcl_WrongNumArgs(interp, 2, objv, - "?OPTIONS? SQL ?ARRAY-NAME? ?SCRIPT?"); - return TCL_ERROR; - } - - if( objc==3 ){ - DbEvalContext sEval; - Tcl_Obj *pRet = Tcl_NewObj(); - Tcl_IncrRefCount(pRet); - dbEvalInit(&sEval, pDb, objv[2], 0, 0); - while( TCL_OK==(rc = dbEvalStep(&sEval)) ){ - int i; - int nCol; - dbEvalRowInfo(&sEval, &nCol, 0); - for(i=0; i=5 && *(char *)Tcl_GetString(objv[3]) ){ - pArray = objv[3]; - } - pScript = objv[objc-1]; - Tcl_IncrRefCount(pScript); - - p = (DbEvalContext *)Tcl_Alloc(sizeof(DbEvalContext)); - dbEvalInit(p, pDb, objv[2], pArray, evalFlags); - - cd2[0] = (void *)p; - cd2[1] = (void *)pScript; - rc = DbEvalNextCmd(cd2, interp, TCL_OK); - } - break; - } - - /* - ** $db function NAME [OPTIONS] SCRIPT - ** - ** Create a new SQL function called NAME. Whenever that function is - ** called, invoke SCRIPT to evaluate the function. - ** - ** Options: - ** --argcount N Function has exactly N arguments - ** --deterministic The function is pure - ** --directonly Prohibit use inside triggers and views - ** --innocuous Has no side effects or information leaks - ** --returntype TYPE Specify the return type of the function - */ - case DB_FUNCTION: { - int flags = SQLITE_UTF8; - SqlFunc *pFunc; - Tcl_Obj *pScript; - char *zName; - int nArg = -1; - int i; - int eType = SQLITE_NULL; - if( objc<4 ){ - Tcl_WrongNumArgs(interp, 2, objv, "NAME ?SWITCHES? SCRIPT"); - return TCL_ERROR; - } - for(i=3; i<(objc-1); i++){ - const char *z = Tcl_GetString(objv[i]); - int n = strlen30(z); - if( n>1 && strncmp(z, "-argcount",n)==0 ){ - if( i==(objc-2) ){ - Tcl_AppendResult(interp, "option requires an argument: ", z,(char*)0); - return TCL_ERROR; - } - if( Tcl_GetIntFromObj(interp, objv[i+1], &nArg) ) return TCL_ERROR; - if( nArg<0 ){ - Tcl_AppendResult(interp, "number of arguments must be non-negative", - (char*)0); - return TCL_ERROR; - } - i++; - }else - if( n>1 && strncmp(z, "-deterministic",n)==0 ){ - flags |= SQLITE_DETERMINISTIC; - }else - if( n>1 && strncmp(z, "-directonly",n)==0 ){ - flags |= SQLITE_DIRECTONLY; - }else - if( n>1 && strncmp(z, "-innocuous",n)==0 ){ - flags |= SQLITE_INNOCUOUS; - }else - if( n>1 && strncmp(z, "-returntype", n)==0 ){ - const char *azType[] = {"integer", "real", "text", "blob", "any", 0}; - assert( SQLITE_INTEGER==1 && SQLITE_FLOAT==2 && SQLITE_TEXT==3 ); - assert( SQLITE_BLOB==4 && SQLITE_NULL==5 ); - if( i==(objc-2) ){ - Tcl_AppendResult(interp, "option requires an argument: ", z,(char*)0); - return TCL_ERROR; - } - i++; - if( Tcl_GetIndexFromObj(interp, objv[i], azType, "type", 0, &eType) ){ - return TCL_ERROR; - } - eType++; - }else{ - Tcl_AppendResult(interp, "bad option \"", z, - "\": must be -argcount, -deterministic, -directonly," - " -innocuous, or -returntype", (char*)0 - ); - return TCL_ERROR; - } - } - - pScript = objv[objc-1]; - zName = Tcl_GetStringFromObj(objv[2], 0); - pFunc = findSqlFunc(pDb, zName); - if( pFunc==0 ) return TCL_ERROR; - if( pFunc->pScript ){ - Tcl_DecrRefCount(pFunc->pScript); - } - pFunc->pScript = pScript; - Tcl_IncrRefCount(pScript); - pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript); - pFunc->eType = eType; - rc = sqlite3_create_function(pDb->db, zName, nArg, flags, - pFunc, tclSqlFunc, 0, 0); - if( rc!=SQLITE_OK ){ - rc = TCL_ERROR; - Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE); - } - break; - } - - /* - ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID - */ - case DB_INCRBLOB: { -#ifdef SQLITE_OMIT_INCRBLOB - Tcl_AppendResult(interp, "incrblob not available in this build", (char*)0); - return TCL_ERROR; -#else - int isReadonly = 0; - const char *zDb = "main"; - const char *zTable; - const char *zColumn; - Tcl_WideInt iRow; - - /* Check for the -readonly option */ - if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){ - isReadonly = 1; - } - - if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){ - Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID"); - return TCL_ERROR; - } - - if( objc==(6+isReadonly) ){ - zDb = Tcl_GetString(objv[2]); - } - zTable = Tcl_GetString(objv[objc-3]); - zColumn = Tcl_GetString(objv[objc-2]); - rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow); - - if( rc==TCL_OK ){ - rc = createIncrblobChannel( - interp, pDb, zDb, zTable, zColumn, (sqlite3_int64)iRow, isReadonly - ); - } -#endif - break; - } - - /* - ** $db interrupt - ** - ** Interrupt the execution of the inner-most SQL interpreter. This - ** causes the SQL statement to return an error of SQLITE_INTERRUPT. - */ - case DB_INTERRUPT: { - sqlite3_interrupt(pDb->db); - break; - } - - /* - ** $db nullvalue ?STRING? - ** - ** Change text used when a NULL comes back from the database. If ?STRING? - ** is not present, then the current string used for NULL is returned. - ** If STRING is present, then STRING is returned. - ** - */ - case DB_NULLVALUE: { - if( objc!=2 && objc!=3 ){ - Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE"); - return TCL_ERROR; - } - if( objc==3 ){ - int len; - char *zNull = Tcl_GetStringFromObj(objv[2], &len); - if( pDb->zNull ){ - Tcl_Free(pDb->zNull); - } - if( zNull && len>0 ){ - pDb->zNull = Tcl_Alloc( len + 1 ); - memcpy(pDb->zNull, zNull, len); - pDb->zNull[len] = '\0'; - }else{ - pDb->zNull = 0; - } - } - Tcl_SetObjResult(interp, Tcl_NewStringObj(pDb->zNull, -1)); - break; - } - - /* - ** $db last_insert_rowid - ** - ** Return an integer which is the ROWID for the most recent insert. - */ - case DB_LAST_INSERT_ROWID: { - Tcl_Obj *pResult; - Tcl_WideInt rowid; - if( objc!=2 ){ - Tcl_WrongNumArgs(interp, 2, objv, ""); - return TCL_ERROR; - } - rowid = sqlite3_last_insert_rowid(pDb->db); - pResult = Tcl_GetObjResult(interp); - Tcl_SetWideIntObj(pResult, rowid); - break; - } - - /* - ** The DB_ONECOLUMN method is implemented together with DB_EXISTS. - */ - - /* $db progress ?N CALLBACK? - ** - ** Invoke the given callback every N virtual machine opcodes while executing - ** queries. - */ - case DB_PROGRESS: { - if( objc==2 ){ - if( pDb->zProgress ){ - Tcl_AppendResult(interp, pDb->zProgress, (char*)0); - } - }else if( objc==4 ){ - char *zProgress; - int len; - int N; - if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){ - return TCL_ERROR; - }; - if( pDb->zProgress ){ - Tcl_Free(pDb->zProgress); - } - zProgress = Tcl_GetStringFromObj(objv[3], &len); - if( zProgress && len>0 ){ - pDb->zProgress = Tcl_Alloc( len + 1 ); - memcpy(pDb->zProgress, zProgress, len+1); - }else{ - pDb->zProgress = 0; - } -#ifndef SQLITE_OMIT_PROGRESS_CALLBACK - if( pDb->zProgress ){ - pDb->interp = interp; - sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb); - }else{ - sqlite3_progress_handler(pDb->db, 0, 0, 0); - } -#endif - }else{ - Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK"); - return TCL_ERROR; - } - break; - } - - /* $db profile ?CALLBACK? - ** - ** Make arrangements to invoke the CALLBACK routine after each SQL statement - ** that has run. The text of the SQL and the amount of elapse time are - ** appended to CALLBACK before the script is run. - */ - case DB_PROFILE: { - if( objc>3 ){ - Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?"); - return TCL_ERROR; - }else if( objc==2 ){ - if( pDb->zProfile ){ - Tcl_AppendResult(interp, pDb->zProfile, (char*)0); - } - }else{ - char *zProfile; - int len; - if( pDb->zProfile ){ - Tcl_Free(pDb->zProfile); - } - zProfile = Tcl_GetStringFromObj(objv[2], &len); - if( zProfile && len>0 ){ - pDb->zProfile = Tcl_Alloc( len + 1 ); - memcpy(pDb->zProfile, zProfile, len+1); - }else{ - pDb->zProfile = 0; - } -#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \ - !defined(SQLITE_OMIT_DEPRECATED) - if( pDb->zProfile ){ - pDb->interp = interp; - sqlite3_profile(pDb->db, DbProfileHandler, pDb); - }else{ - sqlite3_profile(pDb->db, 0, 0); - } -#endif - } - break; - } - - /* - ** $db rekey KEY - ** - ** Change the encryption key on the currently open database. - */ - case DB_REKEY: { - if( objc!=3 ){ - Tcl_WrongNumArgs(interp, 2, objv, "KEY"); - return TCL_ERROR; - } - break; - } - - /* $db restore ?DATABASE? FILENAME - ** - ** Open a database file named FILENAME. Transfer the content - ** of FILENAME into the local database DATABASE (default: "main"). - */ - case DB_RESTORE: { - const char *zSrcFile; - const char *zDestDb; - sqlite3 *pSrc; - sqlite3_backup *pBackup; - int nTimeout = 0; - - if( objc==3 ){ - zDestDb = "main"; - zSrcFile = Tcl_GetString(objv[2]); - }else if( objc==4 ){ - zDestDb = Tcl_GetString(objv[2]); - zSrcFile = Tcl_GetString(objv[3]); - }else{ - Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME"); - return TCL_ERROR; - } - rc = sqlite3_open_v2(zSrcFile, &pSrc, - SQLITE_OPEN_READONLY | pDb->openFlags, 0); - if( rc!=SQLITE_OK ){ - Tcl_AppendResult(interp, "cannot open source database: ", - sqlite3_errmsg(pSrc), (char*)0); - sqlite3_close(pSrc); - return TCL_ERROR; - } - pBackup = sqlite3_backup_init(pDb->db, zDestDb, pSrc, "main"); - if( pBackup==0 ){ - Tcl_AppendResult(interp, "restore failed: ", - sqlite3_errmsg(pDb->db), (char*)0); - sqlite3_close(pSrc); - return TCL_ERROR; - } - while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK - || rc==SQLITE_BUSY ){ - if( rc==SQLITE_BUSY ){ - if( nTimeout++ >= 3 ) break; - sqlite3_sleep(100); - } - } - sqlite3_backup_finish(pBackup); - if( rc==SQLITE_DONE ){ - rc = TCL_OK; - }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){ - Tcl_AppendResult(interp, "restore failed: source database busy", - (char*)0); - rc = TCL_ERROR; - }else{ - Tcl_AppendResult(interp, "restore failed: ", - sqlite3_errmsg(pDb->db), (char*)0); - rc = TCL_ERROR; - } - sqlite3_close(pSrc); - break; - } - - /* - ** $db serialize ?DATABASE? - ** - ** Return a serialization of a database. - */ - case DB_SERIALIZE: { -#ifndef SQLITE_ENABLE_DESERIALIZE - Tcl_AppendResult(interp, "MEMDB not available in this build", - (char*)0); - rc = TCL_ERROR; -#else - const char *zSchema = objc>=3 ? Tcl_GetString(objv[2]) : "main"; - sqlite3_int64 sz = 0; - unsigned char *pData; - if( objc!=2 && objc!=3 ){ - Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE?"); - rc = TCL_ERROR; - }else{ - int needFree; - pData = sqlite3_serialize(pDb->db, zSchema, &sz, SQLITE_SERIALIZE_NOCOPY); - if( pData ){ - needFree = 0; - }else{ - pData = sqlite3_serialize(pDb->db, zSchema, &sz, 0); - needFree = 1; - } - Tcl_SetObjResult(interp, Tcl_NewByteArrayObj(pData,sz)); - if( needFree ) sqlite3_free(pData); - } -#endif - break; - } - - /* - ** $db status (step|sort|autoindex|vmstep) - ** - ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or - ** SQLITE_STMTSTATUS_SORT for the most recent eval. - */ - case DB_STATUS: { - int v; - const char *zOp; - if( objc!=3 ){ - Tcl_WrongNumArgs(interp, 2, objv, "(step|sort|autoindex)"); - return TCL_ERROR; - } - zOp = Tcl_GetString(objv[2]); - if( strcmp(zOp, "step")==0 ){ - v = pDb->nStep; - }else if( strcmp(zOp, "sort")==0 ){ - v = pDb->nSort; - }else if( strcmp(zOp, "autoindex")==0 ){ - v = pDb->nIndex; - }else if( strcmp(zOp, "vmstep")==0 ){ - v = pDb->nVMStep; - }else{ - Tcl_AppendResult(interp, - "bad argument: should be autoindex, step, sort or vmstep", - (char*)0); - return TCL_ERROR; - } - Tcl_SetObjResult(interp, Tcl_NewIntObj(v)); - break; - } - - /* - ** $db timeout MILLESECONDS - ** - ** Delay for the number of milliseconds specified when a file is locked. - */ - case DB_TIMEOUT: { - int ms; - if( objc!=3 ){ - Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS"); - return TCL_ERROR; - } - if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR; - sqlite3_busy_timeout(pDb->db, ms); - break; - } - - /* - ** $db total_changes - ** - ** Return the number of rows that were modified, inserted, or deleted - ** since the database handle was created. - */ - case DB_TOTAL_CHANGES: { - Tcl_Obj *pResult; - if( objc!=2 ){ - Tcl_WrongNumArgs(interp, 2, objv, ""); - return TCL_ERROR; - } - pResult = Tcl_GetObjResult(interp); - Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db)); - break; - } - - /* $db trace ?CALLBACK? - ** - ** Make arrangements to invoke the CALLBACK routine for each SQL statement - ** that is executed. The text of the SQL is appended to CALLBACK before - ** it is executed. - */ - case DB_TRACE: { - if( objc>3 ){ - Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?"); - return TCL_ERROR; - }else if( objc==2 ){ - if( pDb->zTrace ){ - Tcl_AppendResult(interp, pDb->zTrace, (char*)0); - } - }else{ - char *zTrace; - int len; - if( pDb->zTrace ){ - Tcl_Free(pDb->zTrace); - } - zTrace = Tcl_GetStringFromObj(objv[2], &len); - if( zTrace && len>0 ){ - pDb->zTrace = Tcl_Alloc( len + 1 ); - memcpy(pDb->zTrace, zTrace, len+1); - }else{ - pDb->zTrace = 0; - } -#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) && \ - !defined(SQLITE_OMIT_DEPRECATED) - if( pDb->zTrace ){ - pDb->interp = interp; - sqlite3_trace(pDb->db, DbTraceHandler, pDb); - }else{ - sqlite3_trace(pDb->db, 0, 0); - } -#endif - } - break; - } - - /* $db trace_v2 ?CALLBACK? ?MASK? - ** - ** Make arrangements to invoke the CALLBACK routine for each trace event - ** matching the mask that is generated. The parameters are appended to - ** CALLBACK before it is executed. - */ - case DB_TRACE_V2: { - if( objc>4 ){ - Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK? ?MASK?"); - return TCL_ERROR; - }else if( objc==2 ){ - if( pDb->zTraceV2 ){ - Tcl_AppendResult(interp, pDb->zTraceV2, (char*)0); - } - }else{ - char *zTraceV2; - int len; - Tcl_WideInt wMask = 0; - if( objc==4 ){ - static const char *TTYPE_strs[] = { - "statement", "profile", "row", "close", 0 - }; - enum TTYPE_enum { - TTYPE_STMT, TTYPE_PROFILE, TTYPE_ROW, TTYPE_CLOSE - }; - int i; - if( TCL_OK!=Tcl_ListObjLength(interp, objv[3], &len) ){ - return TCL_ERROR; - } - for(i=0; izTraceV2 ){ - Tcl_Free(pDb->zTraceV2); - } - zTraceV2 = Tcl_GetStringFromObj(objv[2], &len); - if( zTraceV2 && len>0 ){ - pDb->zTraceV2 = Tcl_Alloc( len + 1 ); - memcpy(pDb->zTraceV2, zTraceV2, len+1); - }else{ - pDb->zTraceV2 = 0; - } -#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) - if( pDb->zTraceV2 ){ - pDb->interp = interp; - sqlite3_trace_v2(pDb->db, (unsigned)wMask, DbTraceV2Handler, pDb); - }else{ - sqlite3_trace_v2(pDb->db, 0, 0, 0); - } -#endif - } - break; - } - - /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT - ** - ** Start a new transaction (if we are not already in the midst of a - ** transaction) and execute the TCL script SCRIPT. After SCRIPT - ** completes, either commit the transaction or roll it back if SCRIPT - ** throws an exception. Or if no new transation was started, do nothing. - ** pass the exception on up the stack. - ** - ** This command was inspired by Dave Thomas's talk on Ruby at the - ** 2005 O'Reilly Open Source Convention (OSCON). - */ - case DB_TRANSACTION: { - Tcl_Obj *pScript; - const char *zBegin = "SAVEPOINT _tcl_transaction"; - if( objc!=3 && objc!=4 ){ - Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT"); - return TCL_ERROR; - } - - if( pDb->nTransaction==0 && objc==4 ){ - static const char *TTYPE_strs[] = { - "deferred", "exclusive", "immediate", 0 - }; - enum TTYPE_enum { - TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE - }; - int ttype; - if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type", - 0, &ttype) ){ - return TCL_ERROR; - } - switch( (enum TTYPE_enum)ttype ){ - case TTYPE_DEFERRED: /* no-op */; break; - case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break; - case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break; - } - } - pScript = objv[objc-1]; - - /* Run the SQLite BEGIN command to open a transaction or savepoint. */ - pDb->disableAuth++; - rc = sqlite3_exec(pDb->db, zBegin, 0, 0, 0); - pDb->disableAuth--; - if( rc!=SQLITE_OK ){ - Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0); - return TCL_ERROR; - } - pDb->nTransaction++; - - /* If using NRE, schedule a callback to invoke the script pScript, then - ** a second callback to commit (or rollback) the transaction or savepoint - ** opened above. If not using NRE, evaluate the script directly, then - ** call function DbTransPostCmd() to commit (or rollback) the transaction - ** or savepoint. */ - if( DbUseNre() ){ - Tcl_NRAddCallback(interp, DbTransPostCmd, cd, 0, 0, 0); - (void)Tcl_NREvalObj(interp, pScript, 0); - }else{ - rc = DbTransPostCmd(&cd, interp, Tcl_EvalObjEx(interp, pScript, 0)); - } - break; - } - - /* - ** $db unlock_notify ?script? - */ - case DB_UNLOCK_NOTIFY: { -#ifndef SQLITE_ENABLE_UNLOCK_NOTIFY - Tcl_AppendResult(interp, "unlock_notify not available in this build", - (char*)0); - rc = TCL_ERROR; -#else - if( objc!=2 && objc!=3 ){ - Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?"); - rc = TCL_ERROR; - }else{ - void (*xNotify)(void **, int) = 0; - void *pNotifyArg = 0; - - if( pDb->pUnlockNotify ){ - Tcl_DecrRefCount(pDb->pUnlockNotify); - pDb->pUnlockNotify = 0; - } - - if( objc==3 ){ - xNotify = DbUnlockNotify; - pNotifyArg = (void *)pDb; - pDb->pUnlockNotify = objv[2]; - Tcl_IncrRefCount(pDb->pUnlockNotify); - } - - if( sqlite3_unlock_notify(pDb->db, xNotify, pNotifyArg) ){ - Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0); - rc = TCL_ERROR; - } - } -#endif - break; - } - - /* - ** $db preupdate_hook count - ** $db preupdate_hook hook ?SCRIPT? - ** $db preupdate_hook new INDEX - ** $db preupdate_hook old INDEX - */ - case DB_PREUPDATE: { -#ifndef SQLITE_ENABLE_PREUPDATE_HOOK - Tcl_AppendResult(interp, "preupdate_hook was omitted at compile-time", - (char*)0); - rc = TCL_ERROR; -#else - static const char *azSub[] = {"count", "depth", "hook", "new", "old", 0}; - enum DbPreupdateSubCmd { - PRE_COUNT, PRE_DEPTH, PRE_HOOK, PRE_NEW, PRE_OLD - }; - int iSub; - - if( objc<3 ){ - Tcl_WrongNumArgs(interp, 2, objv, "SUB-COMMAND ?ARGS?"); - } - if( Tcl_GetIndexFromObj(interp, objv[2], azSub, "sub-command", 0, &iSub) ){ - return TCL_ERROR; - } - - switch( (enum DbPreupdateSubCmd)iSub ){ - case PRE_COUNT: { - int nCol = sqlite3_preupdate_count(pDb->db); - Tcl_SetObjResult(interp, Tcl_NewIntObj(nCol)); - break; - } - - case PRE_HOOK: { - if( objc>4 ){ - Tcl_WrongNumArgs(interp, 2, objv, "hook ?SCRIPT?"); - return TCL_ERROR; - } - DbHookCmd(interp, pDb, (objc==4 ? objv[3] : 0), &pDb->pPreUpdateHook); - break; - } - - case PRE_DEPTH: { - Tcl_Obj *pRet; - if( objc!=3 ){ - Tcl_WrongNumArgs(interp, 3, objv, ""); - return TCL_ERROR; - } - pRet = Tcl_NewIntObj(sqlite3_preupdate_depth(pDb->db)); - Tcl_SetObjResult(interp, pRet); - break; - } - - case PRE_NEW: - case PRE_OLD: { - int iIdx; - sqlite3_value *pValue; - if( objc!=4 ){ - Tcl_WrongNumArgs(interp, 3, objv, "INDEX"); - return TCL_ERROR; - } - if( Tcl_GetIntFromObj(interp, objv[3], &iIdx) ){ - return TCL_ERROR; - } - - if( iSub==PRE_OLD ){ - rc = sqlite3_preupdate_old(pDb->db, iIdx, &pValue); - }else{ - assert( iSub==PRE_NEW ); - rc = sqlite3_preupdate_new(pDb->db, iIdx, &pValue); - } - - if( rc==SQLITE_OK ){ - Tcl_Obj *pObj; - pObj = Tcl_NewStringObj((char*)sqlite3_value_text(pValue), -1); - Tcl_SetObjResult(interp, pObj); - }else{ - Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0); - return TCL_ERROR; - } - } - } -#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ - break; - } - - /* - ** $db wal_hook ?script? - ** $db update_hook ?script? - ** $db rollback_hook ?script? - */ - case DB_WAL_HOOK: - case DB_UPDATE_HOOK: - case DB_ROLLBACK_HOOK: { - /* set ppHook to point at pUpdateHook or pRollbackHook, depending on - ** whether [$db update_hook] or [$db rollback_hook] was invoked. - */ - Tcl_Obj **ppHook = 0; - if( choice==DB_WAL_HOOK ) ppHook = &pDb->pWalHook; - if( choice==DB_UPDATE_HOOK ) ppHook = &pDb->pUpdateHook; - if( choice==DB_ROLLBACK_HOOK ) ppHook = &pDb->pRollbackHook; - if( objc>3 ){ - Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?"); - return TCL_ERROR; - } - - DbHookCmd(interp, pDb, (objc==3 ? objv[2] : 0), ppHook); - break; - } - - /* $db version - ** - ** Return the version string for this database. - */ - case DB_VERSION: { - int i; - for(i=2; ibLegacyPrepare) ){ - return TCL_ERROR; - } - }else - - /* $db version -last-stmt-ptr - ** - ** Return a string which is a hex encoding of the pointer to the - ** most recent sqlite3_stmt in the statement cache. - */ - if( strcmp(zArg, "-last-stmt-ptr")==0 ){ - char zBuf[100]; - sqlite3_snprintf(sizeof(zBuf), zBuf, "%p", - pDb->stmtList ? pDb->stmtList->pStmt: 0); - Tcl_SetResult(interp, zBuf, TCL_VOLATILE); - }else -#endif /* SQLITE_TEST */ - { - Tcl_AppendResult(interp, "unknown argument: ", zArg, (char*)0); - return TCL_ERROR; - } - } - if( i==2 ){ - Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC); - } - break; - } - - - } /* End of the SWITCH statement */ - return rc; -} - -#if SQLITE_TCL_NRE -/* -** Adaptor that provides an objCmd interface to the NRE-enabled -** interface implementation. -*/ -static int SQLITE_TCLAPI DbObjCmdAdaptor( - void *cd, - Tcl_Interp *interp, - int objc, - Tcl_Obj *const*objv -){ - return Tcl_NRCallObjProc(interp, DbObjCmd, cd, objc, objv); -} -#endif /* SQLITE_TCL_NRE */ - -/* -** Issue the usage message when the "sqlite3" command arguments are -** incorrect. -*/ -static int sqliteCmdUsage( - Tcl_Interp *interp, - Tcl_Obj *const*objv -){ - Tcl_WrongNumArgs(interp, 1, objv, - "HANDLE ?FILENAME? ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?" - " ?-nofollow BOOLEAN?" - " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN? ?-uri BOOLEAN?" - ); - return TCL_ERROR; -} - -/* -** sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN? -** ?-create BOOLEAN? ?-nomutex BOOLEAN? -** ?-nofollow BOOLEAN? -** -** This is the main Tcl command. When the "sqlite" Tcl command is -** invoked, this routine runs to process that command. -** -** The first argument, DBNAME, is an arbitrary name for a new -** database connection. This command creates a new command named -** DBNAME that is used to control that connection. The database -** connection is deleted when the DBNAME command is deleted. -** -** The second argument is the name of the database file. -** -*/ -static int SQLITE_TCLAPI DbMain( - void *cd, - Tcl_Interp *interp, - int objc, - Tcl_Obj *const*objv -){ - SqliteDb *p; - const char *zArg; - char *zErrMsg; - int i; - const char *zFile = 0; - const char *zVfs = 0; - int flags; - int bTranslateFileName = 1; - Tcl_DString translatedFilename; - int rc; - - /* In normal use, each TCL interpreter runs in a single thread. So - ** by default, we can turn off mutexing on SQLite database connections. - ** However, for testing purposes it is useful to have mutexes turned - ** on. So, by default, mutexes default off. But if compiled with - ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on. - */ -#ifdef SQLITE_TCL_DEFAULT_FULLMUTEX - flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX; -#else - flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX; -#endif - - if( objc==1 ) return sqliteCmdUsage(interp, objv); - if( objc==2 ){ - zArg = Tcl_GetStringFromObj(objv[1], 0); - if( strcmp(zArg,"-version")==0 ){ - Tcl_AppendResult(interp,sqlite3_libversion(), (char*)0); - return TCL_OK; - } - if( strcmp(zArg,"-sourceid")==0 ){ - Tcl_AppendResult(interp,sqlite3_sourceid(), (char*)0); - return TCL_OK; - } - if( strcmp(zArg,"-has-codec")==0 ){ - Tcl_AppendResult(interp,"0",(char*)0); - return TCL_OK; - } - if( zArg[0]=='-' ) return sqliteCmdUsage(interp, objv); - } - for(i=2; idb, flags, zVfs); - if( bTranslateFileName ){ - Tcl_DStringFree(&translatedFilename); - } - if( p->db ){ - if( SQLITE_OK!=sqlite3_errcode(p->db) ){ - zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db)); - sqlite3_close(p->db); - p->db = 0; - } - }else{ - zErrMsg = sqlite3_mprintf("%s", sqlite3_errstr(rc)); - } - if( p->db==0 ){ - Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE); - Tcl_Free((char*)p); - sqlite3_free(zErrMsg); - return TCL_ERROR; - } - p->maxStmt = NUM_PREPARED_STMTS; - p->openFlags = flags & SQLITE_OPEN_URI; - p->interp = interp; - zArg = Tcl_GetStringFromObj(objv[1], 0); - if( DbUseNre() ){ - Tcl_NRCreateCommand(interp, zArg, DbObjCmdAdaptor, DbObjCmd, - (char*)p, DbDeleteCmd); - }else{ - Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd); - } - return TCL_OK; -} - -/* -** Provide a dummy Tcl_InitStubs if we are using this as a static -** library. -*/ -#ifndef USE_TCL_STUBS -# undef Tcl_InitStubs -# define Tcl_InitStubs(a,b,c) TCL_VERSION -#endif - -/* -** Make sure we have a PACKAGE_VERSION macro defined. This will be -** defined automatically by the TEA makefile. But other makefiles -** do not define it. -*/ -#ifndef PACKAGE_VERSION -# define PACKAGE_VERSION SQLITE_VERSION -#endif - -/* -** Initialize this module. -** -** This Tcl module contains only a single new Tcl command named "sqlite". -** (Hence there is no namespace. There is no point in using a namespace -** if the extension only supplies one new name!) The "sqlite" command is -** used to open a new SQLite database. See the DbMain() routine above -** for additional information. -** -** The EXTERN macros are required by TCL in order to work on windows. -*/ -EXTERN int Sqlite3_Init(Tcl_Interp *interp){ - int rc = Tcl_InitStubs(interp, "8.4", 0) ? TCL_OK : TCL_ERROR; - if( rc==TCL_OK ){ - Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0); -#ifndef SQLITE_3_SUFFIX_ONLY - /* The "sqlite" alias is undocumented. It is here only to support - ** legacy scripts. All new scripts should use only the "sqlite3" - ** command. */ - Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0); -#endif - rc = Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION); - } - return rc; -} -EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); } -EXTERN int Sqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; } -EXTERN int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; } - -/* Because it accesses the file-system and uses persistent state, SQLite -** is not considered appropriate for safe interpreters. Hence, we cause -** the _SafeInit() interfaces return TCL_ERROR. -*/ -EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_ERROR; } -EXTERN int Sqlite3_SafeUnload(Tcl_Interp *interp, int flags){return TCL_ERROR;} - - - -#ifndef SQLITE_3_SUFFIX_ONLY -int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); } -int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); } -int Sqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; } -int Tclsqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; } -#endif - -/* -** If the TCLSH macro is defined, add code to make a stand-alone program. -*/ -#if defined(TCLSH) - -/* This is the main routine for an ordinary TCL shell. If there are -** are arguments, run the first argument as a script. Otherwise, -** read TCL commands from standard input -*/ -static const char *tclsh_main_loop(void){ - static const char zMainloop[] = - "if {[llength $argv]>=1} {\n" - "set argv0 [lindex $argv 0]\n" - "set argv [lrange $argv 1 end]\n" - "source $argv0\n" - "} else {\n" - "set line {}\n" - "while {![eof stdin]} {\n" - "if {$line!=\"\"} {\n" - "puts -nonewline \"> \"\n" - "} else {\n" - "puts -nonewline \"% \"\n" - "}\n" - "flush stdout\n" - "append line [gets stdin]\n" - "if {[info complete $line]} {\n" - "if {[catch {uplevel #0 $line} result]} {\n" - "puts stderr \"Error: $result\"\n" - "} elseif {$result!=\"\"} {\n" - "puts $result\n" - "}\n" - "set line {}\n" - "} else {\n" - "append line \\n\n" - "}\n" - "}\n" - "}\n" - ; - return zMainloop; -} - -#define TCLSH_MAIN main /* Needed to fake out mktclapp */ -int SQLITE_CDECL TCLSH_MAIN(int argc, char **argv){ - Tcl_Interp *interp; - int i; - const char *zScript = 0; - char zArgc[32]; -#if defined(TCLSH_INIT_PROC) - extern const char *TCLSH_INIT_PROC(Tcl_Interp*); -#endif - -#if !defined(_WIN32_WCE) - if( getenv("SQLITE_DEBUG_BREAK") ){ - if( isatty(0) && isatty(2) ){ - fprintf(stderr, - "attach debugger to process %d and press any key to continue.\n", - GETPID()); - fgetc(stdin); - }else{ -#if defined(_WIN32) || defined(WIN32) - DebugBreak(); -#elif defined(SIGTRAP) - raise(SIGTRAP); -#endif - } - } -#endif - - /* Call sqlite3_shutdown() once before doing anything else. This is to - ** test that sqlite3_shutdown() can be safely called by a process before - ** sqlite3_initialize() is. */ - sqlite3_shutdown(); - - Tcl_FindExecutable(argv[0]); - Tcl_SetSystemEncoding(NULL, "utf-8"); - interp = Tcl_CreateInterp(); - Sqlite3_Init(interp); - - sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-1); - Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY); - Tcl_SetVar(interp,"argv0",argv[0],TCL_GLOBAL_ONLY); - Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY); - for(i=1; i0 diff --git a/third_party/sqlite3/tokenize.c b/third_party/sqlite3/tokenize.c index 5e01de2b..a26973a4 100644 --- a/third_party/sqlite3/tokenize.c +++ b/third_party/sqlite3/tokenize.c @@ -15,8 +15,9 @@ ** individual tokens and sends those tokens one-by-one over to the ** parser for analysis. */ -#include "sqliteInt.h" -#include +#include "libc/mem/mem.h" +#include "third_party/sqlite3/sqliteInt.h" +/* clang-format off */ /* Character classes for tokenizing ** @@ -144,7 +145,7 @@ const unsigned char ebcdicToAscii[] = { ** named keywordhash.h and then included into this source file by ** the #include below. */ -#include "keywordhash.h" +#include "third_party/sqlite3/keywordhash.h" /* diff --git a/third_party/sqlite3/treeview.c b/third_party/sqlite3/treeview.c index b696d764..3bdf7e1e 100644 --- a/third_party/sqlite3/treeview.c +++ b/third_party/sqlite3/treeview.c @@ -12,13 +12,14 @@ ** ** This file contains C code to implement the TreeView debugging routines. ** These routines print a parse tree to standard output for debugging and -** analysis. +** analysis. ** ** The interfaces in this file is only available when compiling ** with SQLITE_DEBUG. */ -#include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" #ifdef SQLITE_DEBUG +/* clang-format off */ /* ** Add a new subitem to the tree. The moreToFollow flag indicates that this diff --git a/third_party/sqlite3/trigger.c b/third_party/sqlite3/trigger.c index 4c7cb548..46bdbba6 100644 --- a/third_party/sqlite3/trigger.c +++ b/third_party/sqlite3/trigger.c @@ -10,7 +10,8 @@ ************************************************************************* ** This file contains the implementation for TRIGGERs */ -#include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" +/* clang-format off */ #ifndef SQLITE_OMIT_TRIGGER /* diff --git a/third_party/sqlite3/update.c b/third_party/sqlite3/update.c index b360766b..c25c45bf 100644 --- a/third_party/sqlite3/update.c +++ b/third_party/sqlite3/update.c @@ -12,7 +12,8 @@ ** This file contains C code routines that are called by the parser ** to handle UPDATE statements. */ -#include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" +/* clang-format off */ #ifndef SQLITE_OMIT_VIRTUALTABLE /* Forward declaration */ diff --git a/third_party/sqlite3/upsert.c b/third_party/sqlite3/upsert.c index 982dc7db..041d6446 100644 --- a/third_party/sqlite3/upsert.c +++ b/third_party/sqlite3/upsert.c @@ -12,7 +12,8 @@ ** This file contains code to implement various aspects of UPSERT ** processing and handling of the Upsert object. */ -#include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" +/* clang-format off */ #ifndef SQLITE_OMIT_UPSERT /* diff --git a/third_party/sqlite3/userauth.c b/third_party/sqlite3/userauth.c index fa708516..e9e5b9cc 100644 --- a/third_party/sqlite3/userauth.c +++ b/third_party/sqlite3/userauth.c @@ -23,8 +23,9 @@ */ #ifdef SQLITE_USER_AUTHENTICATION #ifndef SQLITEINT_H -# include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" #endif +/* clang-format off */ /* ** Prepare an SQL statement for use by the user authentication logic. diff --git a/third_party/sqlite3/utf.c b/third_party/sqlite3/utf.c index 5f27babd..e781139d 100644 --- a/third_party/sqlite3/utf.c +++ b/third_party/sqlite3/utf.c @@ -9,7 +9,7 @@ ** May you share freely, never taking more than you give. ** ************************************************************************* -** This file contains routines used to translate between UTF-8, +** This file contains routines used to translate between UTF-8, ** UTF-16, UTF-16BE, and UTF-16LE. ** ** Notes on UTF-8: @@ -33,9 +33,10 @@ ** 0xfe 0xff big-endian utf-16 follows ** */ -#include "sqliteInt.h" -#include -#include "vdbeInt.h" +#include "libc/assert.h" +#include "third_party/sqlite3/sqliteInt.h" +#include "third_party/sqlite3/vdbeInt.h" +/* clang-format off */ #if !defined(SQLITE_AMALGAMATION) && SQLITE_BYTEORDER==0 /* diff --git a/third_party/sqlite3/util.c b/third_party/sqlite3/util.c index fc0c2042..d32cf638 100644 --- a/third_party/sqlite3/util.c +++ b/third_party/sqlite3/util.c @@ -15,10 +15,11 @@ ** strings, and stuff like that. ** */ -#include "sqliteInt.h" -#include +/* clang-format off */ + +#include "third_party/sqlite3/sqliteInt.h" #ifndef SQLITE_OMIT_FLOATING_POINT -#include +#include "libc/math.h" #endif /* diff --git a/third_party/sqlite3/vacuum.c b/third_party/sqlite3/vacuum.c index 93e2307d..dc916616 100644 --- a/third_party/sqlite3/vacuum.c +++ b/third_party/sqlite3/vacuum.c @@ -14,8 +14,9 @@ ** Most of the code in this file may be omitted by defining the ** SQLITE_OMIT_VACUUM macro. */ -#include "sqliteInt.h" -#include "vdbeInt.h" +#include "third_party/sqlite3/sqliteInt.h" +#include "third_party/sqlite3/vdbeInt.h" +/* clang-format off */ #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH) diff --git a/third_party/sqlite3/vdbe.c b/third_party/sqlite3/vdbe.c index 9bd6f89b..07de9425 100644 --- a/third_party/sqlite3/vdbe.c +++ b/third_party/sqlite3/vdbe.c @@ -18,8 +18,9 @@ ** in this file for details. If in doubt, do not deviate from existing ** commenting and indentation practices when changing or adding code. */ -#include "sqliteInt.h" -#include "vdbeInt.h" +#include "third_party/sqlite3/sqliteInt.h" +#include "third_party/sqlite3/vdbeInt.h" +/* clang-format off */ /* ** Invoke this macro on memory cells just prior to changing the @@ -598,7 +599,7 @@ void sqlite3VdbeRegisterDump(Vdbe *v){ ** hwtime.h contains inline assembler code for implementing ** high-performance timing routines. */ -#include "hwtime.h" +#include "third_party/sqlite3/hwtime.h" #endif diff --git a/third_party/sqlite3/vdbe.h b/third_party/sqlite3/vdbe.h index 3257ff68..51db23e0 100644 --- a/third_party/sqlite3/vdbe.h +++ b/third_party/sqlite3/vdbe.h @@ -17,7 +17,8 @@ */ #ifndef SQLITE_VDBE_H #define SQLITE_VDBE_H -#include +#include "libc/stdio/stdio.h" +/* clang-format off */ /* ** A single VDBE is an opaque structure named "Vdbe". Only routines @@ -166,7 +167,7 @@ typedef struct VdbeOpList VdbeOpList; ** The makefile scans the vdbe.c source file and creates the "opcodes.h" ** header file that defines a number for each opcode used by the VDBE. */ -#include "opcodes.h" +#include "third_party/sqlite3/opcodes.h" /* ** Additional non-public SQLITE_PREPARE_* flags diff --git a/third_party/sqlite3/vdbeInt.h b/third_party/sqlite3/vdbeInt.h index cb423f20..ba575126 100644 --- a/third_party/sqlite3/vdbeInt.h +++ b/third_party/sqlite3/vdbeInt.h @@ -17,6 +17,7 @@ */ #ifndef SQLITE_VDBEINT_H #define SQLITE_VDBEINT_H +/* clang-format off */ /* ** The maximum number of times that a statement will try to reparse diff --git a/third_party/sqlite3/vdbeapi.c b/third_party/sqlite3/vdbeapi.c index ba3bdf6a..b1b99d39 100644 --- a/third_party/sqlite3/vdbeapi.c +++ b/third_party/sqlite3/vdbeapi.c @@ -13,8 +13,9 @@ ** This file contains code use to implement APIs that are part of the ** VDBE. */ -#include "sqliteInt.h" -#include "vdbeInt.h" +#include "third_party/sqlite3/sqliteInt.h" +#include "third_party/sqlite3/vdbeInt.h" +/* clang-format off */ #ifndef SQLITE_OMIT_DEPRECATED /* diff --git a/third_party/sqlite3/vdbeaux.c b/third_party/sqlite3/vdbeaux.c index 38315e9f..13334c58 100644 --- a/third_party/sqlite3/vdbeaux.c +++ b/third_party/sqlite3/vdbeaux.c @@ -10,10 +10,11 @@ ** ************************************************************************* ** This file contains code used for creating, destroying, and populating -** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.) +** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.) */ -#include "sqliteInt.h" -#include "vdbeInt.h" +#include "third_party/sqlite3/sqliteInt.h" +#include "third_party/sqlite3/vdbeInt.h" +/* clang-format off */ /* Forward references */ static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef); diff --git a/third_party/sqlite3/vdbeblob.c b/third_party/sqlite3/vdbeblob.c index d34e3cf9..eaf07f14 100644 --- a/third_party/sqlite3/vdbeblob.c +++ b/third_party/sqlite3/vdbeblob.c @@ -12,9 +12,10 @@ ** ** This file contains code used to implement incremental BLOB I/O. */ +/* clang-format off */ -#include "sqliteInt.h" -#include "vdbeInt.h" +#include "third_party/sqlite3/sqliteInt.h" +#include "third_party/sqlite3/vdbeInt.h" #ifndef SQLITE_OMIT_INCRBLOB diff --git a/third_party/sqlite3/vdbemem.c b/third_party/sqlite3/vdbemem.c index 384eacc0..03ec6450 100644 --- a/third_party/sqlite3/vdbemem.c +++ b/third_party/sqlite3/vdbemem.c @@ -15,8 +15,9 @@ ** only within the VDBE. Interface routines refer to a Mem using the ** name sqlite_value */ -#include "sqliteInt.h" -#include "vdbeInt.h" +#include "third_party/sqlite3/sqliteInt.h" +#include "third_party/sqlite3/vdbeInt.h" +/* clang-format off */ /* True if X is a power of two. 0 is considered a power of two here. ** In other words, return true if X has at most one bit set. diff --git a/third_party/sqlite3/vdbesort.c b/third_party/sqlite3/vdbesort.c index f61b8b73..ef2a48e5 100644 --- a/third_party/sqlite3/vdbesort.c +++ b/third_party/sqlite3/vdbesort.c @@ -55,7 +55,7 @@ ** is like Close() followed by Init() only ** much faster. ** -** The interfaces above must be called in a particular order. Write() can +** The interfaces above must be called in a particular order. Write() can ** only occur in between Init()/Reset() and Rewind(). Next(), Rowkey(), and ** Compare() can only occur in between Rewind() and Close()/Reset(). i.e. ** @@ -63,16 +63,16 @@ ** for each record: Write() ** Rewind() ** Rowkey()/Compare() -** Next() +** Next() ** Close() ** ** Algorithm: ** -** Records passed to the sorter via calls to Write() are initially held +** Records passed to the sorter via calls to Write() are initially held ** unsorted in main memory. Assuming the amount of memory used never exceeds ** a threshold, when Rewind() is called the set of records is sorted using ** an in-memory merge sort. In this case, no temporary files are required -** and subsequent calls to Rowkey(), Next() and Compare() read records +** and subsequent calls to Rowkey(), Next() and Compare() read records ** directly from main memory. ** ** If the amount of space used to store records in main memory exceeds the @@ -82,10 +82,10 @@ ** of PMAs may be created by merging existing PMAs together - for example ** merging two or more level-0 PMAs together creates a level-1 PMA. ** -** The threshold for the amount of main memory to use before flushing +** The threshold for the amount of main memory to use before flushing ** records to a PMA is roughly the same as the limit configured for the -** page-cache of the main database. Specifically, the threshold is set to -** the value returned by "PRAGMA main.page_size" multipled by +** page-cache of the main database. Specifically, the threshold is set to +** the value returned by "PRAGMA main.page_size" multipled by ** that returned by "PRAGMA main.cache_size", in bytes. ** ** If the sorter is running in single-threaded mode, then all PMAs generated @@ -102,7 +102,7 @@ ** than zero, and (b) worker threads have been enabled at runtime by calling ** "PRAGMA threads=N" with some value of N greater than 0. ** -** When Rewind() is called, any data remaining in memory is flushed to a +** When Rewind() is called, any data remaining in memory is flushed to a ** final PMA. So at this point the data is stored in some number of sorted ** PMAs within temporary files on disk. ** @@ -114,16 +114,16 @@ ** ** Or, if running in multi-threaded mode, then a background thread is ** launched to merge the existing PMAs. Once the background thread has -** merged T bytes of data into a single sorted PMA, the main thread +** merged T bytes of data into a single sorted PMA, the main thread ** begins reading keys from that PMA while the background thread proceeds ** with merging the next T bytes of data. And so on. ** -** Parameter T is set to half the value of the memory threshold used +** Parameter T is set to half the value of the memory threshold used ** by Write() above to determine when to create a new PMA. ** -** If there are more than SORTER_MAX_MERGE_COUNT PMAs in total when -** Rewind() is called, then a hierarchy of incremental-merges is used. -** First, T bytes of data from the first SORTER_MAX_MERGE_COUNT PMAs on +** If there are more than SORTER_MAX_MERGE_COUNT PMAs in total when +** Rewind() is called, then a hierarchy of incremental-merges is used. +** First, T bytes of data from the first SORTER_MAX_MERGE_COUNT PMAs on ** disk are merged together. Then T bytes of data from the second set, and ** so on, such that no operation ever merges more than SORTER_MAX_MERGE_COUNT ** PMAs at a time. This done is to improve locality. @@ -135,8 +135,9 @@ ** thread to merge the output of each of the others to a single PMA for ** the main thread to read from. */ -#include "sqliteInt.h" -#include "vdbeInt.h" +#include "third_party/sqlite3/sqliteInt.h" +#include "third_party/sqlite3/vdbeInt.h" +/* clang-format off */ /* ** If SQLITE_DEBUG_SORTER_THREADS is defined, this module outputs various diff --git a/third_party/sqlite3/vdbetrace.c b/third_party/sqlite3/vdbetrace.c index 1095e7f5..896a813d 100644 --- a/third_party/sqlite3/vdbetrace.c +++ b/third_party/sqlite3/vdbetrace.c @@ -15,8 +15,9 @@ ** ** The Vdbe parse-tree explainer is also found here. */ -#include "sqliteInt.h" -#include "vdbeInt.h" +#include "third_party/sqlite3/sqliteInt.h" +#include "third_party/sqlite3/vdbeInt.h" +/* clang-format off */ #ifndef SQLITE_OMIT_TRACE diff --git a/third_party/sqlite3/vdbevtab.c b/third_party/sqlite3/vdbevtab.c index e9bafd45..d80058ec 100644 --- a/third_party/sqlite3/vdbevtab.c +++ b/third_party/sqlite3/vdbevtab.c @@ -13,9 +13,10 @@ ** This file implements virtual-tables for examining the bytecode content ** of a prepared statement. */ -#include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" #if defined(SQLITE_ENABLE_BYTECODE_VTAB) && !defined(SQLITE_OMIT_VIRTUALTABLE) -#include "vdbeInt.h" +#include "third_party/sqlite3/vdbeInt.h" +/* clang-format off */ /* An instance of the bytecode() table-valued function. */ diff --git a/third_party/sqlite3/vtab.c b/third_party/sqlite3/vtab.c index ded12c13..e72e7034 100644 --- a/third_party/sqlite3/vtab.c +++ b/third_party/sqlite3/vtab.c @@ -12,7 +12,8 @@ ** This file contains code used to help implement virtual tables. */ #ifndef SQLITE_OMIT_VIRTUALTABLE -#include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" +/* clang-format off */ /* ** Before a virtual table xCreate() or xConnect() method is invoked, the diff --git a/third_party/sqlite3/vxworks.h b/third_party/sqlite3/vxworks.h index e7013c3f..0e0cf3ea 100644 --- a/third_party/sqlite3/vxworks.h +++ b/third_party/sqlite3/vxworks.h @@ -14,19 +14,20 @@ */ #if defined(__RTP__) || defined(_WRS_KERNEL) /* This is VxWorks. Set up things specially for that OS -*/ + */ +#include /* amalgamator: dontcache */ #include -#include /* amalgamator: dontcache */ -#define OS_VXWORKS 1 -#define SQLITE_OS_OTHER 0 +#define OS_VXWORKS 1 +#define SQLITE_OS_OTHER 0 #define SQLITE_HOMEGROWN_RECURSIVE_MUTEX 1 -#define SQLITE_OMIT_LOAD_EXTENSION 1 -#define SQLITE_ENABLE_LOCKING_STYLE 0 -#define HAVE_UTIME 1 +#define SQLITE_OMIT_LOAD_EXTENSION 1 +#define SQLITE_ENABLE_LOCKING_STYLE 0 +#define HAVE_UTIME 1 #else /* This is not VxWorks. */ -#define OS_VXWORKS 0 -#define HAVE_FCHOWN 1 +#define OS_VXWORKS 0 +#define HAVE_FCHOWN 1 #define HAVE_READLINK 1 -#define HAVE_LSTAT 1 +#define HAVE_LSTAT 1 #endif /* defined(_WRS_KERNEL) */ + /* clang-format off */ diff --git a/third_party/sqlite3/wal.c b/third_party/sqlite3/wal.c index ac0a03e9..8d43638b 100644 --- a/third_party/sqlite3/wal.c +++ b/third_party/sqlite3/wal.c @@ -10,7 +10,7 @@ ** ************************************************************************* ** -** This file contains the implementation of a write-ahead log (WAL) used in +** This file contains the implementation of a write-ahead log (WAL) used in ** "journal_mode=WAL" mode. ** ** WRITE-AHEAD LOG (WAL) FILE FORMAT @@ -19,7 +19,7 @@ ** Each frame records the revised content of a single page from the ** database file. All changes to the database are recorded by writing ** frames into the WAL. Transactions commit when a frame is written that -** contains a commit marker. A single WAL can and usually does record +** contains a commit marker. A single WAL can and usually does record ** multiple transactions. Periodically, the content of the WAL is ** transferred back into the database file in an operation called a ** "checkpoint". @@ -45,11 +45,11 @@ ** ** Immediately following the wal-header are zero or more frames. Each ** frame consists of a 24-byte frame-header followed by a bytes -** of page data. The frame-header is six big-endian 32-bit unsigned +** of page data. The frame-header is six big-endian 32-bit unsigned ** integer values, as follows: ** ** 0: Page number. -** 4: For commit records, the size of the database image in pages +** 4: For commit records, the size of the database image in pages ** after the commit. For all other records, zero. ** 8: Salt-1 (copied from the header) ** 12: Salt-2 (copied from the header) @@ -75,7 +75,7 @@ ** the checksum. The checksum is computed by interpreting the input as ** an even number of unsigned 32-bit integers: x[0] through x[N]. The ** algorithm used for the checksum is as follows: -** +** ** for i from 0 to n-1 step 2: ** s0 += x[i] + s1; ** s1 += x[i+1] + s0; @@ -83,7 +83,7 @@ ** ** Note that s0 and s1 are both weighted checksums using fibonacci weights ** in reverse order (the largest fibonacci weight occurs on the first element -** of the sequence being summed.) The s1 value spans all 32-bit +** of the sequence being summed.) The s1 value spans all 32-bit ** terms of the sequence whereas s0 omits the final term. ** ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the @@ -116,19 +116,19 @@ ** multiple concurrent readers to view different versions of the database ** content simultaneously. ** -** The reader algorithm in the previous paragraphs works correctly, but +** The reader algorithm in the previous paragraphs works correctly, but ** because frames for page P can appear anywhere within the WAL, the ** reader has to scan the entire WAL looking for page P frames. If the ** WAL is large (multiple megabytes is typical) that scan can be slow, ** and read performance suffers. To overcome this problem, a separate ** data structure called the wal-index is maintained to expedite the ** search for frames of a particular page. -** +** ** WAL-INDEX FORMAT ** ** Conceptually, the wal-index is shared memory, though VFS implementations ** might choose to implement the wal-index using a mmapped file. Because -** the wal-index is shared memory, SQLite does not support journal_mode=WAL +** the wal-index is shared memory, SQLite does not support journal_mode=WAL ** on a network filesystem. All users of the database must be able to ** share memory. ** @@ -146,28 +146,28 @@ ** byte order of the host computer. ** ** The purpose of the wal-index is to answer this question quickly: Given -** a page number P and a maximum frame index M, return the index of the +** a page number P and a maximum frame index M, return the index of the ** last frame in the wal before frame M for page P in the WAL, or return ** NULL if there are no frames for page P in the WAL prior to M. ** ** The wal-index consists of a header region, followed by an one or -** more index blocks. +** more index blocks. ** ** The wal-index header contains the total number of frames within the WAL ** in the mxFrame field. ** -** Each index block except for the first contains information on +** Each index block except for the first contains information on ** HASHTABLE_NPAGE frames. The first index block contains information on -** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and +** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and ** HASHTABLE_NPAGE are selected so that together the wal-index header and ** first index block are the same size as all other index blocks in the ** wal-index. ** ** Each index block contains two sections, a page-mapping that contains the -** database page number associated with each wal frame, and a hash-table +** database page number associated with each wal frame, and a hash-table ** that allows readers to query an index block for a specific page number. ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE -** for the first index block) 32-bit page numbers. The first entry in the +** for the first index block) 32-bit page numbers. The first entry in the ** first index-block contains the database page number corresponding to the ** first frame in the WAL file. The first entry in the second index block ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in @@ -188,8 +188,8 @@ ** ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers. ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the -** hash table for each page number in the mapping section, so the hash -** table is never more than half full. The expected number of collisions +** hash table for each page number in the mapping section, so the hash +** table is never more than half full. The expected number of collisions ** prior to finding a match is 1. Each entry of the hash table is an ** 1-based index of an entry in the mapping section of the same ** index block. Let K be the 1-based index of the largest entry in @@ -208,12 +208,12 @@ ** reached) until an unused hash slot is found. Let the first unused slot ** be at index iUnused. (iUnused might be less than iKey if there was ** wrap-around.) Because the hash table is never more than half full, -** the search is guaranteed to eventually hit an unused entry. Let +** the search is guaranteed to eventually hit an unused entry. Let ** iMax be the value between iKey and iUnused, closest to iUnused, ** where aHash[iMax]==P. If there is no iMax entry (if there exists ** no hash slot such that aHash[i]==p) then page P is not in the ** current index block. Otherwise the iMax-th mapping entry of the -** current index block corresponds to the last entry that references +** current index block corresponds to the last entry that references ** page P. ** ** A hash search begins with the last index block and moves toward the @@ -238,15 +238,16 @@ ** if no values greater than K0 had ever been inserted into the hash table ** in the first place - which is what reader one wants. Meanwhile, the ** second reader using K1 will see additional values that were inserted -** later, which is exactly what reader two wants. +** later, which is exactly what reader two wants. ** ** When a rollback occurs, the value of K is decreased. Hash table entries ** that correspond to frames greater than the new K value are removed ** from the hash table at this point. */ #ifndef SQLITE_OMIT_WAL +/* clang-format off */ -#include "wal.h" +#include "third_party/sqlite3/wal.h" /* ** Trace output macros diff --git a/third_party/sqlite3/wal.h b/third_party/sqlite3/wal.h index 02e2bab3..0ea24e0a 100644 --- a/third_party/sqlite3/wal.h +++ b/third_party/sqlite3/wal.h @@ -9,15 +9,16 @@ ** May you share freely, never taking more than you give. ** ************************************************************************* -** This header file defines the interface to the write-ahead logging -** system. Refer to the comments below and the header comment attached to +** This header file defines the interface to the write-ahead logging +** system. Refer to the comments below and the header comment attached to ** the implementation of each function in log.c for further details. */ +/* clang-format off */ #ifndef SQLITE_WAL_H #define SQLITE_WAL_H -#include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" /* Macros for extracting appropriate sync flags for either transaction ** commits (WAL_SYNC_FLAGS(X)) or for checkpoint ops (CKPT_SYNC_FLAGS(X)): diff --git a/third_party/sqlite3/walker.c b/third_party/sqlite3/walker.c index 927f7e52..54f09ba7 100644 --- a/third_party/sqlite3/walker.c +++ b/third_party/sqlite3/walker.c @@ -12,36 +12,35 @@ ** This file contains routines used for walking the parser tree for ** an SQL statement. */ -#include "sqliteInt.h" -#include -#include - +#include "libc/mem/mem.h" +#include "libc/str/str.h" +#include "third_party/sqlite3/sqliteInt.h" #if !defined(SQLITE_OMIT_WINDOWFUNC) /* ** Walk all expressions linked into the list of Window objects passed ** as the second argument. */ -static int walkWindowList(Walker *pWalker, Window *pList, int bOneOnly){ +static int walkWindowList(Walker *pWalker, Window *pList, int bOneOnly) { Window *pWin; - for(pWin=pList; pWin; pWin=pWin->pNextWin){ + for (pWin = pList; pWin; pWin = pWin->pNextWin) { int rc; rc = sqlite3WalkExprList(pWalker, pWin->pOrderBy); - if( rc ) return WRC_Abort; + if (rc) return WRC_Abort; rc = sqlite3WalkExprList(pWalker, pWin->pPartition); - if( rc ) return WRC_Abort; + if (rc) return WRC_Abort; rc = sqlite3WalkExpr(pWalker, pWin->pFilter); - if( rc ) return WRC_Abort; + if (rc) return WRC_Abort; /* The next two are purely for calls to sqlite3RenameExprUnmap() ** within sqlite3WindowOffsetExpr(). Because of constraints imposed ** by sqlite3WindowOffsetExpr(), they can never fail. The results do ** not matter anyhow. */ rc = sqlite3WalkExpr(pWalker, pWin->pStart); - if( NEVER(rc) ) return WRC_Abort; + if (NEVER(rc)) return WRC_Abort; rc = sqlite3WalkExpr(pWalker, pWin->pEnd); - if( NEVER(rc) ) return WRC_Abort; - if( bOneOnly ) break; + if (NEVER(rc)) return WRC_Abort; + if (bOneOnly) break; } return WRC_Continue; } @@ -66,30 +65,30 @@ static int walkWindowList(Walker *pWalker, Window *pList, int bOneOnly){ ** The return value from this routine is WRC_Abort to abandon the tree walk ** and WRC_Continue to continue. */ -static SQLITE_NOINLINE int walkExpr(Walker *pWalker, Expr *pExpr){ +static SQLITE_NOINLINE int walkExpr(Walker *pWalker, Expr *pExpr) { int rc; - testcase( ExprHasProperty(pExpr, EP_TokenOnly) ); - testcase( ExprHasProperty(pExpr, EP_Reduced) ); - while(1){ + testcase(ExprHasProperty(pExpr, EP_TokenOnly)); + testcase(ExprHasProperty(pExpr, EP_Reduced)); + while (1) { rc = pWalker->xExprCallback(pWalker, pExpr); - if( rc ) return rc & WRC_Abort; - if( !ExprHasProperty(pExpr,(EP_TokenOnly|EP_Leaf)) ){ - assert( pExpr->x.pList==0 || pExpr->pRight==0 ); - if( pExpr->pLeft && walkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort; - if( pExpr->pRight ){ - assert( !ExprHasProperty(pExpr, EP_WinFunc) ); + if (rc) return rc & WRC_Abort; + if (!ExprHasProperty(pExpr, (EP_TokenOnly | EP_Leaf))) { + assert(pExpr->x.pList == 0 || pExpr->pRight == 0); + if (pExpr->pLeft && walkExpr(pWalker, pExpr->pLeft)) return WRC_Abort; + if (pExpr->pRight) { + assert(!ExprHasProperty(pExpr, EP_WinFunc)); pExpr = pExpr->pRight; continue; - }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){ - assert( !ExprHasProperty(pExpr, EP_WinFunc) ); - if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort; - }else{ - if( pExpr->x.pList ){ - if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort; + } else if (ExprHasProperty(pExpr, EP_xIsSelect)) { + assert(!ExprHasProperty(pExpr, EP_WinFunc)); + if (sqlite3WalkSelect(pWalker, pExpr->x.pSelect)) return WRC_Abort; + } else { + if (pExpr->x.pList) { + if (sqlite3WalkExprList(pWalker, pExpr->x.pList)) return WRC_Abort; } #ifndef SQLITE_OMIT_WINDOWFUNC - if( ExprHasProperty(pExpr, EP_WinFunc) ){ - if( walkWindowList(pWalker, pExpr->y.pWin, 1) ) return WRC_Abort; + if (ExprHasProperty(pExpr, EP_WinFunc)) { + if (walkWindowList(pWalker, pExpr->y.pWin, 1)) return WRC_Abort; } #endif } @@ -98,20 +97,20 @@ static SQLITE_NOINLINE int walkExpr(Walker *pWalker, Expr *pExpr){ } return WRC_Continue; } -int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){ - return pExpr ? walkExpr(pWalker,pExpr) : WRC_Continue; +int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr) { + return pExpr ? walkExpr(pWalker, pExpr) : WRC_Continue; } /* ** Call sqlite3WalkExpr() for every expression in list p or until ** an abort request is seen. */ -int sqlite3WalkExprList(Walker *pWalker, ExprList *p){ +int sqlite3WalkExprList(Walker *pWalker, ExprList *p) { int i; struct ExprList_item *pItem; - if( p ){ - for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){ - if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort; + if (p) { + for (i = p->nExpr, pItem = p->a; i > 0; i--, pItem++) { + if (sqlite3WalkExpr(pWalker, pItem->pExpr)) return WRC_Abort; } } return WRC_Continue; @@ -123,17 +122,17 @@ int sqlite3WalkExprList(Walker *pWalker, ExprList *p){ ** any expr callbacks and SELECT callbacks that come from subqueries. ** Return WRC_Abort or WRC_Continue. */ -int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){ - if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort; - if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort; - if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort; - if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort; - if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort; - if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort; +int sqlite3WalkSelectExpr(Walker *pWalker, Select *p) { + if (sqlite3WalkExprList(pWalker, p->pEList)) return WRC_Abort; + if (sqlite3WalkExpr(pWalker, p->pWhere)) return WRC_Abort; + if (sqlite3WalkExprList(pWalker, p->pGroupBy)) return WRC_Abort; + if (sqlite3WalkExpr(pWalker, p->pHaving)) return WRC_Abort; + if (sqlite3WalkExprList(pWalker, p->pOrderBy)) return WRC_Abort; + if (sqlite3WalkExpr(pWalker, p->pLimit)) return WRC_Abort; #if !defined(SQLITE_OMIT_WINDOWFUNC) && !defined(SQLITE_OMIT_ALTERTABLE) { Parse *pParse = pWalker->pParse; - if( pParse && IN_RENAME_OBJECT ){ + if (pParse && IN_RENAME_OBJECT) { /* The following may return WRC_Abort if there are unresolvable ** symbols (e.g. a table that does not exist) in a window definition. */ int rc = walkWindowList(pWalker, p->pWinDefn, 0); @@ -148,34 +147,33 @@ int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){ ** Walk the parse trees associated with all subqueries in the ** FROM clause of SELECT statement p. Do not invoke the select ** callback on p, but do invoke it on each FROM clause subquery -** and on any subqueries further down in the tree. Return +** and on any subqueries further down in the tree. Return ** WRC_Abort or WRC_Continue; */ -int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){ +int sqlite3WalkSelectFrom(Walker *pWalker, Select *p) { SrcList *pSrc; int i; SrcItem *pItem; pSrc = p->pSrc; - if( pSrc ){ - for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){ - if( pItem->pSelect && sqlite3WalkSelect(pWalker, pItem->pSelect) ){ + if (pSrc) { + for (i = pSrc->nSrc, pItem = pSrc->a; i > 0; i--, pItem++) { + if (pItem->pSelect && sqlite3WalkSelect(pWalker, pItem->pSelect)) { return WRC_Abort; } - if( pItem->fg.isTabFunc - && sqlite3WalkExprList(pWalker, pItem->u1.pFuncArg) - ){ + if (pItem->fg.isTabFunc && + sqlite3WalkExprList(pWalker, pItem->u1.pFuncArg)) { return WRC_Abort; } } } return WRC_Continue; -} +} /* ** Call sqlite3WalkExpr() for every expression in Select statement p. ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and -** on the compound select chain, p->pPrior. +** on the compound select chain, p->pPrior. ** ** If it is not NULL, the xSelectCallback() callback is invoked before ** the walk of the expressions and FROM clause. The xSelectCallback2() @@ -189,50 +187,48 @@ int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){ ** If the Walker does not have an xSelectCallback() then this routine ** is a no-op returning WRC_Continue. */ -int sqlite3WalkSelect(Walker *pWalker, Select *p){ +int sqlite3WalkSelect(Walker *pWalker, Select *p) { int rc; - if( p==0 ) return WRC_Continue; - if( pWalker->xSelectCallback==0 ) return WRC_Continue; - do{ + if (p == 0) return WRC_Continue; + if (pWalker->xSelectCallback == 0) return WRC_Continue; + do { rc = pWalker->xSelectCallback(pWalker, p); - if( rc ) return rc & WRC_Abort; - if( sqlite3WalkSelectExpr(pWalker, p) - || sqlite3WalkSelectFrom(pWalker, p) - ){ + if (rc) return rc & WRC_Abort; + if (sqlite3WalkSelectExpr(pWalker, p) || + sqlite3WalkSelectFrom(pWalker, p)) { return WRC_Abort; } - if( pWalker->xSelectCallback2 ){ + if (pWalker->xSelectCallback2) { pWalker->xSelectCallback2(pWalker, p); } p = p->pPrior; - }while( p!=0 ); + } while (p != 0); return WRC_Continue; } /* Increase the walkerDepth when entering a subquery, and ** descrease when leaving the subquery. */ -int sqlite3WalkerDepthIncrease(Walker *pWalker, Select *pSelect){ +int sqlite3WalkerDepthIncrease(Walker *pWalker, Select *pSelect) { UNUSED_PARAMETER(pSelect); pWalker->walkerDepth++; return WRC_Continue; } -void sqlite3WalkerDepthDecrease(Walker *pWalker, Select *pSelect){ +void sqlite3WalkerDepthDecrease(Walker *pWalker, Select *pSelect) { UNUSED_PARAMETER(pSelect); pWalker->walkerDepth--; } - /* ** No-op routine for the parse-tree walker. ** ** When this routine is the Walker.xExprCallback then expression trees ** are walked without any actions being taken at each node. Presumably, -** when this routine is used for Walker.xExprCallback then -** Walker.xSelectCallback is set to do something useful for every +** when this routine is used for Walker.xExprCallback then +** Walker.xSelectCallback is set to do something useful for every ** subquery in the parser tree. */ -int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){ +int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2) { UNUSED_PARAMETER2(NotUsed, NotUsed2); return WRC_Continue; } @@ -241,7 +237,7 @@ int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){ ** No-op routine for the parse-tree walker for SELECT statements. ** subquery in the parser tree. */ -int sqlite3SelectWalkNoop(Walker *NotUsed, Select *NotUsed2){ +int sqlite3SelectWalkNoop(Walker *NotUsed, Select *NotUsed2) { UNUSED_PARAMETER2(NotUsed, NotUsed2); return WRC_Continue; } diff --git a/third_party/sqlite3/where.c b/third_party/sqlite3/where.c index 75b3ceff..99896d4a 100644 --- a/third_party/sqlite3/where.c +++ b/third_party/sqlite3/where.c @@ -16,8 +16,9 @@ ** so is applicable. Because this module is responsible for selecting ** indices, you might also think of this module as the "query optimizer". */ -#include "sqliteInt.h" -#include "whereInt.h" +#include "third_party/sqlite3/sqliteInt.h" +#include "third_party/sqlite3/whereInt.h" +/* clang-format off */ /* ** Extra information appended to the end of sqlite3_index_info but not diff --git a/third_party/sqlite3/whereInt.h b/third_party/sqlite3/whereInt.h index 8896da02..36a67bc1 100644 --- a/third_party/sqlite3/whereInt.h +++ b/third_party/sqlite3/whereInt.h @@ -16,6 +16,7 @@ */ #ifndef SQLITE_WHEREINT_H #define SQLITE_WHEREINT_H +/* clang-format off */ /* Forward references diff --git a/third_party/sqlite3/wherecode.c b/third_party/sqlite3/wherecode.c index a7a76fb7..9888d183 100644 --- a/third_party/sqlite3/wherecode.c +++ b/third_party/sqlite3/wherecode.c @@ -17,8 +17,9 @@ ** that actually generate the bulk of the WHERE loop code. The original where.c ** file retains the code that does query planning and analysis. */ -#include "sqliteInt.h" -#include "whereInt.h" +#include "third_party/sqlite3/sqliteInt.h" +#include "third_party/sqlite3/whereInt.h" +/* clang-format off */ #ifndef SQLITE_OMIT_EXPLAIN diff --git a/third_party/sqlite3/whereexpr.c b/third_party/sqlite3/whereexpr.c index 1807fbb0..7676c7c2 100644 --- a/third_party/sqlite3/whereexpr.c +++ b/third_party/sqlite3/whereexpr.c @@ -16,8 +16,9 @@ ** readability and editabiliity. This file contains utility routines for ** analyzing Expr objects in the WHERE clause. */ -#include "sqliteInt.h" -#include "whereInt.h" +#include "third_party/sqlite3/sqliteInt.h" +#include "third_party/sqlite3/whereInt.h" +/* clang-format off */ /* Forward declarations */ static void exprAnalyze(SrcList*, WhereClause*, int); diff --git a/third_party/sqlite3/window.c b/third_party/sqlite3/window.c index 33e905e5..401ed1a1 100644 --- a/third_party/sqlite3/window.c +++ b/third_party/sqlite3/window.c @@ -10,7 +10,8 @@ ** ************************************************************************* */ -#include "sqliteInt.h" +#include "third_party/sqlite3/sqliteInt.h" +/* clang-format off */ #ifndef SQLITE_OMIT_WINDOWFUNC diff --git a/third_party/third_party.mk b/third_party/third_party.mk index bd2ba492..d47e26e7 100644 --- a/third_party/third_party.mk +++ b/third_party/third_party.mk @@ -14,5 +14,6 @@ o/$(MODE)/third_party: \ o/$(MODE)/third_party/quickjs \ o/$(MODE)/third_party/regex \ o/$(MODE)/third_party/stb \ + o/$(MODE)/third_party/sqlite3 \ o/$(MODE)/third_party/xed \ o/$(MODE)/third_party/zlib